# yatra/3.0.6/assets/admin/dist/js/app.js

Yatra – Travel Booking &amp; Tour Operator Software, version 3.0.6. 77,374 lines.

- Page: https://pluginprobe.com/plugins/yatra/3.0.6/code/assets/admin/dist/js/app.js
- Raw: https://pluginprobe.com/plugins/yatra/3.0.6/raw/assets/admin/dist/js/app.js
- Modified: 2026-05-27T14:21:56+00:00

Line numbers below start at 1. Link to a line or a range by appending a fragment to the
page URL, for example `https://pluginprobe.com/plugins/yatra/3.0.6/code/assets/admin/dist/js/app.js#L10-L20`.

```javascript
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["../../../dist/js/TripForm-tFMoMuMs.js","../../../dist/js/react-vendor-CqkbFEvK.js","../css/react-vendor.css","../../../dist/js/index-DRAt5dnR.js","../css/index.css","../../../dist/js/BuildItineraryModal-Dq10SB7H.js","../../../dist/js/ProFeature-DHa4Wgkh.js","../../../dist/js/Settings-DZPiAnb3.js","../../../dist/js/Team-CFV2Lcc6.js","../../../dist/js/Reports-sGU73NQH.js","../../../dist/js/DiscountForm-CWIQB0xy.js","../../../dist/js/ApplicableTripSelector-BQ_5SGb1.js","../../../dist/js/Itinerary-Ap1hthK0.js","../../../dist/js/RecurringRuleForm-qprdlB53.js","./Whatsapp.js","../../../dist/js/module-skeleton-DUioukJc.js","../../../dist/js/ChannelManager-BumsBhiQ.js","../../../dist/js/Webhooks-BmhRcymQ.js","../../../dist/js/TripConsentForm-DeH_xgzl.js","../../../dist/js/BookingForm-DFFoFfQO.js","../../../dist/js/ViewBooking-D0U0ZXpB.js","../../../dist/js/AvailabilityForm-BPWy1f1h.js","../../../dist/js/DynamicPricing-DTdy3svi.js","../../../dist/js/RuleTypeSelectionModal-CjAmWcQE.js","../../../dist/js/toggle-C9qtIVLs.js","../../../dist/js/DynamicPricingRuleForm-wUY86s8E.js","../../../dist/js/AiAssistant-2YNozU84.js","../../../dist/js/AbandonedRecovery-BXWfwama.js","../../../dist/js/WhiteLabel-DoUclAt1.js"])))=>i.map(i=>d[i]);
var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key2, value) => key2 in obj ? __defProp(obj, key2, { enumerable: true, configurable: true, writable: true, value }) : obj[key2] = value;
var __publicField = (obj, key2, value) => __defNormalProp(obj, typeof key2 !== "symbol" ? key2 + "" : key2, value);
import { r as reactExports, j as jsxRuntimeExports, W as Wrench, N as Network, M as MessageCircle, S as Sparkles, R as RotateCcw, P as Puzzle, a as MessageSquare, b as Plane, B as BadgePercent, c as Route, F as FileSignature, K as Key, d as Mail, C as Crown, A as Activity, L as List, T as TrendingUp, e as Tag, f as FolderTree, U as Users, g as CircleUser, h as Package, i as CreditCard, k as FileText, l as Settings$1, m as BarChart3, n as Star, o as CalendarDays, p as Calendar$1, q as MapPin, s as LayoutDashboard, u as useQuery, t as useQueryClient, v as useMutation, Z as Zap, w as Webhook, x as ChevronDown, y as ChevronRight, z as ArrowLeft, G as Gift, D as Loader2, E as Sun, H as Moon, I as User, J as RefreshCw, O as Inbox, Q as AlertTriangle, V as ExternalLink, X as isObjectLike_1, _ as _baseGetTag, Y as isArray_1, $ as _MapCache, a0 as getDefaultExportFromCjs, a1 as _Symbol, a2 as isObject$5, a3 as isFunction, a4 as reactIsExports, a5 as React, a6 as _Stack, a7 as _baseIsEqual, a8 as isObject_1, a9 as keys_1, aa as isLength_1, ab as _isIndex, ac as isArguments_1, ad as _Set, ae as _setToArray, af as _SetCache, ag as _cacheHas, ah as _arrayPush, ai as isArrayLike_1, aj as _baseUnary, ak as _getNative, al as eq_1, am as _root, an as isEqual, ao as Animate, ap as _overArg, aq as _arraySome, ar as Clock, as as DollarSign, at as ArrowRight, au as Shield, av as CheckCircle, aw as Plus, ax as X, ay as reactDomExports, az as AlertCircle, aA as Check, aB as Wand2, aC as ChevronLeft, aD as CheckCircle2, aE as HelpCircle, aF as Info, aG as Copy, aH as MoreVertical, aI as Columns, aJ as PenSquare, aK as ArrowUp, aL as ArrowDown, aM as Archive, aN as Trash2, aO as Search, aP as ArrowUpDown, aQ as Eye, aR as Upload, aS as Image, aT as ReactQuill, aU as Pen, aV as Save, aW as Phone, aX as PauseCircle, aY as ShieldX, aZ as ShieldOff, a_ as Globe, a$ as Award, b0 as Database, b1 as Folder, b2 as Mountain, b3 as UserCheck, b4 as Download, b5 as Server, b6 as XCircle, b7 as Video, b8 as Lock, b9 as GripVertical, ba as ChevronUp, bb as Play, bc as ClipboardCopy, bd as Ban, be as Bell, bf as Heart, bg as Scissors, bh as Send, bi as Filter, bj as ClipboardCheck, bk as PenTool, bl as Camera, bm as BarChart$1, bn as Megaphone, bo as GitBranch, bp as Pause, bq as Settings2, br as Code, bs as Bug, bt as EyeOff, bu as QueryClient, bv as client, bw as QueryClientProvider } from "../../../dist/js/react-vendor-CqkbFEvK.js";
import { a as apiClient, A as API_ENDPOINTS, u as useToast, _ as __, b as apiService, n as normalizeCurrencyPosition, f as formatYatraMoney, r as readYatraCurrencyPositionFromWindow, s as sprintf, c as brandName, g as getCurrencySymbol, d as ajaxService, T as ToastProvider } from "../../../dist/js/index-DRAt5dnR.js";
const scriptRel = "modulepreload";
const assetsURL = function(dep, importerUrl) {
  return new URL(dep, importerUrl).href;
};
const seen = {};
const __vitePreload = function preload(baseModule, deps, importerUrl) {
  let promise = Promise.resolve();
  if (deps && deps.length > 0) {
    const links = document.getElementsByTagName("link");
    const cspNonceMeta = document.querySelector(
      "meta[property=csp-nonce]"
    );
    const cspNonce = (cspNonceMeta == null ? void 0 : cspNonceMeta.nonce) || (cspNonceMeta == null ? void 0 : cspNonceMeta.getAttribute("nonce"));
    promise = Promise.allSettled(
      deps.map((dep) => {
        dep = assetsURL(dep, importerUrl);
        if (dep in seen) return;
        seen[dep] = true;
        const isCss = dep.endsWith(".css");
        const cssSelector = isCss ? '[rel="stylesheet"]' : "";
        const isBaseRelative = !!importerUrl;
        if (isBaseRelative) {
          for (let i = links.length - 1; i >= 0; i--) {
            const link22 = links[i];
            if (link22.href === dep && (!isCss || link22.rel === "stylesheet")) {
              return;
            }
          }
        } else if (document.querySelector(`link[href="${dep}"]${cssSelector}`)) {
          return;
        }
        const link2 = document.createElement("link");
        link2.rel = isCss ? "stylesheet" : scriptRel;
        if (!isCss) {
          link2.as = "script";
        }
        link2.crossOrigin = "";
        link2.href = dep;
        if (cspNonce) {
          link2.setAttribute("nonce", cspNonce);
        }
        document.head.appendChild(link2);
        if (isCss) {
          return new Promise((res, rej) => {
            link2.addEventListener("load", res);
            link2.addEventListener(
              "error",
              () => rej(new Error(`Unable to preload CSS for ${dep}`))
            );
          });
        }
      })
    );
  }
  function handlePreloadError(err) {
    const e = new Event("vite:preloadError", {
      cancelable: true
    });
    e.payload = err;
    window.dispatchEvent(e);
    if (!e.defaultPrevented) {
      throw err;
    }
  }
  return promise.then((res) => {
    for (const item of res || []) {
      if (item.status !== "rejected") continue;
      handlePreloadError(item.reason);
    }
    return baseModule().catch(handlePreloadError);
  });
};
const Button = reactExports.forwardRef(
  ({
    className = "",
    variant = "default",
    size = "default",
    asChild = false,
    children,
    ...props
  }, ref) => {
    const baseClasses = "inline-flex items-center justify-center rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50";
    const variantClasses = {
      default: "bg-blue-600 text-white hover:bg-blue-700 dark:bg-blue-500 dark:hover:bg-blue-600",
      outline: "border border-gray-300 bg-transparent hover:bg-gray-100 dark:border-gray-600 dark:hover:bg-gray-800",
      ghost: "hover:bg-gray-100 dark:hover:bg-gray-800",
      destructive: "bg-red-600 text-white hover:bg-red-700 dark:bg-red-500 dark:hover:bg-red-600"
    };
    const sizeClasses2 = {
      default: "h-10 px-4 py-2",
      sm: "h-9 rounded-md px-3",
      lg: "h-11 rounded-md px-8",
      icon: "h-10 w-10"
    };
    const mergedClassName = `${baseClasses} ${variantClasses[variant]} ${sizeClasses2[size]} ${className}`;
    if (asChild && reactExports.isValidElement(children)) {
      const child = children;
      const childClassName = child.props.className;
      return reactExports.cloneElement(child, {
        ...props,
        className: `${mergedClassName}${childClassName ? ` ${childClassName}` : ""}`
      });
    }
    return /* @__PURE__ */ jsxRuntimeExports.jsx("button", { className: mergedClassName, ref, ...props, children });
  }
);
Button.displayName = "Button";
const Tooltip$1 = ({
  content,
  children,
  side = "top",
  className = ""
}) => {
  const id = reactExports.useId();
  const [open, setOpen] = reactExports.useState(false);
  if (!content) {
    return /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className, children });
  }
  const popoverPos = {
    top: "bottom-full left-1/2 -translate-x-1/2 mb-1.5",
    bottom: "top-full left-1/2 -translate-x-1/2 mt-1.5",
    left: "right-full top-1/2 -translate-y-1/2 mr-1.5",
    right: "left-full top-1/2 -translate-y-1/2 ml-1.5"
  };
  const arrowPos = {
    top: "top-full left-1/2 -translate-x-1/2 border-t-gray-900 dark:border-t-gray-100",
    bottom: "bottom-full left-1/2 -translate-x-1/2 border-b-gray-900 dark:border-b-gray-100",
    left: "left-full top-1/2 -translate-y-1/2 border-l-gray-900 dark:border-l-gray-100",
    right: "right-full top-1/2 -translate-y-1/2 border-r-gray-900 dark:border-r-gray-100"
  };
  const arrowStyle = {
    top: "border-x-transparent border-b-transparent",
    bottom: "border-x-transparent border-t-transparent",
    left: "border-y-transparent border-r-transparent",
    right: "border-y-transparent border-l-transparent"
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(
    "span",
    {
      className: `relative inline-flex items-center ${className}`,
      onMouseEnter: () => setOpen(true),
      onMouseLeave: () => setOpen(false),
      onFocus: () => setOpen(true),
      onBlur: () => setOpen(false),
      onKeyDown: (e) => {
        if (e.key === "Escape") setOpen(false);
      },
      children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { "aria-describedby": open ? id : void 0, tabIndex: 0, children }),
        open && /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "span",
          {
            id,
            role: "tooltip",
            className: `absolute z-50 pointer-events-none whitespace-normal break-words rounded-md bg-gray-900 px-2.5 py-1.5 text-xs font-normal leading-snug text-white shadow-lg max-w-xs w-max dark:bg-gray-100 dark:text-gray-900 ${popoverPos[side]}`,
            children: [
              content,
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "span",
                {
                  "aria-hidden": "true",
                  className: `absolute h-0 w-0 border-[6px] ${arrowStyle[side]} ${arrowPos[side]}`
                }
              )
            ]
          }
        )
      ]
    }
  );
};
function unwrapApiPayload(raw) {
  if (raw !== null && typeof raw === "object") {
    const r2 = raw;
    if (r2.success === true && "data" in r2) {
      return r2.data;
    }
  }
  return raw;
}
async function fetchSettings() {
  return unwrapApiPayload(
    await apiClient.get(API_ENDPOINTS.SETTINGS)
  );
}
async function saveSettings(data) {
  return apiClient.put(API_ENDPOINTS.SETTINGS, data);
}
async function previewCoreEmailTemplate(payload) {
  const response = await apiClient.post(
    API_ENDPOINTS.SETTINGS_EMAIL_TEMPLATE_PREVIEW,
    payload
  );
  return unwrapApiPayload(response);
}
async function fetchWordPressPages() {
  return apiClient.get(API_ENDPOINTS.SETTINGS_PAGES);
}
async function postFlushRewriteRules() {
  return apiClient.post(API_ENDPOINTS.SETTINGS_FLUSH_REWRITE_RULES);
}
async function fetchBookingPageShortcodeStatus(pageId) {
  return apiClient.get(API_ENDPOINTS.SETTINGS_CHECK_SHORTCODE(pageId));
}
async function postInsertBookingShortcode(pageId) {
  return apiClient.post(API_ENDPOINTS.SETTINGS_INSERT_SHORTCODE(pageId));
}
async function fetchPaymentGatewayDefinitions() {
  return apiClient.get(API_ENDPOINTS.PAYMENT_GATEWAY_DEFINITIONS);
}
const usePermissions = () => {
  const permissions = reactExports.useMemo(() => {
    var _a;
    return ((_a = window.yatraAdmin) == null ? void 0 : _a.permissions) || [];
  }, []);
  const roles = reactExports.useMemo(() => {
    var _a;
    return ((_a = window.yatraAdmin) == null ? void 0 : _a.roles) || [];
  }, []);
  const capabilities = reactExports.useMemo(() => {
    var _a;
    return ((_a = window.yatraAdmin) == null ? void 0 : _a.capabilities) || {};
  }, []);
  const isPro = reactExports.useMemo(() => {
    var _a;
    return ((_a = window.yatraAdmin) == null ? void 0 : _a.isPro) || false;
  }, []);
  const can = reactExports.useCallback(
    (capability) => {
      var _a;
      if (capabilities[capability] === true) {
        return true;
      }
      const userCaps = (_a = window.yatraAdmin) == null ? void 0 : _a.userCaps;
      if (Array.isArray(userCaps) && userCaps.includes(capability)) {
        return true;
      }
      if (permissions.includes(capability)) {
        return true;
      }
      const adm = window.yatraAdmin;
      if (adm) {
        if (adm.isWpAdmin === true || adm.isWpAdmin === "1" || adm.isWpAdmin === 1) {
          return true;
        }
        if (Array.isArray(adm.roles) && adm.roles.includes("administrator")) {
          return true;
        }
        if (adm.capabilities && adm.capabilities["manage_options"] === true) {
          return true;
        }
      }
      if (capability.startsWith("yatra_pro_") && !isPro) {
        return false;
      }
      return false;
    },
    [capabilities, permissions, isPro]
  );
  const hasRole = (role) => {
    return roles.includes(role);
  };
  return {
    can,
    hasRole,
    isPro,
    permissions,
    roles
  };
};
const ConditionalRender = ({
  children,
  capability,
  role,
  requirePro = false,
  fallback = null,
  className = ""
}) => {
  const { can, hasRole, isPro } = usePermissions();
  let shouldRender = true;
  if (capability && !can(capability)) {
    shouldRender = false;
  }
  if (role && !hasRole(role)) {
    shouldRender = false;
  }
  if (requirePro && !isPro) {
    shouldRender = false;
  }
  if (!shouldRender) {
    return /* @__PURE__ */ jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: fallback });
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className, children });
};
const DEFAULT_MENU_ITEMS = [
  { slug: "dashboard", label: "Dashboard", iconName: "LayoutDashboard" },
  {
    slug: "trips",
    label: "Trips",
    iconName: "MapPin",
    submenu: [
      {
        key: "trips.all",
        parentSlug: "trips",
        tab: "all",
        label: "All Trips",
        iconName: "List"
      },
      {
        key: "trips.activities",
        parentSlug: "trips",
        tab: "activities",
        label: "Activities",
        iconName: "Activity"
      },
      {
        key: "trips.destinations",
        parentSlug: "trips",
        tab: "destinations",
        label: "Destinations",
        iconName: "Route"
      },
      {
        key: "trips.categories",
        parentSlug: "trips",
        tab: "categories",
        label: "Categories",
        iconName: "FolderTree"
      },
      {
        key: "trips.difficulty-levels",
        parentSlug: "trips",
        tab: "difficulty-levels",
        label: "Difficulty Levels",
        iconName: "TrendingUp"
      },
      {
        key: "trips.availability",
        parentSlug: "trips",
        tab: "availability",
        label: "Availability",
        iconName: "CalendarDays"
      },
      {
        key: "trips.attributes",
        parentSlug: "trips",
        tab: "attributes",
        label: "Attributes",
        iconName: "Tag"
      },
      {
        key: "trips.additional-services",
        parentSlug: "trips",
        tab: "additional-services",
        label: "Additional Services",
        iconName: "Package"
      },
      {
        key: "trips.trip-consent",
        parentSlug: "trips",
        tab: "trip-consent",
        label: "Trip Consent",
        iconName: "FileSignature"
      }
    ]
  },
  {
    slug: "traveler-categories",
    label: "Traveler Categories",
    iconName: "Users"
  },
  {
    slug: "itinerary",
    label: "Itinerary",
    iconName: "Route",
    submenu: [
      {
        key: "itinerary.item-types",
        parentSlug: "itinerary",
        tab: "item-types",
        label: "Item Types",
        iconName: "Tag"
      },
      {
        key: "itinerary.items",
        parentSlug: "itinerary",
        tab: "items",
        label: "Items",
        iconName: "Route"
      },
      {
        key: "itinerary.itinerary",
        parentSlug: "itinerary",
        tab: "itinerary",
        label: "Itinerary",
        iconName: "FileText"
      }
    ]
  },
  { slug: "departures", label: "Departures", iconName: "Calendar" },
  { slug: "discounts", label: "Discounts", iconName: "BadgePercent" },
  { slug: "payments", label: "Payments", iconName: "CreditCard" },
  { slug: "bookings", label: "Bookings", iconName: "Calendar" },
  { slug: "customers", label: "Customers", iconName: "UserCircle" },
  { slug: "travelers", label: "Travelers", iconName: "Plane" },
  { slug: "enquiries", label: "Enquiries", iconName: "MessageSquare" },
  { slug: "reviews", label: "Reviews", iconName: "Star" },
  { slug: "reports", label: "Reports", iconName: "BarChart3" },
  { slug: "email-automation", label: "Email", iconName: "Mail" },
  {
    slug: "abandoned-recovery",
    label: "Abandoned Recovery",
    iconName: "RotateCcw"
  },
  { slug: "dynamic-pricing", label: "Dynamic Pricing", iconName: "TrendingUp" },
  { slug: "modules", label: "Modules", iconName: "Puzzle" },
  { slug: "white-label", label: "White Label", iconName: "Crown" },
  { slug: "ai-assistant", label: "AI Assistant", iconName: "Sparkles" },
  { slug: "whatsapp", label: "WhatsApp", iconName: "MessageCircle" },
  { slug: "channel-manager", label: "Channel Manager", iconName: "Network" },
  { slug: "webhooks", label: "Webhooks", iconName: "Webhook" },
  { slug: "team", label: "Team & Access", iconName: "Users" },
  { slug: "license", label: "License", iconName: "Key" },
  { slug: "settings", label: "Settings", iconName: "Settings" }
];
function readMenuOrder() {
  var _a;
  const raw = (_a = window.yatraAdmin) == null ? void 0 : _a.brandMenuOrder;
  if (Array.isArray(raw)) {
    return { "": raw.filter((s2) => typeof s2 === "string") };
  }
  if (raw && typeof raw === "object") {
    const out = {};
    for (const [key2, list] of Object.entries(raw)) {
      if (typeof key2 === "string" && Array.isArray(list)) {
        out[key2] = list.filter((s2) => typeof s2 === "string");
      }
    }
    return out;
  }
  return {};
}
function readUiChrome() {
  var _a;
  const raw = (_a = window.yatraAdmin) == null ? void 0 : _a.brandUiChrome;
  if (!raw || typeof raw !== "object") return {};
  return raw;
}
function readMenuOverrides() {
  var _a;
  const raw = (_a = window.yatraAdmin) == null ? void 0 : _a.brandMenuOverrides;
  if (!raw || typeof raw !== "object") return {};
  return raw;
}
const ICON_MAP = {
  LayoutDashboard,
  MapPin,
  Calendar: Calendar$1,
  CalendarDays,
  Star,
  BarChart3,
  Settings: Settings$1,
  Wrench,
  FileText,
  CreditCard,
  Package,
  UserCircle: CircleUser,
  Users,
  FolderTree,
  Tag,
  TrendingUp,
  List,
  Activity,
  Crown,
  Mail,
  Key,
  FileSignature,
  Route,
  BadgePercent,
  Plane,
  MessageSquare,
  Puzzle,
  RotateCcw,
  Sparkles,
  MessageCircle,
  Network,
  Tools: Wrench
};
const accessibility = {
  label: "Accessibility",
  category: "general",
  svg: '<svg class="lucide lucide-accessibility" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <circle cx="16" cy="4" r="1" /> <path d="m18 19 1-7-6 1" /> <path d="m5 8 3-3 5.5 3-2.36 3.5" /> <path d="M4.24 14.5a5 5 0 0 0 6.88 6" /> <path d="M13.76 17.5a5 5 0 0 0-6.88-6" /> </svg>'
};
const activity = {
  label: "Activity",
  category: "activity",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6V4m0 2a2 2 0 100 4m0-4a2 2 0 110 4m-6 8a2 2 0 100-4m0 4a2 2 0 100 4m0-4v2m0-6V4m6 6v10m6-2a2 2 0 100-4m0 4a2 2 0 100 4m0-4v2m0-6V4"/></svg>'
};
const anchor = {
  label: "Anchor",
  category: "activity",
  svg: '<svg class="lucide lucide-anchor" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M12 22V8" /> <path d="M5 12H2a10 10 0 0 0 20 0h-3" /> <circle cx="12" cy="5" r="3" /> </svg>'
};
const archive = {
  label: "Archive",
  category: "media",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 7h18m-9 4v6m-3-3h6"/></svg>'
};
const award = {
  label: "Award",
  category: "general",
  svg: '<svg class="lucide lucide-award" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="m15.477 12.89 1.515 8.526a.5.5 0 0 1-.81.47l-3.58-2.687a1 1 0 0 0-1.197 0l-3.586 2.686a.5.5 0 0 1-.81-.469l1.514-8.526" /> <circle cx="12" cy="8" r="6" /> </svg>'
};
const backpack = {
  label: "Backpack",
  category: "general",
  svg: '<svg class="lucide lucide-backpack" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M4 10a4 4 0 0 1 4-4h8a4 4 0 0 1 4 4v10a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2z" /> <path d="M8 10h8" /> <path d="M8 18h8" /> <path d="M8 22v-6a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v6" /> <path d="M9 6V4a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v2" /> </svg>'
};
const banknote = {
  label: "Banknote",
  category: "general",
  svg: '<svg class="lucide lucide-banknote" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <rect width="20" height="12" x="2" y="6" rx="2" /> <circle cx="12" cy="12" r="2" /> <path d="M6 12h.01M18 12h.01" /> </svg>'
};
const beach = {
  label: "Beach",
  category: "activity",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path d="M22 12a10 10 0 0 0-20 0"/><path d="M12 12V2"/><path d="M12 12 8 22"/><path d="M2 18s2-1 3 0 2 1 3 0 2-1 3 0 2 1 3 0 2-1 3 0 2 1 3 0"/></svg>'
};
const bed = {
  label: "Bed",
  category: "accommodation",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 12h18m-9-8v8m-6 4h12a2 2 0 002-2v-4H2v4a2 2 0 002 2z"/></svg>'
};
const bell = {
  label: "Bell",
  category: "general",
  svg: '<svg class="lucide lucide-bell" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M10.268 21a2 2 0 0 0 3.464 0" /> <path d="M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326" /> </svg>'
};
const bike = {
  label: "Bike",
  category: "activity",
  svg: '<svg class="lucide lucide-bike" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <circle cx="18.5" cy="17.5" r="3.5" /> <circle cx="5.5" cy="17.5" r="3.5" /> <circle cx="15" cy="5" r="1" /> <path d="M12 17.5V14l-3-3 4-3 2 3h2" /> </svg>'
};
const binoculars = {
  label: "Binoculars",
  category: "activity",
  svg: '<svg class="lucide lucide-binoculars" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M10 10h4" /> <path d="M19 7V4a1 1 0 0 0-1-1h-2a1 1 0 0 0-1 1v3" /> <path d="M20 21a2 2 0 0 0 2-2v-3.851c0-1.39-2-2.962-2-4.829V8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v11a2 2 0 0 0 2 2z" /> <path d="M 22 16 L 2 16" /> <path d="M4 21a2 2 0 0 1-2-2v-3.851c0-1.39 2-2.962 2-4.829V8a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v11a2 2 0 0 1-2 2z" /> <path d="M9 7V4a1 1 0 0 0-1-1H6a1 1 0 0 0-1 1v3" /> </svg>'
};
const bluetooth = {
  label: "Bluetooth",
  category: "general",
  svg: '<svg class="lucide lucide-bluetooth" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="m7 7 10 10-5 5V2l5 5L7 17" /> </svg>'
};
const book = {
  label: "Education",
  category: "general",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2 3h6a4 4 0 014 4v14a3 3 0 00-3-3H2V3zM22 3h-6a4 4 0 00-4 4v14a3 3 0 013-3h7V3z"/></svg>'
};
const bookmark = {
  label: "Bookmark",
  category: "general",
  svg: '<svg class="lucide lucide-bookmark" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z" /> </svg>'
};
const briefcase = {
  label: "Briefcase",
  category: "general",
  svg: '<svg class="lucide lucide-briefcase" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M16 20V4a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16" /> <rect width="20" height="14" x="2" y="6" rx="2" /> </svg>'
};
const brush = {
  label: "Brush",
  category: "general",
  svg: '<svg class="lucide lucide-brush" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="m9.06 11.9 8.07-8.06a2.85 2.85 0 1 1 4.03 4.03l-8.06 8.08" /> <path d="M7.07 14.94c-1.66 0-3 1.35-3 3.02 0 1.33-2.5 1.52-2 2.02 1.08 1.1 2.49 2.02 4 2.02 2.2 0 4-1.8 4-4.04a3.01 3.01 0 0 0-3-3.02z" /> </svg>'
};
const building = {
  label: "Building",
  category: "accommodation",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"/></svg>'
};
const bus = {
  label: "Bus",
  category: "transport",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 6v6h8V6M6 21h12a2 2 0 002-2v-2H4v2a2 2 0 002 2zM6 6a2 2 0 012-2h8a2 2 0 012 2v6H6V6zM8 17h.01M16 17h.01"/></svg>'
};
const cactus = {
  label: "Cactus",
  category: "activity",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path d="M10 21h4"/><path d="M12 21V8"/><path d="M9 8a3 3 0 0 1 6 0v6"/><path d="M9 12H5a2 2 0 0 1 0-4h1v5"/><path d="M15 14h4a2 2 0 0 0 0-4h-1v6"/></svg>'
};
const cake = {
  label: "Cake",
  category: "food",
  svg: '<svg class="lucide lucide-cake" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M20 21v-8a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8" /> <path d="M4 16s.5-1 2-1 2.5 2 4 2 2.5-2 4-2 2.5 2 4 2 2-1 2-1" /> <path d="M2 21h20" /> <path d="M7 8v3" /> <path d="M12 8v3" /> <path d="M17 8v3" /> <path d="M7 4h.01" /> <path d="M12 4h.01" /> <path d="M17 4h.01" /> </svg>'
};
const calendar$1 = {
  label: "Calendar",
  category: "travel",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"/></svg>'
};
const camera = {
  label: "Photography",
  category: "activity",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V9z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 13a3 3 0 11-6 0 3 3 0 016 0z"/></svg>'
};
const campfire = {
  label: "Campfire",
  category: "activity",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path d="M12 3c-3 4-3 7 0 9 3-2 3-5 0-9z"/><path d="M5 21h14"/><path d="M4 21l16-5"/><path d="M20 21 4 16"/></svg>'
};
const car = {
  label: "Car",
  category: "transport",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 17h2c.6 0 1-.4 1-1v-3c0-.9-.7-1.7-1.5-1.9L18 10c-.1-.1-.4-.6-.7-1.3C16.8 7.3 15.4 6 13.5 6h-3C8.6 6 7.2 7.3 6.7 8.7c-.3.7-.6 1.2-.7 1.3L3.5 11C2.7 11.3 2 12.1 2 13v3c0 .6.4 1 1 1h2m0 0a3 3 0 106 0m6 0a3 3 0 106 0M7 17h10"/></svg>'
};
const caravan = {
  label: "Caravan",
  category: "transport",
  svg: '<svg class="lucide lucide-caravan" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M18 19V9a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v8a2 2 0 0 0 2 2h2" /> <path d="M2 9h3a1 1 0 0 1 1 1v2a1 1 0 0 1-1 1H2" /> <path d="M22 17v1a1 1 0 0 1-1 1H10v-9a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1v9" /> <circle cx="8" cy="19" r="2" /> </svg>'
};
const castle = {
  label: "Castle",
  category: "accommodation",
  svg: '<svg class="lucide lucide-castle" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M22 20v-9H2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2Z" /> <path d="M18 11V4H6v7" /> <path d="M15 22v-4a3 3 0 0 0-3-3a3 3 0 0 0-3 3v4" /> <path d="M22 11V9" /> <path d="M2 11V9" /> <path d="M6 4V2" /> <path d="M18 4V2" /> <path d="M10 4V2" /> <path d="M14 4V2" /> </svg>'
};
const check = {
  label: "Check",
  category: "general",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 6L9 17l-5-5"/></svg>'
};
const church = {
  label: "Church",
  category: "accommodation",
  svg: '<svg class="lucide lucide-church" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M10 9h4" /> <path d="M12 7v5" /> <path d="M14 22v-4a2 2 0 0 0-4 0v4" /> <path d="M18 22V5.618a1 1 0 0 0-.553-.894l-4.553-2.277a2 2 0 0 0-1.788 0L6.553 4.724A1 1 0 0 0 6 5.618V22" /> <path d="m18 7 3.447 1.724a1 1 0 0 1 .553.894V20a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9.618a1 1 0 0 1 .553-.894L6 7" /> </svg>'
};
const climbing = {
  label: "Climbing",
  category: "activity",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><circle cx="9" cy="4" r="2"/><path d="M9 6v6l-3 3v6"/><path d="M9 12l4 1 2 5"/><path d="M15 8l4-2"/></svg>'
};
const clock = {
  label: "Time",
  category: "travel",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>'
};
const cloud = {
  label: "Cloud",
  category: "general",
  svg: '<svg class="lucide lucide-cloud" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z" /> </svg>'
};
const coffee = {
  label: "Coffee",
  category: "food",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M18 8h1a4 4 0 010 8h-1M2 8h16v9a4 4 0 01-4 4H6a4 4 0 01-4-4V8zM6 1v3M10 1v3M14 1v3"/></svg>'
};
const compass = {
  label: "Compass",
  category: "activity",
  svg: '<svg class="lucide lucide-compass" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="m16.24 7.76-1.804 5.411a2 2 0 0 1-1.265 1.265L7.76 16.24l1.804-5.411a2 2 0 0 1 1.265-1.265z" /> <circle cx="12" cy="12" r="10" /> </svg>'
};
const construction = {
  label: "Construction",
  category: "general",
  svg: '<svg class="lucide lucide-construction" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <rect x="2" y="6" width="20" height="8" rx="1" /> <path d="M17 14v7" /> <path d="M7 14v7" /> <path d="M17 3v3" /> <path d="M7 3v3" /> <path d="M10 14 2.3 6.3" /> <path d="m14 6 7.7 7.7" /> <path d="m8 6 8 8" /> </svg>'
};
const cookie = {
  label: "Cookie",
  category: "food",
  svg: '<svg class="lucide lucide-cookie" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M12 2a10 10 0 1 0 10 10 4 4 0 0 1-5-5 4 4 0 0 1-5-5" /> <path d="M8.5 8.5v.01" /> <path d="M16 15.5v.01" /> <path d="M12 12v.01" /> <path d="M11 17v.01" /> <path d="M7 14v.01" /> </svg>'
};
const crown = {
  label: "Crown",
  category: "general",
  svg: '<svg class="lucide lucide-crown" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M11.562 3.266a.5.5 0 0 1 .876 0L15.39 8.87a1 1 0 0 0 1.516.294L21.183 5.5a.5.5 0 0 1 .798.519l-2.834 10.246a1 1 0 0 1-.956.734H5.81a1 1 0 0 1-.957-.734L2.02 6.02a.5.5 0 0 1 .798-.519l4.276 3.664a1 1 0 0 0 1.516-.294z" /> <path d="M5 21h14" /> </svg>'
};
const diamond = {
  label: "Diamond",
  category: "general",
  svg: '<svg class="lucide lucide-diamond" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M2.7 10.3a2.41 2.41 0 0 0 0 3.41l7.59 7.59a2.41 2.41 0 0 0 3.41 0l7.59-7.59a2.41 2.41 0 0 0 0-3.41l-7.59-7.59a2.41 2.41 0 0 0-3.41 0Z" /> </svg>'
};
const download = {
  label: "Download",
  category: "media",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4m4-5l5 5 5-5m-5 5V3"/></svg>'
};
const droplet = {
  label: "Droplet",
  category: "general",
  svg: '<svg class="lucide lucide-droplet" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M12 22a7 7 0 0 0 7-7c0-2-1-3.9-3-5.5s-3.5-4-4-6.5c-.5 2.5-2 4.9-4 6.5C6 11.1 5 13 5 15a7 7 0 0 0 7 7z" /> </svg>'
};
const drum = {
  label: "Drum",
  category: "general",
  svg: '<svg class="lucide lucide-drum" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="m2 2 8 8" /> <path d="m22 2-8 8" /> <ellipse cx="12" cy="9" rx="10" ry="5" /> <path d="M7 13.4v7.9" /> <path d="M12 14v8" /> <path d="M17 13.4v7.9" /> <path d="M2 9v8a10 5 0 0 0 20 0V9" /> </svg>'
};
const dumbbell = {
  label: "Dumbbell",
  category: "activity",
  svg: '<svg class="lucide lucide-dumbbell" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M14.4 14.4 9.6 9.6" /> <path d="M18.657 21.485a2 2 0 1 1-2.829-2.828l-1.767 1.768a2 2 0 1 1-2.829-2.829l6.364-6.364a2 2 0 1 1 2.829 2.829l-1.768 1.767a2 2 0 1 1 2.828 2.829z" /> <path d="m21.5 21.5-1.4-1.4" /> <path d="M3.9 3.9 2.5 2.5" /> <path d="M6.404 12.768a2 2 0 1 1-2.829-2.829l1.768-1.767a2 2 0 1 1-2.828-2.829l2.828-2.828a2 2 0 1 1 2.829 2.828l1.767-1.768a2 2 0 1 1 2.829 2.829z" /> </svg>'
};
const earth = {
  label: "Earth",
  category: "travel",
  svg: '<svg class="lucide lucide-earth" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M21.54 15H17a2 2 0 0 0-2 2v4.54" /> <path d="M7 3.34V5a3 3 0 0 0 3 3a2 2 0 0 1 2 2c0 1.1.9 2 2 2a2 2 0 0 0 2-2c0-1.1.9-2 2-2h3.17" /> <path d="M11 21.95V18a2 2 0 0 0-2-2a2 2 0 0 1-2-2v-1a2 2 0 0 0-2-2H2.05" /> <circle cx="12" cy="12" r="10" /> </svg>'
};
const eye = {
  label: "Sightseeing",
  category: "activity",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/></svg>'
};
const fan = {
  label: "Fan",
  category: "general",
  svg: '<svg class="lucide lucide-fan" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M10.827 16.379a6.082 6.082 0 0 1-8.618-7.002l5.412 1.45a6.082 6.082 0 0 1 7.002-8.618l-1.45 5.412a6.082 6.082 0 0 1 8.618 7.002l-5.412-1.45a6.082 6.082 0 0 1-7.002 8.618l1.45-5.412Z" /> <path d="M12 12v.01" /> </svg>'
};
const feather = {
  label: "Feather",
  category: "general",
  svg: '<svg class="lucide lucide-feather" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M12.67 19a2 2 0 0 0 1.416-.588l6.154-6.172a6 6 0 0 0-8.49-8.49L5.586 9.914A2 2 0 0 0 5 11.328V18a1 1 0 0 0 1 1z" /> <path d="M16 8 2 22" /> <path d="M17.5 15H9" /> </svg>'
};
const film = {
  label: "Film",
  category: "general",
  svg: '<svg class="lucide lucide-film" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <rect width="18" height="18" x="3" y="3" rx="2" /> <path d="M7 3v18" /> <path d="M3 7.5h4" /> <path d="M3 12h18" /> <path d="M3 16.5h4" /> <path d="M17 3v18" /> <path d="M17 7.5h4" /> <path d="M17 16.5h4" /> </svg>'
};
const filter = {
  label: "Filter",
  category: "general",
  svg: '<svg class="lucide lucide-filter" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <polygon points="22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3" /> </svg>'
};
const fish = {
  label: "Fish",
  category: "activity",
  svg: '<svg class="lucide lucide-fish" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M6.5 12c.94-3.46 4.94-6 8.5-6 3.56 0 6.06 2.54 7 6-.94 3.47-3.44 6-7 6s-7.56-2.53-8.5-6Z" /> <path d="M18 12v.5" /> <path d="M16 17.93a9.77 9.77 0 0 1 0-11.86" /> <path d="M7 10.67C7 8 5.58 5.97 2.73 5.5c-1 1.5-1 5 .23 6.5-1.24 1.5-1.24 5-.23 6.5C5.58 18.03 7 16 7 13.33" /> <path d="M10.46 7.26C10.2 5.88 9.17 4.24 8 3h5.8a2 2 0 0 1 1.98 1.67l.23 1.4" /> <path d="m16.01 17.93-.23 1.4A2 2 0 0 1 13.8 21H9.5a5.96 5.96 0 0 0 1.49-3.98" /> </svg>'
};
const flag = {
  label: "Flag",
  category: "activity",
  svg: '<svg class="lucide lucide-flag" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z" /> <line x1="4" x2="4" y1="22" y2="15" /> </svg>'
};
const flame = {
  label: "Adventure",
  category: "activity",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 2c1.5 0 3 1.2 3 3.5 0 2-1 3.5-3 3.5s-3-1.5-3-3.5c0-2.3 1.5-3.5 3-3.5z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9c-2.5 0-4.5 2-4.5 4.5S9.5 18 12 18s4.5-2 4.5-4.5S14.5 9 12 9z"/></svg>'
};
const footprints = {
  label: "Hiking",
  category: "activity",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 2C8.686 2 6 4.686 6 8c0 5.25 6 14 6 14s6-8.75 6-14c0-3.314-2.686-6-6-6z"/><circle cx="12" cy="8" r="2"/></svg>'
};
const fuel = {
  label: "Fuel",
  category: "transport",
  svg: '<svg class="lucide lucide-fuel" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <line x1="3" x2="15" y1="22" y2="22" /> <line x1="4" x2="14" y1="9" y2="9" /> <path d="M14 22V4a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v18" /> <path d="M14 13h2a2 2 0 0 1 2 2v2a2 2 0 0 0 2 2a2 2 0 0 0 2-2V9.83a2 2 0 0 0-.59-1.42L18 5" /> </svg>'
};
const gamepad = {
  label: "Entertainment",
  category: "general",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><line x1="6" y1="11" x2="10" y2="11"/><line x1="8" y1="9" x2="8" y2="13"/><line x1="15" y1="12" x2="15.01" y2="12"/><line x1="18" y1="10" x2="18.01" y2="10"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17.32 5H6.68a4 4 0 00-3.978 3.59c-.006.052-.01.101-.017.152C2.604 9.416 2 14.456 2 16a3 3 0 003 3c1 0 1.5-.5 2.5-1l1.5-1.5c.667-.667 1.5-1 2.5-1s1.833.333 2.5 1L15.5 18c1 .5 1.5 1 2.5 1a3 3 0 003-3c0-1.544-.604-6.584-.685-7.258-.007-.051-.011-.1-.017-.152A4 4 0 0017.32 5z"/></svg>'
};
const gift = {
  label: "Gift",
  category: "general",
  svg: '<svg class="lucide lucide-gift" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <rect x="3" y="8" width="18" height="4" rx="1" /> <path d="M12 8v13" /> <path d="M19 12v7a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2v-7" /> <path d="M7.5 8a2.5 2.5 0 0 1 0-5A4.8 8 0 0 1 12 8a4.8 8 0 0 1 4.5-5 2.5 2.5 0 0 1 0 5" /> </svg>'
};
const globe = {
  label: "Globe",
  category: "media",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9a9 9 0 01-9-9m9 9c1.657 0 3-4.03 3-9s-1.343-9-3-9m0 18c-1.657 0-3-4.03-3-9s1.343-9 3-9m-9 9a9 9 0 019-9"/></svg>'
};
const hammer = {
  label: "Hammer",
  category: "general",
  svg: '<svg class="lucide lucide-hammer" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="m15 12-8.373 8.373a1 1 0 1 1-3-3L12 9" /> <path d="m18 15 4-4" /> <path d="m21.5 11.5-1.914-1.914A2 2 0 0 1 19 8.172V7l-2.26-2.26a6 6 0 0 0-4.202-1.756L9 2.96l.92.82A6.18 6.18 0 0 1 12 8.4V10l2 2h1.172a2 2 0 0 1 1.414.586L18.5 14.5" /> </svg>'
};
const handshake = {
  label: "Handshake",
  category: "general",
  svg: '<svg class="lucide lucide-handshake" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="m11 17 2 2a1 1 0 1 0 3-3" /> <path d="m14 14 2.5 2.5a1 1 0 1 0 3-3l-3.88-3.88a3 3 0 0 0-4.24 0l-.88.88a1 1 0 1 1-3-3l2.81-2.81a5.79 5.79 0 0 1 7.06-.87l.47.28a2 2 0 0 0 1.42.25L21 4" /> <path d="m21 3 1 11h-2" /> <path d="M3 3 2 14l6.5 6.5a1 1 0 1 0 3-3" /> <path d="M3 4h8" /> </svg>'
};
const headphones = {
  label: "Headphones",
  category: "general",
  svg: '<svg class="lucide lucide-headphones" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M3 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a9 9 0 0 1 18 0v7a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3" /> </svg>'
};
const heart = {
  label: "Wellness",
  category: "general",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"/></svg>'
};
const helicopter = {
  label: "Helicopter",
  category: "activity",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path d="M10.5 2v4"/><path d="M2 6h19l-3 4"/><path d="M14 6a5 5 0 0 1 5 5h-9V6Z"/><path d="M13 11H4l3-4"/><path d="M6 12v3"/><path d="M16 12v4a2 2 0 0 1-2 2H9"/></svg>'
};
const helmet = {
  label: "Helmet",
  category: "activity",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path d="M4 14a8 8 0 0 1 16 0v4H4v-4Z"/><path d="M2 18h20"/><path d="M9 9V6"/><path d="M15 9V6"/></svg>'
};
const hexagon = {
  label: "Hexagon",
  category: "general",
  svg: '<svg class="lucide lucide-hexagon" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z" /> </svg>'
};
const hotel = {
  label: "Hotel",
  category: "accommodation",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"/></svg>'
};
const hourglass = {
  label: "Hourglass",
  category: "general",
  svg: '<svg class="lucide lucide-hourglass" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M5 22h14" /> <path d="M5 2h14" /> <path d="M17 22v-4.172a2 2 0 0 0-.586-1.414L12 12l-4.414 4.414A2 2 0 0 0 7 17.828V22" /> <path d="M7 2v4.172a2 2 0 0 0 .586 1.414L12 12l4.414-4.414A2 2 0 0 0 17 6.172V2" /> </svg>'
};
const house = {
  label: "House",
  category: "accommodation",
  svg: '<svg class="lucide lucide-house" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8" /> <path d="M3 10a2 2 0 0 1 .709-1.528l7-5.999a2 2 0 0 1 2.582 0l7 5.999A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" /> </svg>'
};
const image = {
  label: "Image",
  category: "general",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><rect width="18" height="18" x="3" y="3" rx="2" ry="2"/><circle cx="9" cy="9" r="2"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 15l-3.086-3.086a2 2 0 00-2.828 0L6 21"/></svg>'
};
const info = {
  label: "Info",
  category: "general",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>'
};
const island = {
  label: "Island",
  category: "general",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path d="M2 21c2-1 4-1 5 0s3 1 5 0 3-1 5 0 4 1 5 0"/><path d="M9 18h6c0-3-2-5-3-5s-3 2-3 5z"/><path d="M12 13V8"/><path d="M9 8c1-2 3-3 6-2"/></svg>'
};
const kayak = {
  label: "Kayak",
  category: "activity",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path d="M2 16c4-1 8-1 10-1s6 0 10 1"/><path d="M2 16c4 4 8 5 10 5s6-1 10-5"/><path d="M7 8l3 3"/><path d="M17 16l-3-3"/></svg>'
};
const key = {
  label: "Key",
  category: "general",
  svg: '<svg class="lucide lucide-key" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4" /> <path d="m21 2-9.6 9.6" /> <circle cx="7.5" cy="15.5" r="5.5" /> </svg>'
};
const lake = {
  label: "Lake",
  category: "general",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path d="M2 21h20"/><path d="M5 17l5-8 3 5 4-6 5 9"/><path d="M3 14s2 1 4 1 3-1 5-1 3 1 5 1 4-1 4-1"/></svg>'
};
const landmark = {
  label: "Landmark",
  category: "general",
  svg: '<svg class="lucide lucide-landmark" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <line x1="3" x2="21" y1="22" y2="22" /> <line x1="6" x2="6" y1="18" y2="11" /> <line x1="10" x2="10" y1="18" y2="11" /> <line x1="14" x2="14" y1="18" y2="11" /> <line x1="18" x2="18" y1="18" y2="11" /> <polygon points="12 2 20 7 4 7" /> </svg>'
};
const languages = {
  label: "Languages",
  category: "travel",
  svg: '<svg class="lucide lucide-languages" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="m5 8 6 6" /> <path d="m4 14 6-6 2-3" /> <path d="M2 5h12" /> <path d="M7 2h1" /> <path d="m22 22-5-10-5 10" /> <path d="M14 18h6" /> </svg>'
};
const link = {
  label: "Link",
  category: "general",
  svg: '<svg class="lucide lucide-link" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71" /> <path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71" /> </svg>'
};
const lock = {
  label: "Lock",
  category: "media",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><rect x="3" y="11" width="18" height="10" rx="2" ry="2"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 11V7a5 5 0 0110 0v4"/></svg>'
};
const luggage = {
  label: "Luggage",
  category: "transport",
  svg: '<svg class="lucide lucide-luggage" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M6 20a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2" /> <path d="M8 18V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v14" /> <path d="M10 20h4" /> <circle cx="16" cy="20" r="2" /> <circle cx="8" cy="20" r="2" /> </svg>'
};
const mailbox = {
  label: "Mailbox",
  category: "general",
  svg: '<svg class="lucide lucide-mailbox" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M22 17a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9.5C2 7 4 5 6.5 5H18c2.2 0 4 1.8 4 4v8Z" /> <polyline points="15,9 18,9 18,11" /> <path d="M6.5 5C9 5 11 7 11 9.5V17a2 2 0 0 1-2 2" /> <line x1="6" x2="7" y1="10" y2="10" /> </svg>'
};
const map$4 = {
  label: "Map",
  category: "activity",
  svg: '<svg class="lucide lucide-map" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M14.106 5.553a2 2 0 0 0 1.788 0l3.659-1.83A1 1 0 0 1 21 4.619v12.764a1 1 0 0 1-.553.894l-4.553 2.277a2 2 0 0 1-1.788 0l-4.212-2.106a2 2 0 0 0-1.788 0l-3.659 1.83A1 1 0 0 1 3 19.381V6.618a1 1 0 0 1 .553-.894l4.553-2.277a2 2 0 0 1 1.788 0z" /> <path d="M15 5.764v15" /> <path d="M9 3.236v15" /> </svg>'
};
const martini = {
  label: "Martini",
  category: "food",
  svg: '<svg class="lucide lucide-martini" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M8 22h8" /> <path d="M12 11v11" /> <path d="m19 3-7 8-7-8Z" /> </svg>'
};
const medal = {
  label: "Medal",
  category: "activity",
  svg: '<svg class="lucide lucide-medal" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M7.21 15 2.66 7.14a2 2 0 0 1 .13-2.2L4.4 2.8A2 2 0 0 1 6 2h12a2 2 0 0 1 1.6.8l1.6 2.14a2 2 0 0 1 .14 2.2L16.79 15" /> <path d="M11 12 5.12 2.2" /> <path d="m13 12 5.88-9.8" /> <path d="M8 7h8" /> <circle cx="12" cy="17" r="5" /> <path d="M12 18v-2h-.5" /> </svg>'
};
const mic = {
  label: "Mic",
  category: "general",
  svg: '<svg class="lucide lucide-mic" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z" /> <path d="M19 10v2a7 7 0 0 1-14 0v-2" /> <line x1="12" x2="12" y1="19" y2="22" /> </svg>'
};
const milestone = {
  label: "Milestone",
  category: "general",
  svg: '<svg class="lucide lucide-milestone" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M12 13v8" /> <path d="M12 3v3" /> <path d="M4 6a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1h13a2 2 0 0 0 1.152-.365l3.424-2.317a1 1 0 0 0 0-1.635l-3.424-2.318A2 2 0 0 0 17 6z" /> </svg>'
};
const moon = {
  label: "Rest",
  category: "general",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12.79A9 9 0 1111.21 3 7 7 0 0021 12.79z"/></svg>'
};
const mountain = {
  label: "Mountain",
  category: "activity",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 20l4.5-9 3.5 7 4-8 4 10H4z"/></svg>'
};
const museum = {
  label: "Museum",
  category: "general",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path d="M3 21h18"/><path d="M3 10h18"/><path d="M5 10v11"/><path d="M9 10v11"/><path d="M15 10v11"/><path d="M19 10v11"/><path d="M3 10l9-7 9 7"/></svg>'
};
const music = {
  label: "Music",
  category: "general",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 18V5l12-2v13M9 18a3 3 0 100-6 3 3 0 000 6zm12-2a3 3 0 100-6 3 3 0 000 6z"/></svg>'
};
const navigation = {
  label: "Navigation",
  category: "transport",
  svg: '<svg class="lucide lucide-navigation" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <polygon points="3 11 22 2 13 21 11 13 3 11" /> </svg>'
};
const newspaper = {
  label: "Newspaper",
  category: "general",
  svg: '<svg class="lucide lucide-newspaper" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M4 22h16a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2H8a2 2 0 0 0-2 2v16a2 2 0 0 1-2 2Zm0 0a2 2 0 0 1-2-2v-9c0-1.1.9-2 2-2h2" /> <path d="M18 14h-8" /> <path d="M15 18h-5" /> <path d="M10 6h8v4h-8V6Z" /> </svg>'
};
const octagon = {
  label: "Octagon",
  category: "general",
  svg: '<svg class="lucide lucide-octagon" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M2.586 16.726A2 2 0 0 1 2 15.312V8.688a2 2 0 0 1 .586-1.414l4.688-4.688A2 2 0 0 1 8.688 2h6.624a2 2 0 0 1 1.414.586l4.688 4.688A2 2 0 0 1 22 8.688v6.624a2 2 0 0 1-.586 1.414l-4.688 4.688a2 2 0 0 1-1.414.586H8.688a2 2 0 0 1-1.414-.586z" /> </svg>'
};
const palette = {
  label: "Palette",
  category: "general",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><circle cx="13.5" cy="6.5" r=".5"/><circle cx="17.5" cy="10.5" r=".5"/><circle cx="8.5" cy="7.5" r=".5"/><circle cx="6.5" cy="12.5" r=".5"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.926 0 1.648-.746 1.648-1.688 0-.437-.18-.835-.437-1.125-.29-.289-.438-.652-.438-1.125a1.64 1.64 0 011.668-1.668h1.996c3.051 0 5.555-2.503 5.555-5.554C21.965 6.012 17.461 2 12 2z"/></svg>'
};
const passport = {
  label: "Passport",
  category: "general",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><rect width="14" height="18" x="5" y="3" rx="2"/><circle cx="12" cy="10" r="3"/><path d="M9 17h6"/><path d="M9 14h6"/></svg>'
};
const percent = {
  label: "Percent",
  category: "general",
  svg: '<svg class="lucide lucide-percent" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <line x1="19" x2="5" y1="5" y2="19" /> <circle cx="6.5" cy="6.5" r="2.5" /> <circle cx="17.5" cy="17.5" r="2.5" /> </svg>'
};
const phone = {
  label: "Phone",
  category: "general",
  svg: '<svg class="lucide lucide-phone" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z" /> </svg>'
};
const pill = {
  label: "Pill",
  category: "general",
  svg: '<svg class="lucide lucide-pill" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="m10.5 20.5 10-10a4.95 4.95 0 1 0-7-7l-10 10a4.95 4.95 0 1 0 7 7Z" /> <path d="m8.5 8.5 7 7" /> </svg>'
};
const pin = {
  label: "Pin",
  category: "general",
  svg: '<svg class="lucide lucide-pin" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M12 17v5" /> <path d="M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z" /> </svg>'
};
const pizza = {
  label: "Pizza",
  category: "food",
  svg: '<svg class="lucide lucide-pizza" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="m12 14-1 1" /> <path d="m13.75 18.25-1.25 1.42" /> <path d="M17.775 5.654a15.68 15.68 0 0 0-12.121 12.12" /> <path d="M18.8 9.3a1 1 0 0 0 2.1 7.7" /> <path d="M21.964 20.732a1 1 0 0 1-1.232 1.232l-18-5a1 1 0 0 1-.695-1.232A19.68 19.68 0 0 1 15.732 2.037a1 1 0 0 1 1.232.695z" /> </svg>'
};
const plane = {
  label: "Plane",
  category: "transport",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 16v-2l-8-5V3.5a1.5 1.5 0 00-3 0V9l-8 5v2l8-2.5V19l-2 1.5V22l3.5-1 3.5 1v-1.5L13 19v-5.5l8 2.5z"/></svg>'
};
const play = {
  label: "Play",
  category: "media",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>'
};
const plug = {
  label: "Plug",
  category: "general",
  svg: '<svg class="lucide lucide-plug" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M12 22v-5" /> <path d="M9 8V2" /> <path d="M15 8V2" /> <path d="M18 8v5a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V8Z" /> </svg>'
};
const plus = {
  label: "Plus",
  category: "general",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 5v14M5 12h14"/></svg>'
};
const pool = {
  label: "Pool",
  category: "general",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path d="M2 20c2 0 2-2 4-2s2 2 4 2 2-2 4-2 2 2 4 2 2-2 4-2"/><path d="M2 15c2 0 2-2 4-2s2 2 4 2 2-2 4-2 2 2 4 2 2-2 4-2"/><path d="M6 10V3"/><path d="M18 10V3"/></svg>'
};
const power = {
  label: "Power",
  category: "general",
  svg: '<svg class="lucide lucide-power" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M12 2v10" /> <path d="M18.4 6.6a9 9 0 1 1-12.77.04" /> </svg>'
};
const pyramid = {
  label: "Pyramid",
  category: "general",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path d="M12 3 2 21h20Z"/><path d="M12 3v18"/></svg>'
};
const rabbit = {
  label: "Rabbit",
  category: "activity",
  svg: '<svg class="lucide lucide-rabbit" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M13 16a3 3 0 0 1 2.24 5" /> <path d="M18 12h.01" /> <path d="M18 21h-8a4 4 0 0 1-4-4 7 7 0 0 1 7-7h.2L9.6 6.4a1 1 0 1 1 2.8-2.8L15.8 7h.2c3.3 0 6 2.7 6 6v1a2 2 0 0 1-2 2h-1a3 3 0 0 0-3 3" /> <path d="M20 8.54V4a2 2 0 1 0-4 0v3" /> <path d="M7.612 12.524a3 3 0 1 0-1.6 4.3" /> </svg>'
};
const rainbow = {
  label: "Rainbow",
  category: "general",
  svg: '<svg class="lucide lucide-rainbow" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M22 17a10 10 0 0 0-20 0" /> <path d="M6 17a6 6 0 0 1 12 0" /> <path d="M10 17a2 2 0 0 1 4 0" /> </svg>'
};
const refrigerator = {
  label: "Refrigerator",
  category: "general",
  svg: '<svg class="lucide lucide-refrigerator" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M5 6a4 4 0 0 1 4-4h6a4 4 0 0 1 4 4v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6Z" /> <path d="M5 10h14" /> <path d="M15 7v6" /> </svg>'
};
const ribbon = {
  label: "Ribbon",
  category: "general",
  svg: '<svg class="lucide lucide-ribbon" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M12 11.22C11 9.997 10 9 10 8a2 2 0 0 1 4 0c0 1-.998 2.002-2.01 3.22" /> <path d="m12 18 2.57-3.5" /> <path d="M6.243 9.016a7 7 0 0 1 11.507-.009" /> <path d="M9.35 14.53 12 11.22" /> <path d="M9.35 14.53C7.728 12.246 6 10.221 6 7a6 5 0 0 1 12 0c-.005 3.22-1.778 5.235-3.43 7.5l3.557 4.527a1 1 0 0 1-.203 1.43l-1.894 1.36a1 1 0 0 1-1.384-.215L12 18l-2.679 3.593a1 1 0 0 1-1.39.213l-1.865-1.353a1 1 0 0 1-.203-1.422z" /> </svg>'
};
const rocket = {
  label: "Rocket",
  category: "general",
  svg: '<svg class="lucide lucide-rocket" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z" /> <path d="m12 15-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z" /> <path d="M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0" /> <path d="M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5" /> </svg>'
};
const route = {
  label: "Route",
  category: "transport",
  svg: '<svg class="lucide lucide-route" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <circle cx="6" cy="19" r="3" /> <path d="M9 19h8.5a3.5 3.5 0 0 0 0-7h-11a3.5 3.5 0 0 1 0-7H15" /> <circle cx="18" cy="5" r="3" /> </svg>'
};
const ruler = {
  label: "Ruler",
  category: "general",
  svg: '<svg class="lucide lucide-ruler" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M21.3 15.3a2.4 2.4 0 0 1 0 3.4l-2.6 2.6a2.4 2.4 0 0 1-3.4 0L2.7 8.7a2.41 2.41 0 0 1 0-3.4l2.6-2.6a2.41 2.41 0 0 1 3.4 0Z" /> <path d="m14.5 12.5 2-2" /> <path d="m11.5 9.5 2-2" /> <path d="m8.5 6.5 2-2" /> <path d="m17.5 15.5 2-2" /> </svg>'
};
const sailboat = {
  label: "Sailboat",
  category: "transport",
  svg: '<svg class="lucide lucide-sailboat" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M22 18H2a4 4 0 0 0 4 4h12a4 4 0 0 0 4-4Z" /> <path d="M21 14 10 2 3 14h18Z" /> <path d="M10 2v16" /> </svg>'
};
const sandwich = {
  label: "Sandwich",
  category: "food",
  svg: '<svg class="lucide lucide-sandwich" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="m2.37 11.223 8.372-6.777a2 2 0 0 1 2.516 0l8.371 6.777" /> <path d="M21 15a1 1 0 0 1 1 1v2a1 1 0 0 1-1 1h-5.25" /> <path d="M3 15a1 1 0 0 0-1 1v2a1 1 0 0 0 1 1h9" /> <path d="m6.67 15 6.13 4.6a2 2 0 0 0 2.8-.4l3.15-4.2" /> <rect width="20" height="4" x="2" y="11" rx="1" /> </svg>'
};
const scale = {
  label: "Scale",
  category: "general",
  svg: '<svg class="lucide lucide-scale" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="m16 16 3-8 3 8c-.87.65-1.92 1-3 1s-2.13-.35-3-1Z" /> <path d="m2 16 3-8 3 8c-.87.65-1.92 1-3 1s-2.13-.35-3-1Z" /> <path d="M7 21h10" /> <path d="M12 3v18" /> <path d="M3 7h2c2 0 5-1 7-2 2 1 5 2 7 2h2" /> </svg>'
};
const school = {
  label: "School",
  category: "general",
  svg: '<svg class="lucide lucide-school" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M14 22v-4a2 2 0 1 0-4 0v4" /> <path d="m18 10 3.447 1.724a1 1 0 0 1 .553.894V20a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-7.382a1 1 0 0 1 .553-.894L6 10" /> <path d="M18 5v17" /> <path d="m4 6 7.106-3.553a2 2 0 0 1 1.788 0L20 6" /> <path d="M6 5v17" /> <circle cx="12" cy="9" r="2" /> </svg>'
};
const scroll = {
  label: "Scroll",
  category: "general",
  svg: '<svg class="lucide lucide-scroll" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M19 17V5a2 2 0 0 0-2-2H4" /> <path d="M8 21h12a2 2 0 0 0 2-2v-1a1 1 0 0 0-1-1H11a1 1 0 0 0-1 1v1a2 2 0 1 1-4 0V5a2 2 0 1 0-4 0v2a1 1 0 0 0 1 1h3" /> </svg>'
};
const search = {
  label: "Search",
  category: "general",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/></svg>'
};
const settings = {
  label: "Settings",
  category: "general",
  svg: '<svg class="lucide lucide-settings" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z" /> <circle cx="12" cy="12" r="3" /> </svg>'
};
const shell = {
  label: "Shell",
  category: "general",
  svg: '<svg class="lucide lucide-shell" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M14 11a2 2 0 1 1-4 0 4 4 0 0 1 8 0 6 6 0 0 1-12 0 8 8 0 0 1 16 0 10 10 0 1 1-20 0 11.93 11.93 0 0 1 2.42-7.22 2 2 0 1 1 3.16 2.44" /> </svg>'
};
const shield = {
  label: "Shield",
  category: "general",
  svg: '<svg class="lucide lucide-shield" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z" /> </svg>'
};
const ship = {
  label: "Ship",
  category: "transport",
  svg: '<svg class="lucide lucide-ship" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M12 10.189V14" /> <path d="M12 2v3" /> <path d="M19 13V7a2 2 0 0 0-2-2H7a2 2 0 0 0-2 2v6" /> <path d="M19.38 20A11.6 11.6 0 0 0 21 14l-8.188-3.639a2 2 0 0 0-1.624 0L3 14a11.6 11.6 0 0 0 2.81 7.76" /> <path d="M2 21c.6.5 1.2 1 2.5 1 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1s1.2 1 2.5 1c2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1" /> </svg>'
};
const shirt = {
  label: "Shirt",
  category: "general",
  svg: '<svg class="lucide lucide-shirt" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M20.38 3.46 16 2a4 4 0 0 1-8 0L3.62 3.46a2 2 0 0 0-1.34 2.23l.58 3.47a1 1 0 0 0 .99.84H6v10c0 1.1.9 2 2 2h8a2 2 0 0 0 2-2V10h2.15a1 1 0 0 0 .99-.84l.58-3.47a2 2 0 0 0-1.34-2.23z" /> </svg>'
};
const shopping = {
  label: "Shopping",
  category: "general",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7h-3V6a4 4 0 00-8 0v1H5a1 1 0 00-1 1v11a3 3 0 003 3h10a3 3 0 003-3V8a1 1 0 00-1-1zM10 6a2 2 0 114 0v1h-4V6zM8 10v2M16 10v2"/></svg>'
};
const shovel = {
  label: "Shovel",
  category: "general",
  svg: '<svg class="lucide lucide-shovel" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M2 22v-5l5-5 5 5-5 5z" /> <path d="M9.5 14.5 16 8" /> <path d="m17 2 5 5-.5.5a3.53 3.53 0 0 1-5 0s0 0 0 0a3.53 3.53 0 0 1 0-5L17 2" /> </svg>'
};
const signpost = {
  label: "Signpost",
  category: "general",
  svg: '<svg class="lucide lucide-signpost" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M12 13v8" /> <path d="M12 3v3" /> <path d="M18 6a2 2 0 0 1 1.387.56l2.307 2.22a1 1 0 0 1 0 1.44l-2.307 2.22A2 2 0 0 1 18 13H6a2 2 0 0 1-1.387-.56l-2.306-2.22a1 1 0 0 1 0-1.44l2.306-2.22A2 2 0 0 1 6 6z" /> </svg>'
};
const smartphone = {
  label: "Smartphone",
  category: "general",
  svg: '<svg class="lucide lucide-smartphone" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <rect width="14" height="20" x="5" y="2" rx="2" ry="2" /> <path d="M12 18h.01" /> </svg>'
};
const snowflake = {
  label: "Snowflake",
  category: "activity",
  svg: '<svg class="lucide lucide-snowflake" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <line x1="2" x2="22" y1="12" y2="12" /> <line x1="12" x2="12" y1="2" y2="22" /> <path d="m20 16-4-4 4-4" /> <path d="m4 8 4 4-4 4" /> <path d="m16 4-4 4-4-4" /> <path d="m8 20 4-4 4 4" /> </svg>'
};
const spa = {
  label: "Spa",
  category: "general",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path d="M12 22c-4-4-4-9 0-14 4 5 4 10 0 14z"/><path d="M12 22c-4-2-7-6-7-10 4 1 7 4 7 10z"/><path d="M12 22c4-2 7-6 7-10-4 1-7 4-7 10z"/></svg>'
};
const sparkles = {
  label: "Sparkles",
  category: "general",
  svg: '<svg class="lucide lucide-sparkles" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z" /> <path d="M20 3v4" /> <path d="M22 5h-4" /> <path d="M4 17v2" /> <path d="M5 18H3" /> </svg>'
};
const star = {
  label: "Featured",
  category: "general",
  svg: '<svg width="24" height="24" fill="currentColor" viewBox="0 0 24 24"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/></svg>'
};
const suitcase = {
  label: "Suitcase",
  category: "general",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><rect width="16" height="13" x="4" y="8" rx="2"/><path d="M8 8V6a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/><path d="M12 8v13"/></svg>'
};
const sun = {
  label: "Sun",
  category: "activity",
  svg: '<svg class="lucide lucide-sun" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <circle cx="12" cy="12" r="4" /> <path d="M12 2v2" /> <path d="M12 20v2" /> <path d="m4.93 4.93 1.41 1.41" /> <path d="m17.66 17.66 1.41 1.41" /> <path d="M2 12h2" /> <path d="M20 12h2" /> <path d="m6.34 17.66-1.41 1.41" /> <path d="m19.07 4.93-1.41 1.41" /> </svg>'
};
const sunrise = {
  label: "Sunrise",
  category: "activity",
  svg: '<svg class="lucide lucide-sunrise" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M12 2v8" /> <path d="m4.93 10.93 1.41 1.41" /> <path d="M2 18h2" /> <path d="M20 18h2" /> <path d="m19.07 10.93-1.41 1.41" /> <path d="M22 22H2" /> <path d="m8 6 4-4 4 4" /> <path d="M16 18a4 4 0 0 0-8 0" /> </svg>'
};
const sunset = {
  label: "Sunset",
  category: "activity",
  svg: '<svg class="lucide lucide-sunset" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M12 10V2" /> <path d="m4.93 10.93 1.41 1.41" /> <path d="M2 18h2" /> <path d="M20 18h2" /> <path d="m19.07 10.93-1.41 1.41" /> <path d="M22 22H2" /> <path d="m16 6-4 4-4-4" /> <path d="M16 18a4 4 0 0 0-8 0" /> </svg>'
};
const surfboard = {
  label: "Surfboard",
  category: "activity",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path d="M12 2c4 3 6 7 6 10s-2 7-6 10c-4-3-6-7-6-10s2-7 6-10z"/><path d="M12 9v8"/></svg>'
};
const tablet = {
  label: "Tablet",
  category: "general",
  svg: '<svg class="lucide lucide-tablet" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <rect width="16" height="20" x="4" y="2" rx="2" ry="2" /> <line x1="12" x2="12.01" y1="18" y2="18" /> </svg>'
};
const tag = {
  label: "Tag",
  category: "general",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z"/></svg>'
};
const target = {
  label: "Target",
  category: "activity",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="6"/><circle cx="12" cy="12" r="2"/></svg>'
};
const telescope = {
  label: "Telescope",
  category: "activity",
  svg: '<svg class="lucide lucide-telescope" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="m10.065 12.493-6.18 1.318a.934.934 0 0 1-1.108-.702l-.537-2.15a1.07 1.07 0 0 1 .691-1.265l13.504-4.44" /> <path d="m13.56 11.747 4.332-.924" /> <path d="m16 21-3.105-6.21" /> <path d="M16.485 5.94a2 2 0 0 1 1.455-2.425l1.09-.272a1 1 0 0 1 1.212.727l1.515 6.06a1 1 0 0 1-.727 1.213l-1.09.272a2 2 0 0 1-2.425-1.455z" /> <path d="m6.158 8.633 1.114 4.456" /> <path d="m8 21 3.105-6.21" /> <circle cx="12" cy="13" r="2" /> </svg>'
};
const tent = {
  label: "Tent",
  category: "accommodation",
  svg: '<svg class="lucide lucide-tent" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M3.5 21 14 3" /> <path d="M20.5 21 10 3" /> <path d="M15.5 21 12 15l-3.5 6" /> <path d="M2 21h20" /> </svg>'
};
const thermometer = {
  label: "Thermometer",
  category: "general",
  svg: '<svg class="lucide lucide-thermometer" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M14 4v10.54a4 4 0 1 1-4 0V4a2 2 0 0 1 4 0Z" /> </svg>'
};
const ticket = {
  label: "Ticket",
  category: "transport",
  svg: '<svg class="lucide lucide-ticket" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M2 9a3 3 0 0 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 0 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z" /> <path d="M13 5v2" /> <path d="M13 17v2" /> <path d="M13 11v2" /> </svg>'
};
const tickets = {
  label: "Tickets",
  category: "transport",
  svg: '<svg class="lucide lucide-tickets" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="m4.5 8 10.58-5.06a1 1 0 0 1 1.342.488L18.5 8" /> <path d="M6 10V8" /> <path d="M6 14v1" /> <path d="M6 19v2" /> <rect x="2" y="8" width="20" height="13" rx="2" /> </svg>'
};
const timer = {
  label: "Timer",
  category: "general",
  svg: '<svg class="lucide lucide-timer" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <line x1="10" x2="14" y1="2" y2="2" /> <line x1="12" x2="15" y1="14" y2="11" /> <circle cx="12" cy="14" r="8" /> </svg>'
};
const tractor = {
  label: "Tractor",
  category: "general",
  svg: '<svg class="lucide lucide-tractor" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="m10 11 11 .9a1 1 0 0 1 .8 1.1l-.665 4.158a1 1 0 0 1-.988.842H20" /> <path d="M16 18h-5" /> <path d="M18 5a1 1 0 0 0-1 1v5.573" /> <path d="M3 4h8.129a1 1 0 0 1 .99.863L13 11.246" /> <path d="M4 11V4" /> <path d="M7 15h.01" /> <path d="M8 10.1V4" /> <circle cx="18" cy="18" r="2" /> <circle cx="7" cy="15" r="5" /> </svg>'
};
const trees = {
  label: "Trees",
  category: "activity",
  svg: '<svg class="lucide lucide-trees" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M10 10v.2A3 3 0 0 1 8.9 16H5a3 3 0 0 1-1-5.8V10a3 3 0 0 1 6 0Z" /> <path d="M7 16v6" /> <path d="M13 19v3" /> <path d="M12 19h8.3a1 1 0 0 0 .7-1.7L18 14h.3a1 1 0 0 0 .7-1.7L16 9h.2a1 1 0 0 0 .8-1.7L13 3l-1.4 1.5" /> </svg>'
};
const trophy = {
  label: "Trophy",
  category: "activity",
  svg: '<svg class="lucide lucide-trophy" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M6 9H4.5a2.5 2.5 0 0 1 0-5H6" /> <path d="M18 9h1.5a2.5 2.5 0 0 0 0-5H18" /> <path d="M4 22h16" /> <path d="M10 14.66V17c0 .55-.47.98-.97 1.21C7.85 18.75 7 20.24 7 22" /> <path d="M14 14.66V17c0 .55.47.98.97 1.21C16.15 18.75 17 20.24 17 22" /> <path d="M18 2H6v7a6 6 0 0 0 12 0V2Z" /> </svg>'
};
const truck = {
  label: "Truck",
  category: "general",
  svg: '<svg class="lucide lucide-truck" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2" /> <path d="M15 18H9" /> <path d="M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14" /> <circle cx="17" cy="18" r="2" /> <circle cx="7" cy="18" r="2" /> </svg>'
};
const umbrella = {
  label: "Umbrella",
  category: "activity",
  svg: '<svg class="lucide lucide-umbrella" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M22 12a10.06 10.06 1 0 0-20 0Z" /> <path d="M12 12v8a2 2 0 0 0 4 0" /> <path d="M12 2v1" /> </svg>'
};
const usb = {
  label: "Usb",
  category: "general",
  svg: '<svg class="lucide lucide-usb" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <circle cx="10" cy="7" r="1" /> <circle cx="4" cy="20" r="1" /> <path d="M4.7 19.3 19 5" /> <path d="m21 3-3 1 2 2Z" /> <path d="M9.26 7.68 5 12l2 5" /> <path d="m10 14 5 2 3.5-3.5" /> <path d="m18 12 1-1 1 1-1 1Z" /> </svg>'
};
const users = {
  label: "Users",
  category: "general",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 11a4 4 0 100-8 4 4 0 000 8z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M23 21v-2a4 4 0 00-3-3.87"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 3.13a4 4 0 010 7.75"/></svg>'
};
const utensils = {
  label: "Meal",
  category: "food",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 2v7c0 1.1.9 2 2 2h4a2 2 0 0 0 2-2V2"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 2v20"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 15V2a5 5 0 0 0-5 5v6c0 1.1.9 2 2 2h3Zm0 0v7"/></svg>'
};
const video = {
  label: "Video",
  category: "media",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z"/></svg>'
};
const volcano = {
  label: "Volcano",
  category: "general",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path d="M2 21h20"/><path d="M5 21l5-9h4l5 9"/><path d="M11 12V5"/><path d="M8 5h6"/><path d="M11 5c0-1 .5-2 2-2"/></svg>'
};
const volleyball = {
  label: "Volleyball",
  category: "activity",
  svg: '<svg class="lucide lucide-volleyball" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M11.1 7.1a16.55 16.55 0 0 1 10.9 4" /> <path d="M12 12a12.6 12.6 0 0 1-8.7 5" /> <path d="M16.8 13.6a16.55 16.55 0 0 1-9 7.5" /> <path d="M20.7 17a12.8 12.8 0 0 0-8.7-5 13.3 13.3 0 0 1 0-10" /> <path d="M6.3 3.8a16.55 16.55 0 0 0 1.9 11.5" /> <circle cx="12" cy="12" r="10" /> </svg>'
};
const wallet = {
  label: "Wallet",
  category: "general",
  svg: '<svg class="lucide lucide-wallet" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1" /> <path d="M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4" /> </svg>'
};
const watch = {
  label: "Watch",
  category: "general",
  svg: '<svg class="lucide lucide-watch" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <circle cx="12" cy="12" r="6" /> <polyline points="12 10 12 12 13 13" /> <path d="m16.13 7.66-.81-4.05a2 2 0 0 0-2-1.61h-2.68a2 2 0 0 0-2 1.61l-.78 4.05" /> <path d="m7.88 16.36.8 4a2 2 0 0 0 2 1.61h2.72a2 2 0 0 0 2-1.61l.81-4.05" /> </svg>'
};
const waves = {
  label: "Water Sports",
  category: "activity",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2 12c.6-2.4 2.4-4 4-4s3.4 1.6 4 4c.6-2.4 2.4-4 4-4s3.4 1.6 4 4c.6-2.4 2.4-4 4-4"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2 16c.6-2.4 2.4-4 4-4s3.4 1.6 4 4c.6-2.4 2.4-4 4-4s3.4 1.6 4 4c.6-2.4 2.4-4 4-4"/></svg>'
};
const webcam = {
  label: "Webcam",
  category: "general",
  svg: '<svg class="lucide lucide-webcam" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <circle cx="12" cy="10" r="8" /> <circle cx="12" cy="10" r="3" /> <path d="M7 22h10" /> <path d="M12 22v-4" /> </svg>'
};
const weight = {
  label: "Weight",
  category: "general",
  svg: '<svg class="lucide lucide-weight" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <circle cx="12" cy="5" r="3" /> <path d="M6.5 8a2 2 0 0 0-1.905 1.46L2.1 18.5A2 2 0 0 0 4 21h16a2 2 0 0 0 1.925-2.54L19.4 9.5A2 2 0 0 0 17.48 8Z" /> </svg>'
};
const wheat = {
  label: "Wheat",
  category: "general",
  svg: '<svg class="lucide lucide-wheat" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M2 22 16 8" /> <path d="M3.47 12.53 5 11l1.53 1.53a3.5 3.5 0 0 1 0 4.94L5 19l-1.53-1.53a3.5 3.5 0 0 1 0-4.94Z" /> <path d="M7.47 8.53 9 7l1.53 1.53a3.5 3.5 0 0 1 0 4.94L9 15l-1.53-1.53a3.5 3.5 0 0 1 0-4.94Z" /> <path d="M11.47 4.53 13 3l1.53 1.53a3.5 3.5 0 0 1 0 4.94L13 11l-1.53-1.53a3.5 3.5 0 0 1 0-4.94Z" /> <path d="M20 2h2v2a4 4 0 0 1-4 4h-2V6a4 4 0 0 1 4-4Z" /> <path d="M11.47 17.47 13 19l-1.53 1.53a3.5 3.5 0 0 1-4.94 0L5 19l1.53-1.53a3.5 3.5 0 0 1 4.94 0Z" /> <path d="M15.47 13.47 17 15l-1.53 1.53a3.5 3.5 0 0 1-4.94 0L9 15l1.53-1.53a3.5 3.5 0 0 1 4.94 0Z" /> <path d="M19.47 9.47 21 11l-1.53 1.53a3.5 3.5 0 0 1-4.94 0L13 11l1.53-1.53a3.5 3.5 0 0 1 4.94 0Z" /> </svg>'
};
const wifi = {
  label: "Wifi",
  category: "general",
  svg: '<svg class="lucide lucide-wifi" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M12 20h.01" /> <path d="M2 8.82a15 15 0 0 1 20 0" /> <path d="M5 12.859a10 10 0 0 1 14 0" /> <path d="M8.5 16.429a5 5 0 0 1 7 0" /> </svg>'
};
const wind = {
  label: "Wind",
  category: "general",
  svg: '<svg class="lucide lucide-wind" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M12.8 19.6A2 2 0 1 0 14 16H2" /> <path d="M17.5 8a2.5 2.5 0 1 1 2 4H2" /> <path d="M9.8 4.4A2 2 0 1 1 11 8H2" /> </svg>'
};
const wine = {
  label: "Wine",
  category: "food",
  svg: '<svg class="lucide lucide-wine" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M8 22h8" /> <path d="M7 10h10" /> <path d="M12 15v7" /> <path d="M12 15a5 5 0 0 0 5-5c0-2-.5-4-2-8H9c-1.5 4-2 6-2 8a5 5 0 0 0 5 5Z" /> </svg>'
};
const wrench = {
  label: "Wrench",
  category: "general",
  svg: '<svg class="lucide lucide-wrench" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z" /> </svg>'
};
const x$1 = {
  label: "X",
  category: "general",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M18 6L6 18M6 6l12 12"/></svg>'
};
const zap = {
  label: "Energy",
  category: "activity",
  svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"/></svg>'
};
const yatraIconsManifest = {
  accessibility,
  activity,
  anchor,
  archive,
  award,
  backpack,
  banknote,
  beach,
  bed,
  "bed-double": {
    label: "Bed Double",
    category: "accommodation",
    svg: '<svg class="lucide lucide-bed-double" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M2 20v-8a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v8" /> <path d="M4 10V6a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v4" /> <path d="M12 4v6" /> <path d="M2 18h20" /> </svg>'
  },
  "bed-single": {
    label: "Bed Single",
    category: "accommodation",
    svg: '<svg class="lucide lucide-bed-single" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M3 20v-8a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v8" /> <path d="M5 10V6a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v4" /> <path d="M3 18h18" /> </svg>'
  },
  bell,
  "bell-ring": {
    label: "Bell Ring",
    category: "general",
    svg: '<svg class="lucide lucide-bell-ring" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M10.268 21a2 2 0 0 0 3.464 0" /> <path d="M22 8c0-2.3-.8-4.3-2-6" /> <path d="M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326" /> <path d="M4 2C2.8 3.7 2 5.7 2 8" /> </svg>'
  },
  bike,
  binoculars,
  bluetooth,
  book,
  bookmark,
  briefcase,
  brush,
  building,
  bus,
  "bus-front": {
    label: "Bus Front",
    category: "transport",
    svg: '<svg class="lucide lucide-bus-front" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M4 6 2 7" /> <path d="M10 6h4" /> <path d="m22 7-2-1" /> <rect width="16" height="16" x="4" y="3" rx="2" /> <path d="M4 11h16" /> <path d="M8 15h.01" /> <path d="M16 15h.01" /> <path d="M6 19v2" /> <path d="M18 21v-2" /> </svg>'
  },
  cactus,
  cake,
  calendar: calendar$1,
  camera,
  campfire,
  car,
  "car-front": {
    label: "Car Front",
    category: "transport",
    svg: '<svg class="lucide lucide-car-front" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="m21 8-2 2-1.5-3.7A2 2 0 0 0 15.646 5H8.4a2 2 0 0 0-1.903 1.257L5 10 3 8" /> <path d="M7 14h.01" /> <path d="M17 14h.01" /> <rect width="18" height="8" x="3" y="10" rx="2" /> <path d="M5 18v2" /> <path d="M19 18v2" /> </svg>'
  },
  "car-taxi-front": {
    label: "Car Taxi Front",
    category: "transport",
    svg: '<svg class="lucide lucide-car-taxi-front" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M10 2h4" /> <path d="m21 8-2 2-1.5-3.7A2 2 0 0 0 15.646 5H8.4a2 2 0 0 0-1.903 1.257L5 10 3 8" /> <path d="M7 14h.01" /> <path d="M17 14h.01" /> <rect width="18" height="8" x="3" y="10" rx="2" /> <path d="M5 18v2" /> <path d="M19 18v2" /> </svg>'
  },
  caravan,
  castle,
  check,
  "chef-hat": {
    label: "Chef Hat",
    category: "food",
    svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path d="M17 21H7a1 1 0 0 1-1-1v-5h12v5a1 1 0 0 1-1 1Z"/><path d="M6 15c-2 0-3-1-3-3a3 3 0 0 1 3-3 4 4 0 0 1 8 0 4 4 0 0 1 8 0 3 3 0 0 1 3 3c0 2-1 3-3 3"/></svg>'
  },
  "chevron-left": {
    label: "Chevron Left",
    category: "general",
    svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 18l-6-6 6-6"/></svg>'
  },
  "chevron-right": {
    label: "Chevron Right",
    category: "general",
    svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 18l6-6-6-6"/></svg>'
  },
  church,
  climbing,
  clock,
  cloud,
  "cloud-rain": {
    label: "Cloud Rain",
    category: "general",
    svg: '<svg class="lucide lucide-cloud-rain" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242" /> <path d="M16 14v6" /> <path d="M8 14v6" /> <path d="M12 16v6" /> </svg>'
  },
  "cloud-sun": {
    label: "Cloud Sun",
    category: "general",
    svg: '<svg class="lucide lucide-cloud-sun" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M12 2v2" /> <path d="m4.93 4.93 1.41 1.41" /> <path d="M20 12h2" /> <path d="m19.07 4.93-1.41 1.41" /> <path d="M15.947 12.65a4 4 0 0 0-5.925-4.128" /> <path d="M13 22H7a5 5 0 1 1 4.9-6H13a3 3 0 0 1 0 6Z" /> </svg>'
  },
  coffee,
  compass,
  construction,
  cookie,
  "credit-card": {
    label: "Credit Card",
    category: "general",
    svg: '<svg class="lucide lucide-credit-card" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <rect width="20" height="14" x="2" y="5" rx="2" /> <line x1="2" x2="22" y1="10" y2="10" /> </svg>'
  },
  crown,
  "cup-soda": {
    label: "Cup Soda",
    category: "food",
    svg: '<svg class="lucide lucide-cup-soda" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="m6 8 1.75 12.28a2 2 0 0 0 2 1.72h4.54a2 2 0 0 0 2-1.72L18 8" /> <path d="M5 8h14" /> <path d="M7 15a6.47 6.47 0 0 1 5 0 6.47 6.47 0 0 0 5 0" /> <path d="m12 8 1-6h2" /> </svg>'
  },
  diamond,
  "dollar-sign": {
    label: "Price",
    category: "general",
    svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>'
  },
  "door-open": {
    label: "Door Open",
    category: "accommodation",
    svg: '<svg class="lucide lucide-door-open" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M13 4h3a2 2 0 0 1 2 2v14" /> <path d="M2 20h3" /> <path d="M13 20h9" /> <path d="M10 12v.01" /> <path d="M13 4.562v16.157a1 1 0 0 1-1.242.97L5 20V5.562a2 2 0 0 1 1.515-1.94l4-1A2 2 0 0 1 13 4.561Z" /> </svg>'
  },
  download,
  droplet,
  drum,
  dumbbell,
  earth,
  "earth-lock": {
    label: "Earth Lock",
    category: "travel",
    svg: '<svg class="lucide lucide-earth-lock" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M7 3.34V5a3 3 0 0 0 3 3" /> <path d="M11 21.95V18a2 2 0 0 0-2-2 2 2 0 0 1-2-2v-1a2 2 0 0 0-2-2H2.05" /> <path d="M21.54 15H17a2 2 0 0 0-2 2v4.54" /> <path d="M12 2a10 10 0 1 0 9.54 13" /> <path d="M20 6V4a2 2 0 1 0-4 0v2" /> <rect width="8" height="5" x="14" y="6" rx="1" /> </svg>'
  },
  eye,
  fan,
  feather,
  "ferris-wheel": {
    label: "Ferris Wheel",
    category: "activity",
    svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><circle cx="12" cy="11" r="9"/><path d="M12 2v18"/><path d="M3 11h18"/><path d="M5.6 4.6 18.4 17.4"/><path d="M5.6 17.4 18.4 4.6"/><circle cx="12" cy="11" r="2"/></svg>'
  },
  "file-text": {
    label: "Document",
    category: "media",
    svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/></svg>'
  },
  film,
  filter,
  "first-aid": {
    label: "First Aid",
    category: "safety",
    svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><rect width="18" height="14" x="3" y="6" rx="2"/><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/><path d="M12 10v6"/><path d="M9 13h6"/></svg>'
  },
  fish,
  flag,
  flame,
  "flower-2": {
    label: "Flower 2",
    category: "activity",
    svg: '<svg class="lucide lucide-flower-2" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M12 5a3 3 0 1 1 3 3m-3-3a3 3 0 1 0-3 3m3-3v1M9 8a3 3 0 1 0 3 3M9 8h1m5 0a3 3 0 1 1-3 3m3-3h-1m-2 3v-1" /> <circle cx="12" cy="8" r="2" /> <path d="M12 10v12" /> <path d="M12 22c4.2 0 7-1.667 7-5-4.2 0-7 1.667-7 5Z" /> <path d="M12 22c-4.2 0-7-1.667-7-5 4.2 0 7 1.667 7 5Z" /> </svg>'
  },
  footprints,
  fuel,
  gamepad,
  gift,
  "glass-water": {
    label: "Glass Water",
    category: "food",
    svg: '<svg class="lucide lucide-glass-water" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M5.116 4.104A1 1 0 0 1 6.11 3h11.78a1 1 0 0 1 .994 1.105L17.19 20.21A2 2 0 0 1 15.2 22H8.8a2 2 0 0 1-2-1.79z" /> <path d="M6 12a5 5 0 0 1 6 0 5 5 0 0 0 6 0" /> </svg>'
  },
  globe,
  "globe-lock": {
    label: "Globe Lock",
    category: "travel",
    svg: '<svg class="lucide lucide-globe-lock" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M15.686 15A14.5 14.5 0 0 1 12 22a14.5 14.5 0 0 1 0-20 10 10 0 1 0 9.542 13" /> <path d="M2 12h8.5" /> <path d="M20 6V4a2 2 0 1 0-4 0v2" /> <rect width="8" height="5" x="14" y="6" rx="1" /> </svg>'
  },
  "graduation-cap": {
    label: "Graduation Cap",
    category: "general",
    svg: '<svg class="lucide lucide-graduation-cap" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M21.42 10.922a1 1 0 0 0-.019-1.838L12.83 5.18a2 2 0 0 0-1.66 0L2.6 9.08a1 1 0 0 0 0 1.832l8.57 3.908a2 2 0 0 0 1.66 0z" /> <path d="M22 10v6" /> <path d="M6 12.5V16a6 3 0 0 0 12 0v-3.5" /> </svg>'
  },
  hammer,
  handshake,
  headphones,
  heart,
  helicopter,
  helmet,
  "help-circle": {
    label: "Help",
    category: "general",
    svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.09 9a3 3 0 015.83 1c0 2-3 3-3 3"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>'
  },
  hexagon,
  "hot-air-balloon": {
    label: "Hot Air Balloon",
    category: "activity",
    svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path d="M11 22a1 1 0 0 1 0-2"/><path d="M13.6 16.8 12 22h-1l-1.6-5.2"/><path d="M13 20a1 1 0 0 0 0-2"/><path d="M11 20v2"/><path d="M13 20v2"/><path d="M19 10c0 4.97-3.5 9-7 9s-7-4.03-7-9a7 7 0 1 1 14 0Z"/></svg>'
  },
  hotel,
  hourglass,
  house,
  "ice-cream-bowl": {
    label: "Ice Cream Bowl",
    category: "food",
    svg: '<svg class="lucide lucide-ice-cream-bowl" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M12 17c5 0 8-2.69 8-6H4c0 3.31 3 6 8 6m-4 4h8m-4-3v3M5.14 11a3.5 3.5 0 1 1 6.71 0" /> <path d="M12.14 11a3.5 3.5 0 1 1 6.71 0" /> <path d="M15.5 6.5a3.5 3.5 0 1 0-7 0" /> </svg>'
  },
  "id-card": {
    label: "Id Card",
    category: "travel",
    svg: '<svg class="lucide lucide-id-card" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M16 10h2" /> <path d="M16 14h2" /> <path d="M6.17 15a3 3 0 0 1 5.66 0" /> <circle cx="9" cy="11" r="2" /> <rect x="2" y="5" width="20" height="14" rx="2" /> </svg>'
  },
  image,
  info,
  island,
  kayak,
  key,
  lake,
  landmark,
  languages,
  "life-buoy": {
    label: "Life Buoy",
    category: "activity",
    svg: '<svg class="lucide lucide-life-buoy" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <circle cx="12" cy="12" r="10" /> <path d="m4.93 4.93 4.24 4.24" /> <path d="m14.83 9.17 4.24-4.24" /> <path d="m14.83 14.83 4.24 4.24" /> <path d="m9.17 14.83-4.24 4.24" /> <circle cx="12" cy="12" r="4" /> </svg>'
  },
  link,
  lock,
  luggage,
  mailbox,
  map: map$4,
  "map-pin": {
    label: "Location",
    category: "travel",
    svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 11a3 3 0 11-6 0 3 3 0 016 0z"/></svg>'
  },
  "map-pin-check": {
    label: "Map Pin Check",
    category: "activity",
    svg: '<svg class="lucide lucide-map-pin-check" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M19.43 12.935c.357-.967.57-1.955.57-2.935a8 8 0 0 0-16 0c0 4.993 5.539 10.193 7.399 11.799a1 1 0 0 0 1.202 0 32.197 32.197 0 0 0 .813-.728" /> <circle cx="12" cy="10" r="3" /> <path d="m16 18 2 2 4-4" /> </svg>'
  },
  "map-pin-check-inside": {
    label: "Map Pin Check Inside",
    category: "activity",
    svg: '<svg class="lucide lucide-map-pin-check-inside" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0" /> <path d="m9 10 2 2 4-4" /> </svg>'
  },
  "map-pin-house": {
    label: "Map Pin House",
    category: "activity",
    svg: '<svg class="lucide lucide-map-pin-house" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M15 22a1 1 0 0 1-1-1v-4a1 1 0 0 1 .445-.832l3-2a1 1 0 0 1 1.11 0l3 2A1 1 0 0 1 22 17v4a1 1 0 0 1-1 1z" /> <path d="M18 10a8 8 0 0 0-16 0c0 4.993 5.539 10.193 7.399 11.799a1 1 0 0 0 .601.2" /> <path d="M18 22v-3" /> <circle cx="10" cy="10" r="3" /> </svg>'
  },
  "map-pin-plus": {
    label: "Map Pin Plus",
    category: "activity",
    svg: '<svg class="lucide lucide-map-pin-plus" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M19.914 11.105A7.298 7.298 0 0 0 20 10a8 8 0 0 0-16 0c0 4.993 5.539 10.193 7.399 11.799a1 1 0 0 0 1.202 0 32 32 0 0 0 .824-.738" /> <circle cx="12" cy="10" r="3" /> <path d="M16 18h6" /> <path d="M19 15v6" /> </svg>'
  },
  "map-pin-plus-inside": {
    label: "Map Pin Plus Inside",
    category: "activity",
    svg: '<svg class="lucide lucide-map-pin-plus-inside" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0" /> <path d="M12 7v6" /> <path d="M9 10h6" /> </svg>'
  },
  "map-pinned": {
    label: "Map Pinned",
    category: "activity",
    svg: '<svg class="lucide lucide-map-pinned" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M18 8c0 3.613-3.869 7.429-5.393 8.795a1 1 0 0 1-1.214 0C9.87 15.429 6 11.613 6 8a6 6 0 0 1 12 0" /> <circle cx="12" cy="8" r="2" /> <path d="M8.714 14h-3.71a1 1 0 0 0-.948.683l-2.004 6A1 1 0 0 0 3 22h18a1 1 0 0 0 .948-1.316l-2-6a1 1 0 0 0-.949-.684h-3.712" /> </svg>'
  },
  martini,
  medal,
  "message-circle": {
    label: "Message",
    category: "general",
    svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 11.5a8.38 8.38 0 01-.9 3.8 8.5 8.5 0 01-7.6 4.7 8.38 8.38 0 01-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 01-.9-3.8 8.5 8.5 0 014.7-7.6 8.38 8.38 0 013.8-.9h.5a8.48 8.48 0 018 8v.5z"/></svg>'
  },
  mic,
  milestone,
  moon,
  "moon-star": {
    label: "Moon Star",
    category: "activity",
    svg: '<svg class="lucide lucide-moon-star" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9" /> <path d="M20 3v4" /> <path d="M22 5h-4" /> </svg>'
  },
  mountain,
  "mountain-snow": {
    label: "Mountain Snow",
    category: "activity",
    svg: '<svg class="lucide lucide-mountain-snow" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="m8 3 4 8 5-5 5 15H2L8 3z" /> <path d="M4.14 15.08c2.62-1.57 5.24-1.43 7.86.42 2.74 1.94 5.49 2 8.23.19" /> </svg>'
  },
  museum,
  music,
  navigation,
  "navigation-2": {
    label: "Navigation 2",
    category: "transport",
    svg: '<svg class="lucide lucide-navigation-2" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <polygon points="12 2 19 21 12 17 5 21 12 2" /> </svg>'
  },
  newspaper,
  octagon,
  "package": {
    label: "Package",
    category: "general",
    svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16.5 9.4l-9-5.19M21 16V8a2 2 0 00-1-1.73l-7-4a2 2 0 00-2 0l-7 4A2 2 0 003 8v8a2 2 0 001 1.73l7 4a2 2 0 002 0l7-4A2 2 0 0021 16z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3.27 6.96L12 12.01l8.73-5.05M12 22.08V12"/></svg>'
  },
  "package-open": {
    label: "Package Open",
    category: "general",
    svg: '<svg class="lucide lucide-package-open" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M12 22v-9" /> <path d="M15.17 2.21a1.67 1.67 0 0 1 1.63 0L21 4.57a1.93 1.93 0 0 1 0 3.36L8.82 14.79a1.655 1.655 0 0 1-1.64 0L3 12.43a1.93 1.93 0 0 1 0-3.36z" /> <path d="M20 13v3.87a2.06 2.06 0 0 1-1.11 1.83l-6 3.08a1.93 1.93 0 0 1-1.78 0l-6-3.08A2.06 2.06 0 0 1 4 16.87V13" /> <path d="M21 12.43a1.93 1.93 0 0 0 0-3.36L8.83 2.2a1.64 1.64 0 0 0-1.63 0L3 4.57a1.93 1.93 0 0 0 0 3.36l12.18 6.86a1.636 1.636 0 0 0 1.63 0z" /> </svg>'
  },
  palette,
  "palm-tree": {
    label: "Palm Tree",
    category: "general",
    svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path d="M12 22V10"/><path d="M12 10c0-4 2-7 5-7-1 4-5 7-5 7Z"/><path d="M12 10c0-4-2-7-5-7 1 4 5 7 5 7Z"/><path d="M12 10c1.5-3.5 4-5 7-3.5-2 3-5 3.5-7 3.5Z"/><path d="M12 10c-1.5-3.5-4-5-7-3.5 2 3 5 3.5 7 3.5Z"/></svg>'
  },
  "party-popper": {
    label: "Party Popper",
    category: "general",
    svg: '<svg class="lucide lucide-party-popper" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M5.8 11.3 2 22l10.7-3.79" /> <path d="M4 3h.01" /> <path d="M22 8h.01" /> <path d="M15 2h.01" /> <path d="M22 20h.01" /> <path d="m22 2-2.24.75a2.9 2.9 0 0 0-1.96 3.12c.1.86-.57 1.63-1.45 1.63h-.38c-.86 0-1.6.6-1.76 1.44L14 10" /> <path d="m22 13-.82-.33c-.86-.34-1.82.2-1.98 1.11c-.11.7-.72 1.22-1.43 1.22H17" /> <path d="m11 2 .33.82c.34.86-.2 1.82-1.11 1.98C9.52 4.9 9 5.52 9 6.23V7" /> <path d="M11 13c1.93 1.93 2.83 4.17 2 5-.83.83-3.07-.07-5-2-1.93-1.93-2.83-4.17-2-5 .83-.83 3.07.07 5 2Z" /> </svg>'
  },
  passport,
  "paw-print": {
    label: "Paw Print",
    category: "general",
    svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><circle cx="11" cy="4" r="2"/><circle cx="18" cy="8" r="2"/><circle cx="20" cy="16" r="2"/><path d="M9 10a5 5 0 0 1 5 5v3.5a3.5 3.5 0 0 1-6.84 1.045Q6.52 17.48 4.46 16.84A3.5 3.5 0 0 1 5.5 10Z"/></svg>'
  },
  "pen-line": {
    label: "Pen Line",
    category: "general",
    svg: '<svg class="lucide lucide-pen-line" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M12 20h9" /> <path d="M16.376 3.622a1 1 0 0 1 3.002 3.002L7.368 18.635a2 2 0 0 1-.855.506l-2.872.838a.5.5 0 0 1-.62-.62l.838-2.872a2 2 0 0 1 .506-.854z" /> </svg>'
  },
  percent,
  phone,
  "piggy-bank": {
    label: "Piggy Bank",
    category: "general",
    svg: '<svg class="lucide lucide-piggy-bank" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M19 5c-1.5 0-2.8 1.4-3 2-3.5-1.5-11-.3-11 5 0 1.8 0 3 2 4.5V20h4v-2h3v2h4v-4c1-.5 1.7-1 2-2h2v-4h-2c0-1-.5-1.5-1-2V5z" /> <path d="M2 9v1c0 1.1.9 2 2 2h1" /> <path d="M16 11h.01" /> </svg>'
  },
  pill,
  pin,
  pizza,
  plane,
  "plane-landing": {
    label: "Plane Landing",
    category: "transport",
    svg: '<svg class="lucide lucide-plane-landing" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M2 22h20" /> <path d="M3.77 10.77 2 9l2-4.5 1.1.55c.55.28.9.84.9 1.45s.35 1.17.9 1.45L8 8.5l3-6 1.05.53a2 2 0 0 1 1.09 1.52l.72 5.4a2 2 0 0 0 1.09 1.52l4.4 2.2c.42.22.78.55 1.01.96l.6 1.03c.49.88-.06 1.98-1.06 2.1l-1.18.15c-.47.06-.95-.02-1.37-.24L4.29 11.15a2 2 0 0 1-.52-.38Z" /> </svg>'
  },
  "plane-takeoff": {
    label: "Plane Takeoff",
    category: "transport",
    svg: '<svg class="lucide lucide-plane-takeoff" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M2 22h20" /> <path d="M6.36 17.4 4 17l-2-4 1.1-.55a2 2 0 0 1 1.8 0l.17.1a2 2 0 0 0 1.8 0L8 12 5 6l.9-.45a2 2 0 0 1 2.09.2l4.02 3a2 2 0 0 0 2.1.2l4.19-2.06a2.41 2.41 0 0 1 1.73-.17L21 7a1.4 1.4 0 0 1 .87 1.99l-.38.76c-.23.46-.6.84-1.07 1.08L7.58 17.2a2 2 0 0 1-1.22.18Z" /> </svg>'
  },
  play,
  plug,
  plus,
  pool,
  power,
  pyramid,
  "qr-code": {
    label: "Qr Code",
    category: "general",
    svg: '<svg class="lucide lucide-qr-code" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <rect width="5" height="5" x="3" y="3" rx="1" /> <rect width="5" height="5" x="16" y="3" rx="1" /> <rect width="5" height="5" x="3" y="16" rx="1" /> <path d="M21 16h-3a2 2 0 0 0-2 2v3" /> <path d="M21 21v.01" /> <path d="M12 7v3a2 2 0 0 1-2 2H7" /> <path d="M3 12h.01" /> <path d="M12 3h.01" /> <path d="M12 16v.01" /> <path d="M16 12h1" /> <path d="M21 12v.01" /> <path d="M12 21v-1" /> </svg>'
  },
  rabbit,
  rainbow,
  refrigerator,
  ribbon,
  rocket,
  route,
  ruler,
  sailboat,
  sandwich,
  scale,
  "scan-barcode": {
    label: "Scan Barcode",
    category: "travel",
    svg: '<svg class="lucide lucide-scan-barcode" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M3 7V5a2 2 0 0 1 2-2h2" /> <path d="M17 3h2a2 2 0 0 1 2 2v2" /> <path d="M21 17v2a2 2 0 0 1-2 2h-2" /> <path d="M7 21H5a2 2 0 0 1-2-2v-2" /> <path d="M8 7v10" /> <path d="M12 7v10" /> <path d="M17 7v10" /> </svg>'
  },
  "scan-qr-code": {
    label: "Scan Qr Code",
    category: "travel",
    svg: '<svg class="lucide lucide-scan-qr-code" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M17 12v4a1 1 0 0 1-1 1h-4" /> <path d="M17 3h2a2 2 0 0 1 2 2v2" /> <path d="M17 8V7" /> <path d="M21 17v2a2 2 0 0 1-2 2h-2" /> <path d="M3 7V5a2 2 0 0 1 2-2h2" /> <path d="M7 17h.01" /> <path d="M7 21H5a2 2 0 0 1-2-2v-2" /> <rect x="7" y="7" width="5" height="5" rx="1" /> </svg>'
  },
  school,
  scroll,
  search,
  settings,
  shell,
  shield,
  ship,
  "ship-wheel": {
    label: "Ship Wheel",
    category: "transport",
    svg: '<svg class="lucide lucide-ship-wheel" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <circle cx="12" cy="12" r="8" /> <path d="M12 2v7.5" /> <path d="m19 5-5.23 5.23" /> <path d="M22 12h-7.5" /> <path d="m19 19-5.23-5.23" /> <path d="M12 14.5V22" /> <path d="M10.23 13.77 5 19" /> <path d="M9.5 12H2" /> <path d="M10.23 10.23 5 5" /> <circle cx="12" cy="12" r="2.5" /> </svg>'
  },
  shirt,
  shopping,
  "shopping-cart": {
    label: "Shopping Cart",
    category: "general",
    svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 3h2l.4 2M7 13h10l4-8H5.4"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 13L5.4 5M7 13l-2 9h14l-2-9"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 22a1 1 0 100-2 1 1 0 000 2z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 22a1 1 0 100-2 1 1 0 000 2z"/></svg>'
  },
  shovel,
  signpost,
  "signpost-big": {
    label: "Signpost Big",
    category: "travel",
    svg: '<svg class="lucide lucide-signpost-big" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M10 9H4L2 7l2-2h6" /> <path d="M14 5h6l2 2-2 2h-6" /> <path d="M10 22V4a2 2 0 1 1 4 0v18" /> <path d="M8 22h8" /> </svg>'
  },
  smartphone,
  "snorkel-mask": {
    label: "Snorkel Mask",
    category: "activity",
    svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><rect width="18" height="10" x="3" y="6" rx="2"/><circle cx="8" cy="11" r="2"/><circle cx="16" cy="11" r="2"/><path d="M17 16v2a2 2 0 0 1-2 2h-1"/></svg>'
  },
  snowflake,
  spa,
  sparkles,
  star,
  suitcase,
  sun,
  sunrise,
  sunset,
  surfboard,
  tablet,
  tag,
  target,
  telescope,
  tent,
  "tent-tree": {
    label: "Tent Tree",
    category: "accommodation",
    svg: '<svg class="lucide lucide-tent-tree" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <circle cx="4" cy="4" r="2" /> <path d="m14 5 3-3 3 3" /> <path d="m14 10 3-3 3 3" /> <path d="M17 14V2" /> <path d="M17 14H7l-5 8h20Z" /> <path d="M8 14v8" /> <path d="m9 14 5 8" /> </svg>'
  },
  thermometer,
  ticket,
  "ticket-check": {
    label: "Ticket Check",
    category: "transport",
    svg: '<svg class="lucide lucide-ticket-check" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M2 9a3 3 0 0 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 0 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z" /> <path d="m9 12 2 2 4-4" /> </svg>'
  },
  "ticket-minus": {
    label: "Ticket Minus",
    category: "transport",
    svg: '<svg class="lucide lucide-ticket-minus" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M2 9a3 3 0 0 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 0 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z" /> <path d="M9 12h6" /> </svg>'
  },
  "ticket-percent": {
    label: "Ticket Percent",
    category: "transport",
    svg: '<svg class="lucide lucide-ticket-percent" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M2 9a3 3 0 1 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 1 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z" /> <path d="M9 9h.01" /> <path d="m15 9-6 6" /> <path d="M15 15h.01" /> </svg>'
  },
  "ticket-plus": {
    label: "Ticket Plus",
    category: "transport",
    svg: '<svg class="lucide lucide-ticket-plus" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M2 9a3 3 0 0 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 0 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z" /> <path d="M9 12h6" /> <path d="M12 9v6" /> </svg>'
  },
  "ticket-slash": {
    label: "Ticket Slash",
    category: "transport",
    svg: '<svg class="lucide lucide-ticket-slash" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M2 9a3 3 0 0 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 0 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z" /> <path d="m9.5 14.5 5-5" /> </svg>'
  },
  "ticket-x": {
    label: "Ticket X",
    category: "transport",
    svg: '<svg class="lucide lucide-ticket-x" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M2 9a3 3 0 0 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 0 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z" /> <path d="m9.5 14.5 5-5" /> <path d="m9.5 9.5 5 5" /> </svg>'
  },
  tickets,
  "tickets-plane": {
    label: "Tickets Plane",
    category: "transport",
    svg: '<svg class="lucide lucide-tickets-plane" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M10.5 17h1.227a2 2 0 0 0 1.345-.52L18 12" /> <path d="m12 13.5 3.75.5" /> <path d="m4.5 8 10.58-5.06a1 1 0 0 1 1.342.488L18.5 8" /> <path d="M6 10V8" /> <path d="M6 14v1" /> <path d="M6 19v2" /> <rect x="2" y="8" width="20" height="13" rx="2" /> </svg>'
  },
  timer,
  tractor,
  "train-front": {
    label: "Train Front",
    category: "transport",
    svg: '<svg class="lucide lucide-train-front" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M8 3.1V7a4 4 0 0 0 8 0V3.1" /> <path d="m9 15-1-1" /> <path d="m15 15 1-1" /> <path d="M9 19c-2.8 0-5-2.2-5-5v-4a8 8 0 0 1 16 0v4c0 2.8-2.2 5-5 5Z" /> <path d="m8 19-2 3" /> <path d="m16 19 2 3" /> </svg>'
  },
  "train-front-tunnel": {
    label: "Train Front Tunnel",
    category: "transport",
    svg: '<svg class="lucide lucide-train-front-tunnel" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M2 22V12a10 10 0 1 1 20 0v10" /> <path d="M15 6.8v1.4a3 2.8 0 1 1-6 0V6.8" /> <path d="M10 15h.01" /> <path d="M14 15h.01" /> <path d="M10 19a4 4 0 0 1-4-4v-3a6 6 0 1 1 12 0v3a4 4 0 0 1-4 4Z" /> <path d="m9 19-2 3" /> <path d="m15 19 2 3" /> </svg>'
  },
  "train-track": {
    label: "Train Track",
    category: "transport",
    svg: '<svg class="lucide lucide-train-track" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M2 17 17 2" /> <path d="m2 14 8 8" /> <path d="m5 11 8 8" /> <path d="m8 8 8 8" /> <path d="m11 5 8 8" /> <path d="m14 2 8 8" /> <path d="M7 22 22 7" /> </svg>'
  },
  "tram-front": {
    label: "Tram Front",
    category: "transport",
    svg: '<svg class="lucide lucide-tram-front" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <rect width="16" height="16" x="4" y="3" rx="2" /> <path d="M4 11h16" /> <path d="M12 3v8" /> <path d="m8 19-2 3" /> <path d="m18 22-2-3" /> <path d="M8 15h.01" /> <path d="M16 15h.01" /> </svg>'
  },
  "trash-2": {
    label: "Trash 2",
    category: "general",
    svg: '<svg class="lucide lucide-trash-2" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M3 6h18" /> <path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6" /> <path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2" /> <line x1="10" x2="10" y1="11" y2="17" /> <line x1="14" x2="14" y1="11" y2="17" /> </svg>'
  },
  "tree-deciduous": {
    label: "Tree Deciduous",
    category: "activity",
    svg: '<svg class="lucide lucide-tree-deciduous" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M8 19a4 4 0 0 1-2.24-7.32A3.5 3.5 0 0 1 9 6.03V6a3 3 0 1 1 6 0v.04a3.5 3.5 0 0 1 3.24 5.65A4 4 0 0 1 16 19Z" /> <path d="M12 19v3" /> </svg>'
  },
  "tree-pine": {
    label: "Tree Pine",
    category: "activity",
    svg: '<svg class="lucide lucide-tree-pine" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="m17 14 3 3.3a1 1 0 0 1-.7 1.7H4.7a1 1 0 0 1-.7-1.7L7 14h-.3a1 1 0 0 1-.7-1.7L9 9h-.2A1 1 0 0 1 8 7.3L12 3l4 4.3a1 1 0 0 1-.8 1.7H15l3 3.3a1 1 0 0 1-.7 1.7H17Z" /> <path d="M12 22v-3" /> </svg>'
  },
  trees,
  trophy,
  truck,
  umbrella,
  usb,
  users,
  utensils,
  video,
  volcano,
  volleyball,
  wallet,
  watch,
  waves,
  "waves-ladder": {
    label: "Waves Ladder",
    category: "activity",
    svg: '<svg class="lucide lucide-waves-ladder" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <path d="M19 5a2 2 0 0 0-2 2v11" /> <path d="M2 18c.6.5 1.2 1 2.5 1 2.5 0 2.5-2 5-2 2.6 0 2.4 2 5 2 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1" /> <path d="M7 13h10" /> <path d="M7 9h10" /> <path d="M9 5a2 2 0 0 0-2 2v11" /> </svg>'
  },
  webcam,
  weight,
  wheat,
  wifi,
  wind,
  wine,
  "wine-glass": {
    label: "Wine Glass",
    category: "food",
    svg: '<svg stroke-linejoin="round" stroke-linecap="round" stroke-width="2" width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path d="M8 22h8"/><path d="M12 17v5"/><path d="M5 3h14"/><path d="M19 3a7 7 0 0 1-14 0"/></svg>'
  },
  wrench,
  x: x$1,
  zap
};
function getIconOptions() {
  const m = yatraIconsManifest;
  const slugToLabel = (slug) => slug.split(/[-_\s]+/).filter(Boolean).map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(" ");
  return Object.entries(m).map(([name, meta]) => {
    const safeMeta = meta || {};
    return {
      name,
      label: typeof safeMeta.label === "string" && safeMeta.label.length > 0 ? safeMeta.label : slugToLabel(name),
      category: typeof safeMeta.category === "string" && safeMeta.category.length > 0 ? safeMeta.category : "general",
      svg: safeMeta.svg || ""
    };
  });
}
function getYatraIconSvg(slug) {
  var _a;
  const m = yatraIconsManifest;
  return ((_a = m[slug]) == null ? void 0 : _a.svg) ?? null;
}
const solid = [
  "0",
  "1",
  "2",
  "3",
  "4",
  "5",
  "6",
  "7",
  "8",
  "9",
  "a",
  "address-book",
  "address-card",
  "align-center",
  "align-justify",
  "align-left",
  "align-right",
  "anchor",
  "anchor-circle-check",
  "anchor-circle-exclamation",
  "anchor-circle-xmark",
  "anchor-lock",
  "angle-down",
  "angle-left",
  "angle-right",
  "angle-up",
  "angles-down",
  "angles-left",
  "angles-right",
  "angles-up",
  "ankh",
  "apple-whole",
  "archway",
  "arrow-down",
  "arrow-down-1-9",
  "arrow-down-9-1",
  "arrow-down-a-z",
  "arrow-down-long",
  "arrow-down-short-wide",
  "arrow-down-up-across-line",
  "arrow-down-up-lock",
  "arrow-down-wide-short",
  "arrow-down-z-a",
  "arrow-left",
  "arrow-left-long",
  "arrow-pointer",
  "arrow-right",
  "arrow-right-arrow-left",
  "arrow-right-from-bracket",
  "arrow-right-long",
  "arrow-right-to-bracket",
  "arrow-right-to-city",
  "arrow-rotate-left",
  "arrow-rotate-right",
  "arrow-trend-down",
  "arrow-trend-up",
  "arrow-turn-down",
  "arrow-turn-up",
  "arrow-up",
  "arrow-up-1-9",
  "arrow-up-9-1",
  "arrow-up-a-z",
  "arrow-up-from-bracket",
  "arrow-up-from-ground-water",
  "arrow-up-from-water-pump",
  "arrow-up-long",
  "arrow-up-right-dots",
  "arrow-up-right-from-square",
  "arrow-up-short-wide",
  "arrow-up-wide-short",
  "arrow-up-z-a",
  "arrows-down-to-line",
  "arrows-down-to-people",
  "arrows-left-right",
  "arrows-left-right-to-line",
  "arrows-rotate",
  "arrows-spin",
  "arrows-split-up-and-left",
  "arrows-to-circle",
  "arrows-to-dot",
  "arrows-to-eye",
  "arrows-turn-right",
  "arrows-turn-to-dots",
  "arrows-up-down",
  "arrows-up-down-left-right",
  "arrows-up-to-line",
  "asterisk",
  "at",
  "atom",
  "audio-description",
  "austral-sign",
  "award",
  "b",
  "baby",
  "baby-carriage",
  "backward",
  "backward-fast",
  "backward-step",
  "bacon",
  "bacteria",
  "bacterium",
  "bag-shopping",
  "bahai",
  "baht-sign",
  "ban",
  "ban-smoking",
  "bandage",
  "bangladeshi-taka-sign",
  "barcode",
  "bars",
  "bars-progress",
  "bars-staggered",
  "baseball",
  "baseball-bat-ball",
  "basket-shopping",
  "basketball",
  "bath",
  "battery-empty",
  "battery-full",
  "battery-half",
  "battery-quarter",
  "battery-three-quarters",
  "bed",
  "bed-pulse",
  "beer-mug-empty",
  "bell",
  "bell-concierge",
  "bell-slash",
  "bezier-curve",
  "bicycle",
  "binoculars",
  "biohazard",
  "bitcoin-sign",
  "blender",
  "blender-phone",
  "blog",
  "bold",
  "bolt",
  "bolt-lightning",
  "bomb",
  "bone",
  "bong",
  "book",
  "book-atlas",
  "book-bible",
  "book-bookmark",
  "book-journal-whills",
  "book-medical",
  "book-open",
  "book-open-reader",
  "book-quran",
  "book-skull",
  "book-tanakh",
  "bookmark",
  "border-all",
  "border-none",
  "border-top-left",
  "bore-hole",
  "bottle-droplet",
  "bottle-water",
  "bowl-food",
  "bowl-rice",
  "bowling-ball",
  "box",
  "box-archive",
  "box-open",
  "box-tissue",
  "boxes-packing",
  "boxes-stacked",
  "braille",
  "brain",
  "brazilian-real-sign",
  "bread-slice",
  "bridge",
  "bridge-circle-check",
  "bridge-circle-exclamation",
  "bridge-circle-xmark",
  "bridge-lock",
  "bridge-water",
  "briefcase",
  "briefcase-medical",
  "broom",
  "broom-ball",
  "brush",
  "bucket",
  "bug",
  "bug-slash",
  "bugs",
  "building",
  "building-circle-arrow-right",
  "building-circle-check",
  "building-circle-exclamation",
  "building-circle-xmark",
  "building-columns",
  "building-flag",
  "building-lock",
  "building-ngo",
  "building-shield",
  "building-un",
  "building-user",
  "building-wheat",
  "bullhorn",
  "bullseye",
  "burger",
  "burst",
  "bus",
  "bus-simple",
  "business-time",
  "c",
  "cable-car",
  "cake-candles",
  "calculator",
  "calendar",
  "calendar-check",
  "calendar-day",
  "calendar-days",
  "calendar-minus",
  "calendar-plus",
  "calendar-week",
  "calendar-xmark",
  "camera",
  "camera-retro",
  "camera-rotate",
  "campground",
  "candy-cane",
  "cannabis",
  "capsules",
  "car",
  "car-battery",
  "car-burst",
  "car-on",
  "car-rear",
  "car-side",
  "car-tunnel",
  "caravan",
  "caret-down",
  "caret-left",
  "caret-right",
  "caret-up",
  "carrot",
  "cart-arrow-down",
  "cart-flatbed",
  "cart-flatbed-suitcase",
  "cart-plus",
  "cart-shopping",
  "cash-register",
  "cat",
  "cedi-sign",
  "cent-sign",
  "certificate",
  "chair",
  "chalkboard",
  "chalkboard-user",
  "champagne-glasses",
  "charging-station",
  "chart-area",
  "chart-bar",
  "chart-column",
  "chart-diagram",
  "chart-gantt",
  "chart-line",
  "chart-pie",
  "chart-simple",
  "check",
  "check-double",
  "check-to-slot",
  "cheese",
  "chess",
  "chess-bishop",
  "chess-board",
  "chess-king",
  "chess-knight",
  "chess-pawn",
  "chess-queen",
  "chess-rook",
  "chevron-down",
  "chevron-left",
  "chevron-right",
  "chevron-up",
  "child",
  "child-combatant",
  "child-dress",
  "child-reaching",
  "children",
  "church",
  "circle",
  "circle-arrow-down",
  "circle-arrow-left",
  "circle-arrow-right",
  "circle-arrow-up",
  "circle-check",
  "circle-chevron-down",
  "circle-chevron-left",
  "circle-chevron-right",
  "circle-chevron-up",
  "circle-dollar-to-slot",
  "circle-dot",
  "circle-down",
  "circle-exclamation",
  "circle-h",
  "circle-half-stroke",
  "circle-info",
  "circle-left",
  "circle-minus",
  "circle-nodes",
  "circle-notch",
  "circle-pause",
  "circle-play",
  "circle-plus",
  "circle-question",
  "circle-radiation",
  "circle-right",
  "circle-stop",
  "circle-up",
  "circle-user",
  "circle-xmark",
  "city",
  "clapperboard",
  "clipboard",
  "clipboard-check",
  "clipboard-list",
  "clipboard-question",
  "clipboard-user",
  "clock",
  "clock-rotate-left",
  "clone",
  "closed-captioning",
  "cloud",
  "cloud-arrow-down",
  "cloud-arrow-up",
  "cloud-bolt",
  "cloud-meatball",
  "cloud-moon",
  "cloud-moon-rain",
  "cloud-rain",
  "cloud-showers-heavy",
  "cloud-showers-water",
  "cloud-sun",
  "cloud-sun-rain",
  "clover",
  "code",
  "code-branch",
  "code-commit",
  "code-compare",
  "code-fork",
  "code-merge",
  "code-pull-request",
  "coins",
  "colon-sign",
  "comment",
  "comment-dollar",
  "comment-dots",
  "comment-medical",
  "comment-nodes",
  "comment-slash",
  "comment-sms",
  "comments",
  "comments-dollar",
  "compact-disc",
  "compass",
  "compass-drafting",
  "compress",
  "computer",
  "computer-mouse",
  "cookie",
  "cookie-bite",
  "copy",
  "copyright",
  "couch",
  "cow",
  "credit-card",
  "crop",
  "crop-simple",
  "cross",
  "crosshairs",
  "crow",
  "crown",
  "crutch",
  "cruzeiro-sign",
  "cube",
  "cubes",
  "cubes-stacked",
  "d",
  "database",
  "delete-left",
  "democrat",
  "desktop",
  "dharmachakra",
  "diagram-next",
  "diagram-predecessor",
  "diagram-project",
  "diagram-successor",
  "diamond",
  "diamond-turn-right",
  "dice",
  "dice-d20",
  "dice-d6",
  "dice-five",
  "dice-four",
  "dice-one",
  "dice-six",
  "dice-three",
  "dice-two",
  "disease",
  "display",
  "divide",
  "dna",
  "dog",
  "dollar-sign",
  "dolly",
  "dong-sign",
  "door-closed",
  "door-open",
  "dove",
  "down-left-and-up-right-to-center",
  "down-long",
  "download",
  "dragon",
  "draw-polygon",
  "droplet",
  "droplet-slash",
  "drum",
  "drum-steelpan",
  "drumstick-bite",
  "dumbbell",
  "dumpster",
  "dumpster-fire",
  "dungeon",
  "e",
  "ear-deaf",
  "ear-listen",
  "earth-africa",
  "earth-americas",
  "earth-asia",
  "earth-europe",
  "earth-oceania",
  "egg",
  "eject",
  "elevator",
  "ellipsis",
  "ellipsis-vertical",
  "envelope",
  "envelope-circle-check",
  "envelope-open",
  "envelope-open-text",
  "envelopes-bulk",
  "equals",
  "eraser",
  "ethernet",
  "euro-sign",
  "exclamation",
  "expand",
  "explosion",
  "eye",
  "eye-dropper",
  "eye-low-vision",
  "eye-slash",
  "f",
  "face-angry",
  "face-dizzy",
  "face-flushed",
  "face-frown",
  "face-frown-open",
  "face-grimace",
  "face-grin",
  "face-grin-beam",
  "face-grin-beam-sweat",
  "face-grin-hearts",
  "face-grin-squint",
  "face-grin-squint-tears",
  "face-grin-stars",
  "face-grin-tears",
  "face-grin-tongue",
  "face-grin-tongue-squint",
  "face-grin-tongue-wink",
  "face-grin-wide",
  "face-grin-wink",
  "face-kiss",
  "face-kiss-beam",
  "face-kiss-wink-heart",
  "face-laugh",
  "face-laugh-beam",
  "face-laugh-squint",
  "face-laugh-wink",
  "face-meh",
  "face-meh-blank",
  "face-rolling-eyes",
  "face-sad-cry",
  "face-sad-tear",
  "face-smile",
  "face-smile-beam",
  "face-smile-wink",
  "face-surprise",
  "face-tired",
  "fan",
  "faucet",
  "faucet-drip",
  "fax",
  "feather",
  "feather-pointed",
  "ferry",
  "file",
  "file-arrow-down",
  "file-arrow-up",
  "file-audio",
  "file-circle-check",
  "file-circle-exclamation",
  "file-circle-minus",
  "file-circle-plus",
  "file-circle-question",
  "file-circle-xmark",
  "file-code",
  "file-contract",
  "file-csv",
  "file-excel",
  "file-export",
  "file-fragment",
  "file-half-dashed",
  "file-image",
  "file-import",
  "file-invoice",
  "file-invoice-dollar",
  "file-lines",
  "file-medical",
  "file-pdf",
  "file-pen",
  "file-powerpoint",
  "file-prescription",
  "file-shield",
  "file-signature",
  "file-video",
  "file-waveform",
  "file-word",
  "file-zipper",
  "fill",
  "fill-drip",
  "film",
  "filter",
  "filter-circle-dollar",
  "filter-circle-xmark",
  "fingerprint",
  "fire",
  "fire-burner",
  "fire-extinguisher",
  "fire-flame-curved",
  "fire-flame-simple",
  "fish",
  "fish-fins",
  "flag",
  "flag-checkered",
  "flag-usa",
  "flask",
  "flask-vial",
  "floppy-disk",
  "florin-sign",
  "folder",
  "folder-closed",
  "folder-minus",
  "folder-open",
  "folder-plus",
  "folder-tree",
  "font",
  "font-awesome",
  "football",
  "forward",
  "forward-fast",
  "forward-step",
  "franc-sign",
  "frog",
  "futbol",
  "g",
  "gamepad",
  "gas-pump",
  "gauge",
  "gauge-high",
  "gauge-simple",
  "gauge-simple-high",
  "gavel",
  "gear",
  "gears",
  "gem",
  "genderless",
  "ghost",
  "gift",
  "gifts",
  "glass-water",
  "glass-water-droplet",
  "glasses",
  "globe",
  "golf-ball-tee",
  "gopuram",
  "graduation-cap",
  "greater-than",
  "greater-than-equal",
  "grip",
  "grip-lines",
  "grip-lines-vertical",
  "grip-vertical",
  "group-arrows-rotate",
  "guarani-sign",
  "guitar",
  "gun",
  "h",
  "hammer",
  "hamsa",
  "hand",
  "hand-back-fist",
  "hand-dots",
  "hand-fist",
  "hand-holding",
  "hand-holding-dollar",
  "hand-holding-droplet",
  "hand-holding-hand",
  "hand-holding-heart",
  "hand-holding-medical",
  "hand-lizard",
  "hand-middle-finger",
  "hand-peace",
  "hand-point-down",
  "hand-point-left",
  "hand-point-right",
  "hand-point-up",
  "hand-pointer",
  "hand-scissors",
  "hand-sparkles",
  "hand-spock",
  "handcuffs",
  "hands",
  "hands-asl-interpreting",
  "hands-bound",
  "hands-bubbles",
  "hands-clapping",
  "hands-holding",
  "hands-holding-child",
  "hands-holding-circle",
  "hands-praying",
  "handshake",
  "handshake-angle",
  "handshake-simple",
  "handshake-simple-slash",
  "handshake-slash",
  "hanukiah",
  "hard-drive",
  "hashtag",
  "hat-cowboy",
  "hat-cowboy-side",
  "hat-wizard",
  "head-side-cough",
  "head-side-cough-slash",
  "head-side-mask",
  "head-side-virus",
  "heading",
  "headphones",
  "headphones-simple",
  "headset",
  "heart",
  "heart-circle-bolt",
  "heart-circle-check",
  "heart-circle-exclamation",
  "heart-circle-minus",
  "heart-circle-plus",
  "heart-circle-xmark",
  "heart-crack",
  "heart-pulse",
  "helicopter",
  "helicopter-symbol",
  "helmet-safety",
  "helmet-un",
  "hexagon-nodes",
  "hexagon-nodes-bolt",
  "highlighter",
  "hill-avalanche",
  "hill-rockslide",
  "hippo",
  "hockey-puck",
  "holly-berry",
  "horse",
  "horse-head",
  "hospital",
  "hospital-user",
  "hot-tub-person",
  "hotdog",
  "hotel",
  "hourglass",
  "hourglass-end",
  "hourglass-half",
  "hourglass-start",
  "house",
  "house-chimney",
  "house-chimney-crack",
  "house-chimney-medical",
  "house-chimney-user",
  "house-chimney-window",
  "house-circle-check",
  "house-circle-exclamation",
  "house-circle-xmark",
  "house-crack",
  "house-fire",
  "house-flag",
  "house-flood-water",
  "house-flood-water-circle-arrow-right",
  "house-laptop",
  "house-lock",
  "house-medical",
  "house-medical-circle-check",
  "house-medical-circle-exclamation",
  "house-medical-circle-xmark",
  "house-medical-flag",
  "house-signal",
  "house-tsunami",
  "house-user",
  "hryvnia-sign",
  "hurricane",
  "i",
  "i-cursor",
  "ice-cream",
  "icicles",
  "icons",
  "id-badge",
  "id-card",
  "id-card-clip",
  "igloo",
  "image",
  "image-portrait",
  "images",
  "inbox",
  "indent",
  "indian-rupee-sign",
  "industry",
  "infinity",
  "info",
  "italic",
  "j",
  "jar",
  "jar-wheat",
  "jedi",
  "jet-fighter",
  "jet-fighter-up",
  "joint",
  "jug-detergent",
  "k",
  "kaaba",
  "key",
  "keyboard",
  "khanda",
  "kip-sign",
  "kit-medical",
  "kitchen-set",
  "kiwi-bird",
  "l",
  "land-mine-on",
  "landmark",
  "landmark-dome",
  "landmark-flag",
  "language",
  "laptop",
  "laptop-code",
  "laptop-file",
  "laptop-medical",
  "lari-sign",
  "layer-group",
  "leaf",
  "left-long",
  "left-right",
  "lemon",
  "less-than",
  "less-than-equal",
  "life-ring",
  "lightbulb",
  "lines-leaning",
  "link",
  "link-slash",
  "lira-sign",
  "list",
  "list-check",
  "list-ol",
  "list-ul",
  "litecoin-sign",
  "location-arrow",
  "location-crosshairs",
  "location-dot",
  "location-pin",
  "location-pin-lock",
  "lock",
  "lock-open",
  "locust",
  "lungs",
  "lungs-virus",
  "m",
  "magnet",
  "magnifying-glass",
  "magnifying-glass-arrow-right",
  "magnifying-glass-chart",
  "magnifying-glass-dollar",
  "magnifying-glass-location",
  "magnifying-glass-minus",
  "magnifying-glass-plus",
  "manat-sign",
  "map",
  "map-location",
  "map-location-dot",
  "map-pin",
  "marker",
  "mars",
  "mars-and-venus",
  "mars-and-venus-burst",
  "mars-double",
  "mars-stroke",
  "mars-stroke-right",
  "mars-stroke-up",
  "martini-glass",
  "martini-glass-citrus",
  "martini-glass-empty",
  "mask",
  "mask-face",
  "mask-ventilator",
  "masks-theater",
  "mattress-pillow",
  "maximize",
  "medal",
  "memory",
  "menorah",
  "mercury",
  "message",
  "meteor",
  "microchip",
  "microphone",
  "microphone-lines",
  "microphone-lines-slash",
  "microphone-slash",
  "microscope",
  "mill-sign",
  "minimize",
  "minus",
  "mitten",
  "mobile",
  "mobile-button",
  "mobile-retro",
  "mobile-screen",
  "mobile-screen-button",
  "money-bill",
  "money-bill-1",
  "money-bill-1-wave",
  "money-bill-transfer",
  "money-bill-trend-up",
  "money-bill-wave",
  "money-bill-wheat",
  "money-bills",
  "money-check",
  "money-check-dollar",
  "monument",
  "moon",
  "mortar-pestle",
  "mosque",
  "mosquito",
  "mosquito-net",
  "motorcycle",
  "mound",
  "mountain",
  "mountain-city",
  "mountain-sun",
  "mug-hot",
  "mug-saucer",
  "music",
  "n",
  "naira-sign",
  "network-wired",
  "neuter",
  "newspaper",
  "not-equal",
  "notdef",
  "note-sticky",
  "notes-medical",
  "o",
  "object-group",
  "object-ungroup",
  "oil-can",
  "oil-well",
  "om",
  "otter",
  "outdent",
  "p",
  "pager",
  "paint-roller",
  "paintbrush",
  "palette",
  "pallet",
  "panorama",
  "paper-plane",
  "paperclip",
  "parachute-box",
  "paragraph",
  "passport",
  "paste",
  "pause",
  "paw",
  "peace",
  "pen",
  "pen-clip",
  "pen-fancy",
  "pen-nib",
  "pen-ruler",
  "pen-to-square",
  "pencil",
  "people-arrows",
  "people-carry-box",
  "people-group",
  "people-line",
  "people-pulling",
  "people-robbery",
  "people-roof",
  "pepper-hot",
  "percent",
  "person",
  "person-arrow-down-to-line",
  "person-arrow-up-from-line",
  "person-biking",
  "person-booth",
  "person-breastfeeding",
  "person-burst",
  "person-cane",
  "person-chalkboard",
  "person-circle-check",
  "person-circle-exclamation",
  "person-circle-minus",
  "person-circle-plus",
  "person-circle-question",
  "person-circle-xmark",
  "person-digging",
  "person-dots-from-line",
  "person-dress",
  "person-dress-burst",
  "person-drowning",
  "person-falling",
  "person-falling-burst",
  "person-half-dress",
  "person-harassing",
  "person-hiking",
  "person-military-pointing",
  "person-military-rifle",
  "person-military-to-person",
  "person-praying",
  "person-pregnant",
  "person-rays",
  "person-rifle",
  "person-running",
  "person-shelter",
  "person-skating",
  "person-skiing",
  "person-skiing-nordic",
  "person-snowboarding",
  "person-swimming",
  "person-through-window",
  "person-walking",
  "person-walking-arrow-loop-left",
  "person-walking-arrow-right",
  "person-walking-dashed-line-arrow-right",
  "person-walking-luggage",
  "person-walking-with-cane",
  "peseta-sign",
  "peso-sign",
  "phone",
  "phone-flip",
  "phone-slash",
  "phone-volume",
  "photo-film",
  "piggy-bank",
  "pills",
  "pizza-slice",
  "place-of-worship",
  "plane",
  "plane-arrival",
  "plane-circle-check",
  "plane-circle-exclamation",
  "plane-circle-xmark",
  "plane-departure",
  "plane-lock",
  "plane-slash",
  "plane-up",
  "plant-wilt",
  "plate-wheat",
  "play",
  "plug",
  "plug-circle-bolt",
  "plug-circle-check",
  "plug-circle-exclamation",
  "plug-circle-minus",
  "plug-circle-plus",
  "plug-circle-xmark",
  "plus",
  "plus-minus",
  "podcast",
  "poo",
  "poo-storm",
  "poop",
  "power-off",
  "prescription",
  "prescription-bottle",
  "prescription-bottle-medical",
  "print",
  "pump-medical",
  "pump-soap",
  "puzzle-piece",
  "q",
  "qrcode",
  "question",
  "quote-left",
  "quote-right",
  "r",
  "radiation",
  "radio",
  "rainbow",
  "ranking-star",
  "receipt",
  "record-vinyl",
  "rectangle-ad",
  "rectangle-list",
  "rectangle-xmark",
  "recycle",
  "registered",
  "repeat",
  "reply",
  "reply-all",
  "republican",
  "restroom",
  "retweet",
  "ribbon",
  "right-from-bracket",
  "right-left",
  "right-long",
  "right-to-bracket",
  "ring",
  "road",
  "road-barrier",
  "road-bridge",
  "road-circle-check",
  "road-circle-exclamation",
  "road-circle-xmark",
  "road-lock",
  "road-spikes",
  "robot",
  "rocket",
  "rotate",
  "rotate-left",
  "rotate-right",
  "route",
  "rss",
  "ruble-sign",
  "rug",
  "ruler",
  "ruler-combined",
  "ruler-horizontal",
  "ruler-vertical",
  "rupee-sign",
  "rupiah-sign",
  "s",
  "sack-dollar",
  "sack-xmark",
  "sailboat",
  "satellite",
  "satellite-dish",
  "scale-balanced",
  "scale-unbalanced",
  "scale-unbalanced-flip",
  "school",
  "school-circle-check",
  "school-circle-exclamation",
  "school-circle-xmark",
  "school-flag",
  "school-lock",
  "scissors",
  "screwdriver",
  "screwdriver-wrench",
  "scroll",
  "scroll-torah",
  "sd-card",
  "section",
  "seedling",
  "server",
  "shapes",
  "share",
  "share-from-square",
  "share-nodes",
  "sheet-plastic",
  "shekel-sign",
  "shield",
  "shield-cat",
  "shield-dog",
  "shield-halved",
  "shield-heart",
  "shield-virus",
  "ship",
  "shirt",
  "shoe-prints",
  "shop",
  "shop-lock",
  "shop-slash",
  "shower",
  "shrimp",
  "shuffle",
  "shuttle-space",
  "sign-hanging",
  "signal",
  "signature",
  "signs-post",
  "sim-card",
  "sink",
  "sitemap",
  "skull",
  "skull-crossbones",
  "slash",
  "sleigh",
  "sliders",
  "smog",
  "smoking",
  "snowflake",
  "snowman",
  "snowplow",
  "soap",
  "socks",
  "solar-panel",
  "sort",
  "sort-down",
  "sort-up",
  "spa",
  "spaghetti-monster-flying",
  "spell-check",
  "spider",
  "spinner",
  "splotch",
  "spoon",
  "spray-can",
  "spray-can-sparkles",
  "square",
  "square-arrow-up-right",
  "square-binary",
  "square-caret-down",
  "square-caret-left",
  "square-caret-right",
  "square-caret-up",
  "square-check",
  "square-envelope",
  "square-full",
  "square-h",
  "square-minus",
  "square-nfi",
  "square-parking",
  "square-pen",
  "square-person-confined",
  "square-phone",
  "square-phone-flip",
  "square-plus",
  "square-poll-horizontal",
  "square-poll-vertical",
  "square-root-variable",
  "square-rss",
  "square-share-nodes",
  "square-up-right",
  "square-virus",
  "square-xmark",
  "staff-snake",
  "stairs",
  "stamp",
  "stapler",
  "star",
  "star-and-crescent",
  "star-half",
  "star-half-stroke",
  "star-of-david",
  "star-of-life",
  "sterling-sign",
  "stethoscope",
  "stop",
  "stopwatch",
  "stopwatch-20",
  "store",
  "store-slash",
  "street-view",
  "strikethrough",
  "stroopwafel",
  "subscript",
  "suitcase",
  "suitcase-medical",
  "suitcase-rolling",
  "sun",
  "sun-plant-wilt",
  "superscript",
  "swatchbook",
  "synagogue",
  "syringe",
  "t",
  "table",
  "table-cells",
  "table-cells-column-lock",
  "table-cells-large",
  "table-cells-row-lock",
  "table-cells-row-unlock",
  "table-columns",
  "table-list",
  "table-tennis-paddle-ball",
  "tablet",
  "tablet-button",
  "tablet-screen-button",
  "tablets",
  "tachograph-digital",
  "tag",
  "tags",
  "tape",
  "tarp",
  "tarp-droplet",
  "taxi",
  "teeth",
  "teeth-open",
  "temperature-arrow-down",
  "temperature-arrow-up",
  "temperature-empty",
  "temperature-full",
  "temperature-half",
  "temperature-high",
  "temperature-low",
  "temperature-quarter",
  "temperature-three-quarters",
  "tenge-sign",
  "tent",
  "tent-arrow-down-to-line",
  "tent-arrow-left-right",
  "tent-arrow-turn-left",
  "tent-arrows-down",
  "tents",
  "terminal",
  "text-height",
  "text-slash",
  "text-width",
  "thermometer",
  "thumbs-down",
  "thumbs-up",
  "thumbtack",
  "thumbtack-slash",
  "ticket",
  "ticket-simple",
  "timeline",
  "toggle-off",
  "toggle-on",
  "toilet",
  "toilet-paper",
  "toilet-paper-slash",
  "toilet-portable",
  "toilets-portable",
  "toolbox",
  "tooth",
  "torii-gate",
  "tornado",
  "tower-broadcast",
  "tower-cell",
  "tower-observation",
  "tractor",
  "trademark",
  "traffic-light",
  "trailer",
  "train",
  "train-subway",
  "train-tram",
  "transgender",
  "trash",
  "trash-arrow-up",
  "trash-can",
  "trash-can-arrow-up",
  "tree",
  "tree-city",
  "triangle-exclamation",
  "trophy",
  "trowel",
  "trowel-bricks",
  "truck",
  "truck-arrow-right",
  "truck-droplet",
  "truck-fast",
  "truck-field",
  "truck-field-un",
  "truck-front",
  "truck-medical",
  "truck-monster",
  "truck-moving",
  "truck-pickup",
  "truck-plane",
  "truck-ramp-box",
  "tty",
  "turkish-lira-sign",
  "turn-down",
  "turn-up",
  "tv",
  "u",
  "umbrella",
  "umbrella-beach",
  "underline",
  "universal-access",
  "unlock",
  "unlock-keyhole",
  "up-down",
  "up-down-left-right",
  "up-long",
  "up-right-and-down-left-from-center",
  "up-right-from-square",
  "upload",
  "user",
  "user-astronaut",
  "user-check",
  "user-clock",
  "user-doctor",
  "user-gear",
  "user-graduate",
  "user-group",
  "user-injured",
  "user-large",
  "user-large-slash",
  "user-lock",
  "user-minus",
  "user-ninja",
  "user-nurse",
  "user-pen",
  "user-plus",
  "user-secret",
  "user-shield",
  "user-slash",
  "user-tag",
  "user-tie",
  "user-xmark",
  "users",
  "users-between-lines",
  "users-gear",
  "users-line",
  "users-rays",
  "users-rectangle",
  "users-slash",
  "users-viewfinder",
  "utensils",
  "v",
  "van-shuttle",
  "vault",
  "vector-square",
  "venus",
  "venus-double",
  "venus-mars",
  "vest",
  "vest-patches",
  "vial",
  "vial-circle-check",
  "vial-virus",
  "vials",
  "video",
  "video-slash",
  "vihara",
  "virus",
  "virus-covid",
  "virus-covid-slash",
  "virus-slash",
  "viruses",
  "voicemail",
  "volcano",
  "volleyball",
  "volume-high",
  "volume-low",
  "volume-off",
  "volume-xmark",
  "vr-cardboard",
  "w",
  "walkie-talkie",
  "wallet",
  "wand-magic",
  "wand-magic-sparkles",
  "wand-sparkles",
  "warehouse",
  "water",
  "water-ladder",
  "wave-square",
  "web-awesome",
  "weight-hanging",
  "weight-scale",
  "wheat-awn",
  "wheat-awn-circle-exclamation",
  "wheelchair",
  "wheelchair-move",
  "whiskey-glass",
  "wifi",
  "wind",
  "window-maximize",
  "window-minimize",
  "window-restore",
  "wine-bottle",
  "wine-glass",
  "wine-glass-empty",
  "won-sign",
  "worm",
  "wrench",
  "x",
  "x-ray",
  "xmark",
  "xmarks-lines",
  "y",
  "yen-sign",
  "yin-yang",
  "z"
];
const regular = [
  "address-book",
  "address-card",
  "bell",
  "bell-slash",
  "bookmark",
  "building",
  "calendar",
  "calendar-check",
  "calendar-days",
  "calendar-minus",
  "calendar-plus",
  "calendar-xmark",
  "chart-bar",
  "chess-bishop",
  "chess-king",
  "chess-knight",
  "chess-pawn",
  "chess-queen",
  "chess-rook",
  "circle",
  "circle-check",
  "circle-dot",
  "circle-down",
  "circle-left",
  "circle-pause",
  "circle-play",
  "circle-question",
  "circle-right",
  "circle-stop",
  "circle-up",
  "circle-user",
  "circle-xmark",
  "clipboard",
  "clock",
  "clone",
  "closed-captioning",
  "comment",
  "comment-dots",
  "comments",
  "compass",
  "copy",
  "copyright",
  "credit-card",
  "envelope",
  "envelope-open",
  "eye",
  "eye-slash",
  "face-angry",
  "face-dizzy",
  "face-flushed",
  "face-frown",
  "face-frown-open",
  "face-grimace",
  "face-grin",
  "face-grin-beam",
  "face-grin-beam-sweat",
  "face-grin-hearts",
  "face-grin-squint",
  "face-grin-squint-tears",
  "face-grin-stars",
  "face-grin-tears",
  "face-grin-tongue",
  "face-grin-tongue-squint",
  "face-grin-tongue-wink",
  "face-grin-wide",
  "face-grin-wink",
  "face-kiss",
  "face-kiss-beam",
  "face-kiss-wink-heart",
  "face-laugh",
  "face-laugh-beam",
  "face-laugh-squint",
  "face-laugh-wink",
  "face-meh",
  "face-meh-blank",
  "face-rolling-eyes",
  "face-sad-cry",
  "face-sad-tear",
  "face-smile",
  "face-smile-beam",
  "face-smile-wink",
  "face-surprise",
  "face-tired",
  "file",
  "file-audio",
  "file-code",
  "file-excel",
  "file-image",
  "file-lines",
  "file-pdf",
  "file-powerpoint",
  "file-video",
  "file-word",
  "file-zipper",
  "flag",
  "floppy-disk",
  "folder",
  "folder-closed",
  "folder-open",
  "font-awesome",
  "futbol",
  "gem",
  "hand",
  "hand-back-fist",
  "hand-lizard",
  "hand-peace",
  "hand-point-down",
  "hand-point-left",
  "hand-point-right",
  "hand-point-up",
  "hand-pointer",
  "hand-scissors",
  "hand-spock",
  "handshake",
  "hard-drive",
  "heart",
  "hospital",
  "hourglass",
  "hourglass-half",
  "id-badge",
  "id-card",
  "image",
  "images",
  "keyboard",
  "lemon",
  "life-ring",
  "lightbulb",
  "map",
  "message",
  "money-bill-1",
  "moon",
  "newspaper",
  "note-sticky",
  "object-group",
  "object-ungroup",
  "paper-plane",
  "paste",
  "pen-to-square",
  "rectangle-list",
  "rectangle-xmark",
  "registered",
  "share-from-square",
  "snowflake",
  "square",
  "square-caret-down",
  "square-caret-left",
  "square-caret-right",
  "square-caret-up",
  "square-check",
  "square-full",
  "square-minus",
  "square-plus",
  "star",
  "star-half",
  "star-half-stroke",
  "sun",
  "thumbs-down",
  "thumbs-up",
  "trash-can",
  "user",
  "window-maximize",
  "window-minimize",
  "window-restore"
];
const faManifest = {
  solid,
  regular
};
const manifest = faManifest;
function humanizeIconName(iconName) {
  return iconName.split("-").filter(Boolean).map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(" ");
}
function toPickerItems(names, style) {
  return names.map((name) => ({
    name,
    label: humanizeIconName(name),
    style
  }));
}
const FA_FREE_SOLID_PICKER = toPickerItems(
  manifest.solid,
  "fa-solid"
);
const FA_FREE_REGULAR_PICKER = toPickerItems(
  manifest.regular,
  "fa-regular"
);
[
  ...FA_FREE_SOLID_PICKER,
  ...FA_FREE_REGULAR_PICKER
];
const FA_SOLID_NAME_SET = new Set(manifest.solid);
const FA_REGULAR_NAME_SET = new Set(manifest.regular);
const IconSelector = ({
  iconName,
  provider = "yatra",
  className = "w-5 h-5",
  size
}) => {
  const sizeStyle = size !== void 0 ? {
    fontSize: size,
    width: size,
    height: size,
    lineHeight: 1,
    display: "inline-flex",
    alignItems: "center",
    justifyContent: "center"
  } : void 0;
  if (provider === "fa-solid" || provider === "fa-regular") {
    const ok = provider === "fa-regular" ? FA_REGULAR_NAME_SET.has(iconName) : FA_SOLID_NAME_SET.has(iconName);
    if (ok) {
      const prefix2 = provider === "fa-regular" ? "fa-regular" : "fa-solid";
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        "i",
        {
          className: `${prefix2} fa-${iconName} ${className}`,
          style: sizeStyle,
          "aria-hidden": "true"
        }
      );
    }
    return /* @__PURE__ */ jsxRuntimeExports.jsx(Package, { className, style: sizeStyle });
  }
  const svg = getYatraIconSvg(iconName);
  if (svg) {
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "span",
      {
        className: `inline-flex items-center justify-center ${className}`,
        dangerouslySetInnerHTML: { __html: svg },
        style: sizeStyle
      }
    );
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsx(Package, { className, style: sizeStyle });
};
function isPickerValue(value) {
  return typeof value === "object" && value !== null && "type" in value && "value" in value;
}
const attachmentUrlCache = /* @__PURE__ */ new Map();
const attachmentUrlInFlight = /* @__PURE__ */ new Map();
function resolveAttachmentUrl(id) {
  var _a, _b;
  const cached = attachmentUrlCache.get(id);
  if (cached !== void 0) return Promise.resolve(cached);
  const pending = attachmentUrlInFlight.get(id);
  if (pending) return pending;
  const apiUrl = ((_b = (_a = window.yatraAdmin) == null ? void 0 : _a.apiUrl) == null ? void 0 : _b.replace("/yatra/v1", "")) ?? "";
  if (!apiUrl) return Promise.resolve("");
  const promise = fetch(`${apiUrl}/wp/v2/media/${id}`).then((r2) => r2.json()).then((data) => {
    const url = (data == null ? void 0 : data.source_url) ?? "";
    if (url) attachmentUrlCache.set(id, url);
    return url;
  }).catch(() => "").finally(() => {
    attachmentUrlInFlight.delete(id);
  });
  attachmentUrlInFlight.set(id, promise);
  return promise;
}
const ImageOverride = ({
  value,
  className
}) => {
  const initial = value.startsWith("http://") || value.startsWith("https://") || value.startsWith("/") ? value : attachmentUrlCache.get(value) ?? "";
  const [resolved, setResolved] = reactExports.useState(initial);
  reactExports.useEffect(() => {
    if (resolved) return;
    if (!/^\d+$/.test(value)) return;
    let cancelled = false;
    resolveAttachmentUrl(value).then((url) => {
      if (!cancelled && url) setResolved(url);
    });
    return () => {
      cancelled = true;
    };
  }, [value, resolved]);
  if (!resolved) return null;
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    "img",
    {
      src: resolved,
      alt: "",
      className: `${className} object-contain`,
      "aria-hidden": "true"
    }
  );
};
const MenuIcon = ({
  icon,
  fallback: Fallback,
  className = "h-4 w-4"
}) => {
  if (isPickerValue(icon)) {
    if (icon.type === "image" && icon.value) {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(ImageOverride, { value: icon.value, className });
    }
    if (icon.type === "icon" && icon.value) {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        IconSelector,
        {
          iconName: icon.value,
          provider: icon.provider ?? "yatra",
          className
        }
      );
    }
  }
  if (typeof icon === "string" && icon !== "" && ICON_MAP[icon]) {
    const Lucide = ICON_MAP[icon];
    return /* @__PURE__ */ jsxRuntimeExports.jsx(Lucide, { className });
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsx(Fallback, { className });
};
const Card = reactExports.forwardRef(
  ({ className = "", ...props }, ref) => /* @__PURE__ */ jsxRuntimeExports.jsx(
    "div",
    {
      ref,
      className: `rounded-lg border border-gray-100 dark:border-gray-700/50 bg-white dark:bg-gray-800 flex flex-col py-4 ${className}`,
      ...props
    }
  )
);
Card.displayName = "Card";
const CardHeader = reactExports.forwardRef(
  ({ className = "", ...props }, ref) => /* @__PURE__ */ jsxRuntimeExports.jsx(
    "div",
    {
      ref,
      className: `flex flex-col space-y-0.5 p-3 pb-2 border-b border-gray-100 dark:border-gray-700/50 ${className}`,
      ...props
    }
  )
);
CardHeader.displayName = "CardHeader";
const CardTitle = reactExports.forwardRef(({ className = "", ...props }, ref) => /* @__PURE__ */ jsxRuntimeExports.jsx(
  "h3",
  {
    ref,
    className: `text-base font-semibold text-gray-900 dark:text-white ${className}`,
    ...props
  }
));
CardTitle.displayName = "CardTitle";
const CardDescription = reactExports.forwardRef(({ className = "", ...props }, ref) => /* @__PURE__ */ jsxRuntimeExports.jsx(
  "p",
  {
    ref,
    className: `text-sm text-gray-500 dark:text-gray-400 ${className}`,
    ...props
  }
));
CardDescription.displayName = "CardDescription";
const CardContent = reactExports.forwardRef(
  ({ className = "", ...props }, ref) => /* @__PURE__ */ jsxRuntimeExports.jsx("div", { ref, className: `p-3 flex-1 ${className}`, ...props })
);
CardContent.displayName = "CardContent";
const CardFooter = reactExports.forwardRef(
  ({ className = "", ...props }, ref) => /* @__PURE__ */ jsxRuntimeExports.jsx(
    "div",
    {
      ref,
      className: `flex items-center p-6 pt-0 ${className}`,
      ...props
    }
  )
);
CardFooter.displayName = "CardFooter";
const Badge = reactExports.forwardRef(
  ({ className = "", variant = "default", ...props }, ref) => {
    const variantClasses = {
      default: "bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300",
      success: "bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400",
      warning: "bg-yellow-100 text-yellow-800 dark:bg-yellow-900/20 dark:text-yellow-400",
      error: "bg-red-100 text-red-800 dark:bg-red-900/20 dark:text-red-400",
      info: "bg-blue-100 text-blue-800 dark:bg-blue-900/20 dark:text-blue-400",
      outline: "border border-gray-300 dark:border-gray-600 bg-transparent text-gray-700 dark:text-gray-300"
    };
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "div",
      {
        ref,
        className: `inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${variantClasses[variant]} ${className}`,
        ...props
      }
    );
  }
);
Badge.displayName = "Badge";
const fetchModules = async () => {
  const response = await apiClient.get("/modules");
  if (Array.isArray(response)) {
    return response;
  }
  if (Array.isArray(response == null ? void 0 : response.data)) {
    return response.data;
  }
  return [];
};
const useModulesQuery = (options2) => {
  return useQuery({
    queryKey: ["modules"],
    queryFn: fetchModules,
    staleTime: 0,
    ...options2
  });
};
const formatNamesList = (names) => {
  if (names.length <= 2) {
    return names.join(", ");
  }
  return `${names.slice(0, 2).join(", ")} ${__("and", "yatra")} ${names.length - 2} ${__("more", "yatra")}`;
};
const useToggleModule = () => {
  const queryClient2 = useQueryClient();
  const { showToast } = useToast();
  return useMutation({
    mutationFn: async ({ slug, enabled }) => {
      const response = await apiClient.post(
        `/modules/${slug}/toggle`,
        { enabled }
      );
      return Array.isArray(response == null ? void 0 : response.data) ? response.data : [];
    },
    onSuccess: (data, variables) => {
      queryClient2.setQueryData(["modules"], data);
      if (window.yatraAdmin) {
        const enabledModules = data.filter((m) => m.enabled);
        window.yatraAdmin.emailAutomationEnabled = enabledModules.some(
          (m) => m.slug === "email_automation" || m.slug === "email-automation"
        );
        window.yatraAdmin.tripConsentEnabled = enabledModules.some(
          (m) => m.slug === "trip_consent" || m.slug === "trip-consent"
        );
        window.yatraAdmin.additionalServicesEnabled = enabledModules.some(
          (m) => m.slug === "additional_services" || m.slug === "additional-services"
        );
        window.yatraAdmin.abandonedBookingRecoveryEnabled = enabledModules.some(
          (m) => m.slug === "abandoned_booking_recovery" || m.slug === "abandoned-booking-recovery"
        );
        window.yatraAdmin.dynamicPricingEnabled = enabledModules.some(
          (m) => m.slug === "dynamic_pricing" || m.slug === "dynamic-pricing"
        );
        window.yatraAdmin.flexiblePaymentsEnabled = enabledModules.some(
          (m) => m.slug === "flexible_payments"
        );
        window.yatraAdmin.dynamicFormFieldEnabled = enabledModules.some(
          (m) => m.slug === "dynamic_form_field"
        );
        window.yatraAdmin.customLandingPagesModuleEnabled = enabledModules.some(
          (m) => m.slug === "custom_landing_pages"
        );
        window.yatraAdmin.showGoogleCalendarSettingsUI = enabledModules.some(
          (m) => m.slug === "google_calendar" || m.slug === "google-calendar"
        );
        window.yatraAdmin.advancedDiscountEnabled = enabledModules.some(
          (m) => m.slug === "advanced_discount" || m.slug === "advanced-discount"
        );
        window.yatraAdmin.aiAssistantEnabled = enabledModules.some(
          (m) => m.slug === "ai_assistant" || m.slug === "ai-assistant"
        );
        window.yatraAdmin.whiteLabelEnabled = enabledModules.some(
          (m) => m.slug === "white_label" || m.slug === "white-label"
        );
        window.yatraAdmin.whatsappEnabled = enabledModules.some(
          (m) => m.slug === "whatsapp"
        );
        window.yatraAdmin.channelManagerEnabled = enabledModules.some(
          (m) => m.slug === "channel_manager" || m.slug === "channel-manager"
        );
        window.yatraAdmin.webhooksEnabled = enabledModules.some(
          (m) => m.slug === "webhooks"
        );
        window.yatraAdmin.teamEnabled = enabledModules.some(
          (m) => m.slug === "team"
        );
        window.yatraAdmin.showMailchimpSettingsUI = enabledModules.some(
          (m) => m.slug === "mailchimp"
        );
        window.yatraAdmin.showFacebookPixelSettingsUI = enabledModules.some(
          (m) => m.slug === "facebook_pixel"
        );
        window.yatraAdmin.showGoogleAnalyticsSettingsUI = enabledModules.some(
          (m) => m.slug === "google_analytics"
        );
        window.dispatchEvent(
          new CustomEvent("yatra-modules-updated", {
            detail: {
              enabledModules,
              updatedModule: variables
            }
          })
        );
        const urlKey = window.__yatraUrlKey || 0;
        window.__yatraUrlKey = urlKey + 1;
        window.dispatchEvent(new CustomEvent("yatra-force-nav-refresh"));
      }
      const label = variables.name || variables.slug;
      showToast(
        variables.enabled ? __("{module} enabled successfully.", "yatra").replace(
          "{module}",
          label
        ) : __("{module} disabled successfully.", "yatra").replace(
          "{module}",
          label
        ),
        "success"
      );
    },
    onError: (error) => {
      showToast(
        error.message || __("Failed to update module.", "yatra"),
        "error"
      );
    }
  });
};
const useBulkToggleModules = () => {
  const queryClient2 = useQueryClient();
  const { showToast } = useToast();
  return useMutation({
    mutationFn: async (items) => {
      const response = await apiClient.post(
        "/modules/bulk-toggle",
        { items }
      );
      return Array.isArray(response == null ? void 0 : response.data) ? response.data : [];
    },
    onSuccess: (data, variables = [], context) => {
      queryClient2.setQueryData(["modules"], data);
      const response = context;
      if (response == null ? void 0 : response.message) {
        showToast(response.message, "warning");
      }
      if (window.yatraAdmin && data) {
        const enabledModules = data.filter((m) => m.enabled);
        window.yatraAdmin.emailAutomationEnabled = enabledModules.some(
          (m) => m.slug === "email_automation" || m.slug === "email-automation"
        );
        window.yatraAdmin.tripConsentEnabled = enabledModules.some(
          (m) => m.slug === "trip_consent" || m.slug === "trip-consent"
        );
        window.yatraAdmin.additionalServicesEnabled = enabledModules.some(
          (m) => m.slug === "additional_services" || m.slug === "additional-services"
        );
        window.yatraAdmin.abandonedBookingRecoveryEnabled = enabledModules.some(
          (m) => m.slug === "abandoned_booking_recovery" || m.slug === "abandoned-booking-recovery"
        );
        window.yatraAdmin.dynamicPricingEnabled = enabledModules.some(
          (m) => m.slug === "dynamic_pricing" || m.slug === "dynamic-pricing"
        );
        window.yatraAdmin.flexiblePaymentsEnabled = enabledModules.some(
          (m) => m.slug === "flexible_payments"
        );
        window.yatraAdmin.dynamicFormFieldEnabled = enabledModules.some(
          (m) => m.slug === "dynamic_form_field"
        );
        window.yatraAdmin.customLandingPagesModuleEnabled = enabledModules.some(
          (m) => m.slug === "custom_landing_pages"
        );
        window.yatraAdmin.showGoogleCalendarSettingsUI = enabledModules.some(
          (m) => m.slug === "google_calendar" || m.slug === "google-calendar"
        );
        window.yatraAdmin.advancedDiscountEnabled = enabledModules.some(
          (m) => m.slug === "advanced_discount" || m.slug === "advanced-discount"
        );
        window.yatraAdmin.aiAssistantEnabled = enabledModules.some(
          (m) => m.slug === "ai_assistant" || m.slug === "ai-assistant"
        );
        window.yatraAdmin.whiteLabelEnabled = enabledModules.some(
          (m) => m.slug === "white_label" || m.slug === "white-label"
        );
        window.yatraAdmin.whatsappEnabled = enabledModules.some(
          (m) => m.slug === "whatsapp"
        );
        window.yatraAdmin.channelManagerEnabled = enabledModules.some(
          (m) => m.slug === "channel_manager" || m.slug === "channel-manager"
        );
        window.yatraAdmin.webhooksEnabled = enabledModules.some(
          (m) => m.slug === "webhooks"
        );
        window.yatraAdmin.teamEnabled = enabledModules.some(
          (m) => m.slug === "team"
        );
        window.yatraAdmin.showMailchimpSettingsUI = enabledModules.some(
          (m) => m.slug === "mailchimp"
        );
        window.yatraAdmin.showFacebookPixelSettingsUI = enabledModules.some(
          (m) => m.slug === "facebook_pixel"
        );
        window.yatraAdmin.showGoogleAnalyticsSettingsUI = enabledModules.some(
          (m) => m.slug === "google_analytics"
        );
        window.dispatchEvent(
          new CustomEvent("yatra-modules-updated", {
            detail: {
              enabledModules,
              updatedModules: variables || []
            }
          })
        );
        const urlKey = window.__yatraUrlKey || 0;
        window.__yatraUrlKey = urlKey + 1;
        window.dispatchEvent(new CustomEvent("yatra-force-nav-refresh"));
      }
      if (!(response == null ? void 0 : response.message) && variables.length > 0) {
        const names = variables.map((item) => item.name || item.slug);
        const summary = formatNamesList(names);
        const message2 = variables[0].enabled ? __("Enabled: {modules}", "yatra").replace("{modules}", summary) : __("Disabled: {modules}", "yatra").replace("{modules}", summary);
        showToast(message2, "success");
      } else if (!(response == null ? void 0 : response.message)) {
        showToast(__("Modules updated successfully.", "yatra"), "success");
      }
    },
    onError: (error) => {
      showToast(
        error.message || __("Failed to update modules.", "yatra"),
        "error"
      );
    }
  });
};
const isProPluginActive = () => {
  var _a;
  const raw = (_a = window.yatraAdmin) == null ? void 0 : _a.isPro;
  let isPro = false;
  if (raw === true || raw === "true" || raw === 1 || raw === "1" || raw === "yes") {
    isPro = true;
  } else if (raw === false || raw === "false" || raw === 0 || raw === "0" || raw === "no") {
    isPro = false;
  }
  return isPro;
};
const isModuleActive = (moduleName) => {
  var _a;
  if (!isProPluginActive()) {
    return false;
  }
  if (!moduleName || typeof moduleName !== "string") {
    return false;
  }
  const camelCaseName = moduleName.replace(
    /_([a-z])/g,
    (_, letter) => letter.toUpperCase()
  );
  const localizedKey = camelCaseName + "Enabled";
  const raw = (_a = window.yatraAdmin) == null ? void 0 : _a[localizedKey];
  let isActive = false;
  if (raw === true || raw === "true" || raw === 1 || raw === "1" || raw === "yes") {
    isActive = true;
  } else if (raw === false || raw === "false" || raw === 0 || raw === "0" || raw === "no") {
    isActive = false;
  }
  return isActive;
};
const isEmailAutomationModuleEnabled = () => isModuleActive("email_automation");
function navigateMenu(subpage, tabOrParams) {
  const pathname = window.location.pathname;
  const page = new URLSearchParams(window.location.search).get("page") || "yatra";
  const sp = new URLSearchParams();
  sp.set("page", page);
  if (subpage === "dashboard") ;
  else {
    sp.set("subpage", subpage);
    if (typeof tabOrParams === "string") {
      if (tabOrParams !== "") {
        sp.set("tab", tabOrParams);
      }
    } else if (tabOrParams && typeof tabOrParams === "object") {
      Object.entries(tabOrParams).forEach(([key2, value]) => {
        if (value === void 0 || value === null || value === "") return;
        sp.set(key2, String(value));
      });
    }
  }
  const newUrl = `${pathname}?${sp.toString()}`;
  window.history.pushState({}, "", newUrl);
  window.dispatchEvent(new PopStateEvent("popstate"));
}
const useNavigate = () => {
  const navigate = (params) => {
    const urlParams = new URLSearchParams(window.location.search);
    const setParam = (key2, value) => {
      if (value === void 0 || value === null) {
        urlParams.delete(key2);
      } else {
        urlParams.set(key2, value.toString());
      }
    };
    const standardKeys = ["subpage", "tab", "action", "id"];
    standardKeys.forEach((key2) => {
      if (Object.prototype.hasOwnProperty.call(params, key2)) {
        setParam(key2, params[key2]);
      }
    });
    Object.keys(params).forEach((key2) => {
      if (!standardKeys.includes(key2)) {
        setParam(key2, params[key2]);
      }
    });
    const newUrl = `${window.location.pathname}?${urlParams.toString()}`;
    window.history.pushState({}, "", newUrl);
    window.dispatchEvent(new PopStateEvent("popstate"));
  };
  return { navigate, navigateMenu };
};
const subscribers = /* @__PURE__ */ new Set();
function getSnapshot() {
  const w = window.yatraAdmin;
  if (!w) return {};
  return {
    teamEnabled: w.teamEnabled,
    isWpAdmin: w.isWpAdmin,
    userCaps: w.userCaps,
    userScopes: w.userScopes
  };
}
function emit() {
  subscribers.forEach((cb) => cb());
}
function setUserCaps(caps) {
  if (window.yatraAdmin) {
    window.yatraAdmin.userCaps = [...caps];
    emit();
  }
}
function canCap(cap) {
  return evaluateCap(getSnapshot(), cap);
}
function evaluateCap(snapshot, cap) {
  if (!cap) return true;
  if (snapshot.isWpAdmin === true) return true;
  const caps = snapshot.userCaps;
  if (!Array.isArray(caps)) return true;
  return caps.includes(cap);
}
const InlineNotices = () => {
  const [notices, setNotices] = reactExports.useState([]);
  const load = reactExports.useCallback(async () => {
    try {
      const res = await apiService.getNotices();
      const data = res == null ? void 0 : res.data;
      setNotices(Array.isArray(data) ? data : []);
    } catch {
      setNotices([]);
    }
  }, []);
  reactExports.useEffect(() => {
    load();
  }, [load]);
  const dismiss = reactExports.useCallback(
    async (id) => {
      setNotices((prev) => prev.filter((n) => n.id !== id));
      try {
        await apiService.dismissNotice(id);
      } catch {
        load();
      }
    },
    [load]
  );
  if (notices.length === 0) {
    return null;
  }
  const renderUpgradeNotice = (n) => {
    const primary = Array.isArray(n.actions) ? n.actions[0] : void 0;
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "div",
      {
        className: "mx-6 mt-4 border border-amber-200/60 dark:border-amber-900/40 rounded-xl overflow-hidden bg-amber-50/60 dark:bg-amber-950/20 shadow-sm",
        children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "border-l-4 border-amber-400", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "p-4", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start justify-between gap-4", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start gap-3 min-w-0", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-9 h-9 rounded-lg bg-amber-100/70 dark:bg-amber-900/20 border border-amber-200/60 dark:border-amber-900/40 flex items-center justify-center shrink-0", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Crown, { className: "w-5 h-5 text-amber-700 dark:text-amber-300" }) }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "min-w-0", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "font-semibold text-gray-900 dark:text-gray-100", children: n.title || __("Upgrade to Pro", "yatra") }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-600 dark:text-gray-300 mt-1", children: n.message })
              ] })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3 shrink-0", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-[11px] font-bold px-2 py-0.5 rounded-full bg-amber-500 text-white", children: __("LIMITED TIME", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "button",
                {
                  type: "button",
                  onClick: () => dismiss(n.id),
                  className: "text-gray-400 hover:text-gray-700 dark:hover:text-gray-200",
                  "aria-label": __("Dismiss notice", "yatra"),
                  children: "×"
                }
              )
            ] })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-3 rounded-lg bg-amber-100/50 dark:bg-amber-900/15 border-l-4 border-amber-400 px-3 py-2 text-amber-800 dark:text-amber-200 text-sm font-medium flex items-center gap-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Zap, { className: "w-4 h-4" }),
            __(
              "Special Offer: Upgrade today and save 30%+ with premium features and priority support.",
              "yatra"
            )
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-4 flex items-center gap-3", children: [
            (primary == null ? void 0 : primary.url) && (primary == null ? void 0 : primary.label) && /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "a",
              {
                href: primary.url,
                target: primary.target,
                rel: primary.target === "_blank" ? "noopener noreferrer" : void 0,
                className: "inline-flex items-center gap-2 px-3 py-1.5 rounded-md bg-amber-500 hover:bg-amber-600 text-white text-xs font-semibold transition-colors",
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(Zap, { className: "w-4 h-4" }),
                  primary.label
                ]
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "button",
              {
                type: "button",
                onClick: () => dismiss(n.id),
                className: "text-sm text-gray-500 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-200",
                children: __("Maybe later", "yatra")
              }
            )
          ] })
        ] }) })
      },
      n.id
    );
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-3", children: notices.map((n) => {
    if (n.id === "buy_pro") {
      return renderUpgradeNotice(n);
    }
    const primary = Array.isArray(n.actions) ? n.actions[0] : void 0;
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "div",
      {
        className: "mx-6 mt-4 border border-gray-200 dark:border-gray-800 rounded-xl bg-white dark:bg-gray-900 shadow-sm",
        role: "status",
        "aria-live": "polite",
        children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "p-4 flex items-start justify-between gap-4", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start gap-3 min-w-0", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-10 h-10 rounded-lg bg-blue-50 dark:bg-blue-950/30 border border-blue-200/60 dark:border-blue-900/40 flex items-center justify-center shrink-0", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Star, { className: "w-5 h-5 text-blue-700 dark:text-blue-300" }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "min-w-0", children: [
              n.title && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "font-semibold text-gray-900 dark:text-gray-100", children: n.title }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-700 dark:text-gray-300 mt-1", children: n.message })
            ] })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3 shrink-0", children: [
            (primary == null ? void 0 : primary.url) && (primary == null ? void 0 : primary.label) && /* @__PURE__ */ jsxRuntimeExports.jsx(
              "a",
              {
                href: primary.url,
                target: primary.target,
                rel: primary.target === "_blank" ? "noopener noreferrer" : void 0,
                className: "inline-flex items-center px-3 py-1.5 rounded-md bg-blue-600 hover:bg-blue-700 text-white text-xs font-semibold transition-colors",
                children: primary.label
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "button",
              {
                type: "button",
                onClick: () => dismiss(n.id),
                className: "text-gray-400 hover:text-gray-700 dark:hover:text-gray-200",
                "aria-label": __("Dismiss notice", "yatra"),
                children: "×"
              }
            )
          ] })
        ] })
      },
      n.id
    );
  }) });
};
function extractGravatarUrl(avatarHtml, size) {
  if (!avatarHtml) {
    return `https://www.gravatar.com/avatar/00000000000000000000000000000000?s=${size}&d=identicon&r=pg`;
  }
  const imgMatch = avatarHtml.match(/<img[^>]+src=["']([^"']+)["']/i);
  if (imgMatch && imgMatch[1]) {
    return imgMatch[1].replace(/s=\d+/, `s=${size}`);
  }
  return `https://www.gravatar.com/avatar/00000000000000000000000000000000?s=${size}&d=identicon&r=pg`;
}
function getGravatarUrl(size) {
  var _a;
  const avatarHtml = ((_a = window == null ? void 0 : window.yatraAdmin) == null ? void 0 : _a.currentUserAvatar) || "";
  return extractGravatarUrl(avatarHtml, size);
}
const Layout = ({ children }) => {
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
  const [darkMode, setDarkMode] = reactExports.useState(() => {
    const saved = localStorage.getItem("yatra-dark-mode");
    return saved === "true";
  });
  reactExports.useEffect(() => {
    const root2 = document.documentElement;
    if (darkMode) {
      root2.classList.add("dark");
      localStorage.setItem("yatra-dark-mode", "true");
    } else {
      root2.classList.remove("dark");
      localStorage.setItem("yatra-dark-mode", "false");
    }
  }, [darkMode]);
  const [isModulesPanelOpen, setIsModulesPanelOpen] = reactExports.useState(false);
  const [isUserDropdownOpen, setIsUserDropdownOpen] = reactExports.useState(false);
  const modulesPanelRef = reactExports.useRef(null);
  const userDropdownRef = reactExports.useRef(null);
  const [licenseStatus, setLicenseStatus] = reactExports.useState(
    ((_a = window.yatraAdmin) == null ? void 0 : _a.licenseStatus) || null
  );
  const { showToast } = useToast();
  const flushRewriteRulesMutation = useMutation({
    mutationFn: async () => postFlushRewriteRules(),
    onSuccess: () => {
      showToast(__("Rewrite rules flushed successfully", "yatra"), "success");
    },
    onError: (error) => {
      showToast(
        (error == null ? void 0 : error.message) || __("Failed to flush rewrite rules", "yatra"),
        "error"
      );
    }
  });
  const { data: modulesData, isLoading: isLoadingModules } = useModulesQuery({
    enabled: isModulesPanelOpen
  });
  const toggleModuleMutation = useToggleModule();
  const safeModulesData = Array.isArray(modulesData) ? modulesData : [];
  const modulesPreview = reactExports.useMemo(
    () => safeModulesData.slice(0, 3),
    [safeModulesData]
  );
  const handleQuickToggle = (module, enabled) => {
    toggleModuleMutation.mutate({
      slug: module.slug,
      enabled,
      name: module.name
    });
  };
  const [urlKey, setUrlKey] = reactExports.useState(0);
  const [navRefreshKey, setNavRefreshKey] = reactExports.useState(0);
  const handleMenuNavClick = reactExports.useCallback(
    (e, subpage, tab) => {
      if (e.metaKey || e.ctrlKey || e.altKey || e.shiftKey || e.button !== 0) {
        return;
      }
      e.preventDefault();
      navigateMenu(subpage, tab);
    },
    []
  );
  reactExports.useEffect(() => {
    const handleClickOutside = (event) => {
      if (modulesPanelRef.current && !modulesPanelRef.current.contains(event.target)) {
        setIsModulesPanelOpen(false);
      }
      if (userDropdownRef.current && !userDropdownRef.current.contains(event.target)) {
        setIsUserDropdownOpen(false);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);
  reactExports.useEffect(() => {
    const handleLocationChange = () => {
      setUrlKey((prev) => prev + 1);
    };
    window.addEventListener("popstate", handleLocationChange);
    const interval = setInterval(() => {
      const currentSearch = window.location.search;
      if (currentSearch !== window.__lastSearch) {
        window.__lastSearch = currentSearch;
        handleLocationChange();
      }
    }, 100);
    return () => {
      window.removeEventListener("popstate", handleLocationChange);
      clearInterval(interval);
    };
  }, []);
  reactExports.useEffect(() => {
    const handleModuleUpdate = () => {
      setNavRefreshKey((prev) => prev + 1);
      setUrlKey((prev) => prev + 1);
    };
    const handleForceRefresh = () => {
      setNavRefreshKey((prev) => prev + 1);
      setUrlKey((prev) => prev + 1);
    };
    const handleLicenseStatusUpdate = (event) => {
      var _a2;
      const newStatus = (_a2 = event.detail) == null ? void 0 : _a2.status;
      if (newStatus) {
        setLicenseStatus(newStatus);
      }
    };
    window.addEventListener("yatra-modules-updated", handleModuleUpdate);
    window.addEventListener("yatra-force-nav-refresh", handleForceRefresh);
    window.addEventListener(
      "yatra-license-status-updated",
      handleLicenseStatusUpdate
    );
    return () => {
      window.removeEventListener("yatra-modules-updated", handleModuleUpdate);
      window.removeEventListener("yatra-force-nav-refresh", handleForceRefresh);
      window.removeEventListener(
        "yatra-license-status-updated",
        handleLicenseStatusUpdate
      );
    };
  }, []);
  reactExports.useEffect(() => {
    if (!isModulesPanelOpen) return;
    const handleClickOutside = (event) => {
      if (modulesPanelRef.current && !modulesPanelRef.current.contains(event.target)) {
        setIsModulesPanelOpen(false);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, [isModulesPanelOpen]);
  const currentSubpage = reactExports.useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get("subpage") || "dashboard";
  }, [urlKey]);
  const currentTab = reactExports.useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get("tab") || "all";
  }, [urlKey]);
  const currentAction = reactExports.useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get("action");
  }, [urlKey]);
  const isTripFormPage = reactExports.useMemo(() => {
    return currentSubpage === "trips" && (currentTab === "all" || !currentTab) && (currentAction === "create" || currentAction === "edit");
  }, [currentSubpage, currentTab, currentAction, urlKey]);
  const [expandedMenus, setExpandedMenus] = reactExports.useState(() => {
    const params = new URLSearchParams(window.location.search);
    const subpage = params.get("subpage") || "dashboard";
    const menus = [];
    if (subpage === "trips") {
      menus.push("trips");
    }
    if (subpage === "itinerary") {
      menus.push("itinerary");
    }
    return menus;
  });
  reactExports.useEffect(() => {
    const menusToExpand = [];
    if (currentSubpage === "trips") {
      menusToExpand.push("trips");
    }
    if (currentSubpage === "itinerary") {
      menusToExpand.push("itinerary");
    }
    setExpandedMenus((prev) => {
      const newMenus = [.../* @__PURE__ */ new Set([...prev, ...menusToExpand])];
      if (newMenus.length !== prev.length || !newMenus.every((m) => prev.includes(m))) {
        return newMenus;
      }
      return prev;
    });
  }, [currentSubpage, urlKey]);
  const baseUrl = reactExports.useMemo(() => {
    var _a2;
    return ((_a2 = window.yatraAdmin) == null ? void 0 : _a2.siteUrl) ? `${window.yatraAdmin.siteUrl}/wp-admin/admin.php?page=yatra` : "/wp-admin/admin.php?page=yatra";
  }, []);
  const menuItems = reactExports.useMemo(
    // Every menu label is wrapped in __() with a literal string so
    // gettext extraction (scripts/extract-js-pot.mjs) picks them up
    // and Loco / Poedit / wp i18n can translate them. Previously most
    // were raw English literals — translations existed in the .po but
    // never reached the UI because there was no translation lookup at
    // render time. Wrapping is the WordPress-canonical way; the
    // pre_load_script_translations filter then delivers the locale
    // data to wp.i18n on every admin page load.
    () => {
      var _a2, _b2, _c2, _d2, _e2, _f2, _g2, _h2, _i2, _j2, _k2, _l2;
      return [
        {
          subpage: "dashboard",
          label: __("Dashboard", "yatra"),
          icon: LayoutDashboard,
          cap: "yatra_access_admin"
        },
        {
          subpage: "trips",
          label: __("Trips", "yatra"),
          icon: MapPin,
          cap: "yatra_view_trips",
          submenu: [
            { tab: "all", label: __("All Trips", "yatra"), icon: List },
            {
              tab: "activities",
              label: __("Activities", "yatra"),
              icon: Activity
            },
            {
              tab: "destinations",
              label: __("Destinations", "yatra"),
              icon: Route
            },
            {
              tab: "categories",
              label: __("Categories", "yatra"),
              icon: FolderTree
            },
            {
              tab: "difficulty-levels",
              label: __("Difficulty Levels", "yatra"),
              icon: TrendingUp
            },
            // Availability - FREE feature, always show
            {
              tab: "availability",
              label: __("Availability", "yatra"),
              icon: CalendarDays
            },
            // Attributes - FREE feature, always show
            { tab: "attributes", label: __("Attributes", "yatra"), icon: Tag },
            // Additional Services - show only if Pro plugin is active and module is enabled
            ...isProPluginActive() && isModuleActive("additional_services") ? [
              {
                tab: "additional-services",
                label: __("Additional Services", "yatra"),
                icon: Package,
                isPremium: true
              }
            ] : [],
            // Trip Consent - show only if Pro plugin is active and module is enabled
            ...isProPluginActive() && isModuleActive("trip_consent") ? [
              {
                tab: "trip-consent",
                label: __("Trip Consent", "yatra"),
                icon: FileSignature,
                isPremium: true
              }
            ] : []
          ]
        },
        {
          subpage: "traveler-categories",
          label: __("Traveler Categories", "yatra"),
          icon: CircleUser,
          cap: "yatra_manage_trip_taxonomies"
        },
        {
          subpage: "itinerary",
          label: __("Itinerary", "yatra"),
          icon: FileText,
          cap: "yatra_edit_trips",
          submenu: [
            { tab: "item-types", label: __("Item Types", "yatra"), icon: Tag },
            { tab: "items", label: __("Items", "yatra"), icon: Route },
            {
              tab: "itinerary",
              label: __("Itinerary", "yatra"),
              icon: FileText
            }
          ]
        },
        // Departures - FREE feature, always show
        {
          subpage: "departures",
          label: __("Departures", "yatra"),
          icon: Calendar$1,
          cap: "yatra_view_departures"
        },
        {
          subpage: "discounts",
          label: __("Discounts", "yatra"),
          icon: BadgePercent,
          cap: "yatra_manage_discounts"
        },
        {
          subpage: "payments",
          label: __("Payments", "yatra"),
          icon: CreditCard,
          cap: "yatra_view_financial_reports"
        },
        {
          subpage: "bookings",
          label: __("Bookings", "yatra"),
          icon: Calendar$1,
          cap: "yatra_view_bookings"
        },
        {
          subpage: "customers",
          label: __("Customers", "yatra"),
          icon: CircleUser,
          cap: "yatra_view_customers"
        },
        {
          subpage: "travelers",
          label: __("Travelers", "yatra"),
          icon: Plane,
          cap: "yatra_view_customers"
        },
        {
          subpage: "enquiries",
          label: __("Enquiries", "yatra"),
          icon: MessageSquare,
          cap: "yatra_view_enquiries"
        },
        {
          subpage: "reviews",
          label: __("Reviews", "yatra"),
          icon: Star,
          cap: "yatra_view_reviews"
        },
        {
          subpage: "reports",
          label: __("Reports", "yatra"),
          icon: BarChart3,
          cap: "yatra_view_operational_reports"
        },
        // Email — SMTP & transactional for all; Pro adds automation tabs on the same screen
        {
          subpage: "email-automation",
          label: __("Email", "yatra"),
          icon: Mail,
          isPremium: false,
          cap: "yatra_manage_emails"
        },
        // Abandoned Booking Recovery - show only if Pro plugin is active and module is enabled
        ...isProPluginActive() && isModuleActive("abandoned_booking_recovery") ? [
          {
            subpage: "abandoned-recovery",
            label: __("Abandoned Recovery", "yatra"),
            icon: RotateCcw,
            isPremium: true,
            cap: "yatra_manage_email_automation"
          }
        ] : [],
        // Dynamic Pricing - show only if Pro plugin is active and module is enabled
        ...isProPluginActive() && isModuleActive("dynamic_pricing") ? [
          {
            subpage: "dynamic-pricing",
            label: __("Dynamic Pricing", "yatra"),
            icon: TrendingUp,
            isPremium: true,
            cap: "yatra_edit_trips"
          }
        ] : [],
        {
          subpage: "modules",
          label: __("Modules", "yatra"),
          icon: Puzzle,
          cap: "yatra_manage_modules"
        },
        // White Label — only when the Agency-tier module is actually enabled.
        // (Agency license alone is not enough; the module toggle must be on,
        // otherwise users would see a link to a disabled feature. To get
        // here for the first time, an Agency admin enables the module from
        // Yatra → Modules.) The `whiteLabelEnabled` flag from
        // AdminAssetsProvider already implies Agency-active.
        // White Label — needs Agency-tier license AND module toggle on.
        // Mirrors the AI Assistant gate below so both menus appear /
        // disappear instantly when their module toggles, while staying
        // license-safe if the client-side `whiteLabelEnabled` flag is
        // ever stale or over-eager. AdminAssetsProvider seeds both
        // `isAgency` and `whiteLabelEnabled`; useModules.ts updates the
        // latter on toggle and fires `yatra-modules-updated` which bumps
        // navRefreshKey → this memo recomputes → menu appears.
        ...((_a2 = window.yatraAdmin) == null ? void 0 : _a2.isAgency) && ((_b2 = window.yatraAdmin) == null ? void 0 : _b2.whiteLabelEnabled) ? [
          {
            subpage: "white-label",
            label: __("White Label", "yatra"),
            icon: Crown,
            isPremium: true,
            cap: "yatra_manage_white_label"
          }
        ] : [],
        // AI Assistant — only when BOTH the license tier qualifies
        // (Growth or Agency) AND the module toggle is on. Operators who
        // disable the module shouldn't keep seeing the menu item — it
        // would lead to a settings page they've explicitly opted out of.
        // The toggle handler in useModules.ts updates
        // window.yatraAdmin.aiAssistantEnabled and fires
        // `yatra-modules-updated`, which bumps navRefreshKey so this
        // memo recomputes immediately without a page reload.
        ...((_c2 = window.yatraAdmin) == null ? void 0 : _c2.isAiEligible) && ((_d2 = window.yatraAdmin) == null ? void 0 : _d2.aiAssistantEnabled) ? [
          {
            subpage: "ai-assistant",
            label: __("AI Assistant", "yatra"),
            icon: Sparkles,
            isPremium: true,
            cap: "yatra_manage_ai"
          }
        ] : [],
        // WhatsApp Notifications — Growth/Agency module. Same gate
        // pattern as AI Assistant: needs the AI-eligibility flag (which
        // is the Growth-or-Agency tier check) AND the module toggle on.
        // useModules.ts updates `whatsappEnabled` on toggle + fires
        // `yatra-modules-updated` so this menu appears instantly without
        // a page reload.
        ...((_e2 = window.yatraAdmin) == null ? void 0 : _e2.isAiEligible) && ((_f2 = window.yatraAdmin) == null ? void 0 : _f2.whatsappEnabled) ? [
          {
            subpage: "whatsapp",
            label: __("WhatsApp", "yatra"),
            icon: MessageCircle,
            isPremium: true,
            cap: "yatra_manage_whatsapp"
          }
        ] : [],
        // Channel Manager — Agency-tier OTA distribution hub. Same gate
        // pattern as White Label: needs the Agency license AND the module
        // toggle on. useModules.ts updates `channelManagerEnabled` on
        // toggle + fires `yatra-modules-updated` so this menu appears
        // instantly without a page reload.
        ...((_g2 = window.yatraAdmin) == null ? void 0 : _g2.isAgency) && ((_h2 = window.yatraAdmin) == null ? void 0 : _h2.channelManagerEnabled) ? [
          {
            subpage: "channel-manager",
            label: __("Channel Manager", "yatra"),
            icon: Network,
            isPremium: true,
            cap: "yatra_manage_channel_manager"
          }
        ] : [],
        // Webhooks — Agency-tier outbound integration hub. Same gate
        // as Channel Manager / White Label: Agency license + module on.
        ...((_i2 = window.yatraAdmin) == null ? void 0 : _i2.isAgency) && ((_j2 = window.yatraAdmin) == null ? void 0 : _j2.webhooksEnabled) ? [
          {
            subpage: "webhooks",
            label: __("Webhooks", "yatra"),
            icon: Webhook,
            isPremium: true,
            cap: "yatra_manage_webhooks"
          }
        ] : [],
        // Team & Access — Agency-tier granular roles + capability-level
        // access + audit log. Gate matches Webhooks: Agency license +
        // module on. The page itself is also cap-gated server-side; the
        // sidebar entry is just UX.
        ...((_k2 = window.yatraAdmin) == null ? void 0 : _k2.isAgency) && ((_l2 = window.yatraAdmin) == null ? void 0 : _l2.teamEnabled) ? [
          {
            subpage: "team",
            label: __("Team & Access", "yatra"),
            icon: Users,
            isPremium: true,
            cap: "yatra_manage_team"
          }
        ] : [],
        {
          subpage: "license",
          label: __("License", "yatra"),
          icon: Key,
          cap: "yatra_manage_settings"
        },
        {
          subpage: "settings",
          label: __("Settings", "yatra"),
          icon: Settings$1,
          cap: "yatra_manage_settings"
        }
      ].filter((item) => !item.cap || canCap(item.cap));
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [navRefreshKey]
  );
  const brandedMenuItems = reactExports.useMemo(() => {
    const overrides = readMenuOverrides();
    const orderMap = readMenuOrder();
    const atoms = [];
    const atomByKey = /* @__PURE__ */ new Map();
    const apply2 = (key2, defaultParent, base, fallbackLabel) => {
      const ov = overrides[key2];
      if (ov == null ? void 0 : ov.hidden) return null;
      const labelOverride = (ov == null ? void 0 : ov.label) && typeof ov.label === "string" && ov.label.trim() !== "" ? ov.label : null;
      const atom = {
        key: key2,
        defaultParent,
        label: labelOverride ?? fallbackLabel,
        iconOverride: ov == null ? void 0 : ov.icon,
        icon: base.icon,
        subpage: base.subpage ?? defaultParent ?? key2,
        tab: base.tab,
        isPremium: base.isPremium
      };
      atoms.push(atom);
      atomByKey.set(key2, atom);
      return atom;
    };
    for (const item of menuItems) {
      apply2(item.subpage, "", item, item.label);
      if (item.submenu) {
        for (const sub of item.submenu) {
          apply2(
            `${item.subpage}.${sub.tab}`,
            item.subpage,
            { icon: sub.icon, subpage: item.subpage, tab: sub.tab },
            sub.label
          );
        }
      }
    }
    const effectiveParent = (atom) => {
      var _a2;
      const ov = overrides[atom.key];
      if (ov && typeof ov.parent === "string") {
        if (ov.parent === "") return "";
        if (((_a2 = atomByKey.get(ov.parent)) == null ? void 0 : _a2.defaultParent) === "") return ov.parent;
      }
      return atom.defaultParent;
    };
    const groups = /* @__PURE__ */ new Map();
    for (const atom of atoms) {
      const parent = effectiveParent(atom);
      if (parent === atom.key) continue;
      const list = groups.get(parent) ?? [];
      list.push(atom);
      groups.set(parent, list);
    }
    const orderGroup = (parent, group) => {
      const saved = orderMap[parent] ?? [];
      if (saved.length === 0) return group;
      const byKey = new Map(group.map((a2) => [a2.key, a2]));
      const seen2 = /* @__PURE__ */ new Set();
      const ordered = [];
      for (const k2 of saved) {
        const atom = byKey.get(k2);
        if (atom && !seen2.has(k2)) {
          ordered.push(atom);
          seen2.add(k2);
        }
      }
      for (const atom of group) {
        if (!seen2.has(atom.key)) ordered.push(atom);
      }
      return ordered;
    };
    const topLevel = orderGroup("", groups.get("") ?? []);
    return topLevel.map((atom) => {
      const childAtoms = orderGroup(atom.key, groups.get(atom.key) ?? []);
      return {
        subpage: atom.subpage,
        label: atom.label,
        icon: atom.icon,
        iconOverride: atom.iconOverride,
        isPremium: atom.isPremium,
        submenu: childAtoms.length ? childAtoms.map((child) => ({
          // Submenu rendering supports both legacy intra-parent items
          // (matching parent's subpage) and promoted/demoted items
          // that point at their own subpage.
          tab: child.defaultParent === atom.subpage ? child.tab : void 0,
          label: child.label,
          icon: child.icon,
          iconOverride: child.iconOverride,
          // Promoted top-level items now-as-children get an absolute href.
          href: child.defaultParent === atom.subpage ? void 0 : `${baseUrl}&subpage=${child.subpage}${child.tab ? `&tab=${child.tab}` : ""}`,
          subpage: child.subpage,
          tab_orig: child.tab
        })) : void 0
      };
    });
  }, [menuItems, baseUrl]);
  const uiChrome = reactExports.useMemo(() => readUiChrome(), []);
  const isActive = (subpage, tab) => {
    if (tab) {
      return currentSubpage === subpage && currentTab === tab;
    }
    if (currentSubpage === subpage) {
      const menuItem = menuItems.find((item) => item.subpage === subpage);
      if (menuItem == null ? void 0 : menuItem.submenu) {
        return menuItem.submenu.some((sub) => sub.tab === currentTab);
      }
      return true;
    }
    return false;
  };
  const isMenuExpanded = (subpage) => {
    return expandedMenus.includes(subpage);
  };
  const toggleMenu = (subpage) => {
    setExpandedMenus(
      (prev) => prev.includes(subpage) ? prev.filter((m) => m !== subpage) : [...prev, subpage]
    );
  };
  const getUrl = (subpage, tab) => {
    if (subpage === "dashboard") {
      return baseUrl;
    }
    if (tab) {
      return `${baseUrl}&subpage=${subpage}&tab=${tab}`;
    }
    return `${baseUrl}&subpage=${subpage}`;
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    "div",
    {
      className: `min-h-screen ${darkMode ? "dark bg-gray-900" : "bg-gray-50"}`,
      children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex h-screen overflow-hidden", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("aside", { className: "w-64 bg-white dark:bg-gray-800 border-r border-gray-200 dark:border-gray-700 flex flex-col", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-16 px-6 flex items-center justify-center border-b border-gray-200 dark:border-gray-700", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex flex-col gap-1", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3", children: [
            (() => {
              var _a2, _b2;
              const brandName2 = ((_a2 = window.yatraAdmin) == null ? void 0 : _a2.brandName) || "Yatra";
              const brandInitial = brandName2.charAt(0).toUpperCase() || "Y";
              return ((_b2 = window.yatraAdmin) == null ? void 0 : _b2.brandLogoUrl) ? /* @__PURE__ */ jsxRuntimeExports.jsx(
                "img",
                {
                  src: window.yatraAdmin.brandLogoUrl,
                  alt: brandName2,
                  width: 32,
                  height: 32,
                  className: "w-8 h-8 rounded-lg object-contain shrink-0 bg-blue-600 p-1 border border-blue-700 dark:border-blue-500"
                }
              ) : /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-8 h-8 bg-blue-600 rounded-lg flex items-center justify-center shrink-0", children: /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-white font-bold text-lg", children: brandInitial }) });
            })(),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xl font-bold text-gray-900 dark:text-white", children: ((_b = window.yatraAdmin) == null ? void 0 : _b.brandName) || "Yatra" }),
              !uiChrome.hideVersion && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2 text-[10px] text-gray-500 dark:text-gray-400", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { children: [
                  "v",
                  ((_c = window.yatraAdmin) == null ? void 0 : _c.version) || "1.0.0"
                ] }),
                ((_d = window.yatraAdmin) == null ? void 0 : _d.proVersion) && /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "px-1.5 py-0.5 bg-green-100 dark:bg-green-900/30 text-green-600 dark:text-green-400 rounded font-medium", children: [
                  "Pro v",
                  (_e = window.yatraAdmin) == null ? void 0 : _e.proVersion
                ] })
              ] })
            ] })
          ] }) }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("nav", { className: "flex-1 p-4 space-y-1 overflow-y-auto", children: brandedMenuItems.map((item) => {
            const Icon = item.icon;
            const hasSubmenu = item.submenu && item.submenu.length > 0;
            const isExpanded = hasSubmenu && isMenuExpanded(item.subpage);
            const active = isActive(item.subpage);
            return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: hasSubmenu ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs(
                "button",
                {
                  onClick: () => toggleMenu(item.subpage),
                  className: `w-full flex items-center justify-between gap-3 px-4 py-3 rounded-lg text-sm transition-colors ${active ? "bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 font-medium" : "text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"}`,
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3", children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx(
                        MenuIcon,
                        {
                          icon: item.iconOverride,
                          fallback: Icon,
                          className: "w-5 h-5"
                        }
                      ),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: item.label })
                    ] }),
                    isExpanded ? /* @__PURE__ */ jsxRuntimeExports.jsx(ChevronDown, { className: "w-4 h-4" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(ChevronRight, { className: "w-4 h-4" })
                  ]
                }
              ),
              isExpanded && item.submenu && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "ml-4 mt-1 space-y-1", children: item.submenu.map((subItem) => {
                const navSubpage = subItem.subpage ?? item.subpage;
                const navTab = subItem.tab ?? subItem.tab_orig;
                const subActive = navTab ? isActive(navSubpage, navTab) : isActive(navSubpage);
                const SubIcon = subItem.icon;
                return /* @__PURE__ */ jsxRuntimeExports.jsxs(
                  "a",
                  {
                    href: getUrl(navSubpage, navTab),
                    onClick: (e) => handleMenuNavClick(e, navSubpage, navTab),
                    className: `flex items-center gap-3 px-4 py-2 rounded-lg transition-colors relative ${subActive ? "bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 font-medium" : "text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700"}`,
                    children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3", children: [
                        SubIcon && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-4 h-4", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                          MenuIcon,
                          {
                            icon: subItem.iconOverride,
                            fallback: SubIcon,
                            className: "w-4 h-4"
                          }
                        ) }),
                        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm", children: subItem.label })
                      ] }),
                      subItem.isPremium && !isProPluginActive() && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "absolute inset-y-0 right-2 flex items-center justify-center", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-4 h-4 rounded-full bg-gradient-to-r from-amber-500 to-orange-500 text-white flex items-center justify-center", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Crown, { className: "w-2.5 h-2.5" }) }) })
                    ]
                  },
                  `${navSubpage}.${navTab ?? ""}`
                );
              }) })
            ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "a",
              {
                href: getUrl(item.subpage),
                onClick: (e) => handleMenuNavClick(e, item.subpage),
                className: `flex items-center gap-3 px-4 py-3 rounded-lg text-sm transition-colors relative ${active ? "bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 font-medium" : "text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"}`,
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3", children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(
                      MenuIcon,
                      {
                        icon: item.iconOverride,
                        fallback: Icon,
                        className: "w-5 h-5"
                      }
                    ),
                    /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: item.label })
                  ] }),
                  item.isPremium && !isProPluginActive() && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "absolute inset-y-0 right-2 flex items-center justify-center", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-4 h-4 rounded-full bg-gradient-to-r from-amber-500 to-orange-500 text-white flex items-center justify-center", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Crown, { className: "w-2.5 h-2.5" }) }) }),
                  item.subpage === "license" && isProPluginActive() && licenseStatus && /* @__PURE__ */ jsxRuntimeExports.jsx(
                    Badge,
                    {
                      variant: licenseStatus === "active" ? "success" : licenseStatus === "expired" ? "error" : licenseStatus === "invalid" ? "error" : "error",
                      className: "text-[10px] px-2 py-0.5",
                      children: licenseStatus === "active" ? "Active" : licenseStatus === "expired" ? "Expired" : licenseStatus === "invalid" ? "Invalid" : "Inactive"
                    }
                  )
                ]
              }
            ) }, item.subpage);
          }) }),
          !isProPluginActive() && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "shrink-0 px-4 pb-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "a",
            {
              href: "https://wpyatra.com/pricing/",
              target: "_blank",
              rel: "noopener noreferrer",
              className: "group flex flex-col gap-0.5 rounded-lg border border-amber-200/90 dark:border-amber-800/40 bg-amber-50/60 dark:bg-amber-950/25 px-3 py-2.5 text-left transition-colors hover:bg-amber-50 dark:hover:bg-amber-950/40 focus:outline-none focus-visible:ring-2 focus-visible:ring-amber-500 focus-visible:ring-offset-2 focus-visible:ring-offset-white dark:focus-visible:ring-offset-gray-800",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "inline-flex items-center gap-1.5 text-xs font-semibold text-amber-900 dark:text-amber-200", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    Crown,
                    {
                      className: "w-3.5 h-3.5 shrink-0 text-amber-600 dark:text-amber-400",
                      "aria-hidden": true
                    }
                  ),
                  __("Upgrade to Pro", "yatra")
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-[11px] leading-snug text-amber-800/75 dark:text-amber-300/70", children: __("Premium features & integrations — view plans.", "yatra") })
              ]
            }
          ) }),
          !uiChrome.hideBackToWp && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "border-t border-gray-200 dark:border-gray-700 p-4", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            "a",
            {
              href: ((_f = window.yatraAdmin) == null ? void 0 : _f.siteUrl) ? `${window.yatraAdmin.siteUrl}/wp-admin/` : "/wp-admin/",
              className: "flex items-center justify-between gap-2 px-3 py-2 rounded-lg text-xs font-medium text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700",
              children: /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "inline-flex items-center gap-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowLeft, { className: "w-3 h-3" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: __("Back to WordPress", "yatra") })
              ] })
            }
          ) })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "div",
          {
            className: `flex-1 flex flex-col ${isTripFormPage ? "overflow-hidden" : "overflow-y-auto"}`,
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("header", { className: "h-16 bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 px-6 flex items-center", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between w-full", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3 flex-wrap min-w-0", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("h1", { className: "text-2xl font-semibold text-gray-900 dark:text-white", children: (() => {
                    if (isTripFormPage) {
                      return currentAction === "create" ? "Create Trip" : "Edit Trip";
                    }
                    const activeItem = brandedMenuItems.find(
                      (item) => isActive(item.subpage)
                    );
                    if ((activeItem == null ? void 0 : activeItem.submenu) && currentTab) {
                      const activeSubItem = activeItem.submenu.find(
                        (sub) => sub.tab === currentTab
                      );
                      return (activeSubItem == null ? void 0 : activeSubItem.label) || activeItem.label;
                    }
                    return (activeItem == null ? void 0 : activeItem.label) || "Dashboard";
                  })() }),
                  !isProPluginActive() && /* @__PURE__ */ jsxRuntimeExports.jsx(
                    Tooltip$1,
                    {
                      side: "bottom",
                      content: __(
                        "Spin up a free Pro trial site in one click — no credit card required.",
                        "yatra"
                      ),
                      children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
                        "a",
                        {
                          href: "https://try.wpyatra.com/try-yatra-pro/",
                          target: "_blank",
                          rel: "noopener noreferrer",
                          className: "inline-flex items-center gap-1.5 rounded-full bg-amber-50 px-3 py-1 text-xs font-semibold text-amber-900 ring-1 ring-amber-200 hover:bg-amber-100 hover:ring-amber-300 dark:bg-amber-950/40 dark:text-amber-100 dark:ring-amber-800 dark:hover:bg-amber-900/50 transition-colors",
                          children: [
                            /* @__PURE__ */ jsxRuntimeExports.jsx(Gift, { className: "h-3.5 w-3.5" }),
                            __("Try Yatra Pro for free", "yatra")
                          ]
                        }
                      )
                    }
                  )
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-4", children: [
                  !uiChrome.hideBackToWp && /* @__PURE__ */ jsxRuntimeExports.jsxs(
                    "a",
                    {
                      href: ((_g = window.yatraAdmin) == null ? void 0 : _g.siteUrl) ? `${window.yatraAdmin.siteUrl}/wp-admin/` : "/wp-admin/",
                      target: "_blank",
                      rel: "noopener noreferrer",
                      className: "inline-flex items-center gap-2 px-3 py-2 text-sm text-gray-600 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors",
                      children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowLeft, { className: "w-4 h-4" }),
                        __("Back to WordPress", "yatra")
                      ]
                    }
                  ),
                  !uiChrome.hideJoinCommunity && /* @__PURE__ */ jsxRuntimeExports.jsxs(
                    "a",
                    {
                      href: "https://www.facebook.com/groups/yatrawordpressplugin",
                      target: "_blank",
                      rel: "noopener noreferrer",
                      className: "inline-flex items-center gap-2 px-3 py-2 text-sm text-gray-600 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors",
                      children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsx(MessageSquare, { className: "w-4 h-4 shrink-0", "aria-hidden": true }),
                        __("Join Community", "yatra")
                      ]
                    }
                  ),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    Button,
                    {
                      type: "button",
                      variant: "outline",
                      size: "icon",
                      onClick: () => flushRewriteRulesMutation.mutate(),
                      disabled: flushRewriteRulesMutation.isPending,
                      className: "h-9 w-9 shrink-0 border-gray-300 dark:border-gray-600",
                      title: flushRewriteRulesMutation.isPending ? __("Flushing...", "yatra") : __("Flush permalink", "yatra"),
                      "aria-label": flushRewriteRulesMutation.isPending ? __("Flushing rewrite rules", "yatra") : __("Flush permalink", "yatra"),
                      children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                        RotateCcw,
                        {
                          className: `h-4 w-4 ${flushRewriteRulesMutation.isPending ? "animate-spin" : ""}`,
                          "aria-hidden": true
                        }
                      )
                    }
                  ),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_edit_trips", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
                    Button,
                    {
                      variant: currentSubpage === "tools" ? "default" : "outline",
                      onClick: () => {
                        navigateMenu("tools");
                      },
                      className: `flex items-center gap-2 ${currentSubpage === "tools" ? "bg-blue-600 hover:bg-blue-700 text-white border-blue-600" : ""}`,
                      children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsx(Wrench, { className: "w-4 h-4" }),
                        __("Tools", "yatra")
                      ]
                    }
                  ) }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_edit_trips", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative", children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "button",
                      {
                        onClick: () => setIsModulesPanelOpen((prev) => !prev),
                        className: `p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-600 dark:text-gray-400 ${isModulesPanelOpen ? "bg-gray-100 dark:bg-gray-700" : ""}`,
                        "aria-label": __("Toggle modules panel", "yatra"),
                        children: /* @__PURE__ */ jsxRuntimeExports.jsx(Puzzle, { className: "w-5 h-5" })
                      }
                    ),
                    isModulesPanelOpen && /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "div",
                      {
                        ref: modulesPanelRef,
                        className: "absolute right-0 top-12 z-50 w-80",
                        children: /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { className: "shadow-xl border border-gray-200 dark:border-gray-700", children: [
                          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
                            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                              /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Modules", "yatra") }),
                              /* @__PURE__ */ jsxRuntimeExports.jsx(CardDescription, { children: __(
                                "Quickly enable or disable feature packs.",
                                "yatra"
                              ) })
                            ] }),
                            /* @__PURE__ */ jsxRuntimeExports.jsx(
                              Button,
                              {
                                size: "sm",
                                variant: "ghost",
                                onClick: () => {
                                  setIsModulesPanelOpen(false);
                                  navigateMenu("modules");
                                },
                                children: __("Open", "yatra")
                              }
                            )
                          ] }) }),
                          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3", children: [
                            isLoadingModules && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2 text-gray-500 dark:text-gray-400 text-sm", children: [
                              /* @__PURE__ */ jsxRuntimeExports.jsx(Loader2, { className: "w-4 h-4 animate-spin" }),
                              __("Loading modules…", "yatra")
                            ] }),
                            !isLoadingModules && modulesPreview.length === 0 && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-500 dark:text-gray-400", children: __("No modules found.", "yatra") }),
                            !isLoadingModules && modulesPreview.length > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-3", children: modulesPreview.map((module) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
                              "div",
                              {
                                className: "flex items-center justify-between border border-gray-100 dark:border-gray-800 rounded-lg p-2",
                                children: [
                                  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                                    /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "text-sm font-medium text-gray-900 dark:text-white flex items-center gap-2", children: [
                                      module.name,
                                      module.is_core && /* @__PURE__ */ jsxRuntimeExports.jsx(
                                        Badge,
                                        {
                                          variant: "outline",
                                          className: "text-[10px]",
                                          children: __("Core", "yatra")
                                        }
                                      )
                                    ] }),
                                    /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400", children: module.enabled ? __("Enabled", "yatra") : __("Disabled", "yatra") })
                                  ] }),
                                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                                    "button",
                                    {
                                      onClick: () => handleQuickToggle(
                                        module,
                                        !module.enabled
                                      ),
                                      disabled: module.is_core || toggleModuleMutation.isPending,
                                      className: `relative inline-flex h-6 w-11 items-center rounded-full transition ${module.enabled ? "bg-blue-600" : "bg-gray-300 dark:bg-gray-600"} ${module.is_core ? "opacity-60 cursor-not-allowed" : "cursor-pointer"}`,
                                      "aria-pressed": module.enabled,
                                      "aria-label": module.enabled ? __("Disable module", "yatra") : __("Enable module", "yatra"),
                                      children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                                        "span",
                                        {
                                          className: `inline-block h-5 w-5 transform rounded-full bg-white transition ${module.enabled ? "translate-x-5" : "translate-x-1"}`
                                        }
                                      )
                                    }
                                  )
                                ]
                              },
                              module.slug
                            )) }),
                            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "pt-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                              Button,
                              {
                                variant: "outline",
                                size: "sm",
                                className: "w-full",
                                onClick: () => {
                                  setIsModulesPanelOpen(false);
                                  navigateMenu("modules");
                                },
                                children: __("Manage all modules", "yatra")
                              }
                            ) })
                          ] })
                        ] })
                      }
                    )
                  ] }) }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "button",
                    {
                      onClick: () => {
                        setDarkMode(!darkMode);
                      },
                      className: "p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-600 dark:text-gray-400",
                      "aria-label": darkMode ? "Switch to light mode" : "Switch to dark mode",
                      children: darkMode ? /* @__PURE__ */ jsxRuntimeExports.jsx(Sun, { className: "w-5 h-5" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(Moon, { className: "w-5 h-5" })
                    }
                  ),
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative", children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "button",
                      {
                        onClick: () => setIsUserDropdownOpen((prev) => !prev),
                        className: "flex items-center gap-3 pl-4 border-l border-gray-200 dark:border-gray-700 hover:bg-gray-100 dark:hover:bg-gray-700 p-2 transition-colors",
                        "aria-label": __("User menu", "yatra"),
                        children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-8 h-8 rounded-full overflow-hidden bg-gray-200 dark:bg-gray-700", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                          "img",
                          {
                            src: getGravatarUrl(32),
                            alt: __("User avatar", "yatra"),
                            className: "w-full h-full object-cover",
                            onError: (e) => {
                              e.currentTarget.style.display = "none";
                              e.currentTarget.parentElement.innerHTML = '<svg class="w-5 h-5 text-gray-600 dark:text-gray-400 m-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"></path></svg>';
                            }
                          }
                        ) })
                      }
                    ),
                    isUserDropdownOpen && /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "div",
                      {
                        ref: userDropdownRef,
                        className: "absolute right-0 top-12 z-50 w-64",
                        children: /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { className: "shadow-xl border border-gray-200 dark:border-gray-700", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "p-0", children: [
                          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "px-4 py-3 border-b border-gray-200 dark:border-gray-700", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3", children: [
                            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-10 h-10 rounded-full overflow-hidden bg-gray-200 dark:bg-gray-700", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                              "img",
                              {
                                src: getGravatarUrl(40),
                                alt: __("User avatar", "yatra"),
                                className: "w-full h-full object-cover",
                                onError: (e) => {
                                  e.currentTarget.style.display = "none";
                                  e.currentTarget.parentElement.innerHTML = '<svg class="w-6 h-6 text-gray-600 dark:text-gray-400 m-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"></path></svg>';
                                }
                              }
                            ) }),
                            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1 min-w-0", children: [
                              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm font-medium text-gray-900 dark:text-white truncate", children: ((_h = window == null ? void 0 : window.yatraAdmin) == null ? void 0 : _h.currentUserDisplayName) || ((_i = window == null ? void 0 : window.yatraAdmin) == null ? void 0 : _i.currentUserLogin) || "Admin" }),
                              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-xs text-gray-500 dark:text-gray-400 truncate", children: ((_j = window == null ? void 0 : window.yatraAdmin) == null ? void 0 : _j.currentUserEmail) || "" })
                            ] })
                          ] }) }),
                          /* @__PURE__ */ jsxRuntimeExports.jsxs(
                            "a",
                            {
                              href: `${((_k = window == null ? void 0 : window.yatraAdmin) == null ? void 0 : _k.siteUrl) || ""}/wp-admin/profile.php`,
                              target: "_blank",
                              rel: "noopener noreferrer",
                              className: "w-full text-left px-4 py-3 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 flex items-center gap-3 transition-colors",
                              children: [
                                /* @__PURE__ */ jsxRuntimeExports.jsx(User, { className: "w-4 h-4" }),
                                __("Edit Profile", "yatra")
                              ]
                            }
                          ),
                          /* @__PURE__ */ jsxRuntimeExports.jsxs(
                            "a",
                            {
                              href: `${((_l = window == null ? void 0 : window.yatraAdmin) == null ? void 0 : _l.siteUrl) || ""}/wp-admin/`,
                              target: "_blank",
                              rel: "noopener noreferrer",
                              className: "w-full text-left px-4 py-3 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 flex items-center gap-3 transition-colors",
                              children: [
                                /* @__PURE__ */ jsxRuntimeExports.jsx(
                                  "svg",
                                  {
                                    className: "w-4 h-4",
                                    fill: "none",
                                    stroke: "currentColor",
                                    viewBox: "0 0 24 24",
                                    children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                                      "path",
                                      {
                                        strokeLinecap: "round",
                                        strokeLinejoin: "round",
                                        strokeWidth: 2,
                                        d: "M10 19l-7-7m0 0l7-7m-7 7h18"
                                      }
                                    )
                                  }
                                ),
                                __("Back to WordPress", "yatra")
                              ]
                            }
                          ),
                          /* @__PURE__ */ jsxRuntimeExports.jsxs(
                            "button",
                            {
                              onClick: () => {
                                const admin = window == null ? void 0 : window.yatraAdmin;
                                const siteUrl = (admin == null ? void 0 : admin.siteUrl) || "";
                                window.location.href = `${siteUrl}/wp-login.php?action=logout`;
                              },
                              className: "w-full text-left px-4 py-3 text-sm text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-950/20 flex items-center gap-3 transition-colors",
                              children: [
                                /* @__PURE__ */ jsxRuntimeExports.jsx(
                                  "svg",
                                  {
                                    className: "w-4 h-4",
                                    fill: "none",
                                    stroke: "currentColor",
                                    viewBox: "0 0 24 24",
                                    children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                                      "path",
                                      {
                                        strokeLinecap: "round",
                                        strokeLinejoin: "round",
                                        strokeWidth: 2,
                                        d: "M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"
                                      }
                                    )
                                  }
                                ),
                                __("Logout", "yatra")
                              ]
                            }
                          )
                        ] }) })
                      }
                    )
                  ] })
                ] })
              ] }) }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(InlineNotices, {}),
              isProPluginActive() && licenseStatus && licenseStatus !== "active" && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "bg-red-50 dark:bg-red-950/30 border-l-4 border-b-2 border-red-500", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "px-6 py-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-4", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex-shrink-0", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-10 h-10 rounded-lg bg-red-500 flex items-center justify-center", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "svg",
                  {
                    className: "w-6 h-6 text-white",
                    fill: "currentColor",
                    viewBox: "0 0 20 20",
                    children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "path",
                      {
                        fillRule: "evenodd",
                        d: "M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z",
                        clipRule: "evenodd"
                      }
                    )
                  }
                ) }) }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex-1 min-w-0", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "text-sm font-medium text-red-800 dark:text-red-200", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-semibold", children: licenseStatus === "expired" ? "License Expired: " : licenseStatus === "invalid" ? "Invalid License: " : "License Not Activated: " }),
                  licenseStatus === "expired" ? "Renew your license to continue receiving updates and support." : licenseStatus === "invalid" ? "Please check your license key." : "Activate your license to receive updates and support."
                ] }) }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "a",
                  {
                    href: getUrl("license"),
                    onClick: (e) => handleMenuNavClick(e, "license"),
                    className: "flex-shrink-0 px-4 py-2 bg-red-600 hover:bg-red-700 text-white text-sm font-medium rounded-md transition-colors",
                    children: licenseStatus === "expired" ? "Renew Now" : "Activate Now"
                  }
                )
              ] }) }) }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "main",
                {
                  className: `flex-1 ${isTripFormPage ? "p-0 overflow-hidden flex flex-col" : "p-6 overflow-y-auto"}`,
                  children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "div",
                    {
                      className: isTripFormPage ? "flex-1 min-h-0 overflow-hidden flex flex-col" : currentSubpage === "tools" ? "" : "space-y-6",
                      children
                    }
                  )
                }
              )
            ]
          }
        )
      ] })
    }
  );
};
const Skeleton = ({ className = "" }) => {
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    "div",
    {
      className: `animate-pulse bg-gray-200 dark:bg-gray-700 rounded ${className}`
    }
  );
};
const aiApi = {
  meta: () => apiClient.get("/ai/meta"),
  generate: (task, context, options2 = {}) => apiClient.post("/ai/generate", {
    task,
    context,
    options: options2
  }),
  improve: (task, currentValue, options2 = {}) => apiClient.post("/ai/improve", {
    task,
    current_value: currentValue,
    options: options2
  }),
  getBrandVoice: () => apiClient.get("/ai/brand-voice"),
  saveBrandVoice: (data) => apiClient.put("/ai/brand-voice", data),
  setKey: (provider, apiKey) => apiClient.post(`/ai/keys/${encodeURIComponent(provider)}`, {
    api_key: apiKey
  }),
  deleteKey: (provider) => apiClient.delete(`/ai/keys/${encodeURIComponent(provider)}`),
  testKey: (provider) => apiClient.post(
    `/ai/keys/${encodeURIComponent(provider)}/test`,
    {}
  ),
  getUsage: () => apiClient.get("/ai/usage"),
  // Operations AI
  draftEnquiryReply: (enquiryId, opts = {}) => apiClient.post(
    `/ai/enquiry/${encodeURIComponent(String(enquiryId))}/draft-reply`,
    {
      variant: opts.variant ?? "fresh",
      current_value: opts.current_value ?? "",
      include_sensitive: opts.include_sensitive ?? false
    }
  ),
  getDashboardDigest: () => apiClient.get("/ai/dashboard/digest"),
  /**
   * AI customer summary — 3-line operator-facing snapshot
   * (status / history, last trip, operationally-relevant notes).
   * Sensitive fields (medical / dietary / notes) only flow when
   * `include_sensitive` is true.
   */
  getCustomerSummary: (customerId, includeSensitive = false) => apiClient.post(
    `/ai/customer/${encodeURIComponent(String(customerId))}/summary`,
    { include_sensitive: includeSensitive }
  ),
  refreshDashboardDigest: () => apiClient.post("/ai/dashboard/digest/refresh", {}),
  // Prompt overrides
  listPrompts: () => apiClient.get("/ai/prompts"),
  savePromptOverride: (task, override) => apiClient.put(
    `/ai/prompts/${encodeURIComponent(task)}`,
    override
  ),
  resetPrompt: (task) => apiClient.delete(`/ai/prompts/${encodeURIComponent(task)}`),
  resetAllPrompts: () => apiClient.delete("/ai/prompts"),
  // Public chat toggle
  setTripChatEnabled: (enabled) => apiClient.put("/ai/trip-chat-toggle", { enabled }),
  setTripChatLimits: (patch) => apiClient.put("/ai/trip-chat-limits", patch),
  /**
   * Trip Creation agent — generates every section in one coherent
   * agent run instead of N parallel single-shot calls. Replaces the
   * old fire-10-parallel-`generate()` design in the wizard.
   *
   * Response shape:
   *   { wizard_session_id, sections: { description, short_description,
   *     trip_details, what_makes_special, trip_story, highlights,
   *     included_items, excluded_items, cancellation_policy, faqs,
   *     itinerary, starting_location, ending_location,
   *     accommodation_type, meta_title, meta_description },
   *     missing[], tool_trace[], prompt_tokens, completion_tokens, … }
   */
  wizardCreateTrip: (setup) => apiClient.post("/ai/wizard/trip", { setup }),
  /**
   * Regenerate one wizard section, keeping the others. The agent
   * reads the existing sections so the new one stays consistent.
   */
  wizardRegenSection: (section, setup, sections, guidance = "") => apiClient.post("/ai/wizard/trip/section", {
    section,
    setup,
    sections,
    guidance
  }),
  /**
   * Generate a {subject, body} pair for an email template. Caller
   * passes the template_key + catalog metadata + the operator's
   * tone/extra-context. The agent references only the merge tags
   * supplied in `merge_tags`.
   */
  generateEmailTemplate: (request) => apiClient.post("/ai/email-template/generate", request),
  // Standalone itinerary builder
  draftItinerary: (tripId, extraContextOrSetup = "") => apiClient.post(
    `/ai/itinerary/${encodeURIComponent(String(tripId))}/draft`,
    typeof extraContextOrSetup === "string" ? { extra_context: extraContextOrSetup } : { setup: extraContextOrSetup }
  ),
  applyItinerary: (tripId, days, replace) => apiClient.post(
    `/ai/itinerary/${encodeURIComponent(String(tripId))}/apply`,
    {
      days,
      replace
    }
  )
};
function readAdmin() {
  return window.yatraAdmin ?? {};
}
function isAiReady() {
  const a2 = readAdmin();
  return Boolean(
    a2.isAiEligible && a2.aiAssistantEnabled && a2.aiAssistantConfigured
  );
}
function isAiEligible() {
  return Boolean(readAdmin().isAiEligible);
}
function isAiModuleEnabled() {
  return Boolean(readAdmin().aiAssistantEnabled);
}
const QUERY_KEY = ["ai-dashboard-digest"];
const TodaysBriefCard = () => {
  const queryClient2 = useQueryClient();
  const aiAvailable = isAiEligible() && isAiModuleEnabled();
  const { data, isLoading, isError } = useQuery({
    queryKey: QUERY_KEY,
    queryFn: () => aiApi.getDashboardDigest(),
    staleTime: 15 * 60 * 1e3,
    // matches server-side 30m cache; client refresh
    enabled: aiAvailable
  });
  const refresh = useMutation({
    mutationFn: () => aiApi.refreshDashboardDigest(),
    onSuccess: (resp) => {
      queryClient2.setQueryData(QUERY_KEY, resp);
    }
  });
  if (!aiAvailable) {
    return null;
  }
  if (isLoading) {
    return /* @__PURE__ */ jsxRuntimeExports.jsx(SkeletonCard, {});
  }
  const digest = data == null ? void 0 : data.data;
  if (!digest) {
    return null;
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mb-6 overflow-hidden rounded-lg border border-blue-200 bg-gradient-to-r from-blue-50 to-blue-50 shadow-sm dark:border-blue-500/40 dark:from-blue-900/20 dark:to-blue-900/20", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between px-5 py-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "rounded-md bg-blue-600 p-1.5 text-white", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Sparkles, { className: "h-4 w-4" }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm font-semibold text-gray-900 dark:text-white", children: __("Today's Brief", "yatra") }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-[11px] text-gray-500 dark:text-gray-400", children: digest.cached ? __(
            "Last updated a few minutes ago — refreshes when something material changes.",
            "yatra"
          ) : digest.generated_at ? __("Just now", "yatra") : __("Operations summary", "yatra") })
        ] })
      ] }),
      digest.state === "ready" && /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "button",
        {
          type: "button",
          onClick: () => refresh.mutate(),
          disabled: refresh.isPending,
          title: __("Regenerate brief", "yatra"),
          className: "inline-flex items-center gap-1 rounded-md border border-transparent bg-white/70 px-2 py-1 text-xs text-blue-700 hover:bg-white dark:bg-gray-800/70 dark:text-blue-300 dark:hover:bg-gray-800",
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              RefreshCw,
              {
                className: `h-3.5 w-3.5 ${refresh.isPending ? "animate-spin" : ""}`
              }
            ),
            __("Refresh", "yatra")
          ]
        }
      )
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-2 gap-2 px-5 pb-3 sm:grid-cols-4", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        MetricPill,
        {
          icon: Inbox,
          label: __("Unanswered enquiries", "yatra"),
          value: digest.metrics.enquiries_unresponded_count,
          tooltip: __(
            "How many enquiries are still waiting for a reply from the operator. Click to open the Enquiries list and respond.",
            "yatra"
          ),
          link: "admin.php?page=yatra&subpage=enquiries"
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        MetricPill,
        {
          icon: Mail,
          label: __("Longest wait (hrs)", "yatra"),
          value: digest.metrics.enquiries_oldest_waiting_hours,
          tooltip: __(
            "Hours the OLDEST unanswered enquiry has been waiting for a reply. A high number means at least one customer hasn't heard back for that long — answer it before it goes cold.",
            "yatra"
          ),
          tone: "amber"
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        MetricPill,
        {
          icon: CreditCard,
          label: __("Pending payments", "yatra"),
          value: digest.metrics.bookings_payment_pending_count,
          tooltip: __(
            "Bookings whose payment has not been received yet. Click to open the Payments page and follow up.",
            "yatra"
          ),
          link: "admin.php?page=yatra&subpage=payments"
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        MetricPill,
        {
          icon: Plane,
          label: __("Departing in 7d", "yatra"),
          value: digest.metrics.bookings_departing_soon_count,
          tooltip: __(
            "Bookings whose departure date falls within the next 7 days. Useful for last-minute prep — final reminders, group lists, paperwork.",
            "yatra"
          ),
          link: "admin.php?page=yatra&subpage=departures"
        }
      )
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "border-t border-blue-100 bg-white/40 px-5 py-3 dark:border-blue-500/30 dark:bg-gray-900/30", children: [
      isError && /* @__PURE__ */ jsxRuntimeExports.jsx(
        BriefError,
        {
          onRetry: () => refresh.mutate(),
          retrying: refresh.isPending
        }
      ),
      !isError && /* @__PURE__ */ jsxRuntimeExports.jsx(
        BriefBody,
        {
          digest,
          onRetry: () => refresh.mutate(),
          retrying: refresh.isPending
        }
      )
    ] })
  ] });
};
const BriefBody = ({ digest, onRetry, retrying }) => {
  if (digest.state === "all_caught_up") {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "text-sm text-emerald-700 dark:text-emerald-300", children: [
      "✓",
      " ",
      __(
        "You're caught up. Nothing urgent needs attention right now.",
        "yatra"
      )
    ] });
  }
  if (digest.state === "upgrade_required") {
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      CtaLine,
      {
        message: __(
          "Today's Brief is part of the AI Assistant module — available on Growth and Scale plans.",
          "yatra"
        ),
        href: "admin.php?page=yatra&subpage=license",
        label: __("View plans", "yatra")
      }
    );
  }
  if (digest.state === "no_api_key") {
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      CtaLine,
      {
        message: __(
          "Add an OpenAI or Anthropic key to unlock the AI summary. Numbers above don't need a key.",
          "yatra"
        ),
        href: "admin.php?page=yatra&subpage=ai-assistant",
        label: __("Open AI settings", "yatra")
      }
    );
  }
  if (digest.state === "error") {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start gap-2 text-sm text-red-700 dark:text-red-300", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(AlertTriangle, { className: "mt-0.5 h-4 w-4 shrink-0" }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
          __("Couldn't generate the brief.", "yatra"),
          " ",
          digest.error ? `(${digest.error})` : ""
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "button",
          {
            type: "button",
            onClick: onRetry,
            disabled: retrying,
            className: "mt-1 inline-flex items-center gap-1 rounded border border-red-200 px-2 py-0.5 text-xs hover:bg-red-50 dark:border-red-500/40 dark:hover:bg-red-900/20",
            children: retrying ? __("Retrying…", "yatra") : __("Retry", "yatra")
          }
        )
      ] })
    ] });
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "whitespace-pre-wrap text-sm leading-relaxed text-gray-800 dark:text-gray-200", children: digest.text || __("AI summary is empty for today — try refreshing.", "yatra") });
};
const BriefError = ({
  onRetry,
  retrying
}) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start gap-2 text-sm text-red-700 dark:text-red-300", children: [
  /* @__PURE__ */ jsxRuntimeExports.jsx(AlertTriangle, { className: "mt-0.5 h-4 w-4 shrink-0" }),
  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: __("Failed to load today's brief.", "yatra") }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      "button",
      {
        type: "button",
        onClick: onRetry,
        disabled: retrying,
        className: "mt-1 inline-flex items-center gap-1 rounded border border-red-200 px-2 py-0.5 text-xs hover:bg-red-50 dark:border-red-500/40 dark:hover:bg-red-900/20",
        children: retrying ? __("Retrying…", "yatra") : __("Retry", "yatra")
      }
    )
  ] })
] });
const CtaLine = ({
  message: message2,
  href,
  label
}) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-wrap items-center justify-between gap-2 text-sm text-gray-700 dark:text-gray-200", children: [
  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: message2 }),
  /* @__PURE__ */ jsxRuntimeExports.jsxs(
    "a",
    {
      href,
      className: "inline-flex items-center gap-1 rounded-md bg-blue-600 px-2 py-1 text-xs font-medium text-white hover:bg-blue-700",
      children: [
        label,
        /* @__PURE__ */ jsxRuntimeExports.jsx(ExternalLink, { className: "h-3 w-3" })
      ]
    }
  )
] });
const MetricPill = ({ icon: Icon, label, value, tone = "default", link: link2, tooltip }) => {
  const n = parseInt(value, 10);
  const safe = Number.isFinite(n) ? n : 0;
  const accent = tone === "amber" && safe > 24 ? "text-amber-700 dark:text-amber-300" : tone === "amber" && safe > 8 ? "text-yellow-700 dark:text-yellow-300" : "text-gray-900 dark:text-white";
  const body = /* @__PURE__ */ jsxRuntimeExports.jsxs(
    "div",
    {
      className: "flex items-center gap-2 rounded-md bg-white px-2.5 py-2 shadow-sm ring-1 ring-blue-100 hover:ring-blue-300 dark:bg-gray-900/60 dark:ring-blue-500/30",
      title: tooltip,
      children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Icon, { className: "h-4 w-4 text-blue-500" }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: `text-base font-semibold leading-none ${accent}`, children: safe.toLocaleString() }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-[10px] uppercase tracking-wide text-gray-500 dark:text-gray-400", children: label })
        ] })
      ]
    }
  );
  if (link2 && safe > 0) {
    return /* @__PURE__ */ jsxRuntimeExports.jsx("a", { href: link2, className: "transition-transform hover:scale-[1.02]", children: body });
  }
  return body;
};
const SkeletonCard = () => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mb-6 overflow-hidden rounded-lg border border-gray-200 bg-white p-5 shadow-sm dark:border-gray-700 dark:bg-gray-800", children: [
  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-6 w-6 animate-pulse rounded bg-blue-100 dark:bg-blue-900/40" }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 w-32 animate-pulse rounded bg-gray-100 dark:bg-gray-700" })
  ] }),
  /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-3 grid grid-cols-2 gap-2 sm:grid-cols-4", children: [0, 1, 2, 3].map((i) => /* @__PURE__ */ jsxRuntimeExports.jsx(
    "div",
    {
      className: "h-12 animate-pulse rounded bg-gray-100 dark:bg-gray-700"
    },
    i
  )) }),
  /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-3 h-4 w-full animate-pulse rounded bg-gray-100 dark:bg-gray-700" }),
  /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-1 h-4 w-2/3 animate-pulse rounded bg-gray-100 dark:bg-gray-700" })
] });
const StatCard = ({
  title: title2,
  value,
  icon: Icon,
  trend,
  color: color2 = "blue",
  loading = false,
  tooltip,
  onClick
}) => {
  const interactive = !!onClick;
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    "div",
    {
      className: `group relative bg-white dark:bg-gray-800 rounded-lg border border-gray-100 dark:border-gray-700/50 p-3 transition-colors ${interactive ? "cursor-pointer hover:border-blue-300 dark:hover:border-blue-600/70" : "hover:border-gray-200 dark:hover:border-gray-600"}`,
      onClick,
      role: interactive ? "button" : void 0,
      tabIndex: interactive ? 0 : void 0,
      onKeyDown: interactive ? (e) => {
        if (e.key === "Enter" || e.key === " ") {
          e.preventDefault();
          onClick == null ? void 0 : onClick();
        }
      } : void 0,
      children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start justify-between gap-2", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1 min-w-0", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1.5 mb-1", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400 truncate", children: title2 }),
            tooltip && // Real hover-popover (see components/ui/tooltip.tsx). Native
            // `title=` was previously used here but had a ~700ms delay
            // and an easy-to-miss OS-default style — operators reported
            // the `?` icon "didn't show anything". The new tooltip
            // appears instantly on hover/focus and matches admin theme.
            /* @__PURE__ */ jsxRuntimeExports.jsx(Tooltip$1, { content: tooltip, side: "top", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
              "span",
              {
                className: "inline-flex h-3.5 w-3.5 shrink-0 cursor-help items-center justify-center rounded-full bg-gray-100 text-[10px] font-bold leading-none text-gray-500 transition-colors hover:bg-gray-200 hover:text-gray-700 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 dark:bg-gray-700 dark:text-gray-300 dark:hover:bg-gray-600 dark:hover:text-gray-100",
                "aria-label": typeof tooltip === "string" ? tooltip : void 0,
                role: "img",
                children: "?"
              }
            ) })
          ] }),
          loading ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-6 w-20 bg-gray-100 dark:bg-gray-700 rounded animate-pulse" }) : /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xl font-semibold tabular-nums text-gray-900 dark:text-white truncate", children: value }),
          trend && !loading && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1 mt-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "span",
              {
                className: `text-xs font-medium tabular-nums ${trend.isPositive ? "text-green-600 dark:text-green-400" : "text-red-600 dark:text-red-400"}`,
                children: [
                  trend.isPositive ? "↑" : "↓",
                  " ",
                  Math.abs(trend.value).toFixed(1),
                  "%"
                ]
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs text-gray-400 dark:text-gray-500", children: trend.label || "vs prev. period" })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-2.5 rounded-lg bg-gray-50 dark:bg-gray-700/50 shrink-0", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          Icon,
          {
            className: `w-4 h-4 ${color2 === "blue" ? "text-blue-600 dark:text-blue-400" : color2 === "green" ? "text-green-600 dark:text-green-400" : color2 === "purple" ? "text-purple-600 dark:text-purple-400" : color2 === "red" ? "text-red-600 dark:text-red-400" : "text-orange-600 dark:text-orange-400"}`
          }
        ) })
      ] })
    }
  );
};
const SimpleBarChart = ({
  data,
  title: title2,
  height = 200,
  showValues = true
}) => {
  if (!data || data.length === 0) {
    return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex items-center justify-center h-full text-gray-500 dark:text-gray-400", children: __("No data available", "yatra") });
  }
  const maxValue = Math.max(...data.map((d) => d.value), 1);
  const chartHeight = height - 60;
  const defaultColors = ["#3b82f6", "#10b981", "#f59e0b", "#ef4444", "#8b5cf6"];
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "w-full", children: [
    title2 && /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-sm font-medium text-gray-700 dark:text-gray-300 mb-4", children: title2 }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      "div",
      {
        className: "flex items-end justify-between gap-3",
        style: { height: `${chartHeight}px` },
        children: data.map((item, index) => {
          const ratio = item.value / maxValue;
          const barPixelHeight = item.value > 0 ? Math.max(ratio * chartHeight, 24) : 0;
          const color2 = item.color || defaultColors[index % defaultColors.length];
          return /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "div",
            {
              className: "flex-1 flex flex-col items-center group min-w-0",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "div",
                  {
                    className: "relative w-full flex items-end justify-center mb-3",
                    style: { height: "100%" },
                    children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "div",
                      {
                        className: "w-3/4 max-w-[32px] rounded-t-md transition-all hover:opacity-90 relative group/bar",
                        style: {
                          height: `${barPixelHeight}px`,
                          backgroundColor: color2,
                          minHeight: item.value > 0 ? "24px" : "4px"
                        },
                        title: `${item.label}: ${item.value}`,
                        children: showValues && item.value > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "absolute -top-7 left-1/2 transform -translate-x-1/2 text-xs font-medium text-gray-600 dark:text-gray-400 whitespace-nowrap opacity-0 group-hover/bar:opacity-100 transition-opacity", children: item.value })
                      }
                    )
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs font-medium text-gray-500 dark:text-gray-400 text-center truncate w-full px-1", children: item.label })
              ]
            },
            index
          );
        })
      }
    )
  ] });
};
function r(e) {
  var t, f, n = "";
  if ("string" == typeof e || "number" == typeof e) n += e;
  else if ("object" == typeof e) if (Array.isArray(e)) {
    var o = e.length;
    for (t = 0; t < o; t++) e[t] && (f = r(e[t])) && (n && (n += " "), n += f);
  } else for (f in e) e[f] && (n && (n += " "), n += f);
  return n;
}
function clsx() {
  for (var e, t, f = 0, n = "", o = arguments.length; f < o; f++) (e = arguments[f]) && (t = r(e)) && (n && (n += " "), n += t);
  return n;
}
var baseGetTag$4 = _baseGetTag, isObjectLike$4 = isObjectLike_1;
var symbolTag = "[object Symbol]";
function isSymbol$6(value) {
  return typeof value == "symbol" || isObjectLike$4(value) && baseGetTag$4(value) == symbolTag;
}
var isSymbol_1 = isSymbol$6;
var isArray$a = isArray_1, isSymbol$5 = isSymbol_1;
var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/;
function isKey$3(value, object2) {
  if (isArray$a(value)) {
    return false;
  }
  var type = typeof value;
  if (type == "number" || type == "symbol" || type == "boolean" || value == null || isSymbol$5(value)) {
    return true;
  }
  return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object2 != null && value in Object(object2);
}
var _isKey = isKey$3;
var MapCache = _MapCache;
var FUNC_ERROR_TEXT$2 = "Expected a function";
function memoize$2(func, resolver) {
  if (typeof func != "function" || resolver != null && typeof resolver != "function") {
    throw new TypeError(FUNC_ERROR_TEXT$2);
  }
  var memoized = function() {
    var args = arguments, key2 = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache;
    if (cache.has(key2)) {
      return cache.get(key2);
    }
    var result = func.apply(this, args);
    memoized.cache = cache.set(key2, result) || cache;
    return result;
  };
  memoized.cache = new (memoize$2.Cache || MapCache)();
  return memoized;
}
memoize$2.Cache = MapCache;
var memoize_1 = memoize$2;
const memoize$3 = /* @__PURE__ */ getDefaultExportFromCjs(memoize_1);
var memoize$1 = memoize_1;
var MAX_MEMOIZE_SIZE = 500;
function memoizeCapped$1(func) {
  var result = memoize$1(func, function(key2) {
    if (cache.size === MAX_MEMOIZE_SIZE) {
      cache.clear();
    }
    return key2;
  });
  var cache = result.cache;
  return result;
}
var _memoizeCapped = memoizeCapped$1;
var memoizeCapped = _memoizeCapped;
var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
var reEscapeChar = /\\(\\)?/g;
var stringToPath$1 = memoizeCapped(function(string2) {
  var result = [];
  if (string2.charCodeAt(0) === 46) {
    result.push("");
  }
  string2.replace(rePropName, function(match2, number2, quote, subString) {
    result.push(quote ? subString.replace(reEscapeChar, "$1") : number2 || match2);
  });
  return result;
});
var _stringToPath = stringToPath$1;
function arrayMap$3(array2, iteratee) {
  var index = -1, length = array2 == null ? 0 : array2.length, result = Array(length);
  while (++index < length) {
    result[index] = iteratee(array2[index], index, array2);
  }
  return result;
}
var _arrayMap = arrayMap$3;
var Symbol$3 = _Symbol, arrayMap$2 = _arrayMap, isArray$9 = isArray_1, isSymbol$4 = isSymbol_1;
var symbolProto = Symbol$3 ? Symbol$3.prototype : void 0, symbolToString = symbolProto ? symbolProto.toString : void 0;
function baseToString$1(value) {
  if (typeof value == "string") {
    return value;
  }
  if (isArray$9(value)) {
    return arrayMap$2(value, baseToString$1) + "";
  }
  if (isSymbol$4(value)) {
    return symbolToString ? symbolToString.call(value) : "";
  }
  var result = value + "";
  return result == "0" && 1 / value == -Infinity ? "-0" : result;
}
var _baseToString = baseToString$1;
var baseToString = _baseToString;
function toString$3(value) {
  return value == null ? "" : baseToString(value);
}
var toString_1 = toString$3;
var isArray$8 = isArray_1, isKey$2 = _isKey, stringToPath = _stringToPath, toString$2 = toString_1;
function castPath$2(value, object2) {
  if (isArray$8(value)) {
    return value;
  }
  return isKey$2(value, object2) ? [value] : stringToPath(toString$2(value));
}
var _castPath = castPath$2;
var isSymbol$3 = isSymbol_1;
function toKey$4(value) {
  if (typeof value == "string" || isSymbol$3(value)) {
    return value;
  }
  var result = value + "";
  return result == "0" && 1 / value == -Infinity ? "-0" : result;
}
var _toKey = toKey$4;
var castPath$1 = _castPath, toKey$3 = _toKey;
function baseGet$3(object2, path) {
  path = castPath$1(path, object2);
  var index = 0, length = path.length;
  while (object2 != null && index < length) {
    object2 = object2[toKey$3(path[index++])];
  }
  return index && index == length ? object2 : void 0;
}
var _baseGet = baseGet$3;
var baseGet$2 = _baseGet;
function get$1(object2, path, defaultValue) {
  var result = object2 == null ? void 0 : baseGet$2(object2, path);
  return result === void 0 ? defaultValue : result;
}
var get_1 = get$1;
const get$2 = /* @__PURE__ */ getDefaultExportFromCjs(get_1);
function isNil(value) {
  return value == null;
}
var isNil_1 = isNil;
const isNil$1 = /* @__PURE__ */ getDefaultExportFromCjs(isNil_1);
var baseGetTag$3 = _baseGetTag, isArray$7 = isArray_1, isObjectLike$3 = isObjectLike_1;
var stringTag = "[object String]";
function isString(value) {
  return typeof value == "string" || !isArray$7(value) && isObjectLike$3(value) && baseGetTag$3(value) == stringTag;
}
var isString_1 = isString;
const isString$1 = /* @__PURE__ */ getDefaultExportFromCjs(isString_1);
var baseGetTag$2 = _baseGetTag, isObjectLike$2 = isObjectLike_1;
var numberTag = "[object Number]";
function isNumber$2(value) {
  return typeof value == "number" || isObjectLike$2(value) && baseGetTag$2(value) == numberTag;
}
var isNumber_1 = isNumber$2;
const isNumber$3 = /* @__PURE__ */ getDefaultExportFromCjs(isNumber_1);
var isNumber$1 = isNumber_1;
function isNaN$1(value) {
  return isNumber$1(value) && value != +value;
}
var _isNaN = isNaN$1;
const isNan = /* @__PURE__ */ getDefaultExportFromCjs(_isNaN);
var mathSign = function mathSign2(value) {
  if (value === 0) {
    return 0;
  }
  if (value > 0) {
    return 1;
  }
  return -1;
};
var isPercent = function isPercent2(value) {
  return isString$1(value) && value.indexOf("%") === value.length - 1;
};
var isNumber = function isNumber2(value) {
  return isNumber$3(value) && !isNan(value);
};
var isNullish = function isNullish2(value) {
  return isNil$1(value);
};
var isNumOrStr = function isNumOrStr2(value) {
  return isNumber(value) || isString$1(value);
};
var idCounter = 0;
var uniqueId = function uniqueId2(prefix2) {
  var id = ++idCounter;
  return "".concat(prefix2 || "").concat(id);
};
var getPercentValue = function getPercentValue2(percent2, totalValue) {
  var defaultValue = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : 0;
  var validate = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : false;
  if (!isNumber(percent2) && !isString$1(percent2)) {
    return defaultValue;
  }
  var value;
  if (isPercent(percent2)) {
    var index = percent2.indexOf("%");
    value = totalValue * parseFloat(percent2.slice(0, index)) / 100;
  } else {
    value = +percent2;
  }
  if (isNan(value)) {
    value = defaultValue;
  }
  if (validate && value > totalValue) {
    value = totalValue;
  }
  return value;
};
var getAnyElementOfObject = function getAnyElementOfObject2(obj) {
  if (!obj) {
    return null;
  }
  var keys2 = Object.keys(obj);
  if (keys2 && keys2.length) {
    return obj[keys2[0]];
  }
  return null;
};
var hasDuplicate = function hasDuplicate2(ary) {
  if (!Array.isArray(ary)) {
    return false;
  }
  var len = ary.length;
  var cache = {};
  for (var i = 0; i < len; i++) {
    if (!cache[ary[i]]) {
      cache[ary[i]] = true;
    } else {
      return true;
    }
  }
  return false;
};
var interpolateNumber$2 = function interpolateNumber2(numberA, numberB) {
  if (isNumber(numberA) && isNumber(numberB)) {
    return function(t) {
      return numberA + t * (numberB - numberA);
    };
  }
  return function() {
    return numberB;
  };
};
function findEntryInArray(ary, specifiedKey, specifiedValue) {
  if (!ary || !ary.length) {
    return null;
  }
  return ary.find(function(entry) {
    return entry && (typeof specifiedKey === "function" ? specifiedKey(entry) : get$2(entry, specifiedKey)) === specifiedValue;
  });
}
var compareValues = function compareValues2(a2, b) {
  if (isNumber(a2) && isNumber(b)) {
    return a2 - b;
  }
  if (isString$1(a2) && isString$1(b)) {
    return a2.localeCompare(b);
  }
  if (a2 instanceof Date && b instanceof Date) {
    return a2.getTime() - b.getTime();
  }
  return String(a2).localeCompare(String(b));
};
function shallowEqual(a2, b) {
  for (var key2 in a2) {
    if ({}.hasOwnProperty.call(a2, key2) && (!{}.hasOwnProperty.call(b, key2) || a2[key2] !== b[key2])) {
      return false;
    }
  }
  for (var _key in b) {
    if ({}.hasOwnProperty.call(b, _key) && !{}.hasOwnProperty.call(a2, _key)) {
      return false;
    }
  }
  return true;
}
function _typeof$G(o) {
  "@babel/helpers - typeof";
  return _typeof$G = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
    return typeof o2;
  } : function(o2) {
    return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
  }, _typeof$G(o);
}
var SVGContainerPropKeys = ["viewBox", "children"];
var SVGElementPropKeys = [
  "aria-activedescendant",
  "aria-atomic",
  "aria-autocomplete",
  "aria-busy",
  "aria-checked",
  "aria-colcount",
  "aria-colindex",
  "aria-colspan",
  "aria-controls",
  "aria-current",
  "aria-describedby",
  "aria-details",
  "aria-disabled",
  "aria-errormessage",
  "aria-expanded",
  "aria-flowto",
  "aria-haspopup",
  "aria-hidden",
  "aria-invalid",
  "aria-keyshortcuts",
  "aria-label",
  "aria-labelledby",
  "aria-level",
  "aria-live",
  "aria-modal",
  "aria-multiline",
  "aria-multiselectable",
  "aria-orientation",
  "aria-owns",
  "aria-placeholder",
  "aria-posinset",
  "aria-pressed",
  "aria-readonly",
  "aria-relevant",
  "aria-required",
  "aria-roledescription",
  "aria-rowcount",
  "aria-rowindex",
  "aria-rowspan",
  "aria-selected",
  "aria-setsize",
  "aria-sort",
  "aria-valuemax",
  "aria-valuemin",
  "aria-valuenow",
  "aria-valuetext",
  "className",
  "color",
  "height",
  "id",
  "lang",
  "max",
  "media",
  "method",
  "min",
  "name",
  "style",
  /*
   * removed 'type' SVGElementPropKey because we do not currently use any SVG elements
   * that can use it and it conflicts with the recharts prop 'type'
   * https://github.com/recharts/recharts/pull/3327
   * https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/type
   */
  // 'type',
  "target",
  "width",
  "role",
  "tabIndex",
  "accentHeight",
  "accumulate",
  "additive",
  "alignmentBaseline",
  "allowReorder",
  "alphabetic",
  "amplitude",
  "arabicForm",
  "ascent",
  "attributeName",
  "attributeType",
  "autoReverse",
  "azimuth",
  "baseFrequency",
  "baselineShift",
  "baseProfile",
  "bbox",
  "begin",
  "bias",
  "by",
  "calcMode",
  "capHeight",
  "clip",
  "clipPath",
  "clipPathUnits",
  "clipRule",
  "colorInterpolation",
  "colorInterpolationFilters",
  "colorProfile",
  "colorRendering",
  "contentScriptType",
  "contentStyleType",
  "cursor",
  "cx",
  "cy",
  "d",
  "decelerate",
  "descent",
  "diffuseConstant",
  "direction",
  "display",
  "divisor",
  "dominantBaseline",
  "dur",
  "dx",
  "dy",
  "edgeMode",
  "elevation",
  "enableBackground",
  "end",
  "exponent",
  "externalResourcesRequired",
  "fill",
  "fillOpacity",
  "fillRule",
  "filter",
  "filterRes",
  "filterUnits",
  "floodColor",
  "floodOpacity",
  "focusable",
  "fontFamily",
  "fontSize",
  "fontSizeAdjust",
  "fontStretch",
  "fontStyle",
  "fontVariant",
  "fontWeight",
  "format",
  "from",
  "fx",
  "fy",
  "g1",
  "g2",
  "glyphName",
  "glyphOrientationHorizontal",
  "glyphOrientationVertical",
  "glyphRef",
  "gradientTransform",
  "gradientUnits",
  "hanging",
  "horizAdvX",
  "horizOriginX",
  "href",
  "ideographic",
  "imageRendering",
  "in2",
  "in",
  "intercept",
  "k1",
  "k2",
  "k3",
  "k4",
  "k",
  "kernelMatrix",
  "kernelUnitLength",
  "kerning",
  "keyPoints",
  "keySplines",
  "keyTimes",
  "lengthAdjust",
  "letterSpacing",
  "lightingColor",
  "limitingConeAngle",
  "local",
  "markerEnd",
  "markerHeight",
  "markerMid",
  "markerStart",
  "markerUnits",
  "markerWidth",
  "mask",
  "maskContentUnits",
  "maskUnits",
  "mathematical",
  "mode",
  "numOctaves",
  "offset",
  "opacity",
  "operator",
  "order",
  "orient",
  "orientation",
  "origin",
  "overflow",
  "overlinePosition",
  "overlineThickness",
  "paintOrder",
  "panose1",
  "pathLength",
  "patternContentUnits",
  "patternTransform",
  "patternUnits",
  "pointerEvents",
  "pointsAtX",
  "pointsAtY",
  "pointsAtZ",
  "preserveAlpha",
  "preserveAspectRatio",
  "primitiveUnits",
  "r",
  "radius",
  "refX",
  "refY",
  "renderingIntent",
  "repeatCount",
  "repeatDur",
  "requiredExtensions",
  "requiredFeatures",
  "restart",
  "result",
  "rotate",
  "rx",
  "ry",
  "seed",
  "shapeRendering",
  "slope",
  "spacing",
  "specularConstant",
  "specularExponent",
  "speed",
  "spreadMethod",
  "startOffset",
  "stdDeviation",
  "stemh",
  "stemv",
  "stitchTiles",
  "stopColor",
  "stopOpacity",
  "strikethroughPosition",
  "strikethroughThickness",
  "string",
  "stroke",
  "strokeDasharray",
  "strokeDashoffset",
  "strokeLinecap",
  "strokeLinejoin",
  "strokeMiterlimit",
  "strokeOpacity",
  "strokeWidth",
  "surfaceScale",
  "systemLanguage",
  "tableValues",
  "targetX",
  "targetY",
  "textAnchor",
  "textDecoration",
  "textLength",
  "textRendering",
  "to",
  "transform",
  "u1",
  "u2",
  "underlinePosition",
  "underlineThickness",
  "unicode",
  "unicodeBidi",
  "unicodeRange",
  "unitsPerEm",
  "vAlphabetic",
  "values",
  "vectorEffect",
  "version",
  "vertAdvY",
  "vertOriginX",
  "vertOriginY",
  "vHanging",
  "vIdeographic",
  "viewTarget",
  "visibility",
  "vMathematical",
  "widths",
  "wordSpacing",
  "writingMode",
  "x1",
  "x2",
  "x",
  "xChannelSelector",
  "xHeight",
  "xlinkActuate",
  "xlinkArcrole",
  "xlinkHref",
  "xlinkRole",
  "xlinkShow",
  "xlinkTitle",
  "xlinkType",
  "xmlBase",
  "xmlLang",
  "xmlns",
  "xmlnsXlink",
  "xmlSpace",
  "y1",
  "y2",
  "y",
  "yChannelSelector",
  "z",
  "zoomAndPan",
  "ref",
  "key",
  "angle"
];
var PolyElementKeys = ["points", "pathLength"];
var FilteredElementKeyMap = {
  svg: SVGContainerPropKeys,
  polygon: PolyElementKeys,
  polyline: PolyElementKeys
};
var EventKeys = ["dangerouslySetInnerHTML", "onCopy", "onCopyCapture", "onCut", "onCutCapture", "onPaste", "onPasteCapture", "onCompositionEnd", "onCompositionEndCapture", "onCompositionStart", "onCompositionStartCapture", "onCompositionUpdate", "onCompositionUpdateCapture", "onFocus", "onFocusCapture", "onBlur", "onBlurCapture", "onChange", "onChangeCapture", "onBeforeInput", "onBeforeInputCapture", "onInput", "onInputCapture", "onReset", "onResetCapture", "onSubmit", "onSubmitCapture", "onInvalid", "onInvalidCapture", "onLoad", "onLoadCapture", "onError", "onErrorCapture", "onKeyDown", "onKeyDownCapture", "onKeyPress", "onKeyPressCapture", "onKeyUp", "onKeyUpCapture", "onAbort", "onAbortCapture", "onCanPlay", "onCanPlayCapture", "onCanPlayThrough", "onCanPlayThroughCapture", "onDurationChange", "onDurationChangeCapture", "onEmptied", "onEmptiedCapture", "onEncrypted", "onEncryptedCapture", "onEnded", "onEndedCapture", "onLoadedData", "onLoadedDataCapture", "onLoadedMetadata", "onLoadedMetadataCapture", "onLoadStart", "onLoadStartCapture", "onPause", "onPauseCapture", "onPlay", "onPlayCapture", "onPlaying", "onPlayingCapture", "onProgress", "onProgressCapture", "onRateChange", "onRateChangeCapture", "onSeeked", "onSeekedCapture", "onSeeking", "onSeekingCapture", "onStalled", "onStalledCapture", "onSuspend", "onSuspendCapture", "onTimeUpdate", "onTimeUpdateCapture", "onVolumeChange", "onVolumeChangeCapture", "onWaiting", "onWaitingCapture", "onAuxClick", "onAuxClickCapture", "onClick", "onClickCapture", "onContextMenu", "onContextMenuCapture", "onDoubleClick", "onDoubleClickCapture", "onDrag", "onDragCapture", "onDragEnd", "onDragEndCapture", "onDragEnter", "onDragEnterCapture", "onDragExit", "onDragExitCapture", "onDragLeave", "onDragLeaveCapture", "onDragOver", "onDragOverCapture", "onDragStart", "onDragStartCapture", "onDrop", "onDropCapture", "onMouseDown", "onMouseDownCapture", "onMouseEnter", "onMouseLeave", "onMouseMove", "onMouseMoveCapture", "onMouseOut", "onMouseOutCapture", "onMouseOver", "onMouseOverCapture", "onMouseUp", "onMouseUpCapture", "onSelect", "onSelectCapture", "onTouchCancel", "onTouchCancelCapture", "onTouchEnd", "onTouchEndCapture", "onTouchMove", "onTouchMoveCapture", "onTouchStart", "onTouchStartCapture", "onPointerDown", "onPointerDownCapture", "onPointerMove", "onPointerMoveCapture", "onPointerUp", "onPointerUpCapture", "onPointerCancel", "onPointerCancelCapture", "onPointerEnter", "onPointerEnterCapture", "onPointerLeave", "onPointerLeaveCapture", "onPointerOver", "onPointerOverCapture", "onPointerOut", "onPointerOutCapture", "onGotPointerCapture", "onGotPointerCaptureCapture", "onLostPointerCapture", "onLostPointerCaptureCapture", "onScroll", "onScrollCapture", "onWheel", "onWheelCapture", "onAnimationStart", "onAnimationStartCapture", "onAnimationEnd", "onAnimationEndCapture", "onAnimationIteration", "onAnimationIterationCapture", "onTransitionEnd", "onTransitionEndCapture"];
var adaptEventHandlers = function adaptEventHandlers2(props, newHandler) {
  if (!props || typeof props === "function" || typeof props === "boolean") {
    return null;
  }
  var inputProps = props;
  if (/* @__PURE__ */ reactExports.isValidElement(props)) {
    inputProps = props.props;
  }
  if (!isObject$5(inputProps)) {
    return null;
  }
  var out = {};
  Object.keys(inputProps).forEach(function(key2) {
    if (EventKeys.includes(key2)) {
      out[key2] = newHandler || function(e) {
        return inputProps[key2](inputProps, e);
      };
    }
  });
  return out;
};
var getEventHandlerOfChild = function getEventHandlerOfChild2(originalHandler, data, index) {
  return function(e) {
    originalHandler(data, index, e);
    return null;
  };
};
var adaptEventsOfChild = function adaptEventsOfChild2(props, data, index) {
  if (!isObject$5(props) || _typeof$G(props) !== "object") {
    return null;
  }
  var out = null;
  Object.keys(props).forEach(function(key2) {
    var item = props[key2];
    if (EventKeys.includes(key2) && typeof item === "function") {
      if (!out) out = {};
      out[key2] = getEventHandlerOfChild(item, data, index);
    }
  });
  return out;
};
var _excluded$h = ["children"], _excluded2$6 = ["children"];
function _objectWithoutProperties$h(source, excluded) {
  if (source == null) return {};
  var target2 = _objectWithoutPropertiesLoose$h(source, excluded);
  var key2, i;
  if (Object.getOwnPropertySymbols) {
    var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
    for (i = 0; i < sourceSymbolKeys.length; i++) {
      key2 = sourceSymbolKeys[i];
      if (excluded.indexOf(key2) >= 0) continue;
      if (!Object.prototype.propertyIsEnumerable.call(source, key2)) continue;
      target2[key2] = source[key2];
    }
  }
  return target2;
}
function _objectWithoutPropertiesLoose$h(source, excluded) {
  if (source == null) return {};
  var target2 = {};
  for (var key2 in source) {
    if (Object.prototype.hasOwnProperty.call(source, key2)) {
      if (excluded.indexOf(key2) >= 0) continue;
      target2[key2] = source[key2];
    }
  }
  return target2;
}
function _typeof$F(o) {
  "@babel/helpers - typeof";
  return _typeof$F = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
    return typeof o2;
  } : function(o2) {
    return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
  }, _typeof$F(o);
}
var REACT_BROWSER_EVENT_MAP = {
  click: "onClick",
  mousedown: "onMouseDown",
  mouseup: "onMouseUp",
  mouseover: "onMouseOver",
  mousemove: "onMouseMove",
  mouseout: "onMouseOut",
  mouseenter: "onMouseEnter",
  mouseleave: "onMouseLeave",
  touchcancel: "onTouchCancel",
  touchend: "onTouchEnd",
  touchmove: "onTouchMove",
  touchstart: "onTouchStart",
  contextmenu: "onContextMenu",
  dblclick: "onDoubleClick"
};
var getDisplayName = function getDisplayName2(Comp) {
  if (typeof Comp === "string") {
    return Comp;
  }
  if (!Comp) {
    return "";
  }
  return Comp.displayName || Comp.name || "Component";
};
var lastChildren = null;
var lastResult = null;
var toArray = function toArray2(children) {
  if (children === lastChildren && Array.isArray(lastResult)) {
    return lastResult;
  }
  var result = [];
  reactExports.Children.forEach(children, function(child) {
    if (isNil$1(child)) return;
    if (reactIsExports.isFragment(child)) {
      result = result.concat(toArray2(child.props.children));
    } else {
      result.push(child);
    }
  });
  lastResult = result;
  lastChildren = children;
  return result;
};
function findAllByType(children, type) {
  var result = [];
  var types = [];
  if (Array.isArray(type)) {
    types = type.map(function(t) {
      return getDisplayName(t);
    });
  } else {
    types = [getDisplayName(type)];
  }
  toArray(children).forEach(function(child) {
    var childType = get$2(child, "type.displayName") || get$2(child, "type.name");
    if (types.indexOf(childType) !== -1) {
      result.push(child);
    }
  });
  return result;
}
function findChildByType(children, type) {
  var result = findAllByType(children, type);
  return result && result[0];
}
var validateWidthHeight = function validateWidthHeight2(el) {
  if (!el || !el.props) {
    return false;
  }
  var _el$props = el.props, width = _el$props.width, height = _el$props.height;
  if (!isNumber(width) || width <= 0 || !isNumber(height) || height <= 0) {
    return false;
  }
  return true;
};
var SVG_TAGS = ["a", "altGlyph", "altGlyphDef", "altGlyphItem", "animate", "animateColor", "animateMotion", "animateTransform", "circle", "clipPath", "color-profile", "cursor", "defs", "desc", "ellipse", "feBlend", "feColormatrix", "feComponentTransfer", "feComposite", "feConvolveMatrix", "feDiffuseLighting", "feDisplacementMap", "feDistantLight", "feFlood", "feFuncA", "feFuncB", "feFuncG", "feFuncR", "feGaussianBlur", "feImage", "feMerge", "feMergeNode", "feMorphology", "feOffset", "fePointLight", "feSpecularLighting", "feSpotLight", "feTile", "feTurbulence", "filter", "font", "font-face", "font-face-format", "font-face-name", "font-face-url", "foreignObject", "g", "glyph", "glyphRef", "hkern", "image", "line", "lineGradient", "marker", "mask", "metadata", "missing-glyph", "mpath", "path", "pattern", "polygon", "polyline", "radialGradient", "rect", "script", "set", "stop", "style", "svg", "switch", "symbol", "text", "textPath", "title", "tref", "tspan", "use", "view", "vkern"];
var isSvgElement = function isSvgElement2(child) {
  return child && child.type && isString$1(child.type) && SVG_TAGS.indexOf(child.type) >= 0;
};
var hasClipDot = function hasClipDot2(dot) {
  return dot && _typeof$F(dot) === "object" && "clipDot" in dot;
};
var isValidSpreadableProp = function isValidSpreadableProp2(property2, key2, includeEvents, svgElementType) {
  var _FilteredElementKeyMa;
  var matchingElementTypeKeys = (_FilteredElementKeyMa = FilteredElementKeyMap === null || FilteredElementKeyMap === void 0 ? void 0 : FilteredElementKeyMap[svgElementType]) !== null && _FilteredElementKeyMa !== void 0 ? _FilteredElementKeyMa : [];
  return key2.startsWith("data-") || !isFunction(property2) && (svgElementType && matchingElementTypeKeys.includes(key2) || SVGElementPropKeys.includes(key2)) || includeEvents && EventKeys.includes(key2);
};
var filterProps = function filterProps2(props, includeEvents, svgElementType) {
  if (!props || typeof props === "function" || typeof props === "boolean") {
    return null;
  }
  var inputProps = props;
  if (/* @__PURE__ */ reactExports.isValidElement(props)) {
    inputProps = props.props;
  }
  if (!isObject$5(inputProps)) {
    return null;
  }
  var out = {};
  Object.keys(inputProps).forEach(function(key2) {
    var _inputProps;
    if (isValidSpreadableProp((_inputProps = inputProps) === null || _inputProps === void 0 ? void 0 : _inputProps[key2], key2, includeEvents, svgElementType)) {
      out[key2] = inputProps[key2];
    }
  });
  return out;
};
var isChildrenEqual = function isChildrenEqual2(nextChildren, prevChildren) {
  if (nextChildren === prevChildren) {
    return true;
  }
  var count = reactExports.Children.count(nextChildren);
  if (count !== reactExports.Children.count(prevChildren)) {
    return false;
  }
  if (count === 0) {
    return true;
  }
  if (count === 1) {
    return isSingleChildEqual(Array.isArray(nextChildren) ? nextChildren[0] : nextChildren, Array.isArray(prevChildren) ? prevChildren[0] : prevChildren);
  }
  for (var i = 0; i < count; i++) {
    var nextChild = nextChildren[i];
    var prevChild = prevChildren[i];
    if (Array.isArray(nextChild) || Array.isArray(prevChild)) {
      if (!isChildrenEqual2(nextChild, prevChild)) {
        return false;
      }
    } else if (!isSingleChildEqual(nextChild, prevChild)) {
      return false;
    }
  }
  return true;
};
var isSingleChildEqual = function isSingleChildEqual2(nextChild, prevChild) {
  if (isNil$1(nextChild) && isNil$1(prevChild)) {
    return true;
  }
  if (!isNil$1(nextChild) && !isNil$1(prevChild)) {
    var _ref = nextChild.props || {}, nextChildren = _ref.children, nextProps = _objectWithoutProperties$h(_ref, _excluded$h);
    var _ref2 = prevChild.props || {}, prevChildren = _ref2.children, prevProps = _objectWithoutProperties$h(_ref2, _excluded2$6);
    if (nextChildren && prevChildren) {
      return shallowEqual(nextProps, prevProps) && isChildrenEqual(nextChildren, prevChildren);
    }
    if (!nextChildren && !prevChildren) {
      return shallowEqual(nextProps, prevProps);
    }
    return false;
  }
  return false;
};
var renderByOrder = function renderByOrder2(children, renderMap) {
  var elements = [];
  var record = {};
  toArray(children).forEach(function(child, index) {
    if (isSvgElement(child)) {
      elements.push(child);
    } else if (child) {
      var displayName = getDisplayName(child.type);
      var _ref3 = renderMap[displayName] || {}, handler = _ref3.handler, once = _ref3.once;
      if (handler && (!once || !record[displayName])) {
        var results = handler(child, displayName, index);
        elements.push(results);
        record[displayName] = true;
      }
    }
  });
  return elements;
};
var getReactEventByType = function getReactEventByType2(e) {
  var type = e && e.type;
  if (type && REACT_BROWSER_EVENT_MAP[type]) {
    return REACT_BROWSER_EVENT_MAP[type];
  }
  return null;
};
var parseChildIndex = function parseChildIndex2(child, children) {
  return toArray(children).indexOf(child);
};
var _excluded$g = ["children", "width", "height", "viewBox", "className", "style", "title", "desc"];
function _extends$t() {
  _extends$t = Object.assign ? Object.assign.bind() : function(target2) {
    for (var i = 1; i < arguments.length; i++) {
      var source = arguments[i];
      for (var key2 in source) {
        if (Object.prototype.hasOwnProperty.call(source, key2)) {
          target2[key2] = source[key2];
        }
      }
    }
    return target2;
  };
  return _extends$t.apply(this, arguments);
}
function _objectWithoutProperties$g(source, excluded) {
  if (source == null) return {};
  var target2 = _objectWithoutPropertiesLoose$g(source, excluded);
  var key2, i;
  if (Object.getOwnPropertySymbols) {
    var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
    for (i = 0; i < sourceSymbolKeys.length; i++) {
      key2 = sourceSymbolKeys[i];
      if (excluded.indexOf(key2) >= 0) continue;
      if (!Object.prototype.propertyIsEnumerable.call(source, key2)) continue;
      target2[key2] = source[key2];
    }
  }
  return target2;
}
function _objectWithoutPropertiesLoose$g(source, excluded) {
  if (source == null) return {};
  var target2 = {};
  for (var key2 in source) {
    if (Object.prototype.hasOwnProperty.call(source, key2)) {
      if (excluded.indexOf(key2) >= 0) continue;
      target2[key2] = source[key2];
    }
  }
  return target2;
}
function Surface(props) {
  var children = props.children, width = props.width, height = props.height, viewBox = props.viewBox, className = props.className, style = props.style, title2 = props.title, desc = props.desc, others = _objectWithoutProperties$g(props, _excluded$g);
  var svgView = viewBox || {
    width,
    height,
    x: 0,
    y: 0
  };
  var layerClass = clsx("recharts-surface", className);
  return /* @__PURE__ */ React.createElement("svg", _extends$t({}, filterProps(others, true, "svg"), {
    className: layerClass,
    width,
    height,
    style,
    viewBox: "".concat(svgView.x, " ").concat(svgView.y, " ").concat(svgView.width, " ").concat(svgView.height)
  }), /* @__PURE__ */ React.createElement("title", null, title2), /* @__PURE__ */ React.createElement("desc", null, desc), children);
}
var _excluded$f = ["children", "className"];
function _extends$s() {
  _extends$s = Object.assign ? Object.assign.bind() : function(target2) {
    for (var i = 1; i < arguments.length; i++) {
      var source = arguments[i];
      for (var key2 in source) {
        if (Object.prototype.hasOwnProperty.call(source, key2)) {
          target2[key2] = source[key2];
        }
      }
    }
    return target2;
  };
  return _extends$s.apply(this, arguments);
}
function _objectWithoutProperties$f(source, excluded) {
  if (source == null) return {};
  var target2 = _objectWithoutPropertiesLoose$f(source, excluded);
  var key2, i;
  if (Object.getOwnPropertySymbols) {
    var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
    for (i = 0; i < sourceSymbolKeys.length; i++) {
      key2 = sourceSymbolKeys[i];
      if (excluded.indexOf(key2) >= 0) continue;
      if (!Object.prototype.propertyIsEnumerable.call(source, key2)) continue;
      target2[key2] = source[key2];
    }
  }
  return target2;
}
function _objectWithoutPropertiesLoose$f(source, excluded) {
  if (source == null) return {};
  var target2 = {};
  for (var key2 in source) {
    if (Object.prototype.hasOwnProperty.call(source, key2)) {
      if (excluded.indexOf(key2) >= 0) continue;
      target2[key2] = source[key2];
    }
  }
  return target2;
}
var Layer = /* @__PURE__ */ React.forwardRef(function(props, ref) {
  var children = props.children, className = props.className, others = _objectWithoutProperties$f(props, _excluded$f);
  var layerClass = clsx("recharts-layer", className);
  return /* @__PURE__ */ React.createElement("g", _extends$s({
    className: layerClass
  }, filterProps(others, true), {
    ref
  }), children);
});
var warn = function warn2(condition, format2) {
  for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
    args[_key - 2] = arguments[_key];
  }
};
function baseSlice$1(array2, start, end) {
  var index = -1, length = array2.length;
  if (start < 0) {
    start = -start > length ? 0 : length + start;
  }
  end = end > length ? length : end;
  if (end < 0) {
    end += length;
  }
  length = start > end ? 0 : end - start >>> 0;
  start >>>= 0;
  var result = Array(length);
  while (++index < length) {
    result[index] = array2[index + start];
  }
  return result;
}
var _baseSlice = baseSlice$1;
var baseSlice = _baseSlice;
function castSlice$1(array2, start, end) {
  var length = array2.length;
  end = end === void 0 ? length : end;
  return !start && end >= length ? array2 : baseSlice(array2, start, end);
}
var _castSlice = castSlice$1;
var rsAstralRange$1 = "\\ud800-\\udfff", rsComboMarksRange$1 = "\\u0300-\\u036f", reComboHalfMarksRange$1 = "\\ufe20-\\ufe2f", rsComboSymbolsRange$1 = "\\u20d0-\\u20ff", rsComboRange$1 = rsComboMarksRange$1 + reComboHalfMarksRange$1 + rsComboSymbolsRange$1, rsVarRange$1 = "\\ufe0e\\ufe0f";
var rsZWJ$1 = "\\u200d";
var reHasUnicode = RegExp("[" + rsZWJ$1 + rsAstralRange$1 + rsComboRange$1 + rsVarRange$1 + "]");
function hasUnicode$2(string2) {
  return reHasUnicode.test(string2);
}
var _hasUnicode = hasUnicode$2;
function asciiToArray$1(string2) {
  return string2.split("");
}
var _asciiToArray = asciiToArray$1;
var rsAstralRange = "\\ud800-\\udfff", rsComboMarksRange = "\\u0300-\\u036f", reComboHalfMarksRange = "\\ufe20-\\ufe2f", rsComboSymbolsRange = "\\u20d0-\\u20ff", rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, rsVarRange = "\\ufe0e\\ufe0f";
var rsAstral = "[" + rsAstralRange + "]", rsCombo = "[" + rsComboRange + "]", rsFitz = "\\ud83c[\\udffb-\\udfff]", rsModifier = "(?:" + rsCombo + "|" + rsFitz + ")", rsNonAstral = "[^" + rsAstralRange + "]", rsRegional = "(?:\\ud83c[\\udde6-\\uddff]){2}", rsSurrPair = "[\\ud800-\\udbff][\\udc00-\\udfff]", rsZWJ = "\\u200d";
var reOptMod = rsModifier + "?", rsOptVar = "[" + rsVarRange + "]?", rsOptJoin = "(?:" + rsZWJ + "(?:" + [rsNonAstral, rsRegional, rsSurrPair].join("|") + ")" + rsOptVar + reOptMod + ")*", rsSeq = rsOptVar + reOptMod + rsOptJoin, rsSymbol = "(?:" + [rsNonAstral + rsCombo + "?", rsCombo, rsRegional, rsSurrPair, rsAstral].join("|") + ")";
var reUnicode = RegExp(rsFitz + "(?=" + rsFitz + ")|" + rsSymbol + rsSeq, "g");
function unicodeToArray$1(string2) {
  return string2.match(reUnicode) || [];
}
var _unicodeToArray = unicodeToArray$1;
var asciiToArray = _asciiToArray, hasUnicode$1 = _hasUnicode, unicodeToArray = _unicodeToArray;
function stringToArray$1(string2) {
  return hasUnicode$1(string2) ? unicodeToArray(string2) : asciiToArray(string2);
}
var _stringToArray = stringToArray$1;
var castSlice = _castSlice, hasUnicode = _hasUnicode, stringToArray = _stringToArray, toString$1 = toString_1;
function createCaseFirst$1(methodName) {
  return function(string2) {
    string2 = toString$1(string2);
    var strSymbols = hasUnicode(string2) ? stringToArray(string2) : void 0;
    var chr = strSymbols ? strSymbols[0] : string2.charAt(0);
    var trailing = strSymbols ? castSlice(strSymbols, 1).join("") : string2.slice(1);
    return chr[methodName]() + trailing;
  };
}
var _createCaseFirst = createCaseFirst$1;
var createCaseFirst = _createCaseFirst;
var upperFirst = createCaseFirst("toUpperCase");
var upperFirst_1 = upperFirst;
const upperFirst$1 = /* @__PURE__ */ getDefaultExportFromCjs(upperFirst_1);
function constant$3(x2) {
  return function constant2() {
    return x2;
  };
}
const cos = Math.cos;
const sin = Math.sin;
const sqrt$1 = Math.sqrt;
const pi$1 = Math.PI;
const tau$1 = 2 * pi$1;
const pi = Math.PI, tau = 2 * pi, epsilon = 1e-6, tauEpsilon = tau - epsilon;
function append(strings) {
  this._ += strings[0];
  for (let i = 1, n = strings.length; i < n; ++i) {
    this._ += arguments[i] + strings[i];
  }
}
function appendRound(digits) {
  let d = Math.floor(digits);
  if (!(d >= 0)) throw new Error(`invalid digits: ${digits}`);
  if (d > 15) return append;
  const k2 = 10 ** d;
  return function(strings) {
    this._ += strings[0];
    for (let i = 1, n = strings.length; i < n; ++i) {
      this._ += Math.round(arguments[i] * k2) / k2 + strings[i];
    }
  };
}
class Path {
  constructor(digits) {
    this._x0 = this._y0 = // start of current subpath
    this._x1 = this._y1 = null;
    this._ = "";
    this._append = digits == null ? append : appendRound(digits);
  }
  moveTo(x2, y2) {
    this._append`M${this._x0 = this._x1 = +x2},${this._y0 = this._y1 = +y2}`;
  }
  closePath() {
    if (this._x1 !== null) {
      this._x1 = this._x0, this._y1 = this._y0;
      this._append`Z`;
    }
  }
  lineTo(x2, y2) {
    this._append`L${this._x1 = +x2},${this._y1 = +y2}`;
  }
  quadraticCurveTo(x1, y1, x2, y2) {
    this._append`Q${+x1},${+y1},${this._x1 = +x2},${this._y1 = +y2}`;
  }
  bezierCurveTo(x1, y1, x2, y2, x3, y3) {
    this._append`C${+x1},${+y1},${+x2},${+y2},${this._x1 = +x3},${this._y1 = +y3}`;
  }
  arcTo(x1, y1, x2, y2, r2) {
    x1 = +x1, y1 = +y1, x2 = +x2, y2 = +y2, r2 = +r2;
    if (r2 < 0) throw new Error(`negative radius: ${r2}`);
    let x0 = this._x1, y0 = this._y1, x21 = x2 - x1, y21 = y2 - y1, x01 = x0 - x1, y01 = y0 - y1, l01_2 = x01 * x01 + y01 * y01;
    if (this._x1 === null) {
      this._append`M${this._x1 = x1},${this._y1 = y1}`;
    } else if (!(l01_2 > epsilon)) ;
    else if (!(Math.abs(y01 * x21 - y21 * x01) > epsilon) || !r2) {
      this._append`L${this._x1 = x1},${this._y1 = y1}`;
    } else {
      let x20 = x2 - x0, y20 = y2 - y0, l21_2 = x21 * x21 + y21 * y21, l20_2 = x20 * x20 + y20 * y20, l21 = Math.sqrt(l21_2), l01 = Math.sqrt(l01_2), l = r2 * Math.tan((pi - Math.acos((l21_2 + l01_2 - l20_2) / (2 * l21 * l01))) / 2), t01 = l / l01, t21 = l / l21;
      if (Math.abs(t01 - 1) > epsilon) {
        this._append`L${x1 + t01 * x01},${y1 + t01 * y01}`;
      }
      this._append`A${r2},${r2},0,0,${+(y01 * x20 > x01 * y20)},${this._x1 = x1 + t21 * x21},${this._y1 = y1 + t21 * y21}`;
    }
  }
  arc(x2, y2, r2, a0, a1, ccw) {
    x2 = +x2, y2 = +y2, r2 = +r2, ccw = !!ccw;
    if (r2 < 0) throw new Error(`negative radius: ${r2}`);
    let dx = r2 * Math.cos(a0), dy = r2 * Math.sin(a0), x0 = x2 + dx, y0 = y2 + dy, cw = 1 ^ ccw, da = ccw ? a0 - a1 : a1 - a0;
    if (this._x1 === null) {
      this._append`M${x0},${y0}`;
    } else if (Math.abs(this._x1 - x0) > epsilon || Math.abs(this._y1 - y0) > epsilon) {
      this._append`L${x0},${y0}`;
    }
    if (!r2) return;
    if (da < 0) da = da % tau + tau;
    if (da > tauEpsilon) {
      this._append`A${r2},${r2},0,1,${cw},${x2 - dx},${y2 - dy}A${r2},${r2},0,1,${cw},${this._x1 = x0},${this._y1 = y0}`;
    } else if (da > epsilon) {
      this._append`A${r2},${r2},0,${+(da >= pi)},${cw},${this._x1 = x2 + r2 * Math.cos(a1)},${this._y1 = y2 + r2 * Math.sin(a1)}`;
    }
  }
  rect(x2, y2, w, h) {
    this._append`M${this._x0 = this._x1 = +x2},${this._y0 = this._y1 = +y2}h${w = +w}v${+h}h${-w}Z`;
  }
  toString() {
    return this._;
  }
}
function withPath(shape) {
  let digits = 3;
  shape.digits = function(_) {
    if (!arguments.length) return digits;
    if (_ == null) {
      digits = null;
    } else {
      const d = Math.floor(_);
      if (!(d >= 0)) throw new RangeError(`invalid digits: ${_}`);
      digits = d;
    }
    return shape;
  };
  return () => new Path(digits);
}
function array(x2) {
  return typeof x2 === "object" && "length" in x2 ? x2 : Array.from(x2);
}
function Linear(context) {
  this._context = context;
}
Linear.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._point = 0;
  },
  lineEnd: function() {
    if (this._line || this._line !== 0 && this._point === 1) this._context.closePath();
    this._line = 1 - this._line;
  },
  point: function(x2, y2) {
    x2 = +x2, y2 = +y2;
    switch (this._point) {
      case 0:
        this._point = 1;
        this._line ? this._context.lineTo(x2, y2) : this._context.moveTo(x2, y2);
        break;
      case 1:
        this._point = 2;
      default:
        this._context.lineTo(x2, y2);
        break;
    }
  }
};
function curveLinear(context) {
  return new Linear(context);
}
function x(p) {
  return p[0];
}
function y(p) {
  return p[1];
}
function shapeLine(x$12, y$1) {
  var defined3 = constant$3(true), context = null, curve = curveLinear, output = null, path = withPath(line);
  x$12 = typeof x$12 === "function" ? x$12 : x$12 === void 0 ? x : constant$3(x$12);
  y$1 = typeof y$1 === "function" ? y$1 : y$1 === void 0 ? y : constant$3(y$1);
  function line(data) {
    var i, n = (data = array(data)).length, d, defined0 = false, buffer;
    if (context == null) output = curve(buffer = path());
    for (i = 0; i <= n; ++i) {
      if (!(i < n && defined3(d = data[i], i, data)) === defined0) {
        if (defined0 = !defined0) output.lineStart();
        else output.lineEnd();
      }
      if (defined0) output.point(+x$12(d, i, data), +y$1(d, i, data));
    }
    if (buffer) return output = null, buffer + "" || null;
  }
  line.x = function(_) {
    return arguments.length ? (x$12 = typeof _ === "function" ? _ : constant$3(+_), line) : x$12;
  };
  line.y = function(_) {
    return arguments.length ? (y$1 = typeof _ === "function" ? _ : constant$3(+_), line) : y$1;
  };
  line.defined = function(_) {
    return arguments.length ? (defined3 = typeof _ === "function" ? _ : constant$3(!!_), line) : defined3;
  };
  line.curve = function(_) {
    return arguments.length ? (curve = _, context != null && (output = curve(context)), line) : curve;
  };
  line.context = function(_) {
    return arguments.length ? (_ == null ? context = output = null : output = curve(context = _), line) : context;
  };
  return line;
}
function shapeArea(x0, y0, y1) {
  var x1 = null, defined3 = constant$3(true), context = null, curve = curveLinear, output = null, path = withPath(area);
  x0 = typeof x0 === "function" ? x0 : x0 === void 0 ? x : constant$3(+x0);
  y0 = typeof y0 === "function" ? y0 : y0 === void 0 ? constant$3(0) : constant$3(+y0);
  y1 = typeof y1 === "function" ? y1 : y1 === void 0 ? y : constant$3(+y1);
  function area(data) {
    var i, j, k2, n = (data = array(data)).length, d, defined0 = false, buffer, x0z = new Array(n), y0z = new Array(n);
    if (context == null) output = curve(buffer = path());
    for (i = 0; i <= n; ++i) {
      if (!(i < n && defined3(d = data[i], i, data)) === defined0) {
        if (defined0 = !defined0) {
          j = i;
          output.areaStart();
          output.lineStart();
        } else {
          output.lineEnd();
          output.lineStart();
          for (k2 = i - 1; k2 >= j; --k2) {
            output.point(x0z[k2], y0z[k2]);
          }
          output.lineEnd();
          output.areaEnd();
        }
      }
      if (defined0) {
        x0z[i] = +x0(d, i, data), y0z[i] = +y0(d, i, data);
        output.point(x1 ? +x1(d, i, data) : x0z[i], y1 ? +y1(d, i, data) : y0z[i]);
      }
    }
    if (buffer) return output = null, buffer + "" || null;
  }
  function arealine() {
    return shapeLine().defined(defined3).curve(curve).context(context);
  }
  area.x = function(_) {
    return arguments.length ? (x0 = typeof _ === "function" ? _ : constant$3(+_), x1 = null, area) : x0;
  };
  area.x0 = function(_) {
    return arguments.length ? (x0 = typeof _ === "function" ? _ : constant$3(+_), area) : x0;
  };
  area.x1 = function(_) {
    return arguments.length ? (x1 = _ == null ? null : typeof _ === "function" ? _ : constant$3(+_), area) : x1;
  };
  area.y = function(_) {
    return arguments.length ? (y0 = typeof _ === "function" ? _ : constant$3(+_), y1 = null, area) : y0;
  };
  area.y0 = function(_) {
    return arguments.length ? (y0 = typeof _ === "function" ? _ : constant$3(+_), area) : y0;
  };
  area.y1 = function(_) {
    return arguments.length ? (y1 = _ == null ? null : typeof _ === "function" ? _ : constant$3(+_), area) : y1;
  };
  area.lineX0 = area.lineY0 = function() {
    return arealine().x(x0).y(y0);
  };
  area.lineY1 = function() {
    return arealine().x(x0).y(y1);
  };
  area.lineX1 = function() {
    return arealine().x(x1).y(y0);
  };
  area.defined = function(_) {
    return arguments.length ? (defined3 = typeof _ === "function" ? _ : constant$3(!!_), area) : defined3;
  };
  area.curve = function(_) {
    return arguments.length ? (curve = _, context != null && (output = curve(context)), area) : curve;
  };
  area.context = function(_) {
    return arguments.length ? (_ == null ? context = output = null : output = curve(context = _), area) : context;
  };
  return area;
}
class Bump {
  constructor(context, x2) {
    this._context = context;
    this._x = x2;
  }
  areaStart() {
    this._line = 0;
  }
  areaEnd() {
    this._line = NaN;
  }
  lineStart() {
    this._point = 0;
  }
  lineEnd() {
    if (this._line || this._line !== 0 && this._point === 1) this._context.closePath();
    this._line = 1 - this._line;
  }
  point(x2, y2) {
    x2 = +x2, y2 = +y2;
    switch (this._point) {
      case 0: {
        this._point = 1;
        if (this._line) this._context.lineTo(x2, y2);
        else this._context.moveTo(x2, y2);
        break;
      }
      case 1:
        this._point = 2;
      default: {
        if (this._x) this._context.bezierCurveTo(this._x0 = (this._x0 + x2) / 2, this._y0, this._x0, y2, x2, y2);
        else this._context.bezierCurveTo(this._x0, this._y0 = (this._y0 + y2) / 2, x2, this._y0, x2, y2);
        break;
      }
    }
    this._x0 = x2, this._y0 = y2;
  }
}
function bumpX(context) {
  return new Bump(context, true);
}
function bumpY(context) {
  return new Bump(context, false);
}
const symbolCircle = {
  draw(context, size) {
    const r2 = sqrt$1(size / pi$1);
    context.moveTo(r2, 0);
    context.arc(0, 0, r2, 0, tau$1);
  }
};
const symbolCross = {
  draw(context, size) {
    const r2 = sqrt$1(size / 5) / 2;
    context.moveTo(-3 * r2, -r2);
    context.lineTo(-r2, -r2);
    context.lineTo(-r2, -3 * r2);
    context.lineTo(r2, -3 * r2);
    context.lineTo(r2, -r2);
    context.lineTo(3 * r2, -r2);
    context.lineTo(3 * r2, r2);
    context.lineTo(r2, r2);
    context.lineTo(r2, 3 * r2);
    context.lineTo(-r2, 3 * r2);
    context.lineTo(-r2, r2);
    context.lineTo(-3 * r2, r2);
    context.closePath();
  }
};
const tan30 = sqrt$1(1 / 3);
const tan30_2 = tan30 * 2;
const symbolDiamond = {
  draw(context, size) {
    const y2 = sqrt$1(size / tan30_2);
    const x2 = y2 * tan30;
    context.moveTo(0, -y2);
    context.lineTo(x2, 0);
    context.lineTo(0, y2);
    context.lineTo(-x2, 0);
    context.closePath();
  }
};
const symbolSquare = {
  draw(context, size) {
    const w = sqrt$1(size);
    const x2 = -w / 2;
    context.rect(x2, x2, w, w);
  }
};
const ka = 0.8908130915292852;
const kr = sin(pi$1 / 10) / sin(7 * pi$1 / 10);
const kx = sin(tau$1 / 10) * kr;
const ky = -cos(tau$1 / 10) * kr;
const symbolStar = {
  draw(context, size) {
    const r2 = sqrt$1(size * ka);
    const x2 = kx * r2;
    const y2 = ky * r2;
    context.moveTo(0, -r2);
    context.lineTo(x2, y2);
    for (let i = 1; i < 5; ++i) {
      const a2 = tau$1 * i / 5;
      const c2 = cos(a2);
      const s2 = sin(a2);
      context.lineTo(s2 * r2, -c2 * r2);
      context.lineTo(c2 * x2 - s2 * y2, s2 * x2 + c2 * y2);
    }
    context.closePath();
  }
};
const sqrt3 = sqrt$1(3);
const symbolTriangle = {
  draw(context, size) {
    const y2 = -sqrt$1(size / (sqrt3 * 3));
    context.moveTo(0, y2 * 2);
    context.lineTo(-sqrt3 * y2, -y2);
    context.lineTo(sqrt3 * y2, -y2);
    context.closePath();
  }
};
const c = -0.5;
const s = sqrt$1(3) / 2;
const k = 1 / sqrt$1(12);
const a = (k / 2 + 1) * 3;
const symbolWye = {
  draw(context, size) {
    const r2 = sqrt$1(size / a);
    const x0 = r2 / 2, y0 = r2 * k;
    const x1 = x0, y1 = r2 * k + r2;
    const x2 = -x1, y2 = y1;
    context.moveTo(x0, y0);
    context.lineTo(x1, y1);
    context.lineTo(x2, y2);
    context.lineTo(c * x0 - s * y0, s * x0 + c * y0);
    context.lineTo(c * x1 - s * y1, s * x1 + c * y1);
    context.lineTo(c * x2 - s * y2, s * x2 + c * y2);
    context.lineTo(c * x0 + s * y0, c * y0 - s * x0);
    context.lineTo(c * x1 + s * y1, c * y1 - s * x1);
    context.lineTo(c * x2 + s * y2, c * y2 - s * x2);
    context.closePath();
  }
};
function Symbol$2(type, size) {
  let context = null, path = withPath(symbol);
  type = typeof type === "function" ? type : constant$3(type || symbolCircle);
  size = typeof size === "function" ? size : constant$3(size === void 0 ? 64 : +size);
  function symbol() {
    let buffer;
    if (!context) context = buffer = path();
    type.apply(this, arguments).draw(context, +size.apply(this, arguments));
    if (buffer) return context = null, buffer + "" || null;
  }
  symbol.type = function(_) {
    return arguments.length ? (type = typeof _ === "function" ? _ : constant$3(_), symbol) : type;
  };
  symbol.size = function(_) {
    return arguments.length ? (size = typeof _ === "function" ? _ : constant$3(+_), symbol) : size;
  };
  symbol.context = function(_) {
    return arguments.length ? (context = _ == null ? null : _, symbol) : context;
  };
  return symbol;
}
function noop$2() {
}
function point$2(that, x2, y2) {
  that._context.bezierCurveTo(
    (2 * that._x0 + that._x1) / 3,
    (2 * that._y0 + that._y1) / 3,
    (that._x0 + 2 * that._x1) / 3,
    (that._y0 + 2 * that._y1) / 3,
    (that._x0 + 4 * that._x1 + x2) / 6,
    (that._y0 + 4 * that._y1 + y2) / 6
  );
}
function Basis(context) {
  this._context = context;
}
Basis.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._x0 = this._x1 = this._y0 = this._y1 = NaN;
    this._point = 0;
  },
  lineEnd: function() {
    switch (this._point) {
      case 3:
        point$2(this, this._x1, this._y1);
      case 2:
        this._context.lineTo(this._x1, this._y1);
        break;
    }
    if (this._line || this._line !== 0 && this._point === 1) this._context.closePath();
    this._line = 1 - this._line;
  },
  point: function(x2, y2) {
    x2 = +x2, y2 = +y2;
    switch (this._point) {
      case 0:
        this._point = 1;
        this._line ? this._context.lineTo(x2, y2) : this._context.moveTo(x2, y2);
        break;
      case 1:
        this._point = 2;
        break;
      case 2:
        this._point = 3;
        this._context.lineTo((5 * this._x0 + this._x1) / 6, (5 * this._y0 + this._y1) / 6);
      default:
        point$2(this, x2, y2);
        break;
    }
    this._x0 = this._x1, this._x1 = x2;
    this._y0 = this._y1, this._y1 = y2;
  }
};
function curveBasis(context) {
  return new Basis(context);
}
function BasisClosed(context) {
  this._context = context;
}
BasisClosed.prototype = {
  areaStart: noop$2,
  areaEnd: noop$2,
  lineStart: function() {
    this._x0 = this._x1 = this._x2 = this._x3 = this._x4 = this._y0 = this._y1 = this._y2 = this._y3 = this._y4 = NaN;
    this._point = 0;
  },
  lineEnd: function() {
    switch (this._point) {
      case 1: {
        this._context.moveTo(this._x2, this._y2);
        this._context.closePath();
        break;
      }
      case 2: {
        this._context.moveTo((this._x2 + 2 * this._x3) / 3, (this._y2 + 2 * this._y3) / 3);
        this._context.lineTo((this._x3 + 2 * this._x2) / 3, (this._y3 + 2 * this._y2) / 3);
        this._context.closePath();
        break;
      }
      case 3: {
        this.point(this._x2, this._y2);
        this.point(this._x3, this._y3);
        this.point(this._x4, this._y4);
        break;
      }
    }
  },
  point: function(x2, y2) {
    x2 = +x2, y2 = +y2;
    switch (this._point) {
      case 0:
        this._point = 1;
        this._x2 = x2, this._y2 = y2;
        break;
      case 1:
        this._point = 2;
        this._x3 = x2, this._y3 = y2;
        break;
      case 2:
        this._point = 3;
        this._x4 = x2, this._y4 = y2;
        this._context.moveTo((this._x0 + 4 * this._x1 + x2) / 6, (this._y0 + 4 * this._y1 + y2) / 6);
        break;
      default:
        point$2(this, x2, y2);
        break;
    }
    this._x0 = this._x1, this._x1 = x2;
    this._y0 = this._y1, this._y1 = y2;
  }
};
function curveBasisClosed(context) {
  return new BasisClosed(context);
}
function BasisOpen(context) {
  this._context = context;
}
BasisOpen.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._x0 = this._x1 = this._y0 = this._y1 = NaN;
    this._point = 0;
  },
  lineEnd: function() {
    if (this._line || this._line !== 0 && this._point === 3) this._context.closePath();
    this._line = 1 - this._line;
  },
  point: function(x2, y2) {
    x2 = +x2, y2 = +y2;
    switch (this._point) {
      case 0:
        this._point = 1;
        break;
      case 1:
        this._point = 2;
        break;
      case 2:
        this._point = 3;
        var x0 = (this._x0 + 4 * this._x1 + x2) / 6, y0 = (this._y0 + 4 * this._y1 + y2) / 6;
        this._line ? this._context.lineTo(x0, y0) : this._context.moveTo(x0, y0);
        break;
      case 3:
        this._point = 4;
      default:
        point$2(this, x2, y2);
        break;
    }
    this._x0 = this._x1, this._x1 = x2;
    this._y0 = this._y1, this._y1 = y2;
  }
};
function curveBasisOpen(context) {
  return new BasisOpen(context);
}
function LinearClosed(context) {
  this._context = context;
}
LinearClosed.prototype = {
  areaStart: noop$2,
  areaEnd: noop$2,
  lineStart: function() {
    this._point = 0;
  },
  lineEnd: function() {
    if (this._point) this._context.closePath();
  },
  point: function(x2, y2) {
    x2 = +x2, y2 = +y2;
    if (this._point) this._context.lineTo(x2, y2);
    else this._point = 1, this._context.moveTo(x2, y2);
  }
};
function curveLinearClosed(context) {
  return new LinearClosed(context);
}
function sign(x2) {
  return x2 < 0 ? -1 : 1;
}
function slope3(that, x2, y2) {
  var h0 = that._x1 - that._x0, h1 = x2 - that._x1, s0 = (that._y1 - that._y0) / (h0 || h1 < 0 && -0), s1 = (y2 - that._y1) / (h1 || h0 < 0 && -0), p = (s0 * h1 + s1 * h0) / (h0 + h1);
  return (sign(s0) + sign(s1)) * Math.min(Math.abs(s0), Math.abs(s1), 0.5 * Math.abs(p)) || 0;
}
function slope2(that, t) {
  var h = that._x1 - that._x0;
  return h ? (3 * (that._y1 - that._y0) / h - t) / 2 : t;
}
function point$1(that, t02, t12) {
  var x0 = that._x0, y0 = that._y0, x1 = that._x1, y1 = that._y1, dx = (x1 - x0) / 3;
  that._context.bezierCurveTo(x0 + dx, y0 + dx * t02, x1 - dx, y1 - dx * t12, x1, y1);
}
function MonotoneX(context) {
  this._context = context;
}
MonotoneX.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._x0 = this._x1 = this._y0 = this._y1 = this._t0 = NaN;
    this._point = 0;
  },
  lineEnd: function() {
    switch (this._point) {
      case 2:
        this._context.lineTo(this._x1, this._y1);
        break;
      case 3:
        point$1(this, this._t0, slope2(this, this._t0));
        break;
    }
    if (this._line || this._line !== 0 && this._point === 1) this._context.closePath();
    this._line = 1 - this._line;
  },
  point: function(x2, y2) {
    var t12 = NaN;
    x2 = +x2, y2 = +y2;
    if (x2 === this._x1 && y2 === this._y1) return;
    switch (this._point) {
      case 0:
        this._point = 1;
        this._line ? this._context.lineTo(x2, y2) : this._context.moveTo(x2, y2);
        break;
      case 1:
        this._point = 2;
        break;
      case 2:
        this._point = 3;
        point$1(this, slope2(this, t12 = slope3(this, x2, y2)), t12);
        break;
      default:
        point$1(this, this._t0, t12 = slope3(this, x2, y2));
        break;
    }
    this._x0 = this._x1, this._x1 = x2;
    this._y0 = this._y1, this._y1 = y2;
    this._t0 = t12;
  }
};
function MonotoneY(context) {
  this._context = new ReflectContext(context);
}
(MonotoneY.prototype = Object.create(MonotoneX.prototype)).point = function(x2, y2) {
  MonotoneX.prototype.point.call(this, y2, x2);
};
function ReflectContext(context) {
  this._context = context;
}
ReflectContext.prototype = {
  moveTo: function(x2, y2) {
    this._context.moveTo(y2, x2);
  },
  closePath: function() {
    this._context.closePath();
  },
  lineTo: function(x2, y2) {
    this._context.lineTo(y2, x2);
  },
  bezierCurveTo: function(x1, y1, x2, y2, x3, y3) {
    this._context.bezierCurveTo(y1, x1, y2, x2, y3, x3);
  }
};
function monotoneX(context) {
  return new MonotoneX(context);
}
function monotoneY(context) {
  return new MonotoneY(context);
}
function Natural(context) {
  this._context = context;
}
Natural.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._x = [];
    this._y = [];
  },
  lineEnd: function() {
    var x2 = this._x, y2 = this._y, n = x2.length;
    if (n) {
      this._line ? this._context.lineTo(x2[0], y2[0]) : this._context.moveTo(x2[0], y2[0]);
      if (n === 2) {
        this._context.lineTo(x2[1], y2[1]);
      } else {
        var px = controlPoints(x2), py = controlPoints(y2);
        for (var i0 = 0, i1 = 1; i1 < n; ++i0, ++i1) {
          this._context.bezierCurveTo(px[0][i0], py[0][i0], px[1][i0], py[1][i0], x2[i1], y2[i1]);
        }
      }
    }
    if (this._line || this._line !== 0 && n === 1) this._context.closePath();
    this._line = 1 - this._line;
    this._x = this._y = null;
  },
  point: function(x2, y2) {
    this._x.push(+x2);
    this._y.push(+y2);
  }
};
function controlPoints(x2) {
  var i, n = x2.length - 1, m, a2 = new Array(n), b = new Array(n), r2 = new Array(n);
  a2[0] = 0, b[0] = 2, r2[0] = x2[0] + 2 * x2[1];
  for (i = 1; i < n - 1; ++i) a2[i] = 1, b[i] = 4, r2[i] = 4 * x2[i] + 2 * x2[i + 1];
  a2[n - 1] = 2, b[n - 1] = 7, r2[n - 1] = 8 * x2[n - 1] + x2[n];
  for (i = 1; i < n; ++i) m = a2[i] / b[i - 1], b[i] -= m, r2[i] -= m * r2[i - 1];
  a2[n - 1] = r2[n - 1] / b[n - 1];
  for (i = n - 2; i >= 0; --i) a2[i] = (r2[i] - a2[i + 1]) / b[i];
  b[n - 1] = (x2[n] + a2[n - 1]) / 2;
  for (i = 0; i < n - 1; ++i) b[i] = 2 * x2[i + 1] - a2[i + 1];
  return [a2, b];
}
function curveNatural(context) {
  return new Natural(context);
}
function Step(context, t) {
  this._context = context;
  this._t = t;
}
Step.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._x = this._y = NaN;
    this._point = 0;
  },
  lineEnd: function() {
    if (0 < this._t && this._t < 1 && this._point === 2) this._context.lineTo(this._x, this._y);
    if (this._line || this._line !== 0 && this._point === 1) this._context.closePath();
    if (this._line >= 0) this._t = 1 - this._t, this._line = 1 - this._line;
  },
  point: function(x2, y2) {
    x2 = +x2, y2 = +y2;
    switch (this._point) {
      case 0:
        this._point = 1;
        this._line ? this._context.lineTo(x2, y2) : this._context.moveTo(x2, y2);
        break;
      case 1:
        this._point = 2;
      default: {
        if (this._t <= 0) {
          this._context.lineTo(this._x, y2);
          this._context.lineTo(x2, y2);
        } else {
          var x1 = this._x * (1 - this._t) + x2 * this._t;
          this._context.lineTo(x1, this._y);
          this._context.lineTo(x1, y2);
        }
        break;
      }
    }
    this._x = x2, this._y = y2;
  }
};
function curveStep(context) {
  return new Step(context, 0.5);
}
function stepBefore(context) {
  return new Step(context, 0);
}
function stepAfter(context) {
  return new Step(context, 1);
}
function stackOffsetNone(series, order) {
  if (!((n = series.length) > 1)) return;
  for (var i = 1, j, s0, s1 = series[order[0]], n, m = s1.length; i < n; ++i) {
    s0 = s1, s1 = series[order[i]];
    for (j = 0; j < m; ++j) {
      s1[j][1] += s1[j][0] = isNaN(s0[j][1]) ? s0[j][0] : s0[j][1];
    }
  }
}
function stackOrderNone(series) {
  var n = series.length, o = new Array(n);
  while (--n >= 0) o[n] = n;
  return o;
}
function stackValue(d, key2) {
  return d[key2];
}
function stackSeries(key2) {
  const series = [];
  series.key = key2;
  return series;
}
function shapeStack() {
  var keys2 = constant$3([]), order = stackOrderNone, offset = stackOffsetNone, value = stackValue;
  function stack(data) {
    var sz = Array.from(keys2.apply(this, arguments), stackSeries), i, n = sz.length, j = -1, oz;
    for (const d of data) {
      for (i = 0, ++j; i < n; ++i) {
        (sz[i][j] = [0, +value(d, sz[i].key, j, data)]).data = d;
      }
    }
    for (i = 0, oz = array(order(sz)); i < n; ++i) {
      sz[oz[i]].index = i;
    }
    offset(sz, oz);
    return sz;
  }
  stack.keys = function(_) {
    return arguments.length ? (keys2 = typeof _ === "function" ? _ : constant$3(Array.from(_)), stack) : keys2;
  };
  stack.value = function(_) {
    return arguments.length ? (value = typeof _ === "function" ? _ : constant$3(+_), stack) : value;
  };
  stack.order = function(_) {
    return arguments.length ? (order = _ == null ? stackOrderNone : typeof _ === "function" ? _ : constant$3(Array.from(_)), stack) : order;
  };
  stack.offset = function(_) {
    return arguments.length ? (offset = _ == null ? stackOffsetNone : _, stack) : offset;
  };
  return stack;
}
function stackOffsetExpand(series, order) {
  if (!((n = series.length) > 0)) return;
  for (var i, n, j = 0, m = series[0].length, y2; j < m; ++j) {
    for (y2 = i = 0; i < n; ++i) y2 += series[i][j][1] || 0;
    if (y2) for (i = 0; i < n; ++i) series[i][j][1] /= y2;
  }
  stackOffsetNone(series, order);
}
function stackOffsetSilhouette(series, order) {
  if (!((n = series.length) > 0)) return;
  for (var j = 0, s0 = series[order[0]], n, m = s0.length; j < m; ++j) {
    for (var i = 0, y2 = 0; i < n; ++i) y2 += series[i][j][1] || 0;
    s0[j][1] += s0[j][0] = -y2 / 2;
  }
  stackOffsetNone(series, order);
}
function stackOffsetWiggle(series, order) {
  if (!((n = series.length) > 0) || !((m = (s0 = series[order[0]]).length) > 0)) return;
  for (var y2 = 0, j = 1, s0, m, n; j < m; ++j) {
    for (var i = 0, s1 = 0, s2 = 0; i < n; ++i) {
      var si = series[order[i]], sij0 = si[j][1] || 0, sij1 = si[j - 1][1] || 0, s3 = (sij0 - sij1) / 2;
      for (var k2 = 0; k2 < i; ++k2) {
        var sk = series[order[k2]], skj0 = sk[j][1] || 0, skj1 = sk[j - 1][1] || 0;
        s3 += skj0 - skj1;
      }
      s1 += sij0, s2 += s3 * sij0;
    }
    s0[j - 1][1] += s0[j - 1][0] = y2;
    if (s1) y2 -= s2 / s1;
  }
  s0[j - 1][1] += s0[j - 1][0] = y2;
  stackOffsetNone(series, order);
}
function _typeof$E(o) {
  "@babel/helpers - typeof";
  return _typeof$E = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
    return typeof o2;
  } : function(o2) {
    return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
  }, _typeof$E(o);
}
var _excluded$e = ["type", "size", "sizeType"];
function _extends$r() {
  _extends$r = Object.assign ? Object.assign.bind() : function(target2) {
    for (var i = 1; i < arguments.length; i++) {
      var source = arguments[i];
      for (var key2 in source) {
        if (Object.prototype.hasOwnProperty.call(source, key2)) {
          target2[key2] = source[key2];
        }
      }
    }
    return target2;
  };
  return _extends$r.apply(this, arguments);
}
function ownKeys$y(e, r2) {
  var t = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    r2 && (o = o.filter(function(r3) {
      return Object.getOwnPropertyDescriptor(e, r3).enumerable;
    })), t.push.apply(t, o);
  }
  return t;
}
function _objectSpread$y(e) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys$y(Object(t), true).forEach(function(r3) {
      _defineProperty$E(e, r3, t[r3]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$y(Object(t)).forEach(function(r3) {
      Object.defineProperty(e, r3, Object.getOwnPropertyDescriptor(t, r3));
    });
  }
  return e;
}
function _defineProperty$E(obj, key2, value) {
  key2 = _toPropertyKey$E(key2);
  if (key2 in obj) {
    Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key2] = value;
  }
  return obj;
}
function _toPropertyKey$E(t) {
  var i = _toPrimitive$E(t, "string");
  return "symbol" == _typeof$E(i) ? i : i + "";
}
function _toPrimitive$E(t, r2) {
  if ("object" != _typeof$E(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r2);
    if ("object" != _typeof$E(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return ("string" === r2 ? String : Number)(t);
}
function _objectWithoutProperties$e(source, excluded) {
  if (source == null) return {};
  var target2 = _objectWithoutPropertiesLoose$e(source, excluded);
  var key2, i;
  if (Object.getOwnPropertySymbols) {
    var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
    for (i = 0; i < sourceSymbolKeys.length; i++) {
      key2 = sourceSymbolKeys[i];
      if (excluded.indexOf(key2) >= 0) continue;
      if (!Object.prototype.propertyIsEnumerable.call(source, key2)) continue;
      target2[key2] = source[key2];
    }
  }
  return target2;
}
function _objectWithoutPropertiesLoose$e(source, excluded) {
  if (source == null) return {};
  var target2 = {};
  for (var key2 in source) {
    if (Object.prototype.hasOwnProperty.call(source, key2)) {
      if (excluded.indexOf(key2) >= 0) continue;
      target2[key2] = source[key2];
    }
  }
  return target2;
}
var symbolFactories = {
  symbolCircle,
  symbolCross,
  symbolDiamond,
  symbolSquare,
  symbolStar,
  symbolTriangle,
  symbolWye
};
var RADIAN$2 = Math.PI / 180;
var getSymbolFactory = function getSymbolFactory2(type) {
  var name = "symbol".concat(upperFirst$1(type));
  return symbolFactories[name] || symbolCircle;
};
var calculateAreaSize = function calculateAreaSize2(size, sizeType, type) {
  if (sizeType === "area") {
    return size;
  }
  switch (type) {
    case "cross":
      return 5 * size * size / 9;
    case "diamond":
      return 0.5 * size * size / Math.sqrt(3);
    case "square":
      return size * size;
    case "star": {
      var angle = 18 * RADIAN$2;
      return 1.25 * size * size * (Math.tan(angle) - Math.tan(angle * 2) * Math.pow(Math.tan(angle), 2));
    }
    case "triangle":
      return Math.sqrt(3) * size * size / 4;
    case "wye":
      return (21 - 10 * Math.sqrt(3)) * size * size / 8;
    default:
      return Math.PI * size * size / 4;
  }
};
var registerSymbol = function registerSymbol2(key2, factory) {
  symbolFactories["symbol".concat(upperFirst$1(key2))] = factory;
};
var Symbols = function Symbols2(_ref) {
  var _ref$type = _ref.type, type = _ref$type === void 0 ? "circle" : _ref$type, _ref$size = _ref.size, size = _ref$size === void 0 ? 64 : _ref$size, _ref$sizeType = _ref.sizeType, sizeType = _ref$sizeType === void 0 ? "area" : _ref$sizeType, rest = _objectWithoutProperties$e(_ref, _excluded$e);
  var props = _objectSpread$y(_objectSpread$y({}, rest), {}, {
    type,
    size,
    sizeType
  });
  var getPath4 = function getPath5() {
    var symbolFactory = getSymbolFactory(type);
    var symbol = Symbol$2().type(symbolFactory).size(calculateAreaSize(size, sizeType, type));
    return symbol();
  };
  var className = props.className, cx = props.cx, cy = props.cy;
  var filteredProps = filterProps(props, true);
  if (cx === +cx && cy === +cy && size === +size) {
    return /* @__PURE__ */ React.createElement("path", _extends$r({}, filteredProps, {
      className: clsx("recharts-symbols", className),
      transform: "translate(".concat(cx, ", ").concat(cy, ")"),
      d: getPath4()
    }));
  }
  return null;
};
Symbols.registerSymbol = registerSymbol;
function _typeof$D(o) {
  "@babel/helpers - typeof";
  return _typeof$D = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
    return typeof o2;
  } : function(o2) {
    return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
  }, _typeof$D(o);
}
function _extends$q() {
  _extends$q = Object.assign ? Object.assign.bind() : function(target2) {
    for (var i = 1; i < arguments.length; i++) {
      var source = arguments[i];
      for (var key2 in source) {
        if (Object.prototype.hasOwnProperty.call(source, key2)) {
          target2[key2] = source[key2];
        }
      }
    }
    return target2;
  };
  return _extends$q.apply(this, arguments);
}
function ownKeys$x(e, r2) {
  var t = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    r2 && (o = o.filter(function(r3) {
      return Object.getOwnPropertyDescriptor(e, r3).enumerable;
    })), t.push.apply(t, o);
  }
  return t;
}
function _objectSpread$x(e) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys$x(Object(t), true).forEach(function(r3) {
      _defineProperty$D(e, r3, t[r3]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$x(Object(t)).forEach(function(r3) {
      Object.defineProperty(e, r3, Object.getOwnPropertyDescriptor(t, r3));
    });
  }
  return e;
}
function _classCallCheck$j(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function _defineProperties$j(target2, props) {
  for (var i = 0; i < props.length; i++) {
    var descriptor = props[i];
    descriptor.enumerable = descriptor.enumerable || false;
    descriptor.configurable = true;
    if ("value" in descriptor) descriptor.writable = true;
    Object.defineProperty(target2, _toPropertyKey$D(descriptor.key), descriptor);
  }
}
function _createClass$j(Constructor, protoProps, staticProps) {
  if (protoProps) _defineProperties$j(Constructor.prototype, protoProps);
  Object.defineProperty(Constructor, "prototype", { writable: false });
  return Constructor;
}
function _callSuper$g(t, o, e) {
  return o = _getPrototypeOf$g(o), _possibleConstructorReturn$g(t, _isNativeReflectConstruct$g() ? Reflect.construct(o, e || [], _getPrototypeOf$g(t).constructor) : o.apply(t, e));
}
function _possibleConstructorReturn$g(self, call) {
  if (call && (_typeof$D(call) === "object" || typeof call === "function")) {
    return call;
  } else if (call !== void 0) {
    throw new TypeError("Derived constructors may only return object or undefined");
  }
  return _assertThisInitialized$g(self);
}
function _assertThisInitialized$g(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function _isNativeReflectConstruct$g() {
  try {
    var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {
    }));
  } catch (t2) {
  }
  return (_isNativeReflectConstruct$g = function _isNativeReflectConstruct2() {
    return !!t;
  })();
}
function _getPrototypeOf$g(o) {
  _getPrototypeOf$g = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf2(o2) {
    return o2.__proto__ || Object.getPrototypeOf(o2);
  };
  return _getPrototypeOf$g(o);
}
function _inherits$g(subClass, superClass) {
  if (typeof superClass !== "function" && superClass !== null) {
    throw new TypeError("Super expression must either be null or a function");
  }
  subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } });
  Object.defineProperty(subClass, "prototype", { writable: false });
  if (superClass) _setPrototypeOf$g(subClass, superClass);
}
function _setPrototypeOf$g(o, p) {
  _setPrototypeOf$g = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf2(o2, p2) {
    o2.__proto__ = p2;
    return o2;
  };
  return _setPrototypeOf$g(o, p);
}
function _defineProperty$D(obj, key2, value) {
  key2 = _toPropertyKey$D(key2);
  if (key2 in obj) {
    Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key2] = value;
  }
  return obj;
}
function _toPropertyKey$D(t) {
  var i = _toPrimitive$D(t, "string");
  return "symbol" == _typeof$D(i) ? i : i + "";
}
function _toPrimitive$D(t, r2) {
  if ("object" != _typeof$D(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r2);
    if ("object" != _typeof$D(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return String(t);
}
var SIZE = 32;
var DefaultLegendContent = /* @__PURE__ */ function(_PureComponent) {
  function DefaultLegendContent2() {
    _classCallCheck$j(this, DefaultLegendContent2);
    return _callSuper$g(this, DefaultLegendContent2, arguments);
  }
  _inherits$g(DefaultLegendContent2, _PureComponent);
  return _createClass$j(DefaultLegendContent2, [{
    key: "renderIcon",
    value: (
      /**
       * Render the path of icon
       * @param {Object} data Data of each legend item
       * @return {String} Path element
       */
      function renderIcon(data) {
        var inactiveColor = this.props.inactiveColor;
        var halfSize = SIZE / 2;
        var sixthSize = SIZE / 6;
        var thirdSize = SIZE / 3;
        var color2 = data.inactive ? inactiveColor : data.color;
        if (data.type === "plainline") {
          return /* @__PURE__ */ React.createElement("line", {
            strokeWidth: 4,
            fill: "none",
            stroke: color2,
            strokeDasharray: data.payload.strokeDasharray,
            x1: 0,
            y1: halfSize,
            x2: SIZE,
            y2: halfSize,
            className: "recharts-legend-icon"
          });
        }
        if (data.type === "line") {
          return /* @__PURE__ */ React.createElement("path", {
            strokeWidth: 4,
            fill: "none",
            stroke: color2,
            d: "M0,".concat(halfSize, "h").concat(thirdSize, "\n            A").concat(sixthSize, ",").concat(sixthSize, ",0,1,1,").concat(2 * thirdSize, ",").concat(halfSize, "\n            H").concat(SIZE, "M").concat(2 * thirdSize, ",").concat(halfSize, "\n            A").concat(sixthSize, ",").concat(sixthSize, ",0,1,1,").concat(thirdSize, ",").concat(halfSize),
            className: "recharts-legend-icon"
          });
        }
        if (data.type === "rect") {
          return /* @__PURE__ */ React.createElement("path", {
            stroke: "none",
            fill: color2,
            d: "M0,".concat(SIZE / 8, "h").concat(SIZE, "v").concat(SIZE * 3 / 4, "h").concat(-SIZE, "z"),
            className: "recharts-legend-icon"
          });
        }
        if (/* @__PURE__ */ React.isValidElement(data.legendIcon)) {
          var iconProps = _objectSpread$x({}, data);
          delete iconProps.legendIcon;
          return /* @__PURE__ */ React.cloneElement(data.legendIcon, iconProps);
        }
        return /* @__PURE__ */ React.createElement(Symbols, {
          fill: color2,
          cx: halfSize,
          cy: halfSize,
          size: SIZE,
          sizeType: "diameter",
          type: data.type
        });
      }
    )
    /**
     * Draw items of legend
     * @return {ReactElement} Items
     */
  }, {
    key: "renderItems",
    value: function renderItems() {
      var _this = this;
      var _this$props = this.props, payload = _this$props.payload, iconSize = _this$props.iconSize, layout = _this$props.layout, formatter = _this$props.formatter, inactiveColor = _this$props.inactiveColor;
      var viewBox = {
        x: 0,
        y: 0,
        width: SIZE,
        height: SIZE
      };
      var itemStyle = {
        display: layout === "horizontal" ? "inline-block" : "block",
        marginRight: 10
      };
      var svgStyle = {
        display: "inline-block",
        verticalAlign: "middle",
        marginRight: 4
      };
      return payload.map(function(entry, i) {
        var finalFormatter = entry.formatter || formatter;
        var className = clsx(_defineProperty$D(_defineProperty$D({
          "recharts-legend-item": true
        }, "legend-item-".concat(i), true), "inactive", entry.inactive));
        if (entry.type === "none") {
          return null;
        }
        var entryValue = !isFunction(entry.value) ? entry.value : null;
        warn(
          !isFunction(entry.value),
          `The name property is also required when using a function for the dataKey of a chart's cartesian components. Ex: <Bar name="Name of my Data"/>`
          // eslint-disable-line max-len
        );
        var color2 = entry.inactive ? inactiveColor : entry.color;
        return /* @__PURE__ */ React.createElement("li", _extends$q({
          className,
          style: itemStyle,
          key: "legend-item-".concat(i)
        }, adaptEventsOfChild(_this.props, entry, i)), /* @__PURE__ */ React.createElement(Surface, {
          width: iconSize,
          height: iconSize,
          viewBox,
          style: svgStyle
        }, _this.renderIcon(entry)), /* @__PURE__ */ React.createElement("span", {
          className: "recharts-legend-item-text",
          style: {
            color: color2
          }
        }, finalFormatter ? finalFormatter(entryValue, entry, i) : entryValue));
      });
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props2 = this.props, payload = _this$props2.payload, layout = _this$props2.layout, align = _this$props2.align;
      if (!payload || !payload.length) {
        return null;
      }
      var finalStyle = {
        padding: 0,
        margin: 0,
        textAlign: layout === "horizontal" ? align : "left"
      };
      return /* @__PURE__ */ React.createElement("ul", {
        className: "recharts-default-legend",
        style: finalStyle
      }, this.renderItems());
    }
  }]);
}(reactExports.PureComponent);
_defineProperty$D(DefaultLegendContent, "displayName", "Legend");
_defineProperty$D(DefaultLegendContent, "defaultProps", {
  iconSize: 14,
  layout: "horizontal",
  align: "center",
  verticalAlign: "middle",
  inactiveColor: "#ccc"
});
var Stack = _Stack, baseIsEqual$1 = _baseIsEqual;
var COMPARE_PARTIAL_FLAG$1 = 1, COMPARE_UNORDERED_FLAG$1 = 2;
function baseIsMatch$1(object2, source, matchData, customizer) {
  var index = matchData.length, length = index, noCustomizer = !customizer;
  if (object2 == null) {
    return !length;
  }
  object2 = Object(object2);
  while (index--) {
    var data = matchData[index];
    if (noCustomizer && data[2] ? data[1] !== object2[data[0]] : !(data[0] in object2)) {
      return false;
    }
  }
  while (++index < length) {
    data = matchData[index];
    var key2 = data[0], objValue = object2[key2], srcValue = data[1];
    if (noCustomizer && data[2]) {
      if (objValue === void 0 && !(key2 in object2)) {
        return false;
      }
    } else {
      var stack = new Stack();
      if (customizer) {
        var result = customizer(objValue, srcValue, key2, object2, source, stack);
      }
      if (!(result === void 0 ? baseIsEqual$1(srcValue, objValue, COMPARE_PARTIAL_FLAG$1 | COMPARE_UNORDERED_FLAG$1, customizer, stack) : result)) {
        return false;
      }
    }
  }
  return true;
}
var _baseIsMatch = baseIsMatch$1;
var isObject$4 = isObject_1;
function isStrictComparable$2(value) {
  return value === value && !isObject$4(value);
}
var _isStrictComparable = isStrictComparable$2;
var isStrictComparable$1 = _isStrictComparable, keys$2 = keys_1;
function getMatchData$1(object2) {
  var result = keys$2(object2), length = result.length;
  while (length--) {
    var key2 = result[length], value = object2[key2];
    result[length] = [key2, value, isStrictComparable$1(value)];
  }
  return result;
}
var _getMatchData = getMatchData$1;
function matchesStrictComparable$2(key2, srcValue) {
  return function(object2) {
    if (object2 == null) {
      return false;
    }
    return object2[key2] === srcValue && (srcValue !== void 0 || key2 in Object(object2));
  };
}
var _matchesStrictComparable = matchesStrictComparable$2;
var baseIsMatch = _baseIsMatch, getMatchData = _getMatchData, matchesStrictComparable$1 = _matchesStrictComparable;
function baseMatches$1(source) {
  var matchData = getMatchData(source);
  if (matchData.length == 1 && matchData[0][2]) {
    return matchesStrictComparable$1(matchData[0][0], matchData[0][1]);
  }
  return function(object2) {
    return object2 === source || baseIsMatch(object2, source, matchData);
  };
}
var _baseMatches = baseMatches$1;
function baseHasIn$1(object2, key2) {
  return object2 != null && key2 in Object(object2);
}
var _baseHasIn = baseHasIn$1;
var castPath = _castPath, isArguments$1 = isArguments_1, isArray$6 = isArray_1, isIndex$1 = _isIndex, isLength = isLength_1, toKey$2 = _toKey;
function hasPath$1(object2, path, hasFunc) {
  path = castPath(path, object2);
  var index = -1, length = path.length, result = false;
  while (++index < length) {
    var key2 = toKey$2(path[index]);
    if (!(result = object2 != null && hasFunc(object2, key2))) {
      break;
    }
    object2 = object2[key2];
  }
  if (result || ++index != length) {
    return result;
  }
  length = object2 == null ? 0 : object2.length;
  return !!length && isLength(length) && isIndex$1(key2, length) && (isArray$6(object2) || isArguments$1(object2));
}
var _hasPath = hasPath$1;
var baseHasIn = _baseHasIn, hasPath = _hasPath;
function hasIn$1(object2, path) {
  return object2 != null && hasPath(object2, path, baseHasIn);
}
var hasIn_1 = hasIn$1;
var baseIsEqual = _baseIsEqual, get = get_1, hasIn = hasIn_1, isKey$1 = _isKey, isStrictComparable = _isStrictComparable, matchesStrictComparable = _matchesStrictComparable, toKey$1 = _toKey;
var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2;
function baseMatchesProperty$1(path, srcValue) {
  if (isKey$1(path) && isStrictComparable(srcValue)) {
    return matchesStrictComparable(toKey$1(path), srcValue);
  }
  return function(object2) {
    var objValue = get(object2, path);
    return objValue === void 0 && objValue === srcValue ? hasIn(object2, path) : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);
  };
}
var _baseMatchesProperty = baseMatchesProperty$1;
function identity$a(value) {
  return value;
}
var identity_1 = identity$a;
function baseProperty$1(key2) {
  return function(object2) {
    return object2 == null ? void 0 : object2[key2];
  };
}
var _baseProperty = baseProperty$1;
var baseGet$1 = _baseGet;
function basePropertyDeep$1(path) {
  return function(object2) {
    return baseGet$1(object2, path);
  };
}
var _basePropertyDeep = basePropertyDeep$1;
var baseProperty = _baseProperty, basePropertyDeep = _basePropertyDeep, isKey = _isKey, toKey = _toKey;
function property$1(path) {
  return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);
}
var property_1 = property$1;
var baseMatches = _baseMatches, baseMatchesProperty = _baseMatchesProperty, identity$9 = identity_1, isArray$5 = isArray_1, property = property_1;
function baseIteratee$a(value) {
  if (typeof value == "function") {
    return value;
  }
  if (value == null) {
    return identity$9;
  }
  if (typeof value == "object") {
    return isArray$5(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value);
  }
  return property(value);
}
var _baseIteratee = baseIteratee$a;
function baseFindIndex$2(array2, predicate, fromIndex, fromRight) {
  var length = array2.length, index = fromIndex + (fromRight ? 1 : -1);
  while (fromRight ? index-- : ++index < length) {
    if (predicate(array2[index], index, array2)) {
      return index;
    }
  }
  return -1;
}
var _baseFindIndex = baseFindIndex$2;
function baseIsNaN$1(value) {
  return value !== value;
}
var _baseIsNaN = baseIsNaN$1;
function strictIndexOf$1(array2, value, fromIndex) {
  var index = fromIndex - 1, length = array2.length;
  while (++index < length) {
    if (array2[index] === value) {
      return index;
    }
  }
  return -1;
}
var _strictIndexOf = strictIndexOf$1;
var baseFindIndex$1 = _baseFindIndex, baseIsNaN = _baseIsNaN, strictIndexOf = _strictIndexOf;
function baseIndexOf$1(array2, value, fromIndex) {
  return value === value ? strictIndexOf(array2, value, fromIndex) : baseFindIndex$1(array2, baseIsNaN, fromIndex);
}
var _baseIndexOf = baseIndexOf$1;
var baseIndexOf = _baseIndexOf;
function arrayIncludes$1(array2, value) {
  var length = array2 == null ? 0 : array2.length;
  return !!length && baseIndexOf(array2, value, 0) > -1;
}
var _arrayIncludes = arrayIncludes$1;
function arrayIncludesWith$1(array2, value, comparator) {
  var index = -1, length = array2 == null ? 0 : array2.length;
  while (++index < length) {
    if (comparator(value, array2[index])) {
      return true;
    }
  }
  return false;
}
var _arrayIncludesWith = arrayIncludesWith$1;
function noop$1() {
}
var noop_1 = noop$1;
var Set$1 = _Set, noop = noop_1, setToArray$1 = _setToArray;
var INFINITY$1 = 1 / 0;
var createSet$1 = !(Set$1 && 1 / setToArray$1(new Set$1([, -0]))[1] == INFINITY$1) ? noop : function(values) {
  return new Set$1(values);
};
var _createSet = createSet$1;
var SetCache = _SetCache, arrayIncludes = _arrayIncludes, arrayIncludesWith = _arrayIncludesWith, cacheHas = _cacheHas, createSet = _createSet, setToArray = _setToArray;
var LARGE_ARRAY_SIZE = 200;
function baseUniq$1(array2, iteratee, comparator) {
  var index = -1, includes = arrayIncludes, length = array2.length, isCommon = true, result = [], seen2 = result;
  if (comparator) {
    isCommon = false;
    includes = arrayIncludesWith;
  } else if (length >= LARGE_ARRAY_SIZE) {
    var set = iteratee ? null : createSet(array2);
    if (set) {
      return setToArray(set);
    }
    isCommon = false;
    includes = cacheHas;
    seen2 = new SetCache();
  } else {
    seen2 = iteratee ? [] : result;
  }
  outer:
    while (++index < length) {
      var value = array2[index], computed = iteratee ? iteratee(value) : value;
      value = comparator || value !== 0 ? value : 0;
      if (isCommon && computed === computed) {
        var seenIndex = seen2.length;
        while (seenIndex--) {
          if (seen2[seenIndex] === computed) {
            continue outer;
          }
        }
        if (iteratee) {
          seen2.push(computed);
        }
        result.push(value);
      } else if (!includes(seen2, computed, comparator)) {
        if (seen2 !== result) {
          seen2.push(computed);
        }
        result.push(value);
      }
    }
  return result;
}
var _baseUniq = baseUniq$1;
var baseIteratee$9 = _baseIteratee, baseUniq = _baseUniq;
function uniqBy(array2, iteratee) {
  return array2 && array2.length ? baseUniq(array2, baseIteratee$9(iteratee)) : [];
}
var uniqBy_1 = uniqBy;
const uniqBy$1 = /* @__PURE__ */ getDefaultExportFromCjs(uniqBy_1);
function getUniqPayload(payload, option, defaultUniqBy2) {
  if (option === true) {
    return uniqBy$1(payload, defaultUniqBy2);
  }
  if (isFunction(option)) {
    return uniqBy$1(payload, option);
  }
  return payload;
}
function _typeof$C(o) {
  "@babel/helpers - typeof";
  return _typeof$C = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
    return typeof o2;
  } : function(o2) {
    return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
  }, _typeof$C(o);
}
var _excluded$d = ["ref"];
function ownKeys$w(e, r2) {
  var t = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    r2 && (o = o.filter(function(r3) {
      return Object.getOwnPropertyDescriptor(e, r3).enumerable;
    })), t.push.apply(t, o);
  }
  return t;
}
function _objectSpread$w(e) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys$w(Object(t), true).forEach(function(r3) {
      _defineProperty$C(e, r3, t[r3]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$w(Object(t)).forEach(function(r3) {
      Object.defineProperty(e, r3, Object.getOwnPropertyDescriptor(t, r3));
    });
  }
  return e;
}
function _classCallCheck$i(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function _defineProperties$i(target2, props) {
  for (var i = 0; i < props.length; i++) {
    var descriptor = props[i];
    descriptor.enumerable = descriptor.enumerable || false;
    descriptor.configurable = true;
    if ("value" in descriptor) descriptor.writable = true;
    Object.defineProperty(target2, _toPropertyKey$C(descriptor.key), descriptor);
  }
}
function _createClass$i(Constructor, protoProps, staticProps) {
  if (protoProps) _defineProperties$i(Constructor.prototype, protoProps);
  if (staticProps) _defineProperties$i(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", { writable: false });
  return Constructor;
}
function _callSuper$f(t, o, e) {
  return o = _getPrototypeOf$f(o), _possibleConstructorReturn$f(t, _isNativeReflectConstruct$f() ? Reflect.construct(o, e || [], _getPrototypeOf$f(t).constructor) : o.apply(t, e));
}
function _possibleConstructorReturn$f(self, call) {
  if (call && (_typeof$C(call) === "object" || typeof call === "function")) {
    return call;
  } else if (call !== void 0) {
    throw new TypeError("Derived constructors may only return object or undefined");
  }
  return _assertThisInitialized$f(self);
}
function _assertThisInitialized$f(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function _isNativeReflectConstruct$f() {
  try {
    var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {
    }));
  } catch (t2) {
  }
  return (_isNativeReflectConstruct$f = function _isNativeReflectConstruct2() {
    return !!t;
  })();
}
function _getPrototypeOf$f(o) {
  _getPrototypeOf$f = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf2(o2) {
    return o2.__proto__ || Object.getPrototypeOf(o2);
  };
  return _getPrototypeOf$f(o);
}
function _inherits$f(subClass, superClass) {
  if (typeof superClass !== "function" && superClass !== null) {
    throw new TypeError("Super expression must either be null or a function");
  }
  subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } });
  Object.defineProperty(subClass, "prototype", { writable: false });
  if (superClass) _setPrototypeOf$f(subClass, superClass);
}
function _setPrototypeOf$f(o, p) {
  _setPrototypeOf$f = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf2(o2, p2) {
    o2.__proto__ = p2;
    return o2;
  };
  return _setPrototypeOf$f(o, p);
}
function _defineProperty$C(obj, key2, value) {
  key2 = _toPropertyKey$C(key2);
  if (key2 in obj) {
    Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key2] = value;
  }
  return obj;
}
function _toPropertyKey$C(t) {
  var i = _toPrimitive$C(t, "string");
  return "symbol" == _typeof$C(i) ? i : i + "";
}
function _toPrimitive$C(t, r2) {
  if ("object" != _typeof$C(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r2);
    if ("object" != _typeof$C(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return String(t);
}
function _objectWithoutProperties$d(source, excluded) {
  if (source == null) return {};
  var target2 = _objectWithoutPropertiesLoose$d(source, excluded);
  var key2, i;
  if (Object.getOwnPropertySymbols) {
    var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
    for (i = 0; i < sourceSymbolKeys.length; i++) {
      key2 = sourceSymbolKeys[i];
      if (excluded.indexOf(key2) >= 0) continue;
      if (!Object.prototype.propertyIsEnumerable.call(source, key2)) continue;
      target2[key2] = source[key2];
    }
  }
  return target2;
}
function _objectWithoutPropertiesLoose$d(source, excluded) {
  if (source == null) return {};
  var target2 = {};
  for (var key2 in source) {
    if (Object.prototype.hasOwnProperty.call(source, key2)) {
      if (excluded.indexOf(key2) >= 0) continue;
      target2[key2] = source[key2];
    }
  }
  return target2;
}
function defaultUniqBy$1(entry) {
  return entry.value;
}
function renderContent$1(content, props) {
  if (/* @__PURE__ */ React.isValidElement(content)) {
    return /* @__PURE__ */ React.cloneElement(content, props);
  }
  if (typeof content === "function") {
    return /* @__PURE__ */ React.createElement(content, props);
  }
  props.ref;
  var otherProps = _objectWithoutProperties$d(props, _excluded$d);
  return /* @__PURE__ */ React.createElement(DefaultLegendContent, otherProps);
}
var EPS$1 = 1;
var Legend = /* @__PURE__ */ function(_PureComponent) {
  function Legend2() {
    var _this;
    _classCallCheck$i(this, Legend2);
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    _this = _callSuper$f(this, Legend2, [].concat(args));
    _defineProperty$C(_this, "lastBoundingBox", {
      width: -1,
      height: -1
    });
    return _this;
  }
  _inherits$f(Legend2, _PureComponent);
  return _createClass$i(Legend2, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      this.updateBBox();
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate() {
      this.updateBBox();
    }
  }, {
    key: "getBBox",
    value: function getBBox() {
      if (this.wrapperNode && this.wrapperNode.getBoundingClientRect) {
        var box = this.wrapperNode.getBoundingClientRect();
        box.height = this.wrapperNode.offsetHeight;
        box.width = this.wrapperNode.offsetWidth;
        return box;
      }
      return null;
    }
  }, {
    key: "updateBBox",
    value: function updateBBox() {
      var onBBoxUpdate = this.props.onBBoxUpdate;
      var box = this.getBBox();
      if (box) {
        if (Math.abs(box.width - this.lastBoundingBox.width) > EPS$1 || Math.abs(box.height - this.lastBoundingBox.height) > EPS$1) {
          this.lastBoundingBox.width = box.width;
          this.lastBoundingBox.height = box.height;
          if (onBBoxUpdate) {
            onBBoxUpdate(box);
          }
        }
      } else if (this.lastBoundingBox.width !== -1 || this.lastBoundingBox.height !== -1) {
        this.lastBoundingBox.width = -1;
        this.lastBoundingBox.height = -1;
        if (onBBoxUpdate) {
          onBBoxUpdate(null);
        }
      }
    }
  }, {
    key: "getBBoxSnapshot",
    value: function getBBoxSnapshot() {
      if (this.lastBoundingBox.width >= 0 && this.lastBoundingBox.height >= 0) {
        return _objectSpread$w({}, this.lastBoundingBox);
      }
      return {
        width: 0,
        height: 0
      };
    }
  }, {
    key: "getDefaultPosition",
    value: function getDefaultPosition(style) {
      var _this$props = this.props, layout = _this$props.layout, align = _this$props.align, verticalAlign = _this$props.verticalAlign, margin = _this$props.margin, chartWidth = _this$props.chartWidth, chartHeight = _this$props.chartHeight;
      var hPos, vPos;
      if (!style || (style.left === void 0 || style.left === null) && (style.right === void 0 || style.right === null)) {
        if (align === "center" && layout === "vertical") {
          var box = this.getBBoxSnapshot();
          hPos = {
            left: ((chartWidth || 0) - box.width) / 2
          };
        } else {
          hPos = align === "right" ? {
            right: margin && margin.right || 0
          } : {
            left: margin && margin.left || 0
          };
        }
      }
      if (!style || (style.top === void 0 || style.top === null) && (style.bottom === void 0 || style.bottom === null)) {
        if (verticalAlign === "middle") {
          var _box = this.getBBoxSnapshot();
          vPos = {
            top: ((chartHeight || 0) - _box.height) / 2
          };
        } else {
          vPos = verticalAlign === "bottom" ? {
            bottom: margin && margin.bottom || 0
          } : {
            top: margin && margin.top || 0
          };
        }
      }
      return _objectSpread$w(_objectSpread$w({}, hPos), vPos);
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;
      var _this$props2 = this.props, content = _this$props2.content, width = _this$props2.width, height = _this$props2.height, wrapperStyle = _this$props2.wrapperStyle, payloadUniqBy = _this$props2.payloadUniqBy, payload = _this$props2.payload;
      var outerStyle = _objectSpread$w(_objectSpread$w({
        position: "absolute",
        width: width || "auto",
        height: height || "auto"
      }, this.getDefaultPosition(wrapperStyle)), wrapperStyle);
      return /* @__PURE__ */ React.createElement("div", {
        className: "recharts-legend-wrapper",
        style: outerStyle,
        ref: function ref(node) {
          _this2.wrapperNode = node;
        }
      }, renderContent$1(content, _objectSpread$w(_objectSpread$w({}, this.props), {}, {
        payload: getUniqPayload(payload, payloadUniqBy, defaultUniqBy$1)
      })));
    }
  }], [{
    key: "getWithHeight",
    value: function getWithHeight(item, chartWidth) {
      var _this$defaultProps$it = _objectSpread$w(_objectSpread$w({}, this.defaultProps), item.props), layout = _this$defaultProps$it.layout;
      if (layout === "vertical" && isNumber(item.props.height)) {
        return {
          height: item.props.height
        };
      }
      if (layout === "horizontal") {
        return {
          width: item.props.width || chartWidth
        };
      }
      return null;
    }
  }]);
}(reactExports.PureComponent);
_defineProperty$C(Legend, "displayName", "Legend");
_defineProperty$C(Legend, "defaultProps", {
  iconSize: 14,
  layout: "horizontal",
  align: "center",
  verticalAlign: "bottom"
});
var Symbol$1 = _Symbol, isArguments = isArguments_1, isArray$4 = isArray_1;
var spreadableSymbol = Symbol$1 ? Symbol$1.isConcatSpreadable : void 0;
function isFlattenable$1(value) {
  return isArray$4(value) || isArguments(value) || !!(spreadableSymbol && value && value[spreadableSymbol]);
}
var _isFlattenable = isFlattenable$1;
var arrayPush = _arrayPush, isFlattenable = _isFlattenable;
function baseFlatten$2(array2, depth, predicate, isStrict, result) {
  var index = -1, length = array2.length;
  predicate || (predicate = isFlattenable);
  result || (result = []);
  while (++index < length) {
    var value = array2[index];
    if (depth > 0 && predicate(value)) {
      if (depth > 1) {
        baseFlatten$2(value, depth - 1, predicate, isStrict, result);
      } else {
        arrayPush(result, value);
      }
    } else if (!isStrict) {
      result[result.length] = value;
    }
  }
  return result;
}
var _baseFlatten = baseFlatten$2;
function createBaseFor$1(fromRight) {
  return function(object2, iteratee, keysFunc) {
    var index = -1, iterable = Object(object2), props = keysFunc(object2), length = props.length;
    while (length--) {
      var key2 = props[fromRight ? length : ++index];
      if (iteratee(iterable[key2], key2, iterable) === false) {
        break;
      }
    }
    return object2;
  };
}
var _createBaseFor = createBaseFor$1;
var createBaseFor = _createBaseFor;
var baseFor$1 = createBaseFor();
var _baseFor = baseFor$1;
var baseFor = _baseFor, keys$1 = keys_1;
function baseForOwn$2(object2, iteratee) {
  return object2 && baseFor(object2, iteratee, keys$1);
}
var _baseForOwn = baseForOwn$2;
var isArrayLike$3 = isArrayLike_1;
function createBaseEach$1(eachFunc, fromRight) {
  return function(collection, iteratee) {
    if (collection == null) {
      return collection;
    }
    if (!isArrayLike$3(collection)) {
      return eachFunc(collection, iteratee);
    }
    var length = collection.length, index = fromRight ? length : -1, iterable = Object(collection);
    while (fromRight ? index-- : ++index < length) {
      if (iteratee(iterable[index], index, iterable) === false) {
        break;
      }
    }
    return collection;
  };
}
var _createBaseEach = createBaseEach$1;
var baseForOwn$1 = _baseForOwn, createBaseEach = _createBaseEach;
var baseEach$3 = createBaseEach(baseForOwn$1);
var _baseEach = baseEach$3;
var baseEach$2 = _baseEach, isArrayLike$2 = isArrayLike_1;
function baseMap$2(collection, iteratee) {
  var index = -1, result = isArrayLike$2(collection) ? Array(collection.length) : [];
  baseEach$2(collection, function(value, key2, collection2) {
    result[++index] = iteratee(value, key2, collection2);
  });
  return result;
}
var _baseMap = baseMap$2;
function baseSortBy$1(array2, comparer) {
  var length = array2.length;
  array2.sort(comparer);
  while (length--) {
    array2[length] = array2[length].value;
  }
  return array2;
}
var _baseSortBy = baseSortBy$1;
var isSymbol$2 = isSymbol_1;
function compareAscending$1(value, other) {
  if (value !== other) {
    var valIsDefined = value !== void 0, valIsNull = value === null, valIsReflexive = value === value, valIsSymbol = isSymbol$2(value);
    var othIsDefined = other !== void 0, othIsNull = other === null, othIsReflexive = other === other, othIsSymbol = isSymbol$2(other);
    if (!othIsNull && !othIsSymbol && !valIsSymbol && value > other || valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol || valIsNull && othIsDefined && othIsReflexive || !valIsDefined && othIsReflexive || !valIsReflexive) {
      return 1;
    }
    if (!valIsNull && !valIsSymbol && !othIsSymbol && value < other || othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol || othIsNull && valIsDefined && valIsReflexive || !othIsDefined && valIsReflexive || !othIsReflexive) {
      return -1;
    }
  }
  return 0;
}
var _compareAscending = compareAscending$1;
var compareAscending = _compareAscending;
function compareMultiple$1(object2, other, orders) {
  var index = -1, objCriteria = object2.criteria, othCriteria = other.criteria, length = objCriteria.length, ordersLength = orders.length;
  while (++index < length) {
    var result = compareAscending(objCriteria[index], othCriteria[index]);
    if (result) {
      if (index >= ordersLength) {
        return result;
      }
      var order = orders[index];
      return result * (order == "desc" ? -1 : 1);
    }
  }
  return object2.index - other.index;
}
var _compareMultiple = compareMultiple$1;
var arrayMap$1 = _arrayMap, baseGet = _baseGet, baseIteratee$8 = _baseIteratee, baseMap$1 = _baseMap, baseSortBy = _baseSortBy, baseUnary = _baseUnary, compareMultiple = _compareMultiple, identity$8 = identity_1, isArray$3 = isArray_1;
function baseOrderBy$1(collection, iteratees, orders) {
  if (iteratees.length) {
    iteratees = arrayMap$1(iteratees, function(iteratee) {
      if (isArray$3(iteratee)) {
        return function(value) {
          return baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee);
        };
      }
      return iteratee;
    });
  } else {
    iteratees = [identity$8];
  }
  var index = -1;
  iteratees = arrayMap$1(iteratees, baseUnary(baseIteratee$8));
  var result = baseMap$1(collection, function(value, key2, collection2) {
    var criteria = arrayMap$1(iteratees, function(iteratee) {
      return iteratee(value);
    });
    return { "criteria": criteria, "index": ++index, "value": value };
  });
  return baseSortBy(result, function(object2, other) {
    return compareMultiple(object2, other, orders);
  });
}
var _baseOrderBy = baseOrderBy$1;
function apply$1(func, thisArg, args) {
  switch (args.length) {
    case 0:
      return func.call(thisArg);
    case 1:
      return func.call(thisArg, args[0]);
    case 2:
      return func.call(thisArg, args[0], args[1]);
    case 3:
      return func.call(thisArg, args[0], args[1], args[2]);
  }
  return func.apply(thisArg, args);
}
var _apply = apply$1;
var apply = _apply;
var nativeMax$3 = Math.max;
function overRest$1(func, start, transform) {
  start = nativeMax$3(start === void 0 ? func.length - 1 : start, 0);
  return function() {
    var args = arguments, index = -1, length = nativeMax$3(args.length - start, 0), array2 = Array(length);
    while (++index < length) {
      array2[index] = args[start + index];
    }
    index = -1;
    var otherArgs = Array(start + 1);
    while (++index < start) {
      otherArgs[index] = args[index];
    }
    otherArgs[start] = transform(array2);
    return apply(func, this, otherArgs);
  };
}
var _overRest = overRest$1;
function constant$2(value) {
  return function() {
    return value;
  };
}
var constant_1 = constant$2;
var getNative = _getNative;
var defineProperty$2 = function() {
  try {
    var func = getNative(Object, "defineProperty");
    func({}, "", {});
    return func;
  } catch (e) {
  }
}();
var _defineProperty$B = defineProperty$2;
var constant$1 = constant_1, defineProperty$1 = _defineProperty$B, identity$7 = identity_1;
var baseSetToString$1 = !defineProperty$1 ? identity$7 : function(func, string2) {
  return defineProperty$1(func, "toString", {
    "configurable": true,
    "enumerable": false,
    "value": constant$1(string2),
    "writable": true
  });
};
var _baseSetToString = baseSetToString$1;
var HOT_COUNT = 800, HOT_SPAN = 16;
var nativeNow = Date.now;
function shortOut$1(func) {
  var count = 0, lastCalled = 0;
  return function() {
    var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled);
    lastCalled = stamp;
    if (remaining > 0) {
      if (++count >= HOT_COUNT) {
        return arguments[0];
      }
    } else {
      count = 0;
    }
    return func.apply(void 0, arguments);
  };
}
var _shortOut = shortOut$1;
var baseSetToString = _baseSetToString, shortOut = _shortOut;
var setToString$1 = shortOut(baseSetToString);
var _setToString = setToString$1;
var identity$6 = identity_1, overRest = _overRest, setToString = _setToString;
function baseRest$1(func, start) {
  return setToString(overRest(func, start, identity$6), func + "");
}
var _baseRest = baseRest$1;
var eq = eq_1, isArrayLike$1 = isArrayLike_1, isIndex = _isIndex, isObject$3 = isObject_1;
function isIterateeCall$4(value, index, object2) {
  if (!isObject$3(object2)) {
    return false;
  }
  var type = typeof index;
  if (type == "number" ? isArrayLike$1(object2) && isIndex(index, object2.length) : type == "string" && index in object2) {
    return eq(object2[index], value);
  }
  return false;
}
var _isIterateeCall = isIterateeCall$4;
var baseFlatten$1 = _baseFlatten, baseOrderBy = _baseOrderBy, baseRest = _baseRest, isIterateeCall$3 = _isIterateeCall;
var sortBy = baseRest(function(collection, iteratees) {
  if (collection == null) {
    return [];
  }
  var length = iteratees.length;
  if (length > 1 && isIterateeCall$3(collection, iteratees[0], iteratees[1])) {
    iteratees = [];
  } else if (length > 2 && isIterateeCall$3(iteratees[0], iteratees[1], iteratees[2])) {
    iteratees = [iteratees[0]];
  }
  return baseOrderBy(collection, baseFlatten$1(iteratees, 1), []);
});
var sortBy_1 = sortBy;
const sortBy$1 = /* @__PURE__ */ getDefaultExportFromCjs(sortBy_1);
function _typeof$B(o) {
  "@babel/helpers - typeof";
  return _typeof$B = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
    return typeof o2;
  } : function(o2) {
    return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
  }, _typeof$B(o);
}
function _extends$p() {
  _extends$p = Object.assign ? Object.assign.bind() : function(target2) {
    for (var i = 1; i < arguments.length; i++) {
      var source = arguments[i];
      for (var key2 in source) {
        if (Object.prototype.hasOwnProperty.call(source, key2)) {
          target2[key2] = source[key2];
        }
      }
    }
    return target2;
  };
  return _extends$p.apply(this, arguments);
}
function _slicedToArray$a(arr, i) {
  return _arrayWithHoles$a(arr) || _iterableToArrayLimit$a(arr, i) || _unsupportedIterableToArray$g(arr, i) || _nonIterableRest$a();
}
function _nonIterableRest$a() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray$g(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return _arrayLikeToArray$g(o, minLen);
  var n = Object.prototype.toString.call(o).slice(8, -1);
  if (n === "Object" && o.constructor) n = o.constructor.name;
  if (n === "Map" || n === "Set") return Array.from(o);
  if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$g(o, minLen);
}
function _arrayLikeToArray$g(arr, len) {
  if (len == null || len > arr.length) len = arr.length;
  for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  return arr2;
}
function _iterableToArrayLimit$a(r2, l) {
  var t = null == r2 ? null : "undefined" != typeof Symbol && r2[Symbol.iterator] || r2["@@iterator"];
  if (null != t) {
    var e, n, i, u, a2 = [], f = true, o = false;
    try {
      if (i = (t = t.call(r2)).next, 0 === l) ;
      else for (; !(f = (e = i.call(t)).done) && (a2.push(e.value), a2.length !== l); f = true) ;
    } catch (r3) {
      o = true, n = r3;
    } finally {
      try {
        if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return;
      } finally {
        if (o) throw n;
      }
    }
    return a2;
  }
}
function _arrayWithHoles$a(arr) {
  if (Array.isArray(arr)) return arr;
}
function ownKeys$v(e, r2) {
  var t = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    r2 && (o = o.filter(function(r3) {
      return Object.getOwnPropertyDescriptor(e, r3).enumerable;
    })), t.push.apply(t, o);
  }
  return t;
}
function _objectSpread$v(e) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys$v(Object(t), true).forEach(function(r3) {
      _defineProperty$A(e, r3, t[r3]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$v(Object(t)).forEach(function(r3) {
      Object.defineProperty(e, r3, Object.getOwnPropertyDescriptor(t, r3));
    });
  }
  return e;
}
function _defineProperty$A(obj, key2, value) {
  key2 = _toPropertyKey$B(key2);
  if (key2 in obj) {
    Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key2] = value;
  }
  return obj;
}
function _toPropertyKey$B(t) {
  var i = _toPrimitive$B(t, "string");
  return "symbol" == _typeof$B(i) ? i : i + "";
}
function _toPrimitive$B(t, r2) {
  if ("object" != _typeof$B(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r2);
    if ("object" != _typeof$B(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return ("string" === r2 ? String : Number)(t);
}
function defaultFormatter(value) {
  return Array.isArray(value) && isNumOrStr(value[0]) && isNumOrStr(value[1]) ? value.join(" ~ ") : value;
}
var DefaultTooltipContent = function DefaultTooltipContent2(props) {
  var _props$separator = props.separator, separator = _props$separator === void 0 ? " : " : _props$separator, _props$contentStyle = props.contentStyle, contentStyle = _props$contentStyle === void 0 ? {} : _props$contentStyle, _props$itemStyle = props.itemStyle, itemStyle = _props$itemStyle === void 0 ? {} : _props$itemStyle, _props$labelStyle = props.labelStyle, labelStyle = _props$labelStyle === void 0 ? {} : _props$labelStyle, payload = props.payload, formatter = props.formatter, itemSorter = props.itemSorter, wrapperClassName = props.wrapperClassName, labelClassName = props.labelClassName, label = props.label, labelFormatter = props.labelFormatter, _props$accessibilityL = props.accessibilityLayer, accessibilityLayer = _props$accessibilityL === void 0 ? false : _props$accessibilityL;
  var renderContent2 = function renderContent3() {
    if (payload && payload.length) {
      var listStyle = {
        padding: 0,
        margin: 0
      };
      var items = (itemSorter ? sortBy$1(payload, itemSorter) : payload).map(function(entry, i) {
        if (entry.type === "none") {
          return null;
        }
        var finalItemStyle = _objectSpread$v({
          display: "block",
          paddingTop: 4,
          paddingBottom: 4,
          color: entry.color || "#000"
        }, itemStyle);
        var finalFormatter = entry.formatter || formatter || defaultFormatter;
        var value = entry.value, name = entry.name;
        var finalValue = value;
        var finalName = name;
        if (finalFormatter && finalValue != null && finalName != null) {
          var formatted = finalFormatter(value, name, entry, i, payload);
          if (Array.isArray(formatted)) {
            var _formatted = _slicedToArray$a(formatted, 2);
            finalValue = _formatted[0];
            finalName = _formatted[1];
          } else {
            finalValue = formatted;
          }
        }
        return (
          // eslint-disable-next-line react/no-array-index-key
          /* @__PURE__ */ React.createElement("li", {
            className: "recharts-tooltip-item",
            key: "tooltip-item-".concat(i),
            style: finalItemStyle
          }, isNumOrStr(finalName) ? /* @__PURE__ */ React.createElement("span", {
            className: "recharts-tooltip-item-name"
          }, finalName) : null, isNumOrStr(finalName) ? /* @__PURE__ */ React.createElement("span", {
            className: "recharts-tooltip-item-separator"
          }, separator) : null, /* @__PURE__ */ React.createElement("span", {
            className: "recharts-tooltip-item-value"
          }, finalValue), /* @__PURE__ */ React.createElement("span", {
            className: "recharts-tooltip-item-unit"
          }, entry.unit || ""))
        );
      });
      return /* @__PURE__ */ React.createElement("ul", {
        className: "recharts-tooltip-item-list",
        style: listStyle
      }, items);
    }
    return null;
  };
  var finalStyle = _objectSpread$v({
    margin: 0,
    padding: 10,
    backgroundColor: "#fff",
    border: "1px solid #ccc",
    whiteSpace: "nowrap"
  }, contentStyle);
  var finalLabelStyle = _objectSpread$v({
    margin: 0
  }, labelStyle);
  var hasLabel = !isNil$1(label);
  var finalLabel = hasLabel ? label : "";
  var wrapperCN = clsx("recharts-default-tooltip", wrapperClassName);
  var labelCN = clsx("recharts-tooltip-label", labelClassName);
  if (hasLabel && labelFormatter && payload !== void 0 && payload !== null) {
    finalLabel = labelFormatter(label, payload);
  }
  var accessibilityAttributes = accessibilityLayer ? {
    role: "status",
    "aria-live": "assertive"
  } : {};
  return /* @__PURE__ */ React.createElement("div", _extends$p({
    className: wrapperCN,
    style: finalStyle
  }, accessibilityAttributes), /* @__PURE__ */ React.createElement("p", {
    className: labelCN,
    style: finalLabelStyle
  }, /* @__PURE__ */ React.isValidElement(finalLabel) ? finalLabel : "".concat(finalLabel)), renderContent2());
};
function _typeof$A(o) {
  "@babel/helpers - typeof";
  return _typeof$A = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
    return typeof o2;
  } : function(o2) {
    return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
  }, _typeof$A(o);
}
function _defineProperty$z(obj, key2, value) {
  key2 = _toPropertyKey$A(key2);
  if (key2 in obj) {
    Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key2] = value;
  }
  return obj;
}
function _toPropertyKey$A(t) {
  var i = _toPrimitive$A(t, "string");
  return "symbol" == _typeof$A(i) ? i : i + "";
}
function _toPrimitive$A(t, r2) {
  if ("object" != _typeof$A(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r2);
    if ("object" != _typeof$A(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return ("string" === r2 ? String : Number)(t);
}
var CSS_CLASS_PREFIX = "recharts-tooltip-wrapper";
var TOOLTIP_HIDDEN = {
  visibility: "hidden"
};
function getTooltipCSSClassName(_ref) {
  var coordinate = _ref.coordinate, translateX = _ref.translateX, translateY = _ref.translateY;
  return clsx(CSS_CLASS_PREFIX, _defineProperty$z(_defineProperty$z(_defineProperty$z(_defineProperty$z({}, "".concat(CSS_CLASS_PREFIX, "-right"), isNumber(translateX) && coordinate && isNumber(coordinate.x) && translateX >= coordinate.x), "".concat(CSS_CLASS_PREFIX, "-left"), isNumber(translateX) && coordinate && isNumber(coordinate.x) && translateX < coordinate.x), "".concat(CSS_CLASS_PREFIX, "-bottom"), isNumber(translateY) && coordinate && isNumber(coordinate.y) && translateY >= coordinate.y), "".concat(CSS_CLASS_PREFIX, "-top"), isNumber(translateY) && coordinate && isNumber(coordinate.y) && translateY < coordinate.y));
}
function getTooltipTranslateXY(_ref2) {
  var allowEscapeViewBox = _ref2.allowEscapeViewBox, coordinate = _ref2.coordinate, key2 = _ref2.key, offsetTopLeft = _ref2.offsetTopLeft, position = _ref2.position, reverseDirection = _ref2.reverseDirection, tooltipDimension = _ref2.tooltipDimension, viewBox = _ref2.viewBox, viewBoxDimension = _ref2.viewBoxDimension;
  if (position && isNumber(position[key2])) {
    return position[key2];
  }
  var negative = coordinate[key2] - tooltipDimension - offsetTopLeft;
  var positive = coordinate[key2] + offsetTopLeft;
  if (allowEscapeViewBox[key2]) {
    return reverseDirection[key2] ? negative : positive;
  }
  if (reverseDirection[key2]) {
    var _tooltipBoundary = negative;
    var _viewBoxBoundary = viewBox[key2];
    if (_tooltipBoundary < _viewBoxBoundary) {
      return Math.max(positive, viewBox[key2]);
    }
    return Math.max(negative, viewBox[key2]);
  }
  var tooltipBoundary = positive + tooltipDimension;
  var viewBoxBoundary = viewBox[key2] + viewBoxDimension;
  if (tooltipBoundary > viewBoxBoundary) {
    return Math.max(negative, viewBox[key2]);
  }
  return Math.max(positive, viewBox[key2]);
}
function getTransformStyle(_ref3) {
  var translateX = _ref3.translateX, translateY = _ref3.translateY, useTranslate3d = _ref3.useTranslate3d;
  return {
    transform: useTranslate3d ? "translate3d(".concat(translateX, "px, ").concat(translateY, "px, 0)") : "translate(".concat(translateX, "px, ").concat(translateY, "px)")
  };
}
function getTooltipTranslate(_ref4) {
  var allowEscapeViewBox = _ref4.allowEscapeViewBox, coordinate = _ref4.coordinate, offsetTopLeft = _ref4.offsetTopLeft, position = _ref4.position, reverseDirection = _ref4.reverseDirection, tooltipBox = _ref4.tooltipBox, useTranslate3d = _ref4.useTranslate3d, viewBox = _ref4.viewBox;
  var cssProperties, translateX, translateY;
  if (tooltipBox.height > 0 && tooltipBox.width > 0 && coordinate) {
    translateX = getTooltipTranslateXY({
      allowEscapeViewBox,
      coordinate,
      key: "x",
      offsetTopLeft,
      position,
      reverseDirection,
      tooltipDimension: tooltipBox.width,
      viewBox,
      viewBoxDimension: viewBox.width
    });
    translateY = getTooltipTranslateXY({
      allowEscapeViewBox,
      coordinate,
      key: "y",
      offsetTopLeft,
      position,
      reverseDirection,
      tooltipDimension: tooltipBox.height,
      viewBox,
      viewBoxDimension: viewBox.height
    });
    cssProperties = getTransformStyle({
      translateX,
      translateY,
      useTranslate3d
    });
  } else {
    cssProperties = TOOLTIP_HIDDEN;
  }
  return {
    cssProperties,
    cssClasses: getTooltipCSSClassName({
      translateX,
      translateY,
      coordinate
    })
  };
}
function _typeof$z(o) {
  "@babel/helpers - typeof";
  return _typeof$z = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
    return typeof o2;
  } : function(o2) {
    return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
  }, _typeof$z(o);
}
function ownKeys$u(e, r2) {
  var t = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    r2 && (o = o.filter(function(r3) {
      return Object.getOwnPropertyDescriptor(e, r3).enumerable;
    })), t.push.apply(t, o);
  }
  return t;
}
function _objectSpread$u(e) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys$u(Object(t), true).forEach(function(r3) {
      _defineProperty$y(e, r3, t[r3]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$u(Object(t)).forEach(function(r3) {
      Object.defineProperty(e, r3, Object.getOwnPropertyDescriptor(t, r3));
    });
  }
  return e;
}
function _classCallCheck$h(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function _defineProperties$h(target2, props) {
  for (var i = 0; i < props.length; i++) {
    var descriptor = props[i];
    descriptor.enumerable = descriptor.enumerable || false;
    descriptor.configurable = true;
    if ("value" in descriptor) descriptor.writable = true;
    Object.defineProperty(target2, _toPropertyKey$z(descriptor.key), descriptor);
  }
}
function _createClass$h(Constructor, protoProps, staticProps) {
  if (protoProps) _defineProperties$h(Constructor.prototype, protoProps);
  Object.defineProperty(Constructor, "prototype", { writable: false });
  return Constructor;
}
function _callSuper$e(t, o, e) {
  return o = _getPrototypeOf$e(o), _possibleConstructorReturn$e(t, _isNativeReflectConstruct$e() ? Reflect.construct(o, e || [], _getPrototypeOf$e(t).constructor) : o.apply(t, e));
}
function _possibleConstructorReturn$e(self, call) {
  if (call && (_typeof$z(call) === "object" || typeof call === "function")) {
    return call;
  } else if (call !== void 0) {
    throw new TypeError("Derived constructors may only return object or undefined");
  }
  return _assertThisInitialized$e(self);
}
function _assertThisInitialized$e(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function _isNativeReflectConstruct$e() {
  try {
    var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {
    }));
  } catch (t2) {
  }
  return (_isNativeReflectConstruct$e = function _isNativeReflectConstruct2() {
    return !!t;
  })();
}
function _getPrototypeOf$e(o) {
  _getPrototypeOf$e = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf2(o2) {
    return o2.__proto__ || Object.getPrototypeOf(o2);
  };
  return _getPrototypeOf$e(o);
}
function _inherits$e(subClass, superClass) {
  if (typeof superClass !== "function" && superClass !== null) {
    throw new TypeError("Super expression must either be null or a function");
  }
  subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } });
  Object.defineProperty(subClass, "prototype", { writable: false });
  if (superClass) _setPrototypeOf$e(subClass, superClass);
}
function _setPrototypeOf$e(o, p) {
  _setPrototypeOf$e = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf2(o2, p2) {
    o2.__proto__ = p2;
    return o2;
  };
  return _setPrototypeOf$e(o, p);
}
function _defineProperty$y(obj, key2, value) {
  key2 = _toPropertyKey$z(key2);
  if (key2 in obj) {
    Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key2] = value;
  }
  return obj;
}
function _toPropertyKey$z(t) {
  var i = _toPrimitive$z(t, "string");
  return "symbol" == _typeof$z(i) ? i : i + "";
}
function _toPrimitive$z(t, r2) {
  if ("object" != _typeof$z(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r2);
    if ("object" != _typeof$z(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return String(t);
}
var EPSILON = 1;
var TooltipBoundingBox = /* @__PURE__ */ function(_PureComponent) {
  function TooltipBoundingBox2() {
    var _this;
    _classCallCheck$h(this, TooltipBoundingBox2);
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    _this = _callSuper$e(this, TooltipBoundingBox2, [].concat(args));
    _defineProperty$y(_this, "state", {
      dismissed: false,
      dismissedAtCoordinate: {
        x: 0,
        y: 0
      },
      lastBoundingBox: {
        width: -1,
        height: -1
      }
    });
    _defineProperty$y(_this, "handleKeyDown", function(event) {
      if (event.key === "Escape") {
        var _this$props$coordinat, _this$props$coordinat2, _this$props$coordinat3, _this$props$coordinat4;
        _this.setState({
          dismissed: true,
          dismissedAtCoordinate: {
            x: (_this$props$coordinat = (_this$props$coordinat2 = _this.props.coordinate) === null || _this$props$coordinat2 === void 0 ? void 0 : _this$props$coordinat2.x) !== null && _this$props$coordinat !== void 0 ? _this$props$coordinat : 0,
            y: (_this$props$coordinat3 = (_this$props$coordinat4 = _this.props.coordinate) === null || _this$props$coordinat4 === void 0 ? void 0 : _this$props$coordinat4.y) !== null && _this$props$coordinat3 !== void 0 ? _this$props$coordinat3 : 0
          }
        });
      }
    });
    return _this;
  }
  _inherits$e(TooltipBoundingBox2, _PureComponent);
  return _createClass$h(TooltipBoundingBox2, [{
    key: "updateBBox",
    value: function updateBBox() {
      if (this.wrapperNode && this.wrapperNode.getBoundingClientRect) {
        var box = this.wrapperNode.getBoundingClientRect();
        if (Math.abs(box.width - this.state.lastBoundingBox.width) > EPSILON || Math.abs(box.height - this.state.lastBoundingBox.height) > EPSILON) {
          this.setState({
            lastBoundingBox: {
              width: box.width,
              height: box.height
            }
          });
        }
      } else if (this.state.lastBoundingBox.width !== -1 || this.state.lastBoundingBox.height !== -1) {
        this.setState({
          lastBoundingBox: {
            width: -1,
            height: -1
          }
        });
      }
    }
  }, {
    key: "componentDidMount",
    value: function componentDidMount() {
      document.addEventListener("keydown", this.handleKeyDown);
      this.updateBBox();
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      document.removeEventListener("keydown", this.handleKeyDown);
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate() {
      var _this$props$coordinat5, _this$props$coordinat6;
      if (this.props.active) {
        this.updateBBox();
      }
      if (!this.state.dismissed) {
        return;
      }
      if (((_this$props$coordinat5 = this.props.coordinate) === null || _this$props$coordinat5 === void 0 ? void 0 : _this$props$coordinat5.x) !== this.state.dismissedAtCoordinate.x || ((_this$props$coordinat6 = this.props.coordinate) === null || _this$props$coordinat6 === void 0 ? void 0 : _this$props$coordinat6.y) !== this.state.dismissedAtCoordinate.y) {
        this.state.dismissed = false;
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;
      var _this$props = this.props, active = _this$props.active, allowEscapeViewBox = _this$props.allowEscapeViewBox, animationDuration = _this$props.animationDuration, animationEasing = _this$props.animationEasing, children = _this$props.children, coordinate = _this$props.coordinate, hasPayload = _this$props.hasPayload, isAnimationActive = _this$props.isAnimationActive, offset = _this$props.offset, position = _this$props.position, reverseDirection = _this$props.reverseDirection, useTranslate3d = _this$props.useTranslate3d, viewBox = _this$props.viewBox, wrapperStyle = _this$props.wrapperStyle;
      var _getTooltipTranslate = getTooltipTranslate({
        allowEscapeViewBox,
        coordinate,
        offsetTopLeft: offset,
        position,
        reverseDirection,
        tooltipBox: this.state.lastBoundingBox,
        useTranslate3d,
        viewBox
      }), cssClasses = _getTooltipTranslate.cssClasses, cssProperties = _getTooltipTranslate.cssProperties;
      var outerStyle = _objectSpread$u(_objectSpread$u({
        transition: isAnimationActive && active ? "transform ".concat(animationDuration, "ms ").concat(animationEasing) : void 0
      }, cssProperties), {}, {
        pointerEvents: "none",
        visibility: !this.state.dismissed && active && hasPayload ? "visible" : "hidden",
        position: "absolute",
        top: 0,
        left: 0
      }, wrapperStyle);
      return (
        // This element allow listening to the `Escape` key.
        // See https://github.com/recharts/recharts/pull/2925
        /* @__PURE__ */ React.createElement("div", {
          tabIndex: -1,
          className: cssClasses,
          style: outerStyle,
          ref: function ref(node) {
            _this2.wrapperNode = node;
          }
        }, children)
      );
    }
  }]);
}(reactExports.PureComponent);
var parseIsSsrByDefault = function parseIsSsrByDefault2() {
  return !(typeof window !== "undefined" && window.document && window.document.createElement && window.setTimeout);
};
var Global = {
  isSsr: parseIsSsrByDefault()
};
function _typeof$y(o) {
  "@babel/helpers - typeof";
  return _typeof$y = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
    return typeof o2;
  } : function(o2) {
    return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
  }, _typeof$y(o);
}
function ownKeys$t(e, r2) {
  var t = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    r2 && (o = o.filter(function(r3) {
      return Object.getOwnPropertyDescriptor(e, r3).enumerable;
    })), t.push.apply(t, o);
  }
  return t;
}
function _objectSpread$t(e) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys$t(Object(t), true).forEach(function(r3) {
      _defineProperty$x(e, r3, t[r3]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$t(Object(t)).forEach(function(r3) {
      Object.defineProperty(e, r3, Object.getOwnPropertyDescriptor(t, r3));
    });
  }
  return e;
}
function _classCallCheck$g(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function _defineProperties$g(target2, props) {
  for (var i = 0; i < props.length; i++) {
    var descriptor = props[i];
    descriptor.enumerable = descriptor.enumerable || false;
    descriptor.configurable = true;
    if ("value" in descriptor) descriptor.writable = true;
    Object.defineProperty(target2, _toPropertyKey$y(descriptor.key), descriptor);
  }
}
function _createClass$g(Constructor, protoProps, staticProps) {
  if (protoProps) _defineProperties$g(Constructor.prototype, protoProps);
  Object.defineProperty(Constructor, "prototype", { writable: false });
  return Constructor;
}
function _callSuper$d(t, o, e) {
  return o = _getPrototypeOf$d(o), _possibleConstructorReturn$d(t, _isNativeReflectConstruct$d() ? Reflect.construct(o, e || [], _getPrototypeOf$d(t).constructor) : o.apply(t, e));
}
function _possibleConstructorReturn$d(self, call) {
  if (call && (_typeof$y(call) === "object" || typeof call === "function")) {
    return call;
  } else if (call !== void 0) {
    throw new TypeError("Derived constructors may only return object or undefined");
  }
  return _assertThisInitialized$d(self);
}
function _assertThisInitialized$d(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function _isNativeReflectConstruct$d() {
  try {
    var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {
    }));
  } catch (t2) {
  }
  return (_isNativeReflectConstruct$d = function _isNativeReflectConstruct2() {
    return !!t;
  })();
}
function _getPrototypeOf$d(o) {
  _getPrototypeOf$d = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf2(o2) {
    return o2.__proto__ || Object.getPrototypeOf(o2);
  };
  return _getPrototypeOf$d(o);
}
function _inherits$d(subClass, superClass) {
  if (typeof superClass !== "function" && superClass !== null) {
    throw new TypeError("Super expression must either be null or a function");
  }
  subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } });
  Object.defineProperty(subClass, "prototype", { writable: false });
  if (superClass) _setPrototypeOf$d(subClass, superClass);
}
function _setPrototypeOf$d(o, p) {
  _setPrototypeOf$d = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf2(o2, p2) {
    o2.__proto__ = p2;
    return o2;
  };
  return _setPrototypeOf$d(o, p);
}
function _defineProperty$x(obj, key2, value) {
  key2 = _toPropertyKey$y(key2);
  if (key2 in obj) {
    Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key2] = value;
  }
  return obj;
}
function _toPropertyKey$y(t) {
  var i = _toPrimitive$y(t, "string");
  return "symbol" == _typeof$y(i) ? i : i + "";
}
function _toPrimitive$y(t, r2) {
  if ("object" != _typeof$y(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r2);
    if ("object" != _typeof$y(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return String(t);
}
function defaultUniqBy(entry) {
  return entry.dataKey;
}
function renderContent(content, props) {
  if (/* @__PURE__ */ React.isValidElement(content)) {
    return /* @__PURE__ */ React.cloneElement(content, props);
  }
  if (typeof content === "function") {
    return /* @__PURE__ */ React.createElement(content, props);
  }
  return /* @__PURE__ */ React.createElement(DefaultTooltipContent, props);
}
var Tooltip = /* @__PURE__ */ function(_PureComponent) {
  function Tooltip2() {
    _classCallCheck$g(this, Tooltip2);
    return _callSuper$d(this, Tooltip2, arguments);
  }
  _inherits$d(Tooltip2, _PureComponent);
  return _createClass$g(Tooltip2, [{
    key: "render",
    value: function render() {
      var _this = this;
      var _this$props = this.props, active = _this$props.active, allowEscapeViewBox = _this$props.allowEscapeViewBox, animationDuration = _this$props.animationDuration, animationEasing = _this$props.animationEasing, content = _this$props.content, coordinate = _this$props.coordinate, filterNull = _this$props.filterNull, isAnimationActive = _this$props.isAnimationActive, offset = _this$props.offset, payload = _this$props.payload, payloadUniqBy = _this$props.payloadUniqBy, position = _this$props.position, reverseDirection = _this$props.reverseDirection, useTranslate3d = _this$props.useTranslate3d, viewBox = _this$props.viewBox, wrapperStyle = _this$props.wrapperStyle;
      var finalPayload = payload !== null && payload !== void 0 ? payload : [];
      if (filterNull && finalPayload.length) {
        finalPayload = getUniqPayload(payload.filter(function(entry) {
          return entry.value != null && (entry.hide !== true || _this.props.includeHidden);
        }), payloadUniqBy, defaultUniqBy);
      }
      var hasPayload = finalPayload.length > 0;
      return /* @__PURE__ */ React.createElement(TooltipBoundingBox, {
        allowEscapeViewBox,
        animationDuration,
        animationEasing,
        isAnimationActive,
        active,
        coordinate,
        hasPayload,
        offset,
        position,
        reverseDirection,
        useTranslate3d,
        viewBox,
        wrapperStyle
      }, renderContent(content, _objectSpread$t(_objectSpread$t({}, this.props), {}, {
        payload: finalPayload
      })));
    }
  }]);
}(reactExports.PureComponent);
_defineProperty$x(Tooltip, "displayName", "Tooltip");
_defineProperty$x(Tooltip, "defaultProps", {
  accessibilityLayer: false,
  allowEscapeViewBox: {
    x: false,
    y: false
  },
  animationDuration: 400,
  animationEasing: "ease",
  contentStyle: {},
  coordinate: {
    x: 0,
    y: 0
  },
  cursor: true,
  cursorStyle: {},
  filterNull: true,
  isAnimationActive: !Global.isSsr,
  itemStyle: {},
  labelStyle: {},
  offset: 10,
  reverseDirection: {
    x: false,
    y: false
  },
  separator: " : ",
  trigger: "hover",
  useTranslate3d: false,
  viewBox: {
    x: 0,
    y: 0,
    height: 0,
    width: 0
  },
  wrapperStyle: {}
});
var root = _root;
var now$1 = function() {
  return root.Date.now();
};
var now_1 = now$1;
var reWhitespace = /\s/;
function trimmedEndIndex$1(string2) {
  var index = string2.length;
  while (index-- && reWhitespace.test(string2.charAt(index))) {
  }
  return index;
}
var _trimmedEndIndex = trimmedEndIndex$1;
var trimmedEndIndex = _trimmedEndIndex;
var reTrimStart = /^\s+/;
function baseTrim$1(string2) {
  return string2 ? string2.slice(0, trimmedEndIndex(string2) + 1).replace(reTrimStart, "") : string2;
}
var _baseTrim = baseTrim$1;
var baseTrim = _baseTrim, isObject$2 = isObject_1, isSymbol$1 = isSymbol_1;
var NAN = 0 / 0;
var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
var reIsBinary = /^0b[01]+$/i;
var reIsOctal = /^0o[0-7]+$/i;
var freeParseInt = parseInt;
function toNumber$2(value) {
  if (typeof value == "number") {
    return value;
  }
  if (isSymbol$1(value)) {
    return NAN;
  }
  if (isObject$2(value)) {
    var other = typeof value.valueOf == "function" ? value.valueOf() : value;
    value = isObject$2(other) ? other + "" : other;
  }
  if (typeof value != "string") {
    return value === 0 ? value : +value;
  }
  value = baseTrim(value);
  var isBinary = reIsBinary.test(value);
  return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;
}
var toNumber_1 = toNumber$2;
var isObject$1 = isObject_1, now = now_1, toNumber$1 = toNumber_1;
var FUNC_ERROR_TEXT$1 = "Expected a function";
var nativeMax$2 = Math.max, nativeMin = Math.min;
function debounce$1(func, wait, options2) {
  var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true;
  if (typeof func != "function") {
    throw new TypeError(FUNC_ERROR_TEXT$1);
  }
  wait = toNumber$1(wait) || 0;
  if (isObject$1(options2)) {
    leading = !!options2.leading;
    maxing = "maxWait" in options2;
    maxWait = maxing ? nativeMax$2(toNumber$1(options2.maxWait) || 0, wait) : maxWait;
    trailing = "trailing" in options2 ? !!options2.trailing : trailing;
  }
  function invokeFunc(time2) {
    var args = lastArgs, thisArg = lastThis;
    lastArgs = lastThis = void 0;
    lastInvokeTime = time2;
    result = func.apply(thisArg, args);
    return result;
  }
  function leadingEdge(time2) {
    lastInvokeTime = time2;
    timerId = setTimeout(timerExpired, wait);
    return leading ? invokeFunc(time2) : result;
  }
  function remainingWait(time2) {
    var timeSinceLastCall = time2 - lastCallTime, timeSinceLastInvoke = time2 - lastInvokeTime, timeWaiting = wait - timeSinceLastCall;
    return maxing ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting;
  }
  function shouldInvoke(time2) {
    var timeSinceLastCall = time2 - lastCallTime, timeSinceLastInvoke = time2 - lastInvokeTime;
    return lastCallTime === void 0 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
  }
  function timerExpired() {
    var time2 = now();
    if (shouldInvoke(time2)) {
      return trailingEdge(time2);
    }
    timerId = setTimeout(timerExpired, remainingWait(time2));
  }
  function trailingEdge(time2) {
    timerId = void 0;
    if (trailing && lastArgs) {
      return invokeFunc(time2);
    }
    lastArgs = lastThis = void 0;
    return result;
  }
  function cancel() {
    if (timerId !== void 0) {
      clearTimeout(timerId);
    }
    lastInvokeTime = 0;
    lastArgs = lastCallTime = lastThis = timerId = void 0;
  }
  function flush() {
    return timerId === void 0 ? result : trailingEdge(now());
  }
  function debounced() {
    var time2 = now(), isInvoking = shouldInvoke(time2);
    lastArgs = arguments;
    lastThis = this;
    lastCallTime = time2;
    if (isInvoking) {
      if (timerId === void 0) {
        return leadingEdge(lastCallTime);
      }
      if (maxing) {
        clearTimeout(timerId);
        timerId = setTimeout(timerExpired, wait);
        return invokeFunc(lastCallTime);
      }
    }
    if (timerId === void 0) {
      timerId = setTimeout(timerExpired, wait);
    }
    return result;
  }
  debounced.cancel = cancel;
  debounced.flush = flush;
  return debounced;
}
var debounce_1 = debounce$1;
var debounce = debounce_1, isObject = isObject_1;
var FUNC_ERROR_TEXT = "Expected a function";
function throttle(func, wait, options2) {
  var leading = true, trailing = true;
  if (typeof func != "function") {
    throw new TypeError(FUNC_ERROR_TEXT);
  }
  if (isObject(options2)) {
    leading = "leading" in options2 ? !!options2.leading : leading;
    trailing = "trailing" in options2 ? !!options2.trailing : trailing;
  }
  return debounce(func, wait, {
    "leading": leading,
    "maxWait": wait,
    "trailing": trailing
  });
}
var throttle_1 = throttle;
const throttle$1 = /* @__PURE__ */ getDefaultExportFromCjs(throttle_1);
function _typeof$x(o) {
  "@babel/helpers - typeof";
  return _typeof$x = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
    return typeof o2;
  } : function(o2) {
    return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
  }, _typeof$x(o);
}
function ownKeys$s(e, r2) {
  var t = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    r2 && (o = o.filter(function(r3) {
      return Object.getOwnPropertyDescriptor(e, r3).enumerable;
    })), t.push.apply(t, o);
  }
  return t;
}
function _objectSpread$s(e) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys$s(Object(t), true).forEach(function(r3) {
      _defineProperty$w(e, r3, t[r3]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$s(Object(t)).forEach(function(r3) {
      Object.defineProperty(e, r3, Object.getOwnPropertyDescriptor(t, r3));
    });
  }
  return e;
}
function _defineProperty$w(obj, key2, value) {
  key2 = _toPropertyKey$x(key2);
  if (key2 in obj) {
    Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key2] = value;
  }
  return obj;
}
function _toPropertyKey$x(t) {
  var i = _toPrimitive$x(t, "string");
  return "symbol" == _typeof$x(i) ? i : i + "";
}
function _toPrimitive$x(t, r2) {
  if ("object" != _typeof$x(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r2);
    if ("object" != _typeof$x(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return ("string" === r2 ? String : Number)(t);
}
function _slicedToArray$9(arr, i) {
  return _arrayWithHoles$9(arr) || _iterableToArrayLimit$9(arr, i) || _unsupportedIterableToArray$f(arr, i) || _nonIterableRest$9();
}
function _nonIterableRest$9() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray$f(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return _arrayLikeToArray$f(o, minLen);
  var n = Object.prototype.toString.call(o).slice(8, -1);
  if (n === "Object" && o.constructor) n = o.constructor.name;
  if (n === "Map" || n === "Set") return Array.from(o);
  if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$f(o, minLen);
}
function _arrayLikeToArray$f(arr, len) {
  if (len == null || len > arr.length) len = arr.length;
  for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  return arr2;
}
function _iterableToArrayLimit$9(r2, l) {
  var t = null == r2 ? null : "undefined" != typeof Symbol && r2[Symbol.iterator] || r2["@@iterator"];
  if (null != t) {
    var e, n, i, u, a2 = [], f = true, o = false;
    try {
      if (i = (t = t.call(r2)).next, 0 === l) ;
      else for (; !(f = (e = i.call(t)).done) && (a2.push(e.value), a2.length !== l); f = true) ;
    } catch (r3) {
      o = true, n = r3;
    } finally {
      try {
        if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return;
      } finally {
        if (o) throw n;
      }
    }
    return a2;
  }
}
function _arrayWithHoles$9(arr) {
  if (Array.isArray(arr)) return arr;
}
var ResponsiveContainer = /* @__PURE__ */ reactExports.forwardRef(function(_ref, ref) {
  var aspect = _ref.aspect, _ref$initialDimension = _ref.initialDimension, initialDimension = _ref$initialDimension === void 0 ? {
    width: -1,
    height: -1
  } : _ref$initialDimension, _ref$width = _ref.width, width = _ref$width === void 0 ? "100%" : _ref$width, _ref$height = _ref.height, height = _ref$height === void 0 ? "100%" : _ref$height, _ref$minWidth = _ref.minWidth, minWidth = _ref$minWidth === void 0 ? 0 : _ref$minWidth, minHeight = _ref.minHeight, maxHeight = _ref.maxHeight, children = _ref.children, _ref$debounce = _ref.debounce, debounce2 = _ref$debounce === void 0 ? 0 : _ref$debounce, id = _ref.id, className = _ref.className, onResize = _ref.onResize, _ref$style = _ref.style, style = _ref$style === void 0 ? {} : _ref$style;
  var containerRef = reactExports.useRef(null);
  var onResizeRef = reactExports.useRef();
  onResizeRef.current = onResize;
  reactExports.useImperativeHandle(ref, function() {
    return Object.defineProperty(containerRef.current, "current", {
      get: function get2() {
        console.warn("The usage of ref.current.current is deprecated and will no longer be supported.");
        return containerRef.current;
      },
      configurable: true
    });
  });
  var _useState = reactExports.useState({
    containerWidth: initialDimension.width,
    containerHeight: initialDimension.height
  }), _useState2 = _slicedToArray$9(_useState, 2), sizes = _useState2[0], setSizes = _useState2[1];
  var setContainerSize = reactExports.useCallback(function(newWidth, newHeight) {
    setSizes(function(prevState) {
      var roundedWidth = Math.round(newWidth);
      var roundedHeight = Math.round(newHeight);
      if (prevState.containerWidth === roundedWidth && prevState.containerHeight === roundedHeight) {
        return prevState;
      }
      return {
        containerWidth: roundedWidth,
        containerHeight: roundedHeight
      };
    });
  }, []);
  reactExports.useEffect(function() {
    var callback2 = function callback3(entries) {
      var _onResizeRef$current;
      var _entries$0$contentRec = entries[0].contentRect, containerWidth2 = _entries$0$contentRec.width, containerHeight2 = _entries$0$contentRec.height;
      setContainerSize(containerWidth2, containerHeight2);
      (_onResizeRef$current = onResizeRef.current) === null || _onResizeRef$current === void 0 || _onResizeRef$current.call(onResizeRef, containerWidth2, containerHeight2);
    };
    if (debounce2 > 0) {
      callback2 = throttle$1(callback2, debounce2, {
        trailing: true,
        leading: false
      });
    }
    var observer = new ResizeObserver(callback2);
    var _containerRef$current = containerRef.current.getBoundingClientRect(), containerWidth = _containerRef$current.width, containerHeight = _containerRef$current.height;
    setContainerSize(containerWidth, containerHeight);
    observer.observe(containerRef.current);
    return function() {
      observer.disconnect();
    };
  }, [setContainerSize, debounce2]);
  var chartContent = reactExports.useMemo(function() {
    var containerWidth = sizes.containerWidth, containerHeight = sizes.containerHeight;
    if (containerWidth < 0 || containerHeight < 0) {
      return null;
    }
    warn(isPercent(width) || isPercent(height), "The width(%s) and height(%s) are both fixed numbers,\n       maybe you don't need to use a ResponsiveContainer.", width, height);
    warn(!aspect || aspect > 0, "The aspect(%s) must be greater than zero.", aspect);
    var calculatedWidth = isPercent(width) ? containerWidth : width;
    var calculatedHeight = isPercent(height) ? containerHeight : height;
    if (aspect && aspect > 0) {
      if (calculatedWidth) {
        calculatedHeight = calculatedWidth / aspect;
      } else if (calculatedHeight) {
        calculatedWidth = calculatedHeight * aspect;
      }
      if (maxHeight && calculatedHeight > maxHeight) {
        calculatedHeight = maxHeight;
      }
    }
    warn(calculatedWidth > 0 || calculatedHeight > 0, "The width(%s) and height(%s) of chart should be greater than 0,\n       please check the style of container, or the props width(%s) and height(%s),\n       or add a minWidth(%s) or minHeight(%s) or use aspect(%s) to control the\n       height and width.", calculatedWidth, calculatedHeight, width, height, minWidth, minHeight, aspect);
    var isCharts = !Array.isArray(children) && getDisplayName(children.type).endsWith("Chart");
    return React.Children.map(children, function(child) {
      if (/* @__PURE__ */ React.isValidElement(child)) {
        return /* @__PURE__ */ reactExports.cloneElement(child, _objectSpread$s({
          width: calculatedWidth,
          height: calculatedHeight
        }, isCharts ? {
          style: _objectSpread$s({
            height: "100%",
            width: "100%",
            maxHeight: calculatedHeight,
            maxWidth: calculatedWidth
          }, child.props.style)
        } : {}));
      }
      return child;
    });
  }, [aspect, children, height, maxHeight, minHeight, minWidth, sizes, width]);
  return /* @__PURE__ */ React.createElement("div", {
    id: id ? "".concat(id) : void 0,
    className: clsx("recharts-responsive-container", className),
    style: _objectSpread$s(_objectSpread$s({}, style), {}, {
      width,
      height,
      minWidth,
      minHeight,
      maxHeight
    }),
    ref: containerRef
  }, chartContent);
});
var Cell = function Cell2(_props) {
  return null;
};
Cell.displayName = "Cell";
function _typeof$w(o) {
  "@babel/helpers - typeof";
  return _typeof$w = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
    return typeof o2;
  } : function(o2) {
    return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
  }, _typeof$w(o);
}
function ownKeys$r(e, r2) {
  var t = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    r2 && (o = o.filter(function(r3) {
      return Object.getOwnPropertyDescriptor(e, r3).enumerable;
    })), t.push.apply(t, o);
  }
  return t;
}
function _objectSpread$r(e) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys$r(Object(t), true).forEach(function(r3) {
      _defineProperty$v(e, r3, t[r3]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$r(Object(t)).forEach(function(r3) {
      Object.defineProperty(e, r3, Object.getOwnPropertyDescriptor(t, r3));
    });
  }
  return e;
}
function _defineProperty$v(obj, key2, value) {
  key2 = _toPropertyKey$w(key2);
  if (key2 in obj) {
    Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key2] = value;
  }
  return obj;
}
function _toPropertyKey$w(t) {
  var i = _toPrimitive$w(t, "string");
  return "symbol" == _typeof$w(i) ? i : i + "";
}
function _toPrimitive$w(t, r2) {
  if ("object" != _typeof$w(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r2);
    if ("object" != _typeof$w(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return ("string" === r2 ? String : Number)(t);
}
var stringCache = {
  widthCache: {},
  cacheCount: 0
};
var MAX_CACHE_NUM = 2e3;
var SPAN_STYLE = {
  position: "absolute",
  top: "-20000px",
  left: 0,
  padding: 0,
  margin: 0,
  border: "none",
  whiteSpace: "pre"
};
var MEASUREMENT_SPAN_ID = "recharts_measurement_span";
function removeInvalidKeys(obj) {
  var copyObj = _objectSpread$r({}, obj);
  Object.keys(copyObj).forEach(function(key2) {
    if (!copyObj[key2]) {
      delete copyObj[key2];
    }
  });
  return copyObj;
}
var getStringSize = function getStringSize2(text) {
  var style = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
  if (text === void 0 || text === null || Global.isSsr) {
    return {
      width: 0,
      height: 0
    };
  }
  var copyStyle = removeInvalidKeys(style);
  var cacheKey = JSON.stringify({
    text,
    copyStyle
  });
  if (stringCache.widthCache[cacheKey]) {
    return stringCache.widthCache[cacheKey];
  }
  try {
    var measurementSpan = document.getElementById(MEASUREMENT_SPAN_ID);
    if (!measurementSpan) {
      measurementSpan = document.createElement("span");
      measurementSpan.setAttribute("id", MEASUREMENT_SPAN_ID);
      measurementSpan.setAttribute("aria-hidden", "true");
      document.body.appendChild(measurementSpan);
    }
    var measurementSpanStyle = _objectSpread$r(_objectSpread$r({}, SPAN_STYLE), copyStyle);
    Object.assign(measurementSpan.style, measurementSpanStyle);
    measurementSpan.textContent = "".concat(text);
    var rect = measurementSpan.getBoundingClientRect();
    var result = {
      width: rect.width,
      height: rect.height
    };
    stringCache.widthCache[cacheKey] = result;
    if (++stringCache.cacheCount > MAX_CACHE_NUM) {
      stringCache.cacheCount = 0;
      stringCache.widthCache = {};
    }
    return result;
  } catch (e) {
    return {
      width: 0,
      height: 0
    };
  }
};
var getOffset = function getOffset2(rect) {
  return {
    top: rect.top + window.scrollY - document.documentElement.clientTop,
    left: rect.left + window.scrollX - document.documentElement.clientLeft
  };
};
function _typeof$v(o) {
  "@babel/helpers - typeof";
  return _typeof$v = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
    return typeof o2;
  } : function(o2) {
    return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
  }, _typeof$v(o);
}
function _slicedToArray$8(arr, i) {
  return _arrayWithHoles$8(arr) || _iterableToArrayLimit$8(arr, i) || _unsupportedIterableToArray$e(arr, i) || _nonIterableRest$8();
}
function _nonIterableRest$8() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray$e(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return _arrayLikeToArray$e(o, minLen);
  var n = Object.prototype.toString.call(o).slice(8, -1);
  if (n === "Object" && o.constructor) n = o.constructor.name;
  if (n === "Map" || n === "Set") return Array.from(o);
  if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$e(o, minLen);
}
function _arrayLikeToArray$e(arr, len) {
  if (len == null || len > arr.length) len = arr.length;
  for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  return arr2;
}
function _iterableToArrayLimit$8(r2, l) {
  var t = null == r2 ? null : "undefined" != typeof Symbol && r2[Symbol.iterator] || r2["@@iterator"];
  if (null != t) {
    var e, n, i, u, a2 = [], f = true, o = false;
    try {
      if (i = (t = t.call(r2)).next, 0 === l) {
        if (Object(t) !== t) return;
        f = false;
      } else for (; !(f = (e = i.call(t)).done) && (a2.push(e.value), a2.length !== l); f = true) ;
    } catch (r3) {
      o = true, n = r3;
    } finally {
      try {
        if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return;
      } finally {
        if (o) throw n;
      }
    }
    return a2;
  }
}
function _arrayWithHoles$8(arr) {
  if (Array.isArray(arr)) return arr;
}
function _classCallCheck$f(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function _defineProperties$f(target2, props) {
  for (var i = 0; i < props.length; i++) {
    var descriptor = props[i];
    descriptor.enumerable = descriptor.enumerable || false;
    descriptor.configurable = true;
    if ("value" in descriptor) descriptor.writable = true;
    Object.defineProperty(target2, _toPropertyKey$v(descriptor.key), descriptor);
  }
}
function _createClass$f(Constructor, protoProps, staticProps) {
  if (protoProps) _defineProperties$f(Constructor.prototype, protoProps);
  if (staticProps) _defineProperties$f(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", { writable: false });
  return Constructor;
}
function _toPropertyKey$v(t) {
  var i = _toPrimitive$v(t, "string");
  return "symbol" == _typeof$v(i) ? i : i + "";
}
function _toPrimitive$v(t, r2) {
  if ("object" != _typeof$v(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r2);
    if ("object" != _typeof$v(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return String(t);
}
var MULTIPLY_OR_DIVIDE_REGEX = /(-?\d+(?:\.\d+)?[a-zA-Z%]*)([*/])(-?\d+(?:\.\d+)?[a-zA-Z%]*)/;
var ADD_OR_SUBTRACT_REGEX = /(-?\d+(?:\.\d+)?[a-zA-Z%]*)([+-])(-?\d+(?:\.\d+)?[a-zA-Z%]*)/;
var CSS_LENGTH_UNIT_REGEX = /^px|cm|vh|vw|em|rem|%|mm|in|pt|pc|ex|ch|vmin|vmax|Q$/;
var NUM_SPLIT_REGEX = /(-?\d+(?:\.\d+)?)([a-zA-Z%]+)?/;
var CONVERSION_RATES = {
  cm: 96 / 2.54,
  mm: 96 / 25.4,
  pt: 96 / 72,
  pc: 96 / 6,
  "in": 96,
  Q: 96 / (2.54 * 40),
  px: 1
};
var FIXED_CSS_LENGTH_UNITS = Object.keys(CONVERSION_RATES);
var STR_NAN = "NaN";
function convertToPx(value, unit2) {
  return value * CONVERSION_RATES[unit2];
}
var DecimalCSS = /* @__PURE__ */ function() {
  function DecimalCSS2(num, unit2) {
    _classCallCheck$f(this, DecimalCSS2);
    this.num = num;
    this.unit = unit2;
    this.num = num;
    this.unit = unit2;
    if (Number.isNaN(num)) {
      this.unit = "";
    }
    if (unit2 !== "" && !CSS_LENGTH_UNIT_REGEX.test(unit2)) {
      this.num = NaN;
      this.unit = "";
    }
    if (FIXED_CSS_LENGTH_UNITS.includes(unit2)) {
      this.num = convertToPx(num, unit2);
      this.unit = "px";
    }
  }
  return _createClass$f(DecimalCSS2, [{
    key: "add",
    value: function add2(other) {
      if (this.unit !== other.unit) {
        return new DecimalCSS2(NaN, "");
      }
      return new DecimalCSS2(this.num + other.num, this.unit);
    }
  }, {
    key: "subtract",
    value: function subtract2(other) {
      if (this.unit !== other.unit) {
        return new DecimalCSS2(NaN, "");
      }
      return new DecimalCSS2(this.num - other.num, this.unit);
    }
  }, {
    key: "multiply",
    value: function multiply(other) {
      if (this.unit !== "" && other.unit !== "" && this.unit !== other.unit) {
        return new DecimalCSS2(NaN, "");
      }
      return new DecimalCSS2(this.num * other.num, this.unit || other.unit);
    }
  }, {
    key: "divide",
    value: function divide2(other) {
      if (this.unit !== "" && other.unit !== "" && this.unit !== other.unit) {
        return new DecimalCSS2(NaN, "");
      }
      return new DecimalCSS2(this.num / other.num, this.unit || other.unit);
    }
  }, {
    key: "toString",
    value: function toString2() {
      return "".concat(this.num).concat(this.unit);
    }
  }, {
    key: "isNaN",
    value: function isNaN2() {
      return Number.isNaN(this.num);
    }
  }], [{
    key: "parse",
    value: function parse2(str) {
      var _NUM_SPLIT_REGEX$exec;
      var _ref = (_NUM_SPLIT_REGEX$exec = NUM_SPLIT_REGEX.exec(str)) !== null && _NUM_SPLIT_REGEX$exec !== void 0 ? _NUM_SPLIT_REGEX$exec : [], _ref2 = _slicedToArray$8(_ref, 3), numStr = _ref2[1], unit2 = _ref2[2];
      return new DecimalCSS2(parseFloat(numStr), unit2 !== null && unit2 !== void 0 ? unit2 : "");
    }
  }]);
}();
function calculateArithmetic(expr) {
  if (expr.includes(STR_NAN)) {
    return STR_NAN;
  }
  var newExpr = expr;
  while (newExpr.includes("*") || newExpr.includes("/")) {
    var _MULTIPLY_OR_DIVIDE_R;
    var _ref3 = (_MULTIPLY_OR_DIVIDE_R = MULTIPLY_OR_DIVIDE_REGEX.exec(newExpr)) !== null && _MULTIPLY_OR_DIVIDE_R !== void 0 ? _MULTIPLY_OR_DIVIDE_R : [], _ref4 = _slicedToArray$8(_ref3, 4), leftOperand = _ref4[1], operator = _ref4[2], rightOperand = _ref4[3];
    var lTs = DecimalCSS.parse(leftOperand !== null && leftOperand !== void 0 ? leftOperand : "");
    var rTs = DecimalCSS.parse(rightOperand !== null && rightOperand !== void 0 ? rightOperand : "");
    var result = operator === "*" ? lTs.multiply(rTs) : lTs.divide(rTs);
    if (result.isNaN()) {
      return STR_NAN;
    }
    newExpr = newExpr.replace(MULTIPLY_OR_DIVIDE_REGEX, result.toString());
  }
  while (newExpr.includes("+") || /.-\d+(?:\.\d+)?/.test(newExpr)) {
    var _ADD_OR_SUBTRACT_REGE;
    var _ref5 = (_ADD_OR_SUBTRACT_REGE = ADD_OR_SUBTRACT_REGEX.exec(newExpr)) !== null && _ADD_OR_SUBTRACT_REGE !== void 0 ? _ADD_OR_SUBTRACT_REGE : [], _ref6 = _slicedToArray$8(_ref5, 4), _leftOperand = _ref6[1], _operator = _ref6[2], _rightOperand = _ref6[3];
    var _lTs = DecimalCSS.parse(_leftOperand !== null && _leftOperand !== void 0 ? _leftOperand : "");
    var _rTs = DecimalCSS.parse(_rightOperand !== null && _rightOperand !== void 0 ? _rightOperand : "");
    var _result = _operator === "+" ? _lTs.add(_rTs) : _lTs.subtract(_rTs);
    if (_result.isNaN()) {
      return STR_NAN;
    }
    newExpr = newExpr.replace(ADD_OR_SUBTRACT_REGEX, _result.toString());
  }
  return newExpr;
}
var PARENTHESES_REGEX = /\(([^()]*)\)/;
function calculateParentheses(expr) {
  var newExpr = expr;
  while (newExpr.includes("(")) {
    var _PARENTHESES_REGEX$ex = PARENTHESES_REGEX.exec(newExpr), _PARENTHESES_REGEX$ex2 = _slicedToArray$8(_PARENTHESES_REGEX$ex, 2), parentheticalExpression = _PARENTHESES_REGEX$ex2[1];
    newExpr = newExpr.replace(PARENTHESES_REGEX, calculateArithmetic(parentheticalExpression));
  }
  return newExpr;
}
function evaluateExpression(expression) {
  var newExpr = expression.replace(/\s+/g, "");
  newExpr = calculateParentheses(newExpr);
  newExpr = calculateArithmetic(newExpr);
  return newExpr;
}
function safeEvaluateExpression(expression) {
  try {
    return evaluateExpression(expression);
  } catch (e) {
    return STR_NAN;
  }
}
function reduceCSSCalc(expression) {
  var result = safeEvaluateExpression(expression.slice(5, -1));
  if (result === STR_NAN) {
    return "";
  }
  return result;
}
var _excluded$c = ["x", "y", "lineHeight", "capHeight", "scaleToFit", "textAnchor", "verticalAnchor", "fill"], _excluded2$5 = ["dx", "dy", "angle", "className", "breakAll"];
function _extends$o() {
  _extends$o = Object.assign ? Object.assign.bind() : function(target2) {
    for (var i = 1; i < arguments.length; i++) {
      var source = arguments[i];
      for (var key2 in source) {
        if (Object.prototype.hasOwnProperty.call(source, key2)) {
          target2[key2] = source[key2];
        }
      }
    }
    return target2;
  };
  return _extends$o.apply(this, arguments);
}
function _objectWithoutProperties$c(source, excluded) {
  if (source == null) return {};
  var target2 = _objectWithoutPropertiesLoose$c(source, excluded);
  var key2, i;
  if (Object.getOwnPropertySymbols) {
    var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
    for (i = 0; i < sourceSymbolKeys.length; i++) {
      key2 = sourceSymbolKeys[i];
      if (excluded.indexOf(key2) >= 0) continue;
      if (!Object.prototype.propertyIsEnumerable.call(source, key2)) continue;
      target2[key2] = source[key2];
    }
  }
  return target2;
}
function _objectWithoutPropertiesLoose$c(source, excluded) {
  if (source == null) return {};
  var target2 = {};
  for (var key2 in source) {
    if (Object.prototype.hasOwnProperty.call(source, key2)) {
      if (excluded.indexOf(key2) >= 0) continue;
      target2[key2] = source[key2];
    }
  }
  return target2;
}
function _slicedToArray$7(arr, i) {
  return _arrayWithHoles$7(arr) || _iterableToArrayLimit$7(arr, i) || _unsupportedIterableToArray$d(arr, i) || _nonIterableRest$7();
}
function _nonIterableRest$7() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray$d(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return _arrayLikeToArray$d(o, minLen);
  var n = Object.prototype.toString.call(o).slice(8, -1);
  if (n === "Object" && o.constructor) n = o.constructor.name;
  if (n === "Map" || n === "Set") return Array.from(o);
  if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$d(o, minLen);
}
function _arrayLikeToArray$d(arr, len) {
  if (len == null || len > arr.length) len = arr.length;
  for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  return arr2;
}
function _iterableToArrayLimit$7(r2, l) {
  var t = null == r2 ? null : "undefined" != typeof Symbol && r2[Symbol.iterator] || r2["@@iterator"];
  if (null != t) {
    var e, n, i, u, a2 = [], f = true, o = false;
    try {
      if (i = (t = t.call(r2)).next, 0 === l) {
        if (Object(t) !== t) return;
        f = false;
      } else for (; !(f = (e = i.call(t)).done) && (a2.push(e.value), a2.length !== l); f = true) ;
    } catch (r3) {
      o = true, n = r3;
    } finally {
      try {
        if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return;
      } finally {
        if (o) throw n;
      }
    }
    return a2;
  }
}
function _arrayWithHoles$7(arr) {
  if (Array.isArray(arr)) return arr;
}
var BREAKING_SPACES = /[ \f\n\r\t\v\u2028\u2029]+/;
var calculateWordWidths = function calculateWordWidths2(_ref) {
  var children = _ref.children, breakAll = _ref.breakAll, style = _ref.style;
  try {
    var words = [];
    if (!isNil$1(children)) {
      if (breakAll) {
        words = children.toString().split("");
      } else {
        words = children.toString().split(BREAKING_SPACES);
      }
    }
    var wordsWithComputedWidth = words.map(function(word) {
      return {
        word,
        width: getStringSize(word, style).width
      };
    });
    var spaceWidth = breakAll ? 0 : getStringSize(" ", style).width;
    return {
      wordsWithComputedWidth,
      spaceWidth
    };
  } catch (e) {
    return null;
  }
};
var calculateWordsByLines = function calculateWordsByLines2(_ref2, initialWordsWithComputedWith, spaceWidth, lineWidth, scaleToFit) {
  var maxLines = _ref2.maxLines, children = _ref2.children, style = _ref2.style, breakAll = _ref2.breakAll;
  var shouldLimitLines = isNumber(maxLines);
  var text = children;
  var calculate = function calculate2() {
    var words = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : [];
    return words.reduce(function(result2, _ref3) {
      var word = _ref3.word, width = _ref3.width;
      var currentLine = result2[result2.length - 1];
      if (currentLine && (lineWidth == null || scaleToFit || currentLine.width + width + spaceWidth < Number(lineWidth))) {
        currentLine.words.push(word);
        currentLine.width += width + spaceWidth;
      } else {
        var newLine = {
          words: [word],
          width
        };
        result2.push(newLine);
      }
      return result2;
    }, []);
  };
  var originalResult = calculate(initialWordsWithComputedWith);
  var findLongestLine = function findLongestLine2(words) {
    return words.reduce(function(a2, b) {
      return a2.width > b.width ? a2 : b;
    });
  };
  if (!shouldLimitLines) {
    return originalResult;
  }
  var suffix = "…";
  var checkOverflow = function checkOverflow2(index) {
    var tempText = text.slice(0, index);
    var words = calculateWordWidths({
      breakAll,
      style,
      children: tempText + suffix
    }).wordsWithComputedWidth;
    var result2 = calculate(words);
    var doesOverflow = result2.length > maxLines || findLongestLine(result2).width > Number(lineWidth);
    return [doesOverflow, result2];
  };
  var start = 0;
  var end = text.length - 1;
  var iterations = 0;
  var trimmedResult;
  while (start <= end && iterations <= text.length - 1) {
    var middle = Math.floor((start + end) / 2);
    var prev = middle - 1;
    var _checkOverflow = checkOverflow(prev), _checkOverflow2 = _slicedToArray$7(_checkOverflow, 2), doesPrevOverflow = _checkOverflow2[0], result = _checkOverflow2[1];
    var _checkOverflow3 = checkOverflow(middle), _checkOverflow4 = _slicedToArray$7(_checkOverflow3, 1), doesMiddleOverflow = _checkOverflow4[0];
    if (!doesPrevOverflow && !doesMiddleOverflow) {
      start = middle + 1;
    }
    if (doesPrevOverflow && doesMiddleOverflow) {
      end = middle - 1;
    }
    if (!doesPrevOverflow && doesMiddleOverflow) {
      trimmedResult = result;
      break;
    }
    iterations++;
  }
  return trimmedResult || originalResult;
};
var getWordsWithoutCalculate = function getWordsWithoutCalculate2(children) {
  var words = !isNil$1(children) ? children.toString().split(BREAKING_SPACES) : [];
  return [{
    words
  }];
};
var getWordsByLines = function getWordsByLines2(_ref4) {
  var width = _ref4.width, scaleToFit = _ref4.scaleToFit, children = _ref4.children, style = _ref4.style, breakAll = _ref4.breakAll, maxLines = _ref4.maxLines;
  if ((width || scaleToFit) && !Global.isSsr) {
    var wordsWithComputedWidth, spaceWidth;
    var wordWidths = calculateWordWidths({
      breakAll,
      children,
      style
    });
    if (wordWidths) {
      var wcw = wordWidths.wordsWithComputedWidth, sw = wordWidths.spaceWidth;
      wordsWithComputedWidth = wcw;
      spaceWidth = sw;
    } else {
      return getWordsWithoutCalculate(children);
    }
    return calculateWordsByLines({
      breakAll,
      children,
      maxLines,
      style
    }, wordsWithComputedWidth, spaceWidth, width, scaleToFit);
  }
  return getWordsWithoutCalculate(children);
};
var DEFAULT_FILL = "#808080";
var Text = function Text2(_ref5) {
  var _ref5$x = _ref5.x, propsX = _ref5$x === void 0 ? 0 : _ref5$x, _ref5$y = _ref5.y, propsY = _ref5$y === void 0 ? 0 : _ref5$y, _ref5$lineHeight = _ref5.lineHeight, lineHeight = _ref5$lineHeight === void 0 ? "1em" : _ref5$lineHeight, _ref5$capHeight = _ref5.capHeight, capHeight = _ref5$capHeight === void 0 ? "0.71em" : _ref5$capHeight, _ref5$scaleToFit = _ref5.scaleToFit, scaleToFit = _ref5$scaleToFit === void 0 ? false : _ref5$scaleToFit, _ref5$textAnchor = _ref5.textAnchor, textAnchor = _ref5$textAnchor === void 0 ? "start" : _ref5$textAnchor, _ref5$verticalAnchor = _ref5.verticalAnchor, verticalAnchor = _ref5$verticalAnchor === void 0 ? "end" : _ref5$verticalAnchor, _ref5$fill = _ref5.fill, fill = _ref5$fill === void 0 ? DEFAULT_FILL : _ref5$fill, props = _objectWithoutProperties$c(_ref5, _excluded$c);
  var wordsByLines = reactExports.useMemo(function() {
    return getWordsByLines({
      breakAll: props.breakAll,
      children: props.children,
      maxLines: props.maxLines,
      scaleToFit,
      style: props.style,
      width: props.width
    });
  }, [props.breakAll, props.children, props.maxLines, scaleToFit, props.style, props.width]);
  var dx = props.dx, dy = props.dy, angle = props.angle, className = props.className, breakAll = props.breakAll, textProps = _objectWithoutProperties$c(props, _excluded2$5);
  if (!isNumOrStr(propsX) || !isNumOrStr(propsY)) {
    return null;
  }
  var x2 = propsX + (isNumber(dx) ? dx : 0);
  var y2 = propsY + (isNumber(dy) ? dy : 0);
  var startDy;
  switch (verticalAnchor) {
    case "start":
      startDy = reduceCSSCalc("calc(".concat(capHeight, ")"));
      break;
    case "middle":
      startDy = reduceCSSCalc("calc(".concat((wordsByLines.length - 1) / 2, " * -").concat(lineHeight, " + (").concat(capHeight, " / 2))"));
      break;
    default:
      startDy = reduceCSSCalc("calc(".concat(wordsByLines.length - 1, " * -").concat(lineHeight, ")"));
      break;
  }
  var transforms = [];
  if (scaleToFit) {
    var lineWidth = wordsByLines[0].width;
    var width = props.width;
    transforms.push("scale(".concat((isNumber(width) ? width / lineWidth : 1) / lineWidth, ")"));
  }
  if (angle) {
    transforms.push("rotate(".concat(angle, ", ").concat(x2, ", ").concat(y2, ")"));
  }
  if (transforms.length) {
    textProps.transform = transforms.join(" ");
  }
  return /* @__PURE__ */ React.createElement("text", _extends$o({}, filterProps(textProps, true), {
    x: x2,
    y: y2,
    className: clsx("recharts-text", className),
    textAnchor,
    fill: fill.includes("url") ? DEFAULT_FILL : fill
  }), wordsByLines.map(function(line, index) {
    var words = line.words.join(breakAll ? "" : " ");
    return (
      // duplicate words will cause duplicate keys
      // eslint-disable-next-line react/no-array-index-key
      /* @__PURE__ */ React.createElement("tspan", {
        x: x2,
        dy: index === 0 ? startDy : lineHeight,
        key: "".concat(words, "-").concat(index)
      }, words)
    );
  }));
};
function ascending(a2, b) {
  return a2 == null || b == null ? NaN : a2 < b ? -1 : a2 > b ? 1 : a2 >= b ? 0 : NaN;
}
function descending(a2, b) {
  return a2 == null || b == null ? NaN : b < a2 ? -1 : b > a2 ? 1 : b >= a2 ? 0 : NaN;
}
function bisector(f) {
  let compare1, compare2, delta;
  if (f.length !== 2) {
    compare1 = ascending;
    compare2 = (d, x2) => ascending(f(d), x2);
    delta = (d, x2) => f(d) - x2;
  } else {
    compare1 = f === ascending || f === descending ? f : zero$1;
    compare2 = f;
    delta = f;
  }
  function left(a2, x2, lo = 0, hi = a2.length) {
    if (lo < hi) {
      if (compare1(x2, x2) !== 0) return hi;
      do {
        const mid = lo + hi >>> 1;
        if (compare2(a2[mid], x2) < 0) lo = mid + 1;
        else hi = mid;
      } while (lo < hi);
    }
    return lo;
  }
  function right(a2, x2, lo = 0, hi = a2.length) {
    if (lo < hi) {
      if (compare1(x2, x2) !== 0) return hi;
      do {
        const mid = lo + hi >>> 1;
        if (compare2(a2[mid], x2) <= 0) lo = mid + 1;
        else hi = mid;
      } while (lo < hi);
    }
    return lo;
  }
  function center(a2, x2, lo = 0, hi = a2.length) {
    const i = left(a2, x2, lo, hi - 1);
    return i > lo && delta(a2[i - 1], x2) > -delta(a2[i], x2) ? i - 1 : i;
  }
  return { left, center, right };
}
function zero$1() {
  return 0;
}
function number$2(x2) {
  return x2 === null ? NaN : +x2;
}
function* numbers(values, valueof) {
  {
    for (let value of values) {
      if (value != null && (value = +value) >= value) {
        yield value;
      }
    }
  }
}
const ascendingBisect = bisector(ascending);
const bisectRight = ascendingBisect.right;
bisector(number$2).center;
class InternMap extends Map {
  constructor(entries, key2 = keyof) {
    super();
    Object.defineProperties(this, { _intern: { value: /* @__PURE__ */ new Map() }, _key: { value: key2 } });
    if (entries != null) for (const [key3, value] of entries) this.set(key3, value);
  }
  get(key2) {
    return super.get(intern_get(this, key2));
  }
  has(key2) {
    return super.has(intern_get(this, key2));
  }
  set(key2, value) {
    return super.set(intern_set(this, key2), value);
  }
  delete(key2) {
    return super.delete(intern_delete(this, key2));
  }
}
function intern_get({ _intern, _key }, value) {
  const key2 = _key(value);
  return _intern.has(key2) ? _intern.get(key2) : value;
}
function intern_set({ _intern, _key }, value) {
  const key2 = _key(value);
  if (_intern.has(key2)) return _intern.get(key2);
  _intern.set(key2, value);
  return value;
}
function intern_delete({ _intern, _key }, value) {
  const key2 = _key(value);
  if (_intern.has(key2)) {
    value = _intern.get(key2);
    _intern.delete(key2);
  }
  return value;
}
function keyof(value) {
  return value !== null && typeof value === "object" ? value.valueOf() : value;
}
function compareDefined(compare = ascending) {
  if (compare === ascending) return ascendingDefined;
  if (typeof compare !== "function") throw new TypeError("compare is not a function");
  return (a2, b) => {
    const x2 = compare(a2, b);
    if (x2 || x2 === 0) return x2;
    return (compare(b, b) === 0) - (compare(a2, a2) === 0);
  };
}
function ascendingDefined(a2, b) {
  return (a2 == null || !(a2 >= a2)) - (b == null || !(b >= b)) || (a2 < b ? -1 : a2 > b ? 1 : 0);
}
const e10 = Math.sqrt(50), e5 = Math.sqrt(10), e2 = Math.sqrt(2);
function tickSpec(start, stop, count) {
  const step = (stop - start) / Math.max(0, count), power2 = Math.floor(Math.log10(step)), error = step / Math.pow(10, power2), factor = error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1;
  let i1, i2, inc;
  if (power2 < 0) {
    inc = Math.pow(10, -power2) / factor;
    i1 = Math.round(start * inc);
    i2 = Math.round(stop * inc);
    if (i1 / inc < start) ++i1;
    if (i2 / inc > stop) --i2;
    inc = -inc;
  } else {
    inc = Math.pow(10, power2) * factor;
    i1 = Math.round(start / inc);
    i2 = Math.round(stop / inc);
    if (i1 * inc < start) ++i1;
    if (i2 * inc > stop) --i2;
  }
  if (i2 < i1 && 0.5 <= count && count < 2) return tickSpec(start, stop, count * 2);
  return [i1, i2, inc];
}
function ticks(start, stop, count) {
  stop = +stop, start = +start, count = +count;
  if (!(count > 0)) return [];
  if (start === stop) return [start];
  const reverse3 = stop < start, [i1, i2, inc] = reverse3 ? tickSpec(stop, start, count) : tickSpec(start, stop, count);
  if (!(i2 >= i1)) return [];
  const n = i2 - i1 + 1, ticks2 = new Array(n);
  if (reverse3) {
    if (inc < 0) for (let i = 0; i < n; ++i) ticks2[i] = (i2 - i) / -inc;
    else for (let i = 0; i < n; ++i) ticks2[i] = (i2 - i) * inc;
  } else {
    if (inc < 0) for (let i = 0; i < n; ++i) ticks2[i] = (i1 + i) / -inc;
    else for (let i = 0; i < n; ++i) ticks2[i] = (i1 + i) * inc;
  }
  return ticks2;
}
function tickIncrement(start, stop, count) {
  stop = +stop, start = +start, count = +count;
  return tickSpec(start, stop, count)[2];
}
function tickStep(start, stop, count) {
  stop = +stop, start = +start, count = +count;
  const reverse3 = stop < start, inc = reverse3 ? tickIncrement(stop, start, count) : tickIncrement(start, stop, count);
  return (reverse3 ? -1 : 1) * (inc < 0 ? 1 / -inc : inc);
}
function max$2(values, valueof) {
  let max2;
  {
    for (const value of values) {
      if (value != null && (max2 < value || max2 === void 0 && value >= value)) {
        max2 = value;
      }
    }
  }
  return max2;
}
function min$2(values, valueof) {
  let min2;
  {
    for (const value of values) {
      if (value != null && (min2 > value || min2 === void 0 && value >= value)) {
        min2 = value;
      }
    }
  }
  return min2;
}
function quickselect(array2, k2, left = 0, right = Infinity, compare) {
  k2 = Math.floor(k2);
  left = Math.floor(Math.max(0, left));
  right = Math.floor(Math.min(array2.length - 1, right));
  if (!(left <= k2 && k2 <= right)) return array2;
  compare = compare === void 0 ? ascendingDefined : compareDefined(compare);
  while (right > left) {
    if (right - left > 600) {
      const n = right - left + 1;
      const m = k2 - left + 1;
      const z = Math.log(n);
      const s2 = 0.5 * Math.exp(2 * z / 3);
      const sd = 0.5 * Math.sqrt(z * s2 * (n - s2) / n) * (m - n / 2 < 0 ? -1 : 1);
      const newLeft = Math.max(left, Math.floor(k2 - m * s2 / n + sd));
      const newRight = Math.min(right, Math.floor(k2 + (n - m) * s2 / n + sd));
      quickselect(array2, k2, newLeft, newRight, compare);
    }
    const t = array2[k2];
    let i = left;
    let j = right;
    swap(array2, left, k2);
    if (compare(array2[right], t) > 0) swap(array2, left, right);
    while (i < j) {
      swap(array2, i, j), ++i, --j;
      while (compare(array2[i], t) < 0) ++i;
      while (compare(array2[j], t) > 0) --j;
    }
    if (compare(array2[left], t) === 0) swap(array2, left, j);
    else ++j, swap(array2, j, right);
    if (j <= k2) left = j + 1;
    if (k2 <= j) right = j - 1;
  }
  return array2;
}
function swap(array2, i, j) {
  const t = array2[i];
  array2[i] = array2[j];
  array2[j] = t;
}
function quantile$1(values, p, valueof) {
  values = Float64Array.from(numbers(values));
  if (!(n = values.length) || isNaN(p = +p)) return;
  if (p <= 0 || n < 2) return min$2(values);
  if (p >= 1) return max$2(values);
  var n, i = (n - 1) * p, i0 = Math.floor(i), value0 = max$2(quickselect(values, i0).subarray(0, i0 + 1)), value1 = min$2(values.subarray(i0 + 1));
  return value0 + (value1 - value0) * (i - i0);
}
function quantileSorted(values, p, valueof = number$2) {
  if (!(n = values.length) || isNaN(p = +p)) return;
  if (p <= 0 || n < 2) return +valueof(values[0], 0, values);
  if (p >= 1) return +valueof(values[n - 1], n - 1, values);
  var n, i = (n - 1) * p, i0 = Math.floor(i), value0 = +valueof(values[i0], i0, values), value1 = +valueof(values[i0 + 1], i0 + 1, values);
  return value0 + (value1 - value0) * (i - i0);
}
function range$3(start, stop, step) {
  start = +start, stop = +stop, step = (n = arguments.length) < 2 ? (stop = start, start = 0, 1) : n < 3 ? 1 : +step;
  var i = -1, n = Math.max(0, Math.ceil((stop - start) / step)) | 0, range3 = new Array(n);
  while (++i < n) {
    range3[i] = start + i * step;
  }
  return range3;
}
function initRange(domain, range3) {
  switch (arguments.length) {
    case 0:
      break;
    case 1:
      this.range(domain);
      break;
    default:
      this.range(range3).domain(domain);
      break;
  }
  return this;
}
function initInterpolator(domain, interpolator) {
  switch (arguments.length) {
    case 0:
      break;
    case 1: {
      if (typeof domain === "function") this.interpolator(domain);
      else this.range(domain);
      break;
    }
    default: {
      this.domain(domain);
      if (typeof interpolator === "function") this.interpolator(interpolator);
      else this.range(interpolator);
      break;
    }
  }
  return this;
}
const implicit = Symbol("implicit");
function ordinal() {
  var index = new InternMap(), domain = [], range3 = [], unknown = implicit;
  function scale2(d) {
    let i = index.get(d);
    if (i === void 0) {
      if (unknown !== implicit) return unknown;
      index.set(d, i = domain.push(d) - 1);
    }
    return range3[i % range3.length];
  }
  scale2.domain = function(_) {
    if (!arguments.length) return domain.slice();
    domain = [], index = new InternMap();
    for (const value of _) {
      if (index.has(value)) continue;
      index.set(value, domain.push(value) - 1);
    }
    return scale2;
  };
  scale2.range = function(_) {
    return arguments.length ? (range3 = Array.from(_), scale2) : range3.slice();
  };
  scale2.unknown = function(_) {
    return arguments.length ? (unknown = _, scale2) : unknown;
  };
  scale2.copy = function() {
    return ordinal(domain, range3).unknown(unknown);
  };
  initRange.apply(scale2, arguments);
  return scale2;
}
function band() {
  var scale2 = ordinal().unknown(void 0), domain = scale2.domain, ordinalRange = scale2.range, r0 = 0, r1 = 1, step, bandwidth, round2 = false, paddingInner = 0, paddingOuter = 0, align = 0.5;
  delete scale2.unknown;
  function rescale() {
    var n = domain().length, reverse3 = r1 < r0, start = reverse3 ? r1 : r0, stop = reverse3 ? r0 : r1;
    step = (stop - start) / Math.max(1, n - paddingInner + paddingOuter * 2);
    if (round2) step = Math.floor(step);
    start += (stop - start - step * (n - paddingInner)) * align;
    bandwidth = step * (1 - paddingInner);
    if (round2) start = Math.round(start), bandwidth = Math.round(bandwidth);
    var values = range$3(n).map(function(i) {
      return start + step * i;
    });
    return ordinalRange(reverse3 ? values.reverse() : values);
  }
  scale2.domain = function(_) {
    return arguments.length ? (domain(_), rescale()) : domain();
  };
  scale2.range = function(_) {
    return arguments.length ? ([r0, r1] = _, r0 = +r0, r1 = +r1, rescale()) : [r0, r1];
  };
  scale2.rangeRound = function(_) {
    return [r0, r1] = _, r0 = +r0, r1 = +r1, round2 = true, rescale();
  };
  scale2.bandwidth = function() {
    return bandwidth;
  };
  scale2.step = function() {
    return step;
  };
  scale2.round = function(_) {
    return arguments.length ? (round2 = !!_, rescale()) : round2;
  };
  scale2.padding = function(_) {
    return arguments.length ? (paddingInner = Math.min(1, paddingOuter = +_), rescale()) : paddingInner;
  };
  scale2.paddingInner = function(_) {
    return arguments.length ? (paddingInner = Math.min(1, _), rescale()) : paddingInner;
  };
  scale2.paddingOuter = function(_) {
    return arguments.length ? (paddingOuter = +_, rescale()) : paddingOuter;
  };
  scale2.align = function(_) {
    return arguments.length ? (align = Math.max(0, Math.min(1, _)), rescale()) : align;
  };
  scale2.copy = function() {
    return band(domain(), [r0, r1]).round(round2).paddingInner(paddingInner).paddingOuter(paddingOuter).align(align);
  };
  return initRange.apply(rescale(), arguments);
}
function pointish(scale2) {
  var copy2 = scale2.copy;
  scale2.padding = scale2.paddingOuter;
  delete scale2.paddingInner;
  delete scale2.paddingOuter;
  scale2.copy = function() {
    return pointish(copy2());
  };
  return scale2;
}
function point() {
  return pointish(band.apply(null, arguments).paddingInner(1));
}
function define(constructor, factory, prototype) {
  constructor.prototype = factory.prototype = prototype;
  prototype.constructor = constructor;
}
function extend(parent, definition) {
  var prototype = Object.create(parent.prototype);
  for (var key2 in definition) prototype[key2] = definition[key2];
  return prototype;
}
function Color() {
}
var darker = 0.7;
var brighter = 1 / darker;
var reI = "\\s*([+-]?\\d+)\\s*", reN = "\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*", reP = "\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*", reHex = /^#([0-9a-f]{3,8})$/, reRgbInteger = new RegExp(`^rgb\\(${reI},${reI},${reI}\\)$`), reRgbPercent = new RegExp(`^rgb\\(${reP},${reP},${reP}\\)$`), reRgbaInteger = new RegExp(`^rgba\\(${reI},${reI},${reI},${reN}\\)$`), reRgbaPercent = new RegExp(`^rgba\\(${reP},${reP},${reP},${reN}\\)$`), reHslPercent = new RegExp(`^hsl\\(${reN},${reP},${reP}\\)$`), reHslaPercent = new RegExp(`^hsla\\(${reN},${reP},${reP},${reN}\\)$`);
var named = {
  aliceblue: 15792383,
  antiquewhite: 16444375,
  aqua: 65535,
  aquamarine: 8388564,
  azure: 15794175,
  beige: 16119260,
  bisque: 16770244,
  black: 0,
  blanchedalmond: 16772045,
  blue: 255,
  blueviolet: 9055202,
  brown: 10824234,
  burlywood: 14596231,
  cadetblue: 6266528,
  chartreuse: 8388352,
  chocolate: 13789470,
  coral: 16744272,
  cornflowerblue: 6591981,
  cornsilk: 16775388,
  crimson: 14423100,
  cyan: 65535,
  darkblue: 139,
  darkcyan: 35723,
  darkgoldenrod: 12092939,
  darkgray: 11119017,
  darkgreen: 25600,
  darkgrey: 11119017,
  darkkhaki: 12433259,
  darkmagenta: 9109643,
  darkolivegreen: 5597999,
  darkorange: 16747520,
  darkorchid: 10040012,
  darkred: 9109504,
  darksalmon: 15308410,
  darkseagreen: 9419919,
  darkslateblue: 4734347,
  darkslategray: 3100495,
  darkslategrey: 3100495,
  darkturquoise: 52945,
  darkviolet: 9699539,
  deeppink: 16716947,
  deepskyblue: 49151,
  dimgray: 6908265,
  dimgrey: 6908265,
  dodgerblue: 2003199,
  firebrick: 11674146,
  floralwhite: 16775920,
  forestgreen: 2263842,
  fuchsia: 16711935,
  gainsboro: 14474460,
  ghostwhite: 16316671,
  gold: 16766720,
  goldenrod: 14329120,
  gray: 8421504,
  green: 32768,
  greenyellow: 11403055,
  grey: 8421504,
  honeydew: 15794160,
  hotpink: 16738740,
  indianred: 13458524,
  indigo: 4915330,
  ivory: 16777200,
  khaki: 15787660,
  lavender: 15132410,
  lavenderblush: 16773365,
  lawngreen: 8190976,
  lemonchiffon: 16775885,
  lightblue: 11393254,
  lightcoral: 15761536,
  lightcyan: 14745599,
  lightgoldenrodyellow: 16448210,
  lightgray: 13882323,
  lightgreen: 9498256,
  lightgrey: 13882323,
  lightpink: 16758465,
  lightsalmon: 16752762,
  lightseagreen: 2142890,
  lightskyblue: 8900346,
  lightslategray: 7833753,
  lightslategrey: 7833753,
  lightsteelblue: 11584734,
  lightyellow: 16777184,
  lime: 65280,
  limegreen: 3329330,
  linen: 16445670,
  magenta: 16711935,
  maroon: 8388608,
  mediumaquamarine: 6737322,
  mediumblue: 205,
  mediumorchid: 12211667,
  mediumpurple: 9662683,
  mediumseagreen: 3978097,
  mediumslateblue: 8087790,
  mediumspringgreen: 64154,
  mediumturquoise: 4772300,
  mediumvioletred: 13047173,
  midnightblue: 1644912,
  mintcream: 16121850,
  mistyrose: 16770273,
  moccasin: 16770229,
  navajowhite: 16768685,
  navy: 128,
  oldlace: 16643558,
  olive: 8421376,
  olivedrab: 7048739,
  orange: 16753920,
  orangered: 16729344,
  orchid: 14315734,
  palegoldenrod: 15657130,
  palegreen: 10025880,
  paleturquoise: 11529966,
  palevioletred: 14381203,
  papayawhip: 16773077,
  peachpuff: 16767673,
  peru: 13468991,
  pink: 16761035,
  plum: 14524637,
  powderblue: 11591910,
  purple: 8388736,
  rebeccapurple: 6697881,
  red: 16711680,
  rosybrown: 12357519,
  royalblue: 4286945,
  saddlebrown: 9127187,
  salmon: 16416882,
  sandybrown: 16032864,
  seagreen: 3050327,
  seashell: 16774638,
  sienna: 10506797,
  silver: 12632256,
  skyblue: 8900331,
  slateblue: 6970061,
  slategray: 7372944,
  slategrey: 7372944,
  snow: 16775930,
  springgreen: 65407,
  steelblue: 4620980,
  tan: 13808780,
  teal: 32896,
  thistle: 14204888,
  tomato: 16737095,
  turquoise: 4251856,
  violet: 15631086,
  wheat: 16113331,
  white: 16777215,
  whitesmoke: 16119285,
  yellow: 16776960,
  yellowgreen: 10145074
};
define(Color, color, {
  copy(channels) {
    return Object.assign(new this.constructor(), this, channels);
  },
  displayable() {
    return this.rgb().displayable();
  },
  hex: color_formatHex,
  // Deprecated! Use color.formatHex.
  formatHex: color_formatHex,
  formatHex8: color_formatHex8,
  formatHsl: color_formatHsl,
  formatRgb: color_formatRgb,
  toString: color_formatRgb
});
function color_formatHex() {
  return this.rgb().formatHex();
}
function color_formatHex8() {
  return this.rgb().formatHex8();
}
function color_formatHsl() {
  return hslConvert(this).formatHsl();
}
function color_formatRgb() {
  return this.rgb().formatRgb();
}
function color(format2) {
  var m, l;
  format2 = (format2 + "").trim().toLowerCase();
  return (m = reHex.exec(format2)) ? (l = m[1].length, m = parseInt(m[1], 16), l === 6 ? rgbn(m) : l === 3 ? new Rgb(m >> 8 & 15 | m >> 4 & 240, m >> 4 & 15 | m & 240, (m & 15) << 4 | m & 15, 1) : l === 8 ? rgba(m >> 24 & 255, m >> 16 & 255, m >> 8 & 255, (m & 255) / 255) : l === 4 ? rgba(m >> 12 & 15 | m >> 8 & 240, m >> 8 & 15 | m >> 4 & 240, m >> 4 & 15 | m & 240, ((m & 15) << 4 | m & 15) / 255) : null) : (m = reRgbInteger.exec(format2)) ? new Rgb(m[1], m[2], m[3], 1) : (m = reRgbPercent.exec(format2)) ? new Rgb(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, 1) : (m = reRgbaInteger.exec(format2)) ? rgba(m[1], m[2], m[3], m[4]) : (m = reRgbaPercent.exec(format2)) ? rgba(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, m[4]) : (m = reHslPercent.exec(format2)) ? hsla(m[1], m[2] / 100, m[3] / 100, 1) : (m = reHslaPercent.exec(format2)) ? hsla(m[1], m[2] / 100, m[3] / 100, m[4]) : named.hasOwnProperty(format2) ? rgbn(named[format2]) : format2 === "transparent" ? new Rgb(NaN, NaN, NaN, 0) : null;
}
function rgbn(n) {
  return new Rgb(n >> 16 & 255, n >> 8 & 255, n & 255, 1);
}
function rgba(r2, g, b, a2) {
  if (a2 <= 0) r2 = g = b = NaN;
  return new Rgb(r2, g, b, a2);
}
function rgbConvert(o) {
  if (!(o instanceof Color)) o = color(o);
  if (!o) return new Rgb();
  o = o.rgb();
  return new Rgb(o.r, o.g, o.b, o.opacity);
}
function rgb$1(r2, g, b, opacity) {
  return arguments.length === 1 ? rgbConvert(r2) : new Rgb(r2, g, b, opacity == null ? 1 : opacity);
}
function Rgb(r2, g, b, opacity) {
  this.r = +r2;
  this.g = +g;
  this.b = +b;
  this.opacity = +opacity;
}
define(Rgb, rgb$1, extend(Color, {
  brighter(k2) {
    k2 = k2 == null ? brighter : Math.pow(brighter, k2);
    return new Rgb(this.r * k2, this.g * k2, this.b * k2, this.opacity);
  },
  darker(k2) {
    k2 = k2 == null ? darker : Math.pow(darker, k2);
    return new Rgb(this.r * k2, this.g * k2, this.b * k2, this.opacity);
  },
  rgb() {
    return this;
  },
  clamp() {
    return new Rgb(clampi(this.r), clampi(this.g), clampi(this.b), clampa(this.opacity));
  },
  displayable() {
    return -0.5 <= this.r && this.r < 255.5 && (-0.5 <= this.g && this.g < 255.5) && (-0.5 <= this.b && this.b < 255.5) && (0 <= this.opacity && this.opacity <= 1);
  },
  hex: rgb_formatHex,
  // Deprecated! Use color.formatHex.
  formatHex: rgb_formatHex,
  formatHex8: rgb_formatHex8,
  formatRgb: rgb_formatRgb,
  toString: rgb_formatRgb
}));
function rgb_formatHex() {
  return `#${hex(this.r)}${hex(this.g)}${hex(this.b)}`;
}
function rgb_formatHex8() {
  return `#${hex(this.r)}${hex(this.g)}${hex(this.b)}${hex((isNaN(this.opacity) ? 1 : this.opacity) * 255)}`;
}
function rgb_formatRgb() {
  const a2 = clampa(this.opacity);
  return `${a2 === 1 ? "rgb(" : "rgba("}${clampi(this.r)}, ${clampi(this.g)}, ${clampi(this.b)}${a2 === 1 ? ")" : `, ${a2})`}`;
}
function clampa(opacity) {
  return isNaN(opacity) ? 1 : Math.max(0, Math.min(1, opacity));
}
function clampi(value) {
  return Math.max(0, Math.min(255, Math.round(value) || 0));
}
function hex(value) {
  value = clampi(value);
  return (value < 16 ? "0" : "") + value.toString(16);
}
function hsla(h, s2, l, a2) {
  if (a2 <= 0) h = s2 = l = NaN;
  else if (l <= 0 || l >= 1) h = s2 = NaN;
  else if (s2 <= 0) h = NaN;
  return new Hsl(h, s2, l, a2);
}
function hslConvert(o) {
  if (o instanceof Hsl) return new Hsl(o.h, o.s, o.l, o.opacity);
  if (!(o instanceof Color)) o = color(o);
  if (!o) return new Hsl();
  if (o instanceof Hsl) return o;
  o = o.rgb();
  var r2 = o.r / 255, g = o.g / 255, b = o.b / 255, min2 = Math.min(r2, g, b), max2 = Math.max(r2, g, b), h = NaN, s2 = max2 - min2, l = (max2 + min2) / 2;
  if (s2) {
    if (r2 === max2) h = (g - b) / s2 + (g < b) * 6;
    else if (g === max2) h = (b - r2) / s2 + 2;
    else h = (r2 - g) / s2 + 4;
    s2 /= l < 0.5 ? max2 + min2 : 2 - max2 - min2;
    h *= 60;
  } else {
    s2 = l > 0 && l < 1 ? 0 : h;
  }
  return new Hsl(h, s2, l, o.opacity);
}
function hsl(h, s2, l, opacity) {
  return arguments.length === 1 ? hslConvert(h) : new Hsl(h, s2, l, opacity == null ? 1 : opacity);
}
function Hsl(h, s2, l, opacity) {
  this.h = +h;
  this.s = +s2;
  this.l = +l;
  this.opacity = +opacity;
}
define(Hsl, hsl, extend(Color, {
  brighter(k2) {
    k2 = k2 == null ? brighter : Math.pow(brighter, k2);
    return new Hsl(this.h, this.s, this.l * k2, this.opacity);
  },
  darker(k2) {
    k2 = k2 == null ? darker : Math.pow(darker, k2);
    return new Hsl(this.h, this.s, this.l * k2, this.opacity);
  },
  rgb() {
    var h = this.h % 360 + (this.h < 0) * 360, s2 = isNaN(h) || isNaN(this.s) ? 0 : this.s, l = this.l, m2 = l + (l < 0.5 ? l : 1 - l) * s2, m1 = 2 * l - m2;
    return new Rgb(
      hsl2rgb(h >= 240 ? h - 240 : h + 120, m1, m2),
      hsl2rgb(h, m1, m2),
      hsl2rgb(h < 120 ? h + 240 : h - 120, m1, m2),
      this.opacity
    );
  },
  clamp() {
    return new Hsl(clamph(this.h), clampt(this.s), clampt(this.l), clampa(this.opacity));
  },
  displayable() {
    return (0 <= this.s && this.s <= 1 || isNaN(this.s)) && (0 <= this.l && this.l <= 1) && (0 <= this.opacity && this.opacity <= 1);
  },
  formatHsl() {
    const a2 = clampa(this.opacity);
    return `${a2 === 1 ? "hsl(" : "hsla("}${clamph(this.h)}, ${clampt(this.s) * 100}%, ${clampt(this.l) * 100}%${a2 === 1 ? ")" : `, ${a2})`}`;
  }
}));
function clamph(value) {
  value = (value || 0) % 360;
  return value < 0 ? value + 360 : value;
}
function clampt(value) {
  return Math.max(0, Math.min(1, value || 0));
}
function hsl2rgb(h, m1, m2) {
  return (h < 60 ? m1 + (m2 - m1) * h / 60 : h < 180 ? m2 : h < 240 ? m1 + (m2 - m1) * (240 - h) / 60 : m1) * 255;
}
const constant = (x2) => () => x2;
function linear$1(a2, d) {
  return function(t) {
    return a2 + t * d;
  };
}
function exponential(a2, b, y2) {
  return a2 = Math.pow(a2, y2), b = Math.pow(b, y2) - a2, y2 = 1 / y2, function(t) {
    return Math.pow(a2 + t * b, y2);
  };
}
function gamma(y2) {
  return (y2 = +y2) === 1 ? nogamma : function(a2, b) {
    return b - a2 ? exponential(a2, b, y2) : constant(isNaN(a2) ? b : a2);
  };
}
function nogamma(a2, b) {
  var d = b - a2;
  return d ? linear$1(a2, d) : constant(isNaN(a2) ? b : a2);
}
const rgb = function rgbGamma(y2) {
  var color2 = gamma(y2);
  function rgb2(start, end) {
    var r2 = color2((start = rgb$1(start)).r, (end = rgb$1(end)).r), g = color2(start.g, end.g), b = color2(start.b, end.b), opacity = nogamma(start.opacity, end.opacity);
    return function(t) {
      start.r = r2(t);
      start.g = g(t);
      start.b = b(t);
      start.opacity = opacity(t);
      return start + "";
    };
  }
  rgb2.gamma = rgbGamma;
  return rgb2;
}(1);
function numberArray(a2, b) {
  if (!b) b = [];
  var n = a2 ? Math.min(b.length, a2.length) : 0, c2 = b.slice(), i;
  return function(t) {
    for (i = 0; i < n; ++i) c2[i] = a2[i] * (1 - t) + b[i] * t;
    return c2;
  };
}
function isNumberArray(x2) {
  return ArrayBuffer.isView(x2) && !(x2 instanceof DataView);
}
function genericArray(a2, b) {
  var nb = b ? b.length : 0, na = a2 ? Math.min(nb, a2.length) : 0, x2 = new Array(na), c2 = new Array(nb), i;
  for (i = 0; i < na; ++i) x2[i] = interpolate(a2[i], b[i]);
  for (; i < nb; ++i) c2[i] = b[i];
  return function(t) {
    for (i = 0; i < na; ++i) c2[i] = x2[i](t);
    return c2;
  };
}
function date$1(a2, b) {
  var d = /* @__PURE__ */ new Date();
  return a2 = +a2, b = +b, function(t) {
    return d.setTime(a2 * (1 - t) + b * t), d;
  };
}
function interpolateNumber$1(a2, b) {
  return a2 = +a2, b = +b, function(t) {
    return a2 * (1 - t) + b * t;
  };
}
function object(a2, b) {
  var i = {}, c2 = {}, k2;
  if (a2 === null || typeof a2 !== "object") a2 = {};
  if (b === null || typeof b !== "object") b = {};
  for (k2 in b) {
    if (k2 in a2) {
      i[k2] = interpolate(a2[k2], b[k2]);
    } else {
      c2[k2] = b[k2];
    }
  }
  return function(t) {
    for (k2 in i) c2[k2] = i[k2](t);
    return c2;
  };
}
var reA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g, reB = new RegExp(reA.source, "g");
function zero(b) {
  return function() {
    return b;
  };
}
function one(b) {
  return function(t) {
    return b(t) + "";
  };
}
function string(a2, b) {
  var bi = reA.lastIndex = reB.lastIndex = 0, am, bm, bs, i = -1, s2 = [], q = [];
  a2 = a2 + "", b = b + "";
  while ((am = reA.exec(a2)) && (bm = reB.exec(b))) {
    if ((bs = bm.index) > bi) {
      bs = b.slice(bi, bs);
      if (s2[i]) s2[i] += bs;
      else s2[++i] = bs;
    }
    if ((am = am[0]) === (bm = bm[0])) {
      if (s2[i]) s2[i] += bm;
      else s2[++i] = bm;
    } else {
      s2[++i] = null;
      q.push({ i, x: interpolateNumber$1(am, bm) });
    }
    bi = reB.lastIndex;
  }
  if (bi < b.length) {
    bs = b.slice(bi);
    if (s2[i]) s2[i] += bs;
    else s2[++i] = bs;
  }
  return s2.length < 2 ? q[0] ? one(q[0].x) : zero(b) : (b = q.length, function(t) {
    for (var i2 = 0, o; i2 < b; ++i2) s2[(o = q[i2]).i] = o.x(t);
    return s2.join("");
  });
}
function interpolate(a2, b) {
  var t = typeof b, c2;
  return b == null || t === "boolean" ? constant(b) : (t === "number" ? interpolateNumber$1 : t === "string" ? (c2 = color(b)) ? (b = c2, rgb) : string : b instanceof color ? rgb : b instanceof Date ? date$1 : isNumberArray(b) ? numberArray : Array.isArray(b) ? genericArray : typeof b.valueOf !== "function" && typeof b.toString !== "function" || isNaN(b) ? object : interpolateNumber$1)(a2, b);
}
function interpolateRound(a2, b) {
  return a2 = +a2, b = +b, function(t) {
    return Math.round(a2 * (1 - t) + b * t);
  };
}
function piecewise(interpolate$1, values) {
  if (values === void 0) values = interpolate$1, interpolate$1 = interpolate;
  var i = 0, n = values.length - 1, v = values[0], I = new Array(n < 0 ? 0 : n);
  while (i < n) I[i] = interpolate$1(v, v = values[++i]);
  return function(t) {
    var i2 = Math.max(0, Math.min(n - 1, Math.floor(t *= n)));
    return I[i2](t - i2);
  };
}
function constants(x2) {
  return function() {
    return x2;
  };
}
function number$1(x2) {
  return +x2;
}
var unit = [0, 1];
function identity$5(x2) {
  return x2;
}
function normalize(a2, b) {
  return (b -= a2 = +a2) ? function(x2) {
    return (x2 - a2) / b;
  } : constants(isNaN(b) ? NaN : 0.5);
}
function clamper(a2, b) {
  var t;
  if (a2 > b) t = a2, a2 = b, b = t;
  return function(x2) {
    return Math.max(a2, Math.min(b, x2));
  };
}
function bimap(domain, range3, interpolate2) {
  var d0 = domain[0], d1 = domain[1], r0 = range3[0], r1 = range3[1];
  if (d1 < d0) d0 = normalize(d1, d0), r0 = interpolate2(r1, r0);
  else d0 = normalize(d0, d1), r0 = interpolate2(r0, r1);
  return function(x2) {
    return r0(d0(x2));
  };
}
function polymap(domain, range3, interpolate2) {
  var j = Math.min(domain.length, range3.length) - 1, d = new Array(j), r2 = new Array(j), i = -1;
  if (domain[j] < domain[0]) {
    domain = domain.slice().reverse();
    range3 = range3.slice().reverse();
  }
  while (++i < j) {
    d[i] = normalize(domain[i], domain[i + 1]);
    r2[i] = interpolate2(range3[i], range3[i + 1]);
  }
  return function(x2) {
    var i2 = bisectRight(domain, x2, 1, j) - 1;
    return r2[i2](d[i2](x2));
  };
}
function copy$1(source, target2) {
  return target2.domain(source.domain()).range(source.range()).interpolate(source.interpolate()).clamp(source.clamp()).unknown(source.unknown());
}
function transformer$2() {
  var domain = unit, range3 = unit, interpolate$1 = interpolate, transform, untransform, unknown, clamp = identity$5, piecewise2, output, input;
  function rescale() {
    var n = Math.min(domain.length, range3.length);
    if (clamp !== identity$5) clamp = clamper(domain[0], domain[n - 1]);
    piecewise2 = n > 2 ? polymap : bimap;
    output = input = null;
    return scale2;
  }
  function scale2(x2) {
    return x2 == null || isNaN(x2 = +x2) ? unknown : (output || (output = piecewise2(domain.map(transform), range3, interpolate$1)))(transform(clamp(x2)));
  }
  scale2.invert = function(y2) {
    return clamp(untransform((input || (input = piecewise2(range3, domain.map(transform), interpolateNumber$1)))(y2)));
  };
  scale2.domain = function(_) {
    return arguments.length ? (domain = Array.from(_, number$1), rescale()) : domain.slice();
  };
  scale2.range = function(_) {
    return arguments.length ? (range3 = Array.from(_), rescale()) : range3.slice();
  };
  scale2.rangeRound = function(_) {
    return range3 = Array.from(_), interpolate$1 = interpolateRound, rescale();
  };
  scale2.clamp = function(_) {
    return arguments.length ? (clamp = _ ? true : identity$5, rescale()) : clamp !== identity$5;
  };
  scale2.interpolate = function(_) {
    return arguments.length ? (interpolate$1 = _, rescale()) : interpolate$1;
  };
  scale2.unknown = function(_) {
    return arguments.length ? (unknown = _, scale2) : unknown;
  };
  return function(t, u) {
    transform = t, untransform = u;
    return rescale();
  };
}
function continuous() {
  return transformer$2()(identity$5, identity$5);
}
function formatDecimal(x2) {
  return Math.abs(x2 = Math.round(x2)) >= 1e21 ? x2.toLocaleString("en").replace(/,/g, "") : x2.toString(10);
}
function formatDecimalParts(x2, p) {
  if (!isFinite(x2) || x2 === 0) return null;
  var i = (x2 = p ? x2.toExponential(p - 1) : x2.toExponential()).indexOf("e"), coefficient = x2.slice(0, i);
  return [
    coefficient.length > 1 ? coefficient[0] + coefficient.slice(2) : coefficient,
    +x2.slice(i + 1)
  ];
}
function exponent(x2) {
  return x2 = formatDecimalParts(Math.abs(x2)), x2 ? x2[1] : NaN;
}
function formatGroup(grouping, thousands) {
  return function(value, width) {
    var i = value.length, t = [], j = 0, g = grouping[0], length = 0;
    while (i > 0 && g > 0) {
      if (length + g + 1 > width) g = Math.max(1, width - length);
      t.push(value.substring(i -= g, i + g));
      if ((length += g + 1) > width) break;
      g = grouping[j = (j + 1) % grouping.length];
    }
    return t.reverse().join(thousands);
  };
}
function formatNumerals(numerals) {
  return function(value) {
    return value.replace(/[0-9]/g, function(i) {
      return numerals[+i];
    });
  };
}
var re = /^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;
function formatSpecifier(specifier) {
  if (!(match2 = re.exec(specifier))) throw new Error("invalid format: " + specifier);
  var match2;
  return new FormatSpecifier({
    fill: match2[1],
    align: match2[2],
    sign: match2[3],
    symbol: match2[4],
    zero: match2[5],
    width: match2[6],
    comma: match2[7],
    precision: match2[8] && match2[8].slice(1),
    trim: match2[9],
    type: match2[10]
  });
}
formatSpecifier.prototype = FormatSpecifier.prototype;
function FormatSpecifier(specifier) {
  this.fill = specifier.fill === void 0 ? " " : specifier.fill + "";
  this.align = specifier.align === void 0 ? ">" : specifier.align + "";
  this.sign = specifier.sign === void 0 ? "-" : specifier.sign + "";
  this.symbol = specifier.symbol === void 0 ? "" : specifier.symbol + "";
  this.zero = !!specifier.zero;
  this.width = specifier.width === void 0 ? void 0 : +specifier.width;
  this.comma = !!specifier.comma;
  this.precision = specifier.precision === void 0 ? void 0 : +specifier.precision;
  this.trim = !!specifier.trim;
  this.type = specifier.type === void 0 ? "" : specifier.type + "";
}
FormatSpecifier.prototype.toString = function() {
  return this.fill + this.align + this.sign + this.symbol + (this.zero ? "0" : "") + (this.width === void 0 ? "" : Math.max(1, this.width | 0)) + (this.comma ? "," : "") + (this.precision === void 0 ? "" : "." + Math.max(0, this.precision | 0)) + (this.trim ? "~" : "") + this.type;
};
function formatTrim(s2) {
  out: for (var n = s2.length, i = 1, i0 = -1, i1; i < n; ++i) {
    switch (s2[i]) {
      case ".":
        i0 = i1 = i;
        break;
      case "0":
        if (i0 === 0) i0 = i;
        i1 = i;
        break;
      default:
        if (!+s2[i]) break out;
        if (i0 > 0) i0 = 0;
        break;
    }
  }
  return i0 > 0 ? s2.slice(0, i0) + s2.slice(i1 + 1) : s2;
}
var prefixExponent;
function formatPrefixAuto(x2, p) {
  var d = formatDecimalParts(x2, p);
  if (!d) return prefixExponent = void 0, x2.toPrecision(p);
  var coefficient = d[0], exponent2 = d[1], i = exponent2 - (prefixExponent = Math.max(-8, Math.min(8, Math.floor(exponent2 / 3))) * 3) + 1, n = coefficient.length;
  return i === n ? coefficient : i > n ? coefficient + new Array(i - n + 1).join("0") : i > 0 ? coefficient.slice(0, i) + "." + coefficient.slice(i) : "0." + new Array(1 - i).join("0") + formatDecimalParts(x2, Math.max(0, p + i - 1))[0];
}
function formatRounded(x2, p) {
  var d = formatDecimalParts(x2, p);
  if (!d) return x2 + "";
  var coefficient = d[0], exponent2 = d[1];
  return exponent2 < 0 ? "0." + new Array(-exponent2).join("0") + coefficient : coefficient.length > exponent2 + 1 ? coefficient.slice(0, exponent2 + 1) + "." + coefficient.slice(exponent2 + 1) : coefficient + new Array(exponent2 - coefficient.length + 2).join("0");
}
const formatTypes = {
  "%": (x2, p) => (x2 * 100).toFixed(p),
  "b": (x2) => Math.round(x2).toString(2),
  "c": (x2) => x2 + "",
  "d": formatDecimal,
  "e": (x2, p) => x2.toExponential(p),
  "f": (x2, p) => x2.toFixed(p),
  "g": (x2, p) => x2.toPrecision(p),
  "o": (x2) => Math.round(x2).toString(8),
  "p": (x2, p) => formatRounded(x2 * 100, p),
  "r": formatRounded,
  "s": formatPrefixAuto,
  "X": (x2) => Math.round(x2).toString(16).toUpperCase(),
  "x": (x2) => Math.round(x2).toString(16)
};
function identity$4(x2) {
  return x2;
}
var map$3 = Array.prototype.map, prefixes = ["y", "z", "a", "f", "p", "n", "µ", "m", "", "k", "M", "G", "T", "P", "E", "Z", "Y"];
function formatLocale$1(locale2) {
  var group = locale2.grouping === void 0 || locale2.thousands === void 0 ? identity$4 : formatGroup(map$3.call(locale2.grouping, Number), locale2.thousands + ""), currencyPrefix = locale2.currency === void 0 ? "" : locale2.currency[0] + "", currencySuffix = locale2.currency === void 0 ? "" : locale2.currency[1] + "", decimal = locale2.decimal === void 0 ? "." : locale2.decimal + "", numerals = locale2.numerals === void 0 ? identity$4 : formatNumerals(map$3.call(locale2.numerals, String)), percent2 = locale2.percent === void 0 ? "%" : locale2.percent + "", minus = locale2.minus === void 0 ? "−" : locale2.minus + "", nan = locale2.nan === void 0 ? "NaN" : locale2.nan + "";
  function newFormat(specifier, options2) {
    specifier = formatSpecifier(specifier);
    var fill = specifier.fill, align = specifier.align, sign2 = specifier.sign, symbol = specifier.symbol, zero2 = specifier.zero, width = specifier.width, comma = specifier.comma, precision = specifier.precision, trim = specifier.trim, type = specifier.type;
    if (type === "n") comma = true, type = "g";
    else if (!formatTypes[type]) precision === void 0 && (precision = 12), trim = true, type = "g";
    if (zero2 || fill === "0" && align === "=") zero2 = true, fill = "0", align = "=";
    var prefix2 = (options2 && options2.prefix !== void 0 ? options2.prefix : "") + (symbol === "$" ? currencyPrefix : symbol === "#" && /[boxX]/.test(type) ? "0" + type.toLowerCase() : ""), suffix = (symbol === "$" ? currencySuffix : /[%p]/.test(type) ? percent2 : "") + (options2 && options2.suffix !== void 0 ? options2.suffix : "");
    var formatType = formatTypes[type], maybeSuffix = /[defgprs%]/.test(type);
    precision = precision === void 0 ? 6 : /[gprs]/.test(type) ? Math.max(1, Math.min(21, precision)) : Math.max(0, Math.min(20, precision));
    function format2(value) {
      var valuePrefix = prefix2, valueSuffix = suffix, i, n, c2;
      if (type === "c") {
        valueSuffix = formatType(value) + valueSuffix;
        value = "";
      } else {
        value = +value;
        var valueNegative = value < 0 || 1 / value < 0;
        value = isNaN(value) ? nan : formatType(Math.abs(value), precision);
        if (trim) value = formatTrim(value);
        if (valueNegative && +value === 0 && sign2 !== "+") valueNegative = false;
        valuePrefix = (valueNegative ? sign2 === "(" ? sign2 : minus : sign2 === "-" || sign2 === "(" ? "" : sign2) + valuePrefix;
        valueSuffix = (type === "s" && !isNaN(value) && prefixExponent !== void 0 ? prefixes[8 + prefixExponent / 3] : "") + valueSuffix + (valueNegative && sign2 === "(" ? ")" : "");
        if (maybeSuffix) {
          i = -1, n = value.length;
          while (++i < n) {
            if (c2 = value.charCodeAt(i), 48 > c2 || c2 > 57) {
              valueSuffix = (c2 === 46 ? decimal + value.slice(i + 1) : value.slice(i)) + valueSuffix;
              value = value.slice(0, i);
              break;
            }
          }
        }
      }
      if (comma && !zero2) value = group(value, Infinity);
      var length = valuePrefix.length + value.length + valueSuffix.length, padding = length < width ? new Array(width - length + 1).join(fill) : "";
      if (comma && zero2) value = group(padding + value, padding.length ? width - valueSuffix.length : Infinity), padding = "";
      switch (align) {
        case "<":
          value = valuePrefix + value + valueSuffix + padding;
          break;
        case "=":
          value = valuePrefix + padding + value + valueSuffix;
          break;
        case "^":
          value = padding.slice(0, length = padding.length >> 1) + valuePrefix + value + valueSuffix + padding.slice(length);
          break;
        default:
          value = padding + valuePrefix + value + valueSuffix;
          break;
      }
      return numerals(value);
    }
    format2.toString = function() {
      return specifier + "";
    };
    return format2;
  }
  function formatPrefix2(specifier, value) {
    var e = Math.max(-8, Math.min(8, Math.floor(exponent(value) / 3))) * 3, k2 = Math.pow(10, -e), f = newFormat((specifier = formatSpecifier(specifier), specifier.type = "f", specifier), { suffix: prefixes[8 + e / 3] });
    return function(value2) {
      return f(k2 * value2);
    };
  }
  return {
    format: newFormat,
    formatPrefix: formatPrefix2
  };
}
var locale$1;
var format$1;
var formatPrefix;
defaultLocale$1({
  thousands: ",",
  grouping: [3],
  currency: ["$", ""]
});
function defaultLocale$1(definition) {
  locale$1 = formatLocale$1(definition);
  format$1 = locale$1.format;
  formatPrefix = locale$1.formatPrefix;
  return locale$1;
}
function precisionFixed(step) {
  return Math.max(0, -exponent(Math.abs(step)));
}
function precisionPrefix(step, value) {
  return Math.max(0, Math.max(-8, Math.min(8, Math.floor(exponent(value) / 3))) * 3 - exponent(Math.abs(step)));
}
function precisionRound(step, max2) {
  step = Math.abs(step), max2 = Math.abs(max2) - step;
  return Math.max(0, exponent(max2) - exponent(step)) + 1;
}
function tickFormat(start, stop, count, specifier) {
  var step = tickStep(start, stop, count), precision;
  specifier = formatSpecifier(specifier == null ? ",f" : specifier);
  switch (specifier.type) {
    case "s": {
      var value = Math.max(Math.abs(start), Math.abs(stop));
      if (specifier.precision == null && !isNaN(precision = precisionPrefix(step, value))) specifier.precision = precision;
      return formatPrefix(specifier, value);
    }
    case "":
    case "e":
    case "g":
    case "p":
    case "r": {
      if (specifier.precision == null && !isNaN(precision = precisionRound(step, Math.max(Math.abs(start), Math.abs(stop))))) specifier.precision = precision - (specifier.type === "e");
      break;
    }
    case "f":
    case "%": {
      if (specifier.precision == null && !isNaN(precision = precisionFixed(step))) specifier.precision = precision - (specifier.type === "%") * 2;
      break;
    }
  }
  return format$1(specifier);
}
function linearish(scale2) {
  var domain = scale2.domain;
  scale2.ticks = function(count) {
    var d = domain();
    return ticks(d[0], d[d.length - 1], count == null ? 10 : count);
  };
  scale2.tickFormat = function(count, specifier) {
    var d = domain();
    return tickFormat(d[0], d[d.length - 1], count == null ? 10 : count, specifier);
  };
  scale2.nice = function(count) {
    if (count == null) count = 10;
    var d = domain();
    var i0 = 0;
    var i1 = d.length - 1;
    var start = d[i0];
    var stop = d[i1];
    var prestep;
    var step;
    var maxIter = 10;
    if (stop < start) {
      step = start, start = stop, stop = step;
      step = i0, i0 = i1, i1 = step;
    }
    while (maxIter-- > 0) {
      step = tickIncrement(start, stop, count);
      if (step === prestep) {
        d[i0] = start;
        d[i1] = stop;
        return domain(d);
      } else if (step > 0) {
        start = Math.floor(start / step) * step;
        stop = Math.ceil(stop / step) * step;
      } else if (step < 0) {
        start = Math.ceil(start * step) / step;
        stop = Math.floor(stop * step) / step;
      } else {
        break;
      }
      prestep = step;
    }
    return scale2;
  };
  return scale2;
}
function linear() {
  var scale2 = continuous();
  scale2.copy = function() {
    return copy$1(scale2, linear());
  };
  initRange.apply(scale2, arguments);
  return linearish(scale2);
}
function identity$3(domain) {
  var unknown;
  function scale2(x2) {
    return x2 == null || isNaN(x2 = +x2) ? unknown : x2;
  }
  scale2.invert = scale2;
  scale2.domain = scale2.range = function(_) {
    return arguments.length ? (domain = Array.from(_, number$1), scale2) : domain.slice();
  };
  scale2.unknown = function(_) {
    return arguments.length ? (unknown = _, scale2) : unknown;
  };
  scale2.copy = function() {
    return identity$3(domain).unknown(unknown);
  };
  domain = arguments.length ? Array.from(domain, number$1) : [0, 1];
  return linearish(scale2);
}
function nice(domain, interval) {
  domain = domain.slice();
  var i0 = 0, i1 = domain.length - 1, x0 = domain[i0], x1 = domain[i1], t;
  if (x1 < x0) {
    t = i0, i0 = i1, i1 = t;
    t = x0, x0 = x1, x1 = t;
  }
  domain[i0] = interval.floor(x0);
  domain[i1] = interval.ceil(x1);
  return domain;
}
function transformLog(x2) {
  return Math.log(x2);
}
function transformExp(x2) {
  return Math.exp(x2);
}
function transformLogn(x2) {
  return -Math.log(-x2);
}
function transformExpn(x2) {
  return -Math.exp(-x2);
}
function pow10(x2) {
  return isFinite(x2) ? +("1e" + x2) : x2 < 0 ? 0 : x2;
}
function powp(base) {
  return base === 10 ? pow10 : base === Math.E ? Math.exp : (x2) => Math.pow(base, x2);
}
function logp(base) {
  return base === Math.E ? Math.log : base === 10 && Math.log10 || base === 2 && Math.log2 || (base = Math.log(base), (x2) => Math.log(x2) / base);
}
function reflect(f) {
  return (x2, k2) => -f(-x2, k2);
}
function loggish(transform) {
  const scale2 = transform(transformLog, transformExp);
  const domain = scale2.domain;
  let base = 10;
  let logs;
  let pows;
  function rescale() {
    logs = logp(base), pows = powp(base);
    if (domain()[0] < 0) {
      logs = reflect(logs), pows = reflect(pows);
      transform(transformLogn, transformExpn);
    } else {
      transform(transformLog, transformExp);
    }
    return scale2;
  }
  scale2.base = function(_) {
    return arguments.length ? (base = +_, rescale()) : base;
  };
  scale2.domain = function(_) {
    return arguments.length ? (domain(_), rescale()) : domain();
  };
  scale2.ticks = (count) => {
    const d = domain();
    let u = d[0];
    let v = d[d.length - 1];
    const r2 = v < u;
    if (r2) [u, v] = [v, u];
    let i = logs(u);
    let j = logs(v);
    let k2;
    let t;
    const n = count == null ? 10 : +count;
    let z = [];
    if (!(base % 1) && j - i < n) {
      i = Math.floor(i), j = Math.ceil(j);
      if (u > 0) for (; i <= j; ++i) {
        for (k2 = 1; k2 < base; ++k2) {
          t = i < 0 ? k2 / pows(-i) : k2 * pows(i);
          if (t < u) continue;
          if (t > v) break;
          z.push(t);
        }
      }
      else for (; i <= j; ++i) {
        for (k2 = base - 1; k2 >= 1; --k2) {
          t = i > 0 ? k2 / pows(-i) : k2 * pows(i);
          if (t < u) continue;
          if (t > v) break;
          z.push(t);
        }
      }
      if (z.length * 2 < n) z = ticks(u, v, n);
    } else {
      z = ticks(i, j, Math.min(j - i, n)).map(pows);
    }
    return r2 ? z.reverse() : z;
  };
  scale2.tickFormat = (count, specifier) => {
    if (count == null) count = 10;
    if (specifier == null) specifier = base === 10 ? "s" : ",";
    if (typeof specifier !== "function") {
      if (!(base % 1) && (specifier = formatSpecifier(specifier)).precision == null) specifier.trim = true;
      specifier = format$1(specifier);
    }
    if (count === Infinity) return specifier;
    const k2 = Math.max(1, base * count / scale2.ticks().length);
    return (d) => {
      let i = d / pows(Math.round(logs(d)));
      if (i * base < base - 0.5) i *= base;
      return i <= k2 ? specifier(d) : "";
    };
  };
  scale2.nice = () => {
    return domain(nice(domain(), {
      floor: (x2) => pows(Math.floor(logs(x2))),
      ceil: (x2) => pows(Math.ceil(logs(x2)))
    }));
  };
  return scale2;
}
function log() {
  const scale2 = loggish(transformer$2()).domain([1, 10]);
  scale2.copy = () => copy$1(scale2, log()).base(scale2.base());
  initRange.apply(scale2, arguments);
  return scale2;
}
function transformSymlog(c2) {
  return function(x2) {
    return Math.sign(x2) * Math.log1p(Math.abs(x2 / c2));
  };
}
function transformSymexp(c2) {
  return function(x2) {
    return Math.sign(x2) * Math.expm1(Math.abs(x2)) * c2;
  };
}
function symlogish(transform) {
  var c2 = 1, scale2 = transform(transformSymlog(c2), transformSymexp(c2));
  scale2.constant = function(_) {
    return arguments.length ? transform(transformSymlog(c2 = +_), transformSymexp(c2)) : c2;
  };
  return linearish(scale2);
}
function symlog() {
  var scale2 = symlogish(transformer$2());
  scale2.copy = function() {
    return copy$1(scale2, symlog()).constant(scale2.constant());
  };
  return initRange.apply(scale2, arguments);
}
function transformPow(exponent2) {
  return function(x2) {
    return x2 < 0 ? -Math.pow(-x2, exponent2) : Math.pow(x2, exponent2);
  };
}
function transformSqrt(x2) {
  return x2 < 0 ? -Math.sqrt(-x2) : Math.sqrt(x2);
}
function transformSquare(x2) {
  return x2 < 0 ? -x2 * x2 : x2 * x2;
}
function powish(transform) {
  var scale2 = transform(identity$5, identity$5), exponent2 = 1;
  function rescale() {
    return exponent2 === 1 ? transform(identity$5, identity$5) : exponent2 === 0.5 ? transform(transformSqrt, transformSquare) : transform(transformPow(exponent2), transformPow(1 / exponent2));
  }
  scale2.exponent = function(_) {
    return arguments.length ? (exponent2 = +_, rescale()) : exponent2;
  };
  return linearish(scale2);
}
function pow() {
  var scale2 = powish(transformer$2());
  scale2.copy = function() {
    return copy$1(scale2, pow()).exponent(scale2.exponent());
  };
  initRange.apply(scale2, arguments);
  return scale2;
}
function sqrt() {
  return pow.apply(null, arguments).exponent(0.5);
}
function square(x2) {
  return Math.sign(x2) * x2 * x2;
}
function unsquare(x2) {
  return Math.sign(x2) * Math.sqrt(Math.abs(x2));
}
function radial() {
  var squared = continuous(), range3 = [0, 1], round2 = false, unknown;
  function scale2(x2) {
    var y2 = unsquare(squared(x2));
    return isNaN(y2) ? unknown : round2 ? Math.round(y2) : y2;
  }
  scale2.invert = function(y2) {
    return squared.invert(square(y2));
  };
  scale2.domain = function(_) {
    return arguments.length ? (squared.domain(_), scale2) : squared.domain();
  };
  scale2.range = function(_) {
    return arguments.length ? (squared.range((range3 = Array.from(_, number$1)).map(square)), scale2) : range3.slice();
  };
  scale2.rangeRound = function(_) {
    return scale2.range(_).round(true);
  };
  scale2.round = function(_) {
    return arguments.length ? (round2 = !!_, scale2) : round2;
  };
  scale2.clamp = function(_) {
    return arguments.length ? (squared.clamp(_), scale2) : squared.clamp();
  };
  scale2.unknown = function(_) {
    return arguments.length ? (unknown = _, scale2) : unknown;
  };
  scale2.copy = function() {
    return radial(squared.domain(), range3).round(round2).clamp(squared.clamp()).unknown(unknown);
  };
  initRange.apply(scale2, arguments);
  return linearish(scale2);
}
function quantile() {
  var domain = [], range3 = [], thresholds = [], unknown;
  function rescale() {
    var i = 0, n = Math.max(1, range3.length);
    thresholds = new Array(n - 1);
    while (++i < n) thresholds[i - 1] = quantileSorted(domain, i / n);
    return scale2;
  }
  function scale2(x2) {
    return x2 == null || isNaN(x2 = +x2) ? unknown : range3[bisectRight(thresholds, x2)];
  }
  scale2.invertExtent = function(y2) {
    var i = range3.indexOf(y2);
    return i < 0 ? [NaN, NaN] : [
      i > 0 ? thresholds[i - 1] : domain[0],
      i < thresholds.length ? thresholds[i] : domain[domain.length - 1]
    ];
  };
  scale2.domain = function(_) {
    if (!arguments.length) return domain.slice();
    domain = [];
    for (let d of _) if (d != null && !isNaN(d = +d)) domain.push(d);
    domain.sort(ascending);
    return rescale();
  };
  scale2.range = function(_) {
    return arguments.length ? (range3 = Array.from(_), rescale()) : range3.slice();
  };
  scale2.unknown = function(_) {
    return arguments.length ? (unknown = _, scale2) : unknown;
  };
  scale2.quantiles = function() {
    return thresholds.slice();
  };
  scale2.copy = function() {
    return quantile().domain(domain).range(range3).unknown(unknown);
  };
  return initRange.apply(scale2, arguments);
}
function quantize() {
  var x0 = 0, x1 = 1, n = 1, domain = [0.5], range3 = [0, 1], unknown;
  function scale2(x2) {
    return x2 != null && x2 <= x2 ? range3[bisectRight(domain, x2, 0, n)] : unknown;
  }
  function rescale() {
    var i = -1;
    domain = new Array(n);
    while (++i < n) domain[i] = ((i + 1) * x1 - (i - n) * x0) / (n + 1);
    return scale2;
  }
  scale2.domain = function(_) {
    return arguments.length ? ([x0, x1] = _, x0 = +x0, x1 = +x1, rescale()) : [x0, x1];
  };
  scale2.range = function(_) {
    return arguments.length ? (n = (range3 = Array.from(_)).length - 1, rescale()) : range3.slice();
  };
  scale2.invertExtent = function(y2) {
    var i = range3.indexOf(y2);
    return i < 0 ? [NaN, NaN] : i < 1 ? [x0, domain[0]] : i >= n ? [domain[n - 1], x1] : [domain[i - 1], domain[i]];
  };
  scale2.unknown = function(_) {
    return arguments.length ? (unknown = _, scale2) : scale2;
  };
  scale2.thresholds = function() {
    return domain.slice();
  };
  scale2.copy = function() {
    return quantize().domain([x0, x1]).range(range3).unknown(unknown);
  };
  return initRange.apply(linearish(scale2), arguments);
}
function threshold() {
  var domain = [0.5], range3 = [0, 1], unknown, n = 1;
  function scale2(x2) {
    return x2 != null && x2 <= x2 ? range3[bisectRight(domain, x2, 0, n)] : unknown;
  }
  scale2.domain = function(_) {
    return arguments.length ? (domain = Array.from(_), n = Math.min(domain.length, range3.length - 1), scale2) : domain.slice();
  };
  scale2.range = function(_) {
    return arguments.length ? (range3 = Array.from(_), n = Math.min(domain.length, range3.length - 1), scale2) : range3.slice();
  };
  scale2.invertExtent = function(y2) {
    var i = range3.indexOf(y2);
    return [domain[i - 1], domain[i]];
  };
  scale2.unknown = function(_) {
    return arguments.length ? (unknown = _, scale2) : unknown;
  };
  scale2.copy = function() {
    return threshold().domain(domain).range(range3).unknown(unknown);
  };
  return initRange.apply(scale2, arguments);
}
const t0 = /* @__PURE__ */ new Date(), t1 = /* @__PURE__ */ new Date();
function timeInterval(floori, offseti, count, field) {
  function interval(date2) {
    return floori(date2 = arguments.length === 0 ? /* @__PURE__ */ new Date() : /* @__PURE__ */ new Date(+date2)), date2;
  }
  interval.floor = (date2) => {
    return floori(date2 = /* @__PURE__ */ new Date(+date2)), date2;
  };
  interval.ceil = (date2) => {
    return floori(date2 = new Date(date2 - 1)), offseti(date2, 1), floori(date2), date2;
  };
  interval.round = (date2) => {
    const d0 = interval(date2), d1 = interval.ceil(date2);
    return date2 - d0 < d1 - date2 ? d0 : d1;
  };
  interval.offset = (date2, step) => {
    return offseti(date2 = /* @__PURE__ */ new Date(+date2), step == null ? 1 : Math.floor(step)), date2;
  };
  interval.range = (start, stop, step) => {
    const range3 = [];
    start = interval.ceil(start);
    step = step == null ? 1 : Math.floor(step);
    if (!(start < stop) || !(step > 0)) return range3;
    let previous;
    do
      range3.push(previous = /* @__PURE__ */ new Date(+start)), offseti(start, step), floori(start);
    while (previous < start && start < stop);
    return range3;
  };
  interval.filter = (test) => {
    return timeInterval((date2) => {
      if (date2 >= date2) while (floori(date2), !test(date2)) date2.setTime(date2 - 1);
    }, (date2, step) => {
      if (date2 >= date2) {
        if (step < 0) while (++step <= 0) {
          while (offseti(date2, -1), !test(date2)) {
          }
        }
        else while (--step >= 0) {
          while (offseti(date2, 1), !test(date2)) {
          }
        }
      }
    });
  };
  if (count) {
    interval.count = (start, end) => {
      t0.setTime(+start), t1.setTime(+end);
      floori(t0), floori(t1);
      return Math.floor(count(t0, t1));
    };
    interval.every = (step) => {
      step = Math.floor(step);
      return !isFinite(step) || !(step > 0) ? null : !(step > 1) ? interval : interval.filter(field ? (d) => field(d) % step === 0 : (d) => interval.count(0, d) % step === 0);
    };
  }
  return interval;
}
const millisecond = timeInterval(() => {
}, (date2, step) => {
  date2.setTime(+date2 + step);
}, (start, end) => {
  return end - start;
});
millisecond.every = (k2) => {
  k2 = Math.floor(k2);
  if (!isFinite(k2) || !(k2 > 0)) return null;
  if (!(k2 > 1)) return millisecond;
  return timeInterval((date2) => {
    date2.setTime(Math.floor(date2 / k2) * k2);
  }, (date2, step) => {
    date2.setTime(+date2 + step * k2);
  }, (start, end) => {
    return (end - start) / k2;
  });
};
millisecond.range;
const durationSecond = 1e3;
const durationMinute = durationSecond * 60;
const durationHour = durationMinute * 60;
const durationDay = durationHour * 24;
const durationWeek = durationDay * 7;
const durationMonth = durationDay * 30;
const durationYear = durationDay * 365;
const second = timeInterval((date2) => {
  date2.setTime(date2 - date2.getMilliseconds());
}, (date2, step) => {
  date2.setTime(+date2 + step * durationSecond);
}, (start, end) => {
  return (end - start) / durationSecond;
}, (date2) => {
  return date2.getUTCSeconds();
});
second.range;
const timeMinute = timeInterval((date2) => {
  date2.setTime(date2 - date2.getMilliseconds() - date2.getSeconds() * durationSecond);
}, (date2, step) => {
  date2.setTime(+date2 + step * durationMinute);
}, (start, end) => {
  return (end - start) / durationMinute;
}, (date2) => {
  return date2.getMinutes();
});
timeMinute.range;
const utcMinute = timeInterval((date2) => {
  date2.setUTCSeconds(0, 0);
}, (date2, step) => {
  date2.setTime(+date2 + step * durationMinute);
}, (start, end) => {
  return (end - start) / durationMinute;
}, (date2) => {
  return date2.getUTCMinutes();
});
utcMinute.range;
const timeHour = timeInterval((date2) => {
  date2.setTime(date2 - date2.getMilliseconds() - date2.getSeconds() * durationSecond - date2.getMinutes() * durationMinute);
}, (date2, step) => {
  date2.setTime(+date2 + step * durationHour);
}, (start, end) => {
  return (end - start) / durationHour;
}, (date2) => {
  return date2.getHours();
});
timeHour.range;
const utcHour = timeInterval((date2) => {
  date2.setUTCMinutes(0, 0, 0);
}, (date2, step) => {
  date2.setTime(+date2 + step * durationHour);
}, (start, end) => {
  return (end - start) / durationHour;
}, (date2) => {
  return date2.getUTCHours();
});
utcHour.range;
const timeDay = timeInterval(
  (date2) => date2.setHours(0, 0, 0, 0),
  (date2, step) => date2.setDate(date2.getDate() + step),
  (start, end) => (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * durationMinute) / durationDay,
  (date2) => date2.getDate() - 1
);
timeDay.range;
const utcDay = timeInterval((date2) => {
  date2.setUTCHours(0, 0, 0, 0);
}, (date2, step) => {
  date2.setUTCDate(date2.getUTCDate() + step);
}, (start, end) => {
  return (end - start) / durationDay;
}, (date2) => {
  return date2.getUTCDate() - 1;
});
utcDay.range;
const unixDay = timeInterval((date2) => {
  date2.setUTCHours(0, 0, 0, 0);
}, (date2, step) => {
  date2.setUTCDate(date2.getUTCDate() + step);
}, (start, end) => {
  return (end - start) / durationDay;
}, (date2) => {
  return Math.floor(date2 / durationDay);
});
unixDay.range;
function timeWeekday(i) {
  return timeInterval((date2) => {
    date2.setDate(date2.getDate() - (date2.getDay() + 7 - i) % 7);
    date2.setHours(0, 0, 0, 0);
  }, (date2, step) => {
    date2.setDate(date2.getDate() + step * 7);
  }, (start, end) => {
    return (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * durationMinute) / durationWeek;
  });
}
const timeSunday = timeWeekday(0);
const timeMonday = timeWeekday(1);
const timeTuesday = timeWeekday(2);
const timeWednesday = timeWeekday(3);
const timeThursday = timeWeekday(4);
const timeFriday = timeWeekday(5);
const timeSaturday = timeWeekday(6);
timeSunday.range;
timeMonday.range;
timeTuesday.range;
timeWednesday.range;
timeThursday.range;
timeFriday.range;
timeSaturday.range;
function utcWeekday(i) {
  return timeInterval((date2) => {
    date2.setUTCDate(date2.getUTCDate() - (date2.getUTCDay() + 7 - i) % 7);
    date2.setUTCHours(0, 0, 0, 0);
  }, (date2, step) => {
    date2.setUTCDate(date2.getUTCDate() + step * 7);
  }, (start, end) => {
    return (end - start) / durationWeek;
  });
}
const utcSunday = utcWeekday(0);
const utcMonday = utcWeekday(1);
const utcTuesday = utcWeekday(2);
const utcWednesday = utcWeekday(3);
const utcThursday = utcWeekday(4);
const utcFriday = utcWeekday(5);
const utcSaturday = utcWeekday(6);
utcSunday.range;
utcMonday.range;
utcTuesday.range;
utcWednesday.range;
utcThursday.range;
utcFriday.range;
utcSaturday.range;
const timeMonth = timeInterval((date2) => {
  date2.setDate(1);
  date2.setHours(0, 0, 0, 0);
}, (date2, step) => {
  date2.setMonth(date2.getMonth() + step);
}, (start, end) => {
  return end.getMonth() - start.getMonth() + (end.getFullYear() - start.getFullYear()) * 12;
}, (date2) => {
  return date2.getMonth();
});
timeMonth.range;
const utcMonth = timeInterval((date2) => {
  date2.setUTCDate(1);
  date2.setUTCHours(0, 0, 0, 0);
}, (date2, step) => {
  date2.setUTCMonth(date2.getUTCMonth() + step);
}, (start, end) => {
  return end.getUTCMonth() - start.getUTCMonth() + (end.getUTCFullYear() - start.getUTCFullYear()) * 12;
}, (date2) => {
  return date2.getUTCMonth();
});
utcMonth.range;
const timeYear = timeInterval((date2) => {
  date2.setMonth(0, 1);
  date2.setHours(0, 0, 0, 0);
}, (date2, step) => {
  date2.setFullYear(date2.getFullYear() + step);
}, (start, end) => {
  return end.getFullYear() - start.getFullYear();
}, (date2) => {
  return date2.getFullYear();
});
timeYear.every = (k2) => {
  return !isFinite(k2 = Math.floor(k2)) || !(k2 > 0) ? null : timeInterval((date2) => {
    date2.setFullYear(Math.floor(date2.getFullYear() / k2) * k2);
    date2.setMonth(0, 1);
    date2.setHours(0, 0, 0, 0);
  }, (date2, step) => {
    date2.setFullYear(date2.getFullYear() + step * k2);
  });
};
timeYear.range;
const utcYear = timeInterval((date2) => {
  date2.setUTCMonth(0, 1);
  date2.setUTCHours(0, 0, 0, 0);
}, (date2, step) => {
  date2.setUTCFullYear(date2.getUTCFullYear() + step);
}, (start, end) => {
  return end.getUTCFullYear() - start.getUTCFullYear();
}, (date2) => {
  return date2.getUTCFullYear();
});
utcYear.every = (k2) => {
  return !isFinite(k2 = Math.floor(k2)) || !(k2 > 0) ? null : timeInterval((date2) => {
    date2.setUTCFullYear(Math.floor(date2.getUTCFullYear() / k2) * k2);
    date2.setUTCMonth(0, 1);
    date2.setUTCHours(0, 0, 0, 0);
  }, (date2, step) => {
    date2.setUTCFullYear(date2.getUTCFullYear() + step * k2);
  });
};
utcYear.range;
function ticker(year, month, week, day, hour, minute) {
  const tickIntervals = [
    [second, 1, durationSecond],
    [second, 5, 5 * durationSecond],
    [second, 15, 15 * durationSecond],
    [second, 30, 30 * durationSecond],
    [minute, 1, durationMinute],
    [minute, 5, 5 * durationMinute],
    [minute, 15, 15 * durationMinute],
    [minute, 30, 30 * durationMinute],
    [hour, 1, durationHour],
    [hour, 3, 3 * durationHour],
    [hour, 6, 6 * durationHour],
    [hour, 12, 12 * durationHour],
    [day, 1, durationDay],
    [day, 2, 2 * durationDay],
    [week, 1, durationWeek],
    [month, 1, durationMonth],
    [month, 3, 3 * durationMonth],
    [year, 1, durationYear]
  ];
  function ticks2(start, stop, count) {
    const reverse3 = stop < start;
    if (reverse3) [start, stop] = [stop, start];
    const interval = count && typeof count.range === "function" ? count : tickInterval(start, stop, count);
    const ticks3 = interval ? interval.range(start, +stop + 1) : [];
    return reverse3 ? ticks3.reverse() : ticks3;
  }
  function tickInterval(start, stop, count) {
    const target2 = Math.abs(stop - start) / count;
    const i = bisector(([, , step2]) => step2).right(tickIntervals, target2);
    if (i === tickIntervals.length) return year.every(tickStep(start / durationYear, stop / durationYear, count));
    if (i === 0) return millisecond.every(Math.max(tickStep(start, stop, count), 1));
    const [t, step] = tickIntervals[target2 / tickIntervals[i - 1][2] < tickIntervals[i][2] / target2 ? i - 1 : i];
    return t.every(step);
  }
  return [ticks2, tickInterval];
}
const [utcTicks, utcTickInterval] = ticker(utcYear, utcMonth, utcSunday, unixDay, utcHour, utcMinute);
const [timeTicks, timeTickInterval] = ticker(timeYear, timeMonth, timeSunday, timeDay, timeHour, timeMinute);
function localDate(d) {
  if (0 <= d.y && d.y < 100) {
    var date2 = new Date(-1, d.m, d.d, d.H, d.M, d.S, d.L);
    date2.setFullYear(d.y);
    return date2;
  }
  return new Date(d.y, d.m, d.d, d.H, d.M, d.S, d.L);
}
function utcDate(d) {
  if (0 <= d.y && d.y < 100) {
    var date2 = new Date(Date.UTC(-1, d.m, d.d, d.H, d.M, d.S, d.L));
    date2.setUTCFullYear(d.y);
    return date2;
  }
  return new Date(Date.UTC(d.y, d.m, d.d, d.H, d.M, d.S, d.L));
}
function newDate(y2, m, d) {
  return { y: y2, m, d, H: 0, M: 0, S: 0, L: 0 };
}
function formatLocale(locale2) {
  var locale_dateTime = locale2.dateTime, locale_date = locale2.date, locale_time = locale2.time, locale_periods = locale2.periods, locale_weekdays = locale2.days, locale_shortWeekdays = locale2.shortDays, locale_months = locale2.months, locale_shortMonths = locale2.shortMonths;
  var periodRe = formatRe(locale_periods), periodLookup = formatLookup(locale_periods), weekdayRe = formatRe(locale_weekdays), weekdayLookup = formatLookup(locale_weekdays), shortWeekdayRe = formatRe(locale_shortWeekdays), shortWeekdayLookup = formatLookup(locale_shortWeekdays), monthRe = formatRe(locale_months), monthLookup = formatLookup(locale_months), shortMonthRe = formatRe(locale_shortMonths), shortMonthLookup = formatLookup(locale_shortMonths);
  var formats = {
    "a": formatShortWeekday,
    "A": formatWeekday,
    "b": formatShortMonth,
    "B": formatMonth,
    "c": null,
    "d": formatDayOfMonth,
    "e": formatDayOfMonth,
    "f": formatMicroseconds,
    "g": formatYearISO,
    "G": formatFullYearISO,
    "H": formatHour24,
    "I": formatHour12,
    "j": formatDayOfYear,
    "L": formatMilliseconds,
    "m": formatMonthNumber,
    "M": formatMinutes,
    "p": formatPeriod,
    "q": formatQuarter,
    "Q": formatUnixTimestamp,
    "s": formatUnixTimestampSeconds,
    "S": formatSeconds,
    "u": formatWeekdayNumberMonday,
    "U": formatWeekNumberSunday,
    "V": formatWeekNumberISO,
    "w": formatWeekdayNumberSunday,
    "W": formatWeekNumberMonday,
    "x": null,
    "X": null,
    "y": formatYear,
    "Y": formatFullYear,
    "Z": formatZone,
    "%": formatLiteralPercent
  };
  var utcFormats = {
    "a": formatUTCShortWeekday,
    "A": formatUTCWeekday,
    "b": formatUTCShortMonth,
    "B": formatUTCMonth,
    "c": null,
    "d": formatUTCDayOfMonth,
    "e": formatUTCDayOfMonth,
    "f": formatUTCMicroseconds,
    "g": formatUTCYearISO,
    "G": formatUTCFullYearISO,
    "H": formatUTCHour24,
    "I": formatUTCHour12,
    "j": formatUTCDayOfYear,
    "L": formatUTCMilliseconds,
    "m": formatUTCMonthNumber,
    "M": formatUTCMinutes,
    "p": formatUTCPeriod,
    "q": formatUTCQuarter,
    "Q": formatUnixTimestamp,
    "s": formatUnixTimestampSeconds,
    "S": formatUTCSeconds,
    "u": formatUTCWeekdayNumberMonday,
    "U": formatUTCWeekNumberSunday,
    "V": formatUTCWeekNumberISO,
    "w": formatUTCWeekdayNumberSunday,
    "W": formatUTCWeekNumberMonday,
    "x": null,
    "X": null,
    "y": formatUTCYear,
    "Y": formatUTCFullYear,
    "Z": formatUTCZone,
    "%": formatLiteralPercent
  };
  var parses = {
    "a": parseShortWeekday,
    "A": parseWeekday,
    "b": parseShortMonth,
    "B": parseMonth,
    "c": parseLocaleDateTime,
    "d": parseDayOfMonth,
    "e": parseDayOfMonth,
    "f": parseMicroseconds,
    "g": parseYear$1,
    "G": parseFullYear,
    "H": parseHour24,
    "I": parseHour24,
    "j": parseDayOfYear,
    "L": parseMilliseconds,
    "m": parseMonthNumber,
    "M": parseMinutes,
    "p": parsePeriod,
    "q": parseQuarter,
    "Q": parseUnixTimestamp,
    "s": parseUnixTimestampSeconds,
    "S": parseSeconds,
    "u": parseWeekdayNumberMonday,
    "U": parseWeekNumberSunday,
    "V": parseWeekNumberISO,
    "w": parseWeekdayNumberSunday,
    "W": parseWeekNumberMonday,
    "x": parseLocaleDate,
    "X": parseLocaleTime,
    "y": parseYear$1,
    "Y": parseFullYear,
    "Z": parseZone,
    "%": parseLiteralPercent
  };
  formats.x = newFormat(locale_date, formats);
  formats.X = newFormat(locale_time, formats);
  formats.c = newFormat(locale_dateTime, formats);
  utcFormats.x = newFormat(locale_date, utcFormats);
  utcFormats.X = newFormat(locale_time, utcFormats);
  utcFormats.c = newFormat(locale_dateTime, utcFormats);
  function newFormat(specifier, formats2) {
    return function(date2) {
      var string2 = [], i = -1, j = 0, n = specifier.length, c2, pad2, format2;
      if (!(date2 instanceof Date)) date2 = /* @__PURE__ */ new Date(+date2);
      while (++i < n) {
        if (specifier.charCodeAt(i) === 37) {
          string2.push(specifier.slice(j, i));
          if ((pad2 = pads[c2 = specifier.charAt(++i)]) != null) c2 = specifier.charAt(++i);
          else pad2 = c2 === "e" ? " " : "0";
          if (format2 = formats2[c2]) c2 = format2(date2, pad2);
          string2.push(c2);
          j = i + 1;
        }
      }
      string2.push(specifier.slice(j, i));
      return string2.join("");
    };
  }
  function newParse(specifier, Z) {
    return function(string2) {
      var d = newDate(1900, void 0, 1), i = parseSpecifier(d, specifier, string2 += "", 0), week, day;
      if (i != string2.length) return null;
      if ("Q" in d) return new Date(d.Q);
      if ("s" in d) return new Date(d.s * 1e3 + ("L" in d ? d.L : 0));
      if (Z && !("Z" in d)) d.Z = 0;
      if ("p" in d) d.H = d.H % 12 + d.p * 12;
      if (d.m === void 0) d.m = "q" in d ? d.q : 0;
      if ("V" in d) {
        if (d.V < 1 || d.V > 53) return null;
        if (!("w" in d)) d.w = 1;
        if ("Z" in d) {
          week = utcDate(newDate(d.y, 0, 1)), day = week.getUTCDay();
          week = day > 4 || day === 0 ? utcMonday.ceil(week) : utcMonday(week);
          week = utcDay.offset(week, (d.V - 1) * 7);
          d.y = week.getUTCFullYear();
          d.m = week.getUTCMonth();
          d.d = week.getUTCDate() + (d.w + 6) % 7;
        } else {
          week = localDate(newDate(d.y, 0, 1)), day = week.getDay();
          week = day > 4 || day === 0 ? timeMonday.ceil(week) : timeMonday(week);
          week = timeDay.offset(week, (d.V - 1) * 7);
          d.y = week.getFullYear();
          d.m = week.getMonth();
          d.d = week.getDate() + (d.w + 6) % 7;
        }
      } else if ("W" in d || "U" in d) {
        if (!("w" in d)) d.w = "u" in d ? d.u % 7 : "W" in d ? 1 : 0;
        day = "Z" in d ? utcDate(newDate(d.y, 0, 1)).getUTCDay() : localDate(newDate(d.y, 0, 1)).getDay();
        d.m = 0;
        d.d = "W" in d ? (d.w + 6) % 7 + d.W * 7 - (day + 5) % 7 : d.w + d.U * 7 - (day + 6) % 7;
      }
      if ("Z" in d) {
        d.H += d.Z / 100 | 0;
        d.M += d.Z % 100;
        return utcDate(d);
      }
      return localDate(d);
    };
  }
  function parseSpecifier(d, specifier, string2, j) {
    var i = 0, n = specifier.length, m = string2.length, c2, parse2;
    while (i < n) {
      if (j >= m) return -1;
      c2 = specifier.charCodeAt(i++);
      if (c2 === 37) {
        c2 = specifier.charAt(i++);
        parse2 = parses[c2 in pads ? specifier.charAt(i++) : c2];
        if (!parse2 || (j = parse2(d, string2, j)) < 0) return -1;
      } else if (c2 != string2.charCodeAt(j++)) {
        return -1;
      }
    }
    return j;
  }
  function parsePeriod(d, string2, i) {
    var n = periodRe.exec(string2.slice(i));
    return n ? (d.p = periodLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
  }
  function parseShortWeekday(d, string2, i) {
    var n = shortWeekdayRe.exec(string2.slice(i));
    return n ? (d.w = shortWeekdayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
  }
  function parseWeekday(d, string2, i) {
    var n = weekdayRe.exec(string2.slice(i));
    return n ? (d.w = weekdayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
  }
  function parseShortMonth(d, string2, i) {
    var n = shortMonthRe.exec(string2.slice(i));
    return n ? (d.m = shortMonthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
  }
  function parseMonth(d, string2, i) {
    var n = monthRe.exec(string2.slice(i));
    return n ? (d.m = monthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
  }
  function parseLocaleDateTime(d, string2, i) {
    return parseSpecifier(d, locale_dateTime, string2, i);
  }
  function parseLocaleDate(d, string2, i) {
    return parseSpecifier(d, locale_date, string2, i);
  }
  function parseLocaleTime(d, string2, i) {
    return parseSpecifier(d, locale_time, string2, i);
  }
  function formatShortWeekday(d) {
    return locale_shortWeekdays[d.getDay()];
  }
  function formatWeekday(d) {
    return locale_weekdays[d.getDay()];
  }
  function formatShortMonth(d) {
    return locale_shortMonths[d.getMonth()];
  }
  function formatMonth(d) {
    return locale_months[d.getMonth()];
  }
  function formatPeriod(d) {
    return locale_periods[+(d.getHours() >= 12)];
  }
  function formatQuarter(d) {
    return 1 + ~~(d.getMonth() / 3);
  }
  function formatUTCShortWeekday(d) {
    return locale_shortWeekdays[d.getUTCDay()];
  }
  function formatUTCWeekday(d) {
    return locale_weekdays[d.getUTCDay()];
  }
  function formatUTCShortMonth(d) {
    return locale_shortMonths[d.getUTCMonth()];
  }
  function formatUTCMonth(d) {
    return locale_months[d.getUTCMonth()];
  }
  function formatUTCPeriod(d) {
    return locale_periods[+(d.getUTCHours() >= 12)];
  }
  function formatUTCQuarter(d) {
    return 1 + ~~(d.getUTCMonth() / 3);
  }
  return {
    format: function(specifier) {
      var f = newFormat(specifier += "", formats);
      f.toString = function() {
        return specifier;
      };
      return f;
    },
    parse: function(specifier) {
      var p = newParse(specifier += "", false);
      p.toString = function() {
        return specifier;
      };
      return p;
    },
    utcFormat: function(specifier) {
      var f = newFormat(specifier += "", utcFormats);
      f.toString = function() {
        return specifier;
      };
      return f;
    },
    utcParse: function(specifier) {
      var p = newParse(specifier += "", true);
      p.toString = function() {
        return specifier;
      };
      return p;
    }
  };
}
var pads = { "-": "", "_": " ", "0": "0" }, numberRe = /^\s*\d+/, percentRe = /^%/, requoteRe = /[\\^$*+?|[\]().{}]/g;
function pad(value, fill, width) {
  var sign2 = value < 0 ? "-" : "", string2 = (sign2 ? -value : value) + "", length = string2.length;
  return sign2 + (length < width ? new Array(width - length + 1).join(fill) + string2 : string2);
}
function requote(s2) {
  return s2.replace(requoteRe, "\\$&");
}
function formatRe(names) {
  return new RegExp("^(?:" + names.map(requote).join("|") + ")", "i");
}
function formatLookup(names) {
  return new Map(names.map((name, i) => [name.toLowerCase(), i]));
}
function parseWeekdayNumberSunday(d, string2, i) {
  var n = numberRe.exec(string2.slice(i, i + 1));
  return n ? (d.w = +n[0], i + n[0].length) : -1;
}
function parseWeekdayNumberMonday(d, string2, i) {
  var n = numberRe.exec(string2.slice(i, i + 1));
  return n ? (d.u = +n[0], i + n[0].length) : -1;
}
function parseWeekNumberSunday(d, string2, i) {
  var n = numberRe.exec(string2.slice(i, i + 2));
  return n ? (d.U = +n[0], i + n[0].length) : -1;
}
function parseWeekNumberISO(d, string2, i) {
  var n = numberRe.exec(string2.slice(i, i + 2));
  return n ? (d.V = +n[0], i + n[0].length) : -1;
}
function parseWeekNumberMonday(d, string2, i) {
  var n = numberRe.exec(string2.slice(i, i + 2));
  return n ? (d.W = +n[0], i + n[0].length) : -1;
}
function parseFullYear(d, string2, i) {
  var n = numberRe.exec(string2.slice(i, i + 4));
  return n ? (d.y = +n[0], i + n[0].length) : -1;
}
function parseYear$1(d, string2, i) {
  var n = numberRe.exec(string2.slice(i, i + 2));
  return n ? (d.y = +n[0] + (+n[0] > 68 ? 1900 : 2e3), i + n[0].length) : -1;
}
function parseZone(d, string2, i) {
  var n = /^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(string2.slice(i, i + 6));
  return n ? (d.Z = n[1] ? 0 : -(n[2] + (n[3] || "00")), i + n[0].length) : -1;
}
function parseQuarter(d, string2, i) {
  var n = numberRe.exec(string2.slice(i, i + 1));
  return n ? (d.q = n[0] * 3 - 3, i + n[0].length) : -1;
}
function parseMonthNumber(d, string2, i) {
  var n = numberRe.exec(string2.slice(i, i + 2));
  return n ? (d.m = n[0] - 1, i + n[0].length) : -1;
}
function parseDayOfMonth(d, string2, i) {
  var n = numberRe.exec(string2.slice(i, i + 2));
  return n ? (d.d = +n[0], i + n[0].length) : -1;
}
function parseDayOfYear(d, string2, i) {
  var n = numberRe.exec(string2.slice(i, i + 3));
  return n ? (d.m = 0, d.d = +n[0], i + n[0].length) : -1;
}
function parseHour24(d, string2, i) {
  var n = numberRe.exec(string2.slice(i, i + 2));
  return n ? (d.H = +n[0], i + n[0].length) : -1;
}
function parseMinutes(d, string2, i) {
  var n = numberRe.exec(string2.slice(i, i + 2));
  return n ? (d.M = +n[0], i + n[0].length) : -1;
}
function parseSeconds(d, string2, i) {
  var n = numberRe.exec(string2.slice(i, i + 2));
  return n ? (d.S = +n[0], i + n[0].length) : -1;
}
function parseMilliseconds(d, string2, i) {
  var n = numberRe.exec(string2.slice(i, i + 3));
  return n ? (d.L = +n[0], i + n[0].length) : -1;
}
function parseMicroseconds(d, string2, i) {
  var n = numberRe.exec(string2.slice(i, i + 6));
  return n ? (d.L = Math.floor(n[0] / 1e3), i + n[0].length) : -1;
}
function parseLiteralPercent(d, string2, i) {
  var n = percentRe.exec(string2.slice(i, i + 1));
  return n ? i + n[0].length : -1;
}
function parseUnixTimestamp(d, string2, i) {
  var n = numberRe.exec(string2.slice(i));
  return n ? (d.Q = +n[0], i + n[0].length) : -1;
}
function parseUnixTimestampSeconds(d, string2, i) {
  var n = numberRe.exec(string2.slice(i));
  return n ? (d.s = +n[0], i + n[0].length) : -1;
}
function formatDayOfMonth(d, p) {
  return pad(d.getDate(), p, 2);
}
function formatHour24(d, p) {
  return pad(d.getHours(), p, 2);
}
function formatHour12(d, p) {
  return pad(d.getHours() % 12 || 12, p, 2);
}
function formatDayOfYear(d, p) {
  return pad(1 + timeDay.count(timeYear(d), d), p, 3);
}
function formatMilliseconds(d, p) {
  return pad(d.getMilliseconds(), p, 3);
}
function formatMicroseconds(d, p) {
  return formatMilliseconds(d, p) + "000";
}
function formatMonthNumber(d, p) {
  return pad(d.getMonth() + 1, p, 2);
}
function formatMinutes(d, p) {
  return pad(d.getMinutes(), p, 2);
}
function formatSeconds(d, p) {
  return pad(d.getSeconds(), p, 2);
}
function formatWeekdayNumberMonday(d) {
  var day = d.getDay();
  return day === 0 ? 7 : day;
}
function formatWeekNumberSunday(d, p) {
  return pad(timeSunday.count(timeYear(d) - 1, d), p, 2);
}
function dISO(d) {
  var day = d.getDay();
  return day >= 4 || day === 0 ? timeThursday(d) : timeThursday.ceil(d);
}
function formatWeekNumberISO(d, p) {
  d = dISO(d);
  return pad(timeThursday.count(timeYear(d), d) + (timeYear(d).getDay() === 4), p, 2);
}
function formatWeekdayNumberSunday(d) {
  return d.getDay();
}
function formatWeekNumberMonday(d, p) {
  return pad(timeMonday.count(timeYear(d) - 1, d), p, 2);
}
function formatYear(d, p) {
  return pad(d.getFullYear() % 100, p, 2);
}
function formatYearISO(d, p) {
  d = dISO(d);
  return pad(d.getFullYear() % 100, p, 2);
}
function formatFullYear(d, p) {
  return pad(d.getFullYear() % 1e4, p, 4);
}
function formatFullYearISO(d, p) {
  var day = d.getDay();
  d = day >= 4 || day === 0 ? timeThursday(d) : timeThursday.ceil(d);
  return pad(d.getFullYear() % 1e4, p, 4);
}
function formatZone(d) {
  var z = d.getTimezoneOffset();
  return (z > 0 ? "-" : (z *= -1, "+")) + pad(z / 60 | 0, "0", 2) + pad(z % 60, "0", 2);
}
function formatUTCDayOfMonth(d, p) {
  return pad(d.getUTCDate(), p, 2);
}
function formatUTCHour24(d, p) {
  return pad(d.getUTCHours(), p, 2);
}
function formatUTCHour12(d, p) {
  return pad(d.getUTCHours() % 12 || 12, p, 2);
}
function formatUTCDayOfYear(d, p) {
  return pad(1 + utcDay.count(utcYear(d), d), p, 3);
}
function formatUTCMilliseconds(d, p) {
  return pad(d.getUTCMilliseconds(), p, 3);
}
function formatUTCMicroseconds(d, p) {
  return formatUTCMilliseconds(d, p) + "000";
}
function formatUTCMonthNumber(d, p) {
  return pad(d.getUTCMonth() + 1, p, 2);
}
function formatUTCMinutes(d, p) {
  return pad(d.getUTCMinutes(), p, 2);
}
function formatUTCSeconds(d, p) {
  return pad(d.getUTCSeconds(), p, 2);
}
function formatUTCWeekdayNumberMonday(d) {
  var dow = d.getUTCDay();
  return dow === 0 ? 7 : dow;
}
function formatUTCWeekNumberSunday(d, p) {
  return pad(utcSunday.count(utcYear(d) - 1, d), p, 2);
}
function UTCdISO(d) {
  var day = d.getUTCDay();
  return day >= 4 || day === 0 ? utcThursday(d) : utcThursday.ceil(d);
}
function formatUTCWeekNumberISO(d, p) {
  d = UTCdISO(d);
  return pad(utcThursday.count(utcYear(d), d) + (utcYear(d).getUTCDay() === 4), p, 2);
}
function formatUTCWeekdayNumberSunday(d) {
  return d.getUTCDay();
}
function formatUTCWeekNumberMonday(d, p) {
  return pad(utcMonday.count(utcYear(d) - 1, d), p, 2);
}
function formatUTCYear(d, p) {
  return pad(d.getUTCFullYear() % 100, p, 2);
}
function formatUTCYearISO(d, p) {
  d = UTCdISO(d);
  return pad(d.getUTCFullYear() % 100, p, 2);
}
function formatUTCFullYear(d, p) {
  return pad(d.getUTCFullYear() % 1e4, p, 4);
}
function formatUTCFullYearISO(d, p) {
  var day = d.getUTCDay();
  d = day >= 4 || day === 0 ? utcThursday(d) : utcThursday.ceil(d);
  return pad(d.getUTCFullYear() % 1e4, p, 4);
}
function formatUTCZone() {
  return "+0000";
}
function formatLiteralPercent() {
  return "%";
}
function formatUnixTimestamp(d) {
  return +d;
}
function formatUnixTimestampSeconds(d) {
  return Math.floor(+d / 1e3);
}
var locale;
var timeFormat;
var utcFormat;
defaultLocale({
  dateTime: "%x, %X",
  date: "%-m/%-d/%Y",
  time: "%-I:%M:%S %p",
  periods: ["AM", "PM"],
  days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
  shortDays: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
  months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
  shortMonths: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
});
function defaultLocale(definition) {
  locale = formatLocale(definition);
  timeFormat = locale.format;
  locale.parse;
  utcFormat = locale.utcFormat;
  locale.utcParse;
  return locale;
}
function date(t) {
  return new Date(t);
}
function number(t) {
  return t instanceof Date ? +t : +/* @__PURE__ */ new Date(+t);
}
function calendar(ticks2, tickInterval, year, month, week, day, hour, minute, second2, format2) {
  var scale2 = continuous(), invert = scale2.invert, domain = scale2.domain;
  var formatMillisecond = format2(".%L"), formatSecond = format2(":%S"), formatMinute = format2("%I:%M"), formatHour = format2("%I %p"), formatDay = format2("%a %d"), formatWeek = format2("%b %d"), formatMonth = format2("%B"), formatYear2 = format2("%Y");
  function tickFormat2(date2) {
    return (second2(date2) < date2 ? formatMillisecond : minute(date2) < date2 ? formatSecond : hour(date2) < date2 ? formatMinute : day(date2) < date2 ? formatHour : month(date2) < date2 ? week(date2) < date2 ? formatDay : formatWeek : year(date2) < date2 ? formatMonth : formatYear2)(date2);
  }
  scale2.invert = function(y2) {
    return new Date(invert(y2));
  };
  scale2.domain = function(_) {
    return arguments.length ? domain(Array.from(_, number)) : domain().map(date);
  };
  scale2.ticks = function(interval) {
    var d = domain();
    return ticks2(d[0], d[d.length - 1], interval == null ? 10 : interval);
  };
  scale2.tickFormat = function(count, specifier) {
    return specifier == null ? tickFormat2 : format2(specifier);
  };
  scale2.nice = function(interval) {
    var d = domain();
    if (!interval || typeof interval.range !== "function") interval = tickInterval(d[0], d[d.length - 1], interval == null ? 10 : interval);
    return interval ? domain(nice(d, interval)) : scale2;
  };
  scale2.copy = function() {
    return copy$1(scale2, calendar(ticks2, tickInterval, year, month, week, day, hour, minute, second2, format2));
  };
  return scale2;
}
function time() {
  return initRange.apply(calendar(timeTicks, timeTickInterval, timeYear, timeMonth, timeSunday, timeDay, timeHour, timeMinute, second, timeFormat).domain([new Date(2e3, 0, 1), new Date(2e3, 0, 2)]), arguments);
}
function utcTime() {
  return initRange.apply(calendar(utcTicks, utcTickInterval, utcYear, utcMonth, utcSunday, utcDay, utcHour, utcMinute, second, utcFormat).domain([Date.UTC(2e3, 0, 1), Date.UTC(2e3, 0, 2)]), arguments);
}
function transformer$1() {
  var x0 = 0, x1 = 1, t02, t12, k10, transform, interpolator = identity$5, clamp = false, unknown;
  function scale2(x2) {
    return x2 == null || isNaN(x2 = +x2) ? unknown : interpolator(k10 === 0 ? 0.5 : (x2 = (transform(x2) - t02) * k10, clamp ? Math.max(0, Math.min(1, x2)) : x2));
  }
  scale2.domain = function(_) {
    return arguments.length ? ([x0, x1] = _, t02 = transform(x0 = +x0), t12 = transform(x1 = +x1), k10 = t02 === t12 ? 0 : 1 / (t12 - t02), scale2) : [x0, x1];
  };
  scale2.clamp = function(_) {
    return arguments.length ? (clamp = !!_, scale2) : clamp;
  };
  scale2.interpolator = function(_) {
    return arguments.length ? (interpolator = _, scale2) : interpolator;
  };
  function range3(interpolate2) {
    return function(_) {
      var r0, r1;
      return arguments.length ? ([r0, r1] = _, interpolator = interpolate2(r0, r1), scale2) : [interpolator(0), interpolator(1)];
    };
  }
  scale2.range = range3(interpolate);
  scale2.rangeRound = range3(interpolateRound);
  scale2.unknown = function(_) {
    return arguments.length ? (unknown = _, scale2) : unknown;
  };
  return function(t) {
    transform = t, t02 = t(x0), t12 = t(x1), k10 = t02 === t12 ? 0 : 1 / (t12 - t02);
    return scale2;
  };
}
function copy(source, target2) {
  return target2.domain(source.domain()).interpolator(source.interpolator()).clamp(source.clamp()).unknown(source.unknown());
}
function sequential() {
  var scale2 = linearish(transformer$1()(identity$5));
  scale2.copy = function() {
    return copy(scale2, sequential());
  };
  return initInterpolator.apply(scale2, arguments);
}
function sequentialLog() {
  var scale2 = loggish(transformer$1()).domain([1, 10]);
  scale2.copy = function() {
    return copy(scale2, sequentialLog()).base(scale2.base());
  };
  return initInterpolator.apply(scale2, arguments);
}
function sequentialSymlog() {
  var scale2 = symlogish(transformer$1());
  scale2.copy = function() {
    return copy(scale2, sequentialSymlog()).constant(scale2.constant());
  };
  return initInterpolator.apply(scale2, arguments);
}
function sequentialPow() {
  var scale2 = powish(transformer$1());
  scale2.copy = function() {
    return copy(scale2, sequentialPow()).exponent(scale2.exponent());
  };
  return initInterpolator.apply(scale2, arguments);
}
function sequentialSqrt() {
  return sequentialPow.apply(null, arguments).exponent(0.5);
}
function sequentialQuantile() {
  var domain = [], interpolator = identity$5;
  function scale2(x2) {
    if (x2 != null && !isNaN(x2 = +x2)) return interpolator((bisectRight(domain, x2, 1) - 1) / (domain.length - 1));
  }
  scale2.domain = function(_) {
    if (!arguments.length) return domain.slice();
    domain = [];
    for (let d of _) if (d != null && !isNaN(d = +d)) domain.push(d);
    domain.sort(ascending);
    return scale2;
  };
  scale2.interpolator = function(_) {
    return arguments.length ? (interpolator = _, scale2) : interpolator;
  };
  scale2.range = function() {
    return domain.map((d, i) => interpolator(i / (domain.length - 1)));
  };
  scale2.quantiles = function(n) {
    return Array.from({ length: n + 1 }, (_, i) => quantile$1(domain, i / n));
  };
  scale2.copy = function() {
    return sequentialQuantile(interpolator).domain(domain);
  };
  return initInterpolator.apply(scale2, arguments);
}
function transformer() {
  var x0 = 0, x1 = 0.5, x2 = 1, s2 = 1, t02, t12, t2, k10, k21, interpolator = identity$5, transform, clamp = false, unknown;
  function scale2(x3) {
    return isNaN(x3 = +x3) ? unknown : (x3 = 0.5 + ((x3 = +transform(x3)) - t12) * (s2 * x3 < s2 * t12 ? k10 : k21), interpolator(clamp ? Math.max(0, Math.min(1, x3)) : x3));
  }
  scale2.domain = function(_) {
    return arguments.length ? ([x0, x1, x2] = _, t02 = transform(x0 = +x0), t12 = transform(x1 = +x1), t2 = transform(x2 = +x2), k10 = t02 === t12 ? 0 : 0.5 / (t12 - t02), k21 = t12 === t2 ? 0 : 0.5 / (t2 - t12), s2 = t12 < t02 ? -1 : 1, scale2) : [x0, x1, x2];
  };
  scale2.clamp = function(_) {
    return arguments.length ? (clamp = !!_, scale2) : clamp;
  };
  scale2.interpolator = function(_) {
    return arguments.length ? (interpolator = _, scale2) : interpolator;
  };
  function range3(interpolate2) {
    return function(_) {
      var r0, r1, r2;
      return arguments.length ? ([r0, r1, r2] = _, interpolator = piecewise(interpolate2, [r0, r1, r2]), scale2) : [interpolator(0), interpolator(0.5), interpolator(1)];
    };
  }
  scale2.range = range3(interpolate);
  scale2.rangeRound = range3(interpolateRound);
  scale2.unknown = function(_) {
    return arguments.length ? (unknown = _, scale2) : unknown;
  };
  return function(t) {
    transform = t, t02 = t(x0), t12 = t(x1), t2 = t(x2), k10 = t02 === t12 ? 0 : 0.5 / (t12 - t02), k21 = t12 === t2 ? 0 : 0.5 / (t2 - t12), s2 = t12 < t02 ? -1 : 1;
    return scale2;
  };
}
function diverging() {
  var scale2 = linearish(transformer()(identity$5));
  scale2.copy = function() {
    return copy(scale2, diverging());
  };
  return initInterpolator.apply(scale2, arguments);
}
function divergingLog() {
  var scale2 = loggish(transformer()).domain([0.1, 1, 10]);
  scale2.copy = function() {
    return copy(scale2, divergingLog()).base(scale2.base());
  };
  return initInterpolator.apply(scale2, arguments);
}
function divergingSymlog() {
  var scale2 = symlogish(transformer());
  scale2.copy = function() {
    return copy(scale2, divergingSymlog()).constant(scale2.constant());
  };
  return initInterpolator.apply(scale2, arguments);
}
function divergingPow() {
  var scale2 = powish(transformer());
  scale2.copy = function() {
    return copy(scale2, divergingPow()).exponent(scale2.exponent());
  };
  return initInterpolator.apply(scale2, arguments);
}
function divergingSqrt() {
  return divergingPow.apply(null, arguments).exponent(0.5);
}
const d3Scales = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  scaleBand: band,
  scaleDiverging: diverging,
  scaleDivergingLog: divergingLog,
  scaleDivergingPow: divergingPow,
  scaleDivergingSqrt: divergingSqrt,
  scaleDivergingSymlog: divergingSymlog,
  scaleIdentity: identity$3,
  scaleImplicit: implicit,
  scaleLinear: linear,
  scaleLog: log,
  scaleOrdinal: ordinal,
  scalePoint: point,
  scalePow: pow,
  scaleQuantile: quantile,
  scaleQuantize: quantize,
  scaleRadial: radial,
  scaleSequential: sequential,
  scaleSequentialLog: sequentialLog,
  scaleSequentialPow: sequentialPow,
  scaleSequentialQuantile: sequentialQuantile,
  scaleSequentialSqrt: sequentialSqrt,
  scaleSequentialSymlog: sequentialSymlog,
  scaleSqrt: sqrt,
  scaleSymlog: symlog,
  scaleThreshold: threshold,
  scaleTime: time,
  scaleUtc: utcTime,
  tickFormat
}, Symbol.toStringTag, { value: "Module" }));
var isSymbol = isSymbol_1;
function baseExtremum$4(array2, iteratee, comparator) {
  var index = -1, length = array2.length;
  while (++index < length) {
    var value = array2[index], current = iteratee(value);
    if (current != null && (computed === void 0 ? current === current && !isSymbol(current) : comparator(current, computed))) {
      var computed = current, result = value;
    }
  }
  return result;
}
var _baseExtremum = baseExtremum$4;
function baseGt$2(value, other) {
  return value > other;
}
var _baseGt = baseGt$2;
var baseExtremum$3 = _baseExtremum, baseGt$1 = _baseGt, identity$2 = identity_1;
function max(array2) {
  return array2 && array2.length ? baseExtremum$3(array2, identity$2, baseGt$1) : void 0;
}
var max_1 = max;
const max$1 = /* @__PURE__ */ getDefaultExportFromCjs(max_1);
function baseLt$2(value, other) {
  return value < other;
}
var _baseLt = baseLt$2;
var baseExtremum$2 = _baseExtremum, baseLt$1 = _baseLt, identity$1 = identity_1;
function min(array2) {
  return array2 && array2.length ? baseExtremum$2(array2, identity$1, baseLt$1) : void 0;
}
var min_1 = min;
const min$1 = /* @__PURE__ */ getDefaultExportFromCjs(min_1);
var arrayMap = _arrayMap, baseIteratee$7 = _baseIteratee, baseMap = _baseMap, isArray$2 = isArray_1;
function map$2(collection, iteratee) {
  var func = isArray$2(collection) ? arrayMap : baseMap;
  return func(collection, baseIteratee$7(iteratee));
}
var map_1 = map$2;
var baseFlatten = _baseFlatten, map$1 = map_1;
function flatMap(collection, iteratee) {
  return baseFlatten(map$1(collection, iteratee), 1);
}
var flatMap_1 = flatMap;
const flatMap$1 = /* @__PURE__ */ getDefaultExportFromCjs(flatMap_1);
var MAX_DIGITS = 1e9, defaults = {
  // These values must be integers within the stated ranges (inclusive).
  // Most of these values can be changed during run-time using `Decimal.config`.
  // The maximum number of significant digits of the result of a calculation or base conversion.
  // E.g. `Decimal.config({ precision: 20 });`
  precision: 20,
  // 1 to MAX_DIGITS
  // The rounding mode used by default by `toInteger`, `toDecimalPlaces`, `toExponential`,
  // `toFixed`, `toPrecision` and `toSignificantDigits`.
  //
  // ROUND_UP         0 Away from zero.
  // ROUND_DOWN       1 Towards zero.
  // ROUND_CEIL       2 Towards +Infinity.
  // ROUND_FLOOR      3 Towards -Infinity.
  // ROUND_HALF_UP    4 Towards nearest neighbour. If equidistant, up.
  // ROUND_HALF_DOWN  5 Towards nearest neighbour. If equidistant, down.
  // ROUND_HALF_EVEN  6 Towards nearest neighbour. If equidistant, towards even neighbour.
  // ROUND_HALF_CEIL  7 Towards nearest neighbour. If equidistant, towards +Infinity.
  // ROUND_HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.
  //
  // E.g.
  // `Decimal.rounding = 4;`
  // `Decimal.rounding = Decimal.ROUND_HALF_UP;`
  rounding: 4,
  // 0 to 8
  // The exponent value at and beneath which `toString` returns exponential notation.
  // JavaScript numbers: -7
  toExpNeg: -7,
  // 0 to -MAX_E
  // The exponent value at and above which `toString` returns exponential notation.
  // JavaScript numbers: 21
  toExpPos: 21,
  // 0 to MAX_E
  // The natural logarithm of 10.
  // 115 digits
  LN10: "2.302585092994045684017991454684364207601101488628772976033327900967572609677352480235997205089598298341967784042286"
}, Decimal, external = true, decimalError = "[DecimalError] ", invalidArgument = decimalError + "Invalid argument: ", exponentOutOfRange = decimalError + "Exponent out of range: ", mathfloor = Math.floor, mathpow = Math.pow, isDecimal = /^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i, ONE, BASE = 1e7, LOG_BASE = 7, MAX_SAFE_INTEGER = 9007199254740991, MAX_E = mathfloor(MAX_SAFE_INTEGER / LOG_BASE), P = {};
P.absoluteValue = P.abs = function() {
  var x2 = new this.constructor(this);
  if (x2.s) x2.s = 1;
  return x2;
};
P.comparedTo = P.cmp = function(y2) {
  var i, j, xdL, ydL, x2 = this;
  y2 = new x2.constructor(y2);
  if (x2.s !== y2.s) return x2.s || -y2.s;
  if (x2.e !== y2.e) return x2.e > y2.e ^ x2.s < 0 ? 1 : -1;
  xdL = x2.d.length;
  ydL = y2.d.length;
  for (i = 0, j = xdL < ydL ? xdL : ydL; i < j; ++i) {
    if (x2.d[i] !== y2.d[i]) return x2.d[i] > y2.d[i] ^ x2.s < 0 ? 1 : -1;
  }
  return xdL === ydL ? 0 : xdL > ydL ^ x2.s < 0 ? 1 : -1;
};
P.decimalPlaces = P.dp = function() {
  var x2 = this, w = x2.d.length - 1, dp = (w - x2.e) * LOG_BASE;
  w = x2.d[w];
  if (w) for (; w % 10 == 0; w /= 10) dp--;
  return dp < 0 ? 0 : dp;
};
P.dividedBy = P.div = function(y2) {
  return divide(this, new this.constructor(y2));
};
P.dividedToIntegerBy = P.idiv = function(y2) {
  var x2 = this, Ctor = x2.constructor;
  return round(divide(x2, new Ctor(y2), 0, 1), Ctor.precision);
};
P.equals = P.eq = function(y2) {
  return !this.cmp(y2);
};
P.exponent = function() {
  return getBase10Exponent(this);
};
P.greaterThan = P.gt = function(y2) {
  return this.cmp(y2) > 0;
};
P.greaterThanOrEqualTo = P.gte = function(y2) {
  return this.cmp(y2) >= 0;
};
P.isInteger = P.isint = function() {
  return this.e > this.d.length - 2;
};
P.isNegative = P.isneg = function() {
  return this.s < 0;
};
P.isPositive = P.ispos = function() {
  return this.s > 0;
};
P.isZero = function() {
  return this.s === 0;
};
P.lessThan = P.lt = function(y2) {
  return this.cmp(y2) < 0;
};
P.lessThanOrEqualTo = P.lte = function(y2) {
  return this.cmp(y2) < 1;
};
P.logarithm = P.log = function(base) {
  var r2, x2 = this, Ctor = x2.constructor, pr = Ctor.precision, wpr = pr + 5;
  if (base === void 0) {
    base = new Ctor(10);
  } else {
    base = new Ctor(base);
    if (base.s < 1 || base.eq(ONE)) throw Error(decimalError + "NaN");
  }
  if (x2.s < 1) throw Error(decimalError + (x2.s ? "NaN" : "-Infinity"));
  if (x2.eq(ONE)) return new Ctor(0);
  external = false;
  r2 = divide(ln(x2, wpr), ln(base, wpr), wpr);
  external = true;
  return round(r2, pr);
};
P.minus = P.sub = function(y2) {
  var x2 = this;
  y2 = new x2.constructor(y2);
  return x2.s == y2.s ? subtract(x2, y2) : add(x2, (y2.s = -y2.s, y2));
};
P.modulo = P.mod = function(y2) {
  var q, x2 = this, Ctor = x2.constructor, pr = Ctor.precision;
  y2 = new Ctor(y2);
  if (!y2.s) throw Error(decimalError + "NaN");
  if (!x2.s) return round(new Ctor(x2), pr);
  external = false;
  q = divide(x2, y2, 0, 1).times(y2);
  external = true;
  return x2.minus(q);
};
P.naturalExponential = P.exp = function() {
  return exp(this);
};
P.naturalLogarithm = P.ln = function() {
  return ln(this);
};
P.negated = P.neg = function() {
  var x2 = new this.constructor(this);
  x2.s = -x2.s || 0;
  return x2;
};
P.plus = P.add = function(y2) {
  var x2 = this;
  y2 = new x2.constructor(y2);
  return x2.s == y2.s ? add(x2, y2) : subtract(x2, (y2.s = -y2.s, y2));
};
P.precision = P.sd = function(z) {
  var e, sd, w, x2 = this;
  if (z !== void 0 && z !== !!z && z !== 1 && z !== 0) throw Error(invalidArgument + z);
  e = getBase10Exponent(x2) + 1;
  w = x2.d.length - 1;
  sd = w * LOG_BASE + 1;
  w = x2.d[w];
  if (w) {
    for (; w % 10 == 0; w /= 10) sd--;
    for (w = x2.d[0]; w >= 10; w /= 10) sd++;
  }
  return z && e > sd ? e : sd;
};
P.squareRoot = P.sqrt = function() {
  var e, n, pr, r2, s2, t, wpr, x2 = this, Ctor = x2.constructor;
  if (x2.s < 1) {
    if (!x2.s) return new Ctor(0);
    throw Error(decimalError + "NaN");
  }
  e = getBase10Exponent(x2);
  external = false;
  s2 = Math.sqrt(+x2);
  if (s2 == 0 || s2 == 1 / 0) {
    n = digitsToString(x2.d);
    if ((n.length + e) % 2 == 0) n += "0";
    s2 = Math.sqrt(n);
    e = mathfloor((e + 1) / 2) - (e < 0 || e % 2);
    if (s2 == 1 / 0) {
      n = "5e" + e;
    } else {
      n = s2.toExponential();
      n = n.slice(0, n.indexOf("e") + 1) + e;
    }
    r2 = new Ctor(n);
  } else {
    r2 = new Ctor(s2.toString());
  }
  pr = Ctor.precision;
  s2 = wpr = pr + 3;
  for (; ; ) {
    t = r2;
    r2 = t.plus(divide(x2, t, wpr + 2)).times(0.5);
    if (digitsToString(t.d).slice(0, wpr) === (n = digitsToString(r2.d)).slice(0, wpr)) {
      n = n.slice(wpr - 3, wpr + 1);
      if (s2 == wpr && n == "4999") {
        round(t, pr + 1, 0);
        if (t.times(t).eq(x2)) {
          r2 = t;
          break;
        }
      } else if (n != "9999") {
        break;
      }
      wpr += 4;
    }
  }
  external = true;
  return round(r2, pr);
};
P.times = P.mul = function(y2) {
  var carry, e, i, k2, r2, rL, t, xdL, ydL, x2 = this, Ctor = x2.constructor, xd = x2.d, yd = (y2 = new Ctor(y2)).d;
  if (!x2.s || !y2.s) return new Ctor(0);
  y2.s *= x2.s;
  e = x2.e + y2.e;
  xdL = xd.length;
  ydL = yd.length;
  if (xdL < ydL) {
    r2 = xd;
    xd = yd;
    yd = r2;
    rL = xdL;
    xdL = ydL;
    ydL = rL;
  }
  r2 = [];
  rL = xdL + ydL;
  for (i = rL; i--; ) r2.push(0);
  for (i = ydL; --i >= 0; ) {
    carry = 0;
    for (k2 = xdL + i; k2 > i; ) {
      t = r2[k2] + yd[i] * xd[k2 - i - 1] + carry;
      r2[k2--] = t % BASE | 0;
      carry = t / BASE | 0;
    }
    r2[k2] = (r2[k2] + carry) % BASE | 0;
  }
  for (; !r2[--rL]; ) r2.pop();
  if (carry) ++e;
  else r2.shift();
  y2.d = r2;
  y2.e = e;
  return external ? round(y2, Ctor.precision) : y2;
};
P.toDecimalPlaces = P.todp = function(dp, rm) {
  var x2 = this, Ctor = x2.constructor;
  x2 = new Ctor(x2);
  if (dp === void 0) return x2;
  checkInt32(dp, 0, MAX_DIGITS);
  if (rm === void 0) rm = Ctor.rounding;
  else checkInt32(rm, 0, 8);
  return round(x2, dp + getBase10Exponent(x2) + 1, rm);
};
P.toExponential = function(dp, rm) {
  var str, x2 = this, Ctor = x2.constructor;
  if (dp === void 0) {
    str = toString(x2, true);
  } else {
    checkInt32(dp, 0, MAX_DIGITS);
    if (rm === void 0) rm = Ctor.rounding;
    else checkInt32(rm, 0, 8);
    x2 = round(new Ctor(x2), dp + 1, rm);
    str = toString(x2, true, dp + 1);
  }
  return str;
};
P.toFixed = function(dp, rm) {
  var str, y2, x2 = this, Ctor = x2.constructor;
  if (dp === void 0) return toString(x2);
  checkInt32(dp, 0, MAX_DIGITS);
  if (rm === void 0) rm = Ctor.rounding;
  else checkInt32(rm, 0, 8);
  y2 = round(new Ctor(x2), dp + getBase10Exponent(x2) + 1, rm);
  str = toString(y2.abs(), false, dp + getBase10Exponent(y2) + 1);
  return x2.isneg() && !x2.isZero() ? "-" + str : str;
};
P.toInteger = P.toint = function() {
  var x2 = this, Ctor = x2.constructor;
  return round(new Ctor(x2), getBase10Exponent(x2) + 1, Ctor.rounding);
};
P.toNumber = function() {
  return +this;
};
P.toPower = P.pow = function(y2) {
  var e, k2, pr, r2, sign2, yIsInt, x2 = this, Ctor = x2.constructor, guard = 12, yn = +(y2 = new Ctor(y2));
  if (!y2.s) return new Ctor(ONE);
  x2 = new Ctor(x2);
  if (!x2.s) {
    if (y2.s < 1) throw Error(decimalError + "Infinity");
    return x2;
  }
  if (x2.eq(ONE)) return x2;
  pr = Ctor.precision;
  if (y2.eq(ONE)) return round(x2, pr);
  e = y2.e;
  k2 = y2.d.length - 1;
  yIsInt = e >= k2;
  sign2 = x2.s;
  if (!yIsInt) {
    if (sign2 < 0) throw Error(decimalError + "NaN");
  } else if ((k2 = yn < 0 ? -yn : yn) <= MAX_SAFE_INTEGER) {
    r2 = new Ctor(ONE);
    e = Math.ceil(pr / LOG_BASE + 4);
    external = false;
    for (; ; ) {
      if (k2 % 2) {
        r2 = r2.times(x2);
        truncate(r2.d, e);
      }
      k2 = mathfloor(k2 / 2);
      if (k2 === 0) break;
      x2 = x2.times(x2);
      truncate(x2.d, e);
    }
    external = true;
    return y2.s < 0 ? new Ctor(ONE).div(r2) : round(r2, pr);
  }
  sign2 = sign2 < 0 && y2.d[Math.max(e, k2)] & 1 ? -1 : 1;
  x2.s = 1;
  external = false;
  r2 = y2.times(ln(x2, pr + guard));
  external = true;
  r2 = exp(r2);
  r2.s = sign2;
  return r2;
};
P.toPrecision = function(sd, rm) {
  var e, str, x2 = this, Ctor = x2.constructor;
  if (sd === void 0) {
    e = getBase10Exponent(x2);
    str = toString(x2, e <= Ctor.toExpNeg || e >= Ctor.toExpPos);
  } else {
    checkInt32(sd, 1, MAX_DIGITS);
    if (rm === void 0) rm = Ctor.rounding;
    else checkInt32(rm, 0, 8);
    x2 = round(new Ctor(x2), sd, rm);
    e = getBase10Exponent(x2);
    str = toString(x2, sd <= e || e <= Ctor.toExpNeg, sd);
  }
  return str;
};
P.toSignificantDigits = P.tosd = function(sd, rm) {
  var x2 = this, Ctor = x2.constructor;
  if (sd === void 0) {
    sd = Ctor.precision;
    rm = Ctor.rounding;
  } else {
    checkInt32(sd, 1, MAX_DIGITS);
    if (rm === void 0) rm = Ctor.rounding;
    else checkInt32(rm, 0, 8);
  }
  return round(new Ctor(x2), sd, rm);
};
P.toString = P.valueOf = P.val = P.toJSON = P[Symbol.for("nodejs.util.inspect.custom")] = function() {
  var x2 = this, e = getBase10Exponent(x2), Ctor = x2.constructor;
  return toString(x2, e <= Ctor.toExpNeg || e >= Ctor.toExpPos);
};
function add(x2, y2) {
  var carry, d, e, i, k2, len, xd, yd, Ctor = x2.constructor, pr = Ctor.precision;
  if (!x2.s || !y2.s) {
    if (!y2.s) y2 = new Ctor(x2);
    return external ? round(y2, pr) : y2;
  }
  xd = x2.d;
  yd = y2.d;
  k2 = x2.e;
  e = y2.e;
  xd = xd.slice();
  i = k2 - e;
  if (i) {
    if (i < 0) {
      d = xd;
      i = -i;
      len = yd.length;
    } else {
      d = yd;
      e = k2;
      len = xd.length;
    }
    k2 = Math.ceil(pr / LOG_BASE);
    len = k2 > len ? k2 + 1 : len + 1;
    if (i > len) {
      i = len;
      d.length = 1;
    }
    d.reverse();
    for (; i--; ) d.push(0);
    d.reverse();
  }
  len = xd.length;
  i = yd.length;
  if (len - i < 0) {
    i = len;
    d = yd;
    yd = xd;
    xd = d;
  }
  for (carry = 0; i; ) {
    carry = (xd[--i] = xd[i] + yd[i] + carry) / BASE | 0;
    xd[i] %= BASE;
  }
  if (carry) {
    xd.unshift(carry);
    ++e;
  }
  for (len = xd.length; xd[--len] == 0; ) xd.pop();
  y2.d = xd;
  y2.e = e;
  return external ? round(y2, pr) : y2;
}
function checkInt32(i, min2, max2) {
  if (i !== ~~i || i < min2 || i > max2) {
    throw Error(invalidArgument + i);
  }
}
function digitsToString(d) {
  var i, k2, ws, indexOfLastWord = d.length - 1, str = "", w = d[0];
  if (indexOfLastWord > 0) {
    str += w;
    for (i = 1; i < indexOfLastWord; i++) {
      ws = d[i] + "";
      k2 = LOG_BASE - ws.length;
      if (k2) str += getZeroString(k2);
      str += ws;
    }
    w = d[i];
    ws = w + "";
    k2 = LOG_BASE - ws.length;
    if (k2) str += getZeroString(k2);
  } else if (w === 0) {
    return "0";
  }
  for (; w % 10 === 0; ) w /= 10;
  return str + w;
}
var divide = /* @__PURE__ */ function() {
  function multiplyInteger(x2, k2) {
    var temp, carry = 0, i = x2.length;
    for (x2 = x2.slice(); i--; ) {
      temp = x2[i] * k2 + carry;
      x2[i] = temp % BASE | 0;
      carry = temp / BASE | 0;
    }
    if (carry) x2.unshift(carry);
    return x2;
  }
  function compare(a2, b, aL, bL) {
    var i, r2;
    if (aL != bL) {
      r2 = aL > bL ? 1 : -1;
    } else {
      for (i = r2 = 0; i < aL; i++) {
        if (a2[i] != b[i]) {
          r2 = a2[i] > b[i] ? 1 : -1;
          break;
        }
      }
    }
    return r2;
  }
  function subtract2(a2, b, aL) {
    var i = 0;
    for (; aL--; ) {
      a2[aL] -= i;
      i = a2[aL] < b[aL] ? 1 : 0;
      a2[aL] = i * BASE + a2[aL] - b[aL];
    }
    for (; !a2[0] && a2.length > 1; ) a2.shift();
  }
  return function(x2, y2, pr, dp) {
    var cmp, e, i, k2, prod, prodL, q, qd, rem, remL, rem0, sd, t, xi, xL, yd0, yL, yz, Ctor = x2.constructor, sign2 = x2.s == y2.s ? 1 : -1, xd = x2.d, yd = y2.d;
    if (!x2.s) return new Ctor(x2);
    if (!y2.s) throw Error(decimalError + "Division by zero");
    e = x2.e - y2.e;
    yL = yd.length;
    xL = xd.length;
    q = new Ctor(sign2);
    qd = q.d = [];
    for (i = 0; yd[i] == (xd[i] || 0); ) ++i;
    if (yd[i] > (xd[i] || 0)) --e;
    if (pr == null) {
      sd = pr = Ctor.precision;
    } else if (dp) {
      sd = pr + (getBase10Exponent(x2) - getBase10Exponent(y2)) + 1;
    } else {
      sd = pr;
    }
    if (sd < 0) return new Ctor(0);
    sd = sd / LOG_BASE + 2 | 0;
    i = 0;
    if (yL == 1) {
      k2 = 0;
      yd = yd[0];
      sd++;
      for (; (i < xL || k2) && sd--; i++) {
        t = k2 * BASE + (xd[i] || 0);
        qd[i] = t / yd | 0;
        k2 = t % yd | 0;
      }
    } else {
      k2 = BASE / (yd[0] + 1) | 0;
      if (k2 > 1) {
        yd = multiplyInteger(yd, k2);
        xd = multiplyInteger(xd, k2);
        yL = yd.length;
        xL = xd.length;
      }
      xi = yL;
      rem = xd.slice(0, yL);
      remL = rem.length;
      for (; remL < yL; ) rem[remL++] = 0;
      yz = yd.slice();
      yz.unshift(0);
      yd0 = yd[0];
      if (yd[1] >= BASE / 2) ++yd0;
      do {
        k2 = 0;
        cmp = compare(yd, rem, yL, remL);
        if (cmp < 0) {
          rem0 = rem[0];
          if (yL != remL) rem0 = rem0 * BASE + (rem[1] || 0);
          k2 = rem0 / yd0 | 0;
          if (k2 > 1) {
            if (k2 >= BASE) k2 = BASE - 1;
            prod = multiplyInteger(yd, k2);
            prodL = prod.length;
            remL = rem.length;
            cmp = compare(prod, rem, prodL, remL);
            if (cmp == 1) {
              k2--;
              subtract2(prod, yL < prodL ? yz : yd, prodL);
            }
          } else {
            if (k2 == 0) cmp = k2 = 1;
            prod = yd.slice();
          }
          prodL = prod.length;
          if (prodL < remL) prod.unshift(0);
          subtract2(rem, prod, remL);
          if (cmp == -1) {
            remL = rem.length;
            cmp = compare(yd, rem, yL, remL);
            if (cmp < 1) {
              k2++;
              subtract2(rem, yL < remL ? yz : yd, remL);
            }
          }
          remL = rem.length;
        } else if (cmp === 0) {
          k2++;
          rem = [0];
        }
        qd[i++] = k2;
        if (cmp && rem[0]) {
          rem[remL++] = xd[xi] || 0;
        } else {
          rem = [xd[xi]];
          remL = 1;
        }
      } while ((xi++ < xL || rem[0] !== void 0) && sd--);
    }
    if (!qd[0]) qd.shift();
    q.e = e;
    return round(q, dp ? pr + getBase10Exponent(q) + 1 : pr);
  };
}();
function exp(x2, sd) {
  var denominator, guard, pow2, sum, t, wpr, i = 0, k2 = 0, Ctor = x2.constructor, pr = Ctor.precision;
  if (getBase10Exponent(x2) > 16) throw Error(exponentOutOfRange + getBase10Exponent(x2));
  if (!x2.s) return new Ctor(ONE);
  {
    external = false;
    wpr = pr;
  }
  t = new Ctor(0.03125);
  while (x2.abs().gte(0.1)) {
    x2 = x2.times(t);
    k2 += 5;
  }
  guard = Math.log(mathpow(2, k2)) / Math.LN10 * 2 + 5 | 0;
  wpr += guard;
  denominator = pow2 = sum = new Ctor(ONE);
  Ctor.precision = wpr;
  for (; ; ) {
    pow2 = round(pow2.times(x2), wpr);
    denominator = denominator.times(++i);
    t = sum.plus(divide(pow2, denominator, wpr));
    if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) {
      while (k2--) sum = round(sum.times(sum), wpr);
      Ctor.precision = pr;
      return sd == null ? (external = true, round(sum, pr)) : sum;
    }
    sum = t;
  }
}
function getBase10Exponent(x2) {
  var e = x2.e * LOG_BASE, w = x2.d[0];
  for (; w >= 10; w /= 10) e++;
  return e;
}
function getLn10(Ctor, sd, pr) {
  if (sd > Ctor.LN10.sd()) {
    external = true;
    if (pr) Ctor.precision = pr;
    throw Error(decimalError + "LN10 precision limit exceeded");
  }
  return round(new Ctor(Ctor.LN10), sd);
}
function getZeroString(k2) {
  var zs = "";
  for (; k2--; ) zs += "0";
  return zs;
}
function ln(y2, sd) {
  var c2, c0, denominator, e, numerator, sum, t, wpr, x2, n = 1, guard = 10, x3 = y2, xd = x3.d, Ctor = x3.constructor, pr = Ctor.precision;
  if (x3.s < 1) throw Error(decimalError + (x3.s ? "NaN" : "-Infinity"));
  if (x3.eq(ONE)) return new Ctor(0);
  if (sd == null) {
    external = false;
    wpr = pr;
  } else {
    wpr = sd;
  }
  if (x3.eq(10)) {
    if (sd == null) external = true;
    return getLn10(Ctor, wpr);
  }
  wpr += guard;
  Ctor.precision = wpr;
  c2 = digitsToString(xd);
  c0 = c2.charAt(0);
  e = getBase10Exponent(x3);
  if (Math.abs(e) < 15e14) {
    while (c0 < 7 && c0 != 1 || c0 == 1 && c2.charAt(1) > 3) {
      x3 = x3.times(y2);
      c2 = digitsToString(x3.d);
      c0 = c2.charAt(0);
      n++;
    }
    e = getBase10Exponent(x3);
    if (c0 > 1) {
      x3 = new Ctor("0." + c2);
      e++;
    } else {
      x3 = new Ctor(c0 + "." + c2.slice(1));
    }
  } else {
    t = getLn10(Ctor, wpr + 2, pr).times(e + "");
    x3 = ln(new Ctor(c0 + "." + c2.slice(1)), wpr - guard).plus(t);
    Ctor.precision = pr;
    return sd == null ? (external = true, round(x3, pr)) : x3;
  }
  sum = numerator = x3 = divide(x3.minus(ONE), x3.plus(ONE), wpr);
  x2 = round(x3.times(x3), wpr);
  denominator = 3;
  for (; ; ) {
    numerator = round(numerator.times(x2), wpr);
    t = sum.plus(divide(numerator, new Ctor(denominator), wpr));
    if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) {
      sum = sum.times(2);
      if (e !== 0) sum = sum.plus(getLn10(Ctor, wpr + 2, pr).times(e + ""));
      sum = divide(sum, new Ctor(n), wpr);
      Ctor.precision = pr;
      return sd == null ? (external = true, round(sum, pr)) : sum;
    }
    sum = t;
    denominator += 2;
  }
}
function parseDecimal(x2, str) {
  var e, i, len;
  if ((e = str.indexOf(".")) > -1) str = str.replace(".", "");
  if ((i = str.search(/e/i)) > 0) {
    if (e < 0) e = i;
    e += +str.slice(i + 1);
    str = str.substring(0, i);
  } else if (e < 0) {
    e = str.length;
  }
  for (i = 0; str.charCodeAt(i) === 48; ) ++i;
  for (len = str.length; str.charCodeAt(len - 1) === 48; ) --len;
  str = str.slice(i, len);
  if (str) {
    len -= i;
    e = e - i - 1;
    x2.e = mathfloor(e / LOG_BASE);
    x2.d = [];
    i = (e + 1) % LOG_BASE;
    if (e < 0) i += LOG_BASE;
    if (i < len) {
      if (i) x2.d.push(+str.slice(0, i));
      for (len -= LOG_BASE; i < len; ) x2.d.push(+str.slice(i, i += LOG_BASE));
      str = str.slice(i);
      i = LOG_BASE - str.length;
    } else {
      i -= len;
    }
    for (; i--; ) str += "0";
    x2.d.push(+str);
    if (external && (x2.e > MAX_E || x2.e < -MAX_E)) throw Error(exponentOutOfRange + e);
  } else {
    x2.s = 0;
    x2.e = 0;
    x2.d = [0];
  }
  return x2;
}
function round(x2, sd, rm) {
  var i, j, k2, n, rd, doRound, w, xdi, xd = x2.d;
  for (n = 1, k2 = xd[0]; k2 >= 10; k2 /= 10) n++;
  i = sd - n;
  if (i < 0) {
    i += LOG_BASE;
    j = sd;
    w = xd[xdi = 0];
  } else {
    xdi = Math.ceil((i + 1) / LOG_BASE);
    k2 = xd.length;
    if (xdi >= k2) return x2;
    w = k2 = xd[xdi];
    for (n = 1; k2 >= 10; k2 /= 10) n++;
    i %= LOG_BASE;
    j = i - LOG_BASE + n;
  }
  if (rm !== void 0) {
    k2 = mathpow(10, n - j - 1);
    rd = w / k2 % 10 | 0;
    doRound = sd < 0 || xd[xdi + 1] !== void 0 || w % k2;
    doRound = rm < 4 ? (rd || doRound) && (rm == 0 || rm == (x2.s < 0 ? 3 : 2)) : rd > 5 || rd == 5 && (rm == 4 || doRound || rm == 6 && // Check whether the digit to the left of the rounding digit is odd.
    (i > 0 ? j > 0 ? w / mathpow(10, n - j) : 0 : xd[xdi - 1]) % 10 & 1 || rm == (x2.s < 0 ? 8 : 7));
  }
  if (sd < 1 || !xd[0]) {
    if (doRound) {
      k2 = getBase10Exponent(x2);
      xd.length = 1;
      sd = sd - k2 - 1;
      xd[0] = mathpow(10, (LOG_BASE - sd % LOG_BASE) % LOG_BASE);
      x2.e = mathfloor(-sd / LOG_BASE) || 0;
    } else {
      xd.length = 1;
      xd[0] = x2.e = x2.s = 0;
    }
    return x2;
  }
  if (i == 0) {
    xd.length = xdi;
    k2 = 1;
    xdi--;
  } else {
    xd.length = xdi + 1;
    k2 = mathpow(10, LOG_BASE - i);
    xd[xdi] = j > 0 ? (w / mathpow(10, n - j) % mathpow(10, j) | 0) * k2 : 0;
  }
  if (doRound) {
    for (; ; ) {
      if (xdi == 0) {
        if ((xd[0] += k2) == BASE) {
          xd[0] = 1;
          ++x2.e;
        }
        break;
      } else {
        xd[xdi] += k2;
        if (xd[xdi] != BASE) break;
        xd[xdi--] = 0;
        k2 = 1;
      }
    }
  }
  for (i = xd.length; xd[--i] === 0; ) xd.pop();
  if (external && (x2.e > MAX_E || x2.e < -MAX_E)) {
    throw Error(exponentOutOfRange + getBase10Exponent(x2));
  }
  return x2;
}
function subtract(x2, y2) {
  var d, e, i, j, k2, len, xd, xe, xLTy, yd, Ctor = x2.constructor, pr = Ctor.precision;
  if (!x2.s || !y2.s) {
    if (y2.s) y2.s = -y2.s;
    else y2 = new Ctor(x2);
    return external ? round(y2, pr) : y2;
  }
  xd = x2.d;
  yd = y2.d;
  e = y2.e;
  xe = x2.e;
  xd = xd.slice();
  k2 = xe - e;
  if (k2) {
    xLTy = k2 < 0;
    if (xLTy) {
      d = xd;
      k2 = -k2;
      len = yd.length;
    } else {
      d = yd;
      e = xe;
      len = xd.length;
    }
    i = Math.max(Math.ceil(pr / LOG_BASE), len) + 2;
    if (k2 > i) {
      k2 = i;
      d.length = 1;
    }
    d.reverse();
    for (i = k2; i--; ) d.push(0);
    d.reverse();
  } else {
    i = xd.length;
    len = yd.length;
    xLTy = i < len;
    if (xLTy) len = i;
    for (i = 0; i < len; i++) {
      if (xd[i] != yd[i]) {
        xLTy = xd[i] < yd[i];
        break;
      }
    }
    k2 = 0;
  }
  if (xLTy) {
    d = xd;
    xd = yd;
    yd = d;
    y2.s = -y2.s;
  }
  len = xd.length;
  for (i = yd.length - len; i > 0; --i) xd[len++] = 0;
  for (i = yd.length; i > k2; ) {
    if (xd[--i] < yd[i]) {
      for (j = i; j && xd[--j] === 0; ) xd[j] = BASE - 1;
      --xd[j];
      xd[i] += BASE;
    }
    xd[i] -= yd[i];
  }
  for (; xd[--len] === 0; ) xd.pop();
  for (; xd[0] === 0; xd.shift()) --e;
  if (!xd[0]) return new Ctor(0);
  y2.d = xd;
  y2.e = e;
  return external ? round(y2, pr) : y2;
}
function toString(x2, isExp, sd) {
  var k2, e = getBase10Exponent(x2), str = digitsToString(x2.d), len = str.length;
  if (isExp) {
    if (sd && (k2 = sd - len) > 0) {
      str = str.charAt(0) + "." + str.slice(1) + getZeroString(k2);
    } else if (len > 1) {
      str = str.charAt(0) + "." + str.slice(1);
    }
    str = str + (e < 0 ? "e" : "e+") + e;
  } else if (e < 0) {
    str = "0." + getZeroString(-e - 1) + str;
    if (sd && (k2 = sd - len) > 0) str += getZeroString(k2);
  } else if (e >= len) {
    str += getZeroString(e + 1 - len);
    if (sd && (k2 = sd - e - 1) > 0) str = str + "." + getZeroString(k2);
  } else {
    if ((k2 = e + 1) < len) str = str.slice(0, k2) + "." + str.slice(k2);
    if (sd && (k2 = sd - len) > 0) {
      if (e + 1 === len) str += ".";
      str += getZeroString(k2);
    }
  }
  return x2.s < 0 ? "-" + str : str;
}
function truncate(arr, len) {
  if (arr.length > len) {
    arr.length = len;
    return true;
  }
}
function clone(obj) {
  var i, p, ps;
  function Decimal2(value) {
    var x2 = this;
    if (!(x2 instanceof Decimal2)) return new Decimal2(value);
    x2.constructor = Decimal2;
    if (value instanceof Decimal2) {
      x2.s = value.s;
      x2.e = value.e;
      x2.d = (value = value.d) ? value.slice() : value;
      return;
    }
    if (typeof value === "number") {
      if (value * 0 !== 0) {
        throw Error(invalidArgument + value);
      }
      if (value > 0) {
        x2.s = 1;
      } else if (value < 0) {
        value = -value;
        x2.s = -1;
      } else {
        x2.s = 0;
        x2.e = 0;
        x2.d = [0];
        return;
      }
      if (value === ~~value && value < 1e7) {
        x2.e = 0;
        x2.d = [value];
        return;
      }
      return parseDecimal(x2, value.toString());
    } else if (typeof value !== "string") {
      throw Error(invalidArgument + value);
    }
    if (value.charCodeAt(0) === 45) {
      value = value.slice(1);
      x2.s = -1;
    } else {
      x2.s = 1;
    }
    if (isDecimal.test(value)) parseDecimal(x2, value);
    else throw Error(invalidArgument + value);
  }
  Decimal2.prototype = P;
  Decimal2.ROUND_UP = 0;
  Decimal2.ROUND_DOWN = 1;
  Decimal2.ROUND_CEIL = 2;
  Decimal2.ROUND_FLOOR = 3;
  Decimal2.ROUND_HALF_UP = 4;
  Decimal2.ROUND_HALF_DOWN = 5;
  Decimal2.ROUND_HALF_EVEN = 6;
  Decimal2.ROUND_HALF_CEIL = 7;
  Decimal2.ROUND_HALF_FLOOR = 8;
  Decimal2.clone = clone;
  Decimal2.config = Decimal2.set = config;
  if (obj === void 0) obj = {};
  if (obj) {
    ps = ["precision", "rounding", "toExpNeg", "toExpPos", "LN10"];
    for (i = 0; i < ps.length; ) if (!obj.hasOwnProperty(p = ps[i++])) obj[p] = this[p];
  }
  Decimal2.config(obj);
  return Decimal2;
}
function config(obj) {
  if (!obj || typeof obj !== "object") {
    throw Error(decimalError + "Object expected");
  }
  var i, p, v, ps = [
    "precision",
    1,
    MAX_DIGITS,
    "rounding",
    0,
    8,
    "toExpNeg",
    -1 / 0,
    0,
    "toExpPos",
    0,
    1 / 0
  ];
  for (i = 0; i < ps.length; i += 3) {
    if ((v = obj[p = ps[i]]) !== void 0) {
      if (mathfloor(v) === v && v >= ps[i + 1] && v <= ps[i + 2]) this[p] = v;
      else throw Error(invalidArgument + p + ": " + v);
    }
  }
  if ((v = obj[p = "LN10"]) !== void 0) {
    if (v == Math.LN10) this[p] = new this(v);
    else throw Error(invalidArgument + p + ": " + v);
  }
  return this;
}
var Decimal = clone(defaults);
ONE = new Decimal(1);
const Decimal$1 = Decimal;
function _toConsumableArray$7(arr) {
  return _arrayWithoutHoles$7(arr) || _iterableToArray$7(arr) || _unsupportedIterableToArray$c(arr) || _nonIterableSpread$7();
}
function _nonIterableSpread$7() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray$c(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return _arrayLikeToArray$c(o, minLen);
  var n = Object.prototype.toString.call(o).slice(8, -1);
  if (n === "Object" && o.constructor) n = o.constructor.name;
  if (n === "Map" || n === "Set") return Array.from(o);
  if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$c(o, minLen);
}
function _iterableToArray$7(iter) {
  if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
}
function _arrayWithoutHoles$7(arr) {
  if (Array.isArray(arr)) return _arrayLikeToArray$c(arr);
}
function _arrayLikeToArray$c(arr, len) {
  if (len == null || len > arr.length) len = arr.length;
  for (var i = 0, arr2 = new Array(len); i < len; i++) {
    arr2[i] = arr[i];
  }
  return arr2;
}
var identity = function identity2(i) {
  return i;
};
var PLACE_HOLDER = {};
var isPlaceHolder = function isPlaceHolder2(val) {
  return val === PLACE_HOLDER;
};
var curry0 = function curry02(fn) {
  return function _curried() {
    if (arguments.length === 0 || arguments.length === 1 && isPlaceHolder(arguments.length <= 0 ? void 0 : arguments[0])) {
      return _curried;
    }
    return fn.apply(void 0, arguments);
  };
};
var curryN = function curryN2(n, fn) {
  if (n === 1) {
    return fn;
  }
  return curry0(function() {
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    var argsLength = args.filter(function(arg) {
      return arg !== PLACE_HOLDER;
    }).length;
    if (argsLength >= n) {
      return fn.apply(void 0, args);
    }
    return curryN2(n - argsLength, curry0(function() {
      for (var _len2 = arguments.length, restArgs = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
        restArgs[_key2] = arguments[_key2];
      }
      var newArgs = args.map(function(arg) {
        return isPlaceHolder(arg) ? restArgs.shift() : arg;
      });
      return fn.apply(void 0, _toConsumableArray$7(newArgs).concat(restArgs));
    }));
  });
};
var curry = function curry2(fn) {
  return curryN(fn.length, fn);
};
var range$2 = function range2(begin, end) {
  var arr = [];
  for (var i = begin; i < end; ++i) {
    arr[i - begin] = i;
  }
  return arr;
};
var map = curry(function(fn, arr) {
  if (Array.isArray(arr)) {
    return arr.map(fn);
  }
  return Object.keys(arr).map(function(key2) {
    return arr[key2];
  }).map(fn);
});
var compose = function compose2() {
  for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
    args[_key3] = arguments[_key3];
  }
  if (!args.length) {
    return identity;
  }
  var fns = args.reverse();
  var firstFn = fns[0];
  var tailsFn = fns.slice(1);
  return function() {
    return tailsFn.reduce(function(res, fn) {
      return fn(res);
    }, firstFn.apply(void 0, arguments));
  };
};
var reverse = function reverse2(arr) {
  if (Array.isArray(arr)) {
    return arr.reverse();
  }
  return arr.split("").reverse.join("");
};
var memoize = function memoize2(fn) {
  var lastArgs = null;
  var lastResult2 = null;
  return function() {
    for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
      args[_key4] = arguments[_key4];
    }
    if (lastArgs && args.every(function(val, i) {
      return val === lastArgs[i];
    })) {
      return lastResult2;
    }
    lastArgs = args;
    lastResult2 = fn.apply(void 0, args);
    return lastResult2;
  };
};
function getDigitCount(value) {
  var result;
  if (value === 0) {
    result = 1;
  } else {
    result = Math.floor(new Decimal$1(value).abs().log(10).toNumber()) + 1;
  }
  return result;
}
function rangeStep(start, end, step) {
  var num = new Decimal$1(start);
  var i = 0;
  var result = [];
  while (num.lt(end) && i < 1e5) {
    result.push(num.toNumber());
    num = num.add(step);
    i++;
  }
  return result;
}
var interpolateNumber = curry(function(a2, b, t) {
  var newA = +a2;
  var newB = +b;
  return newA + t * (newB - newA);
});
var uninterpolateNumber = curry(function(a2, b, x2) {
  var diff = b - +a2;
  diff = diff || Infinity;
  return (x2 - a2) / diff;
});
var uninterpolateTruncation = curry(function(a2, b, x2) {
  var diff = b - +a2;
  diff = diff || Infinity;
  return Math.max(0, Math.min(1, (x2 - a2) / diff));
});
const Arithmetic = {
  rangeStep,
  getDigitCount,
  interpolateNumber,
  uninterpolateNumber,
  uninterpolateTruncation
};
function _toConsumableArray$6(arr) {
  return _arrayWithoutHoles$6(arr) || _iterableToArray$6(arr) || _unsupportedIterableToArray$b(arr) || _nonIterableSpread$6();
}
function _nonIterableSpread$6() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _iterableToArray$6(iter) {
  if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
}
function _arrayWithoutHoles$6(arr) {
  if (Array.isArray(arr)) return _arrayLikeToArray$b(arr);
}
function _slicedToArray$6(arr, i) {
  return _arrayWithHoles$6(arr) || _iterableToArrayLimit$6(arr, i) || _unsupportedIterableToArray$b(arr, i) || _nonIterableRest$6();
}
function _nonIterableRest$6() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray$b(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return _arrayLikeToArray$b(o, minLen);
  var n = Object.prototype.toString.call(o).slice(8, -1);
  if (n === "Object" && o.constructor) n = o.constructor.name;
  if (n === "Map" || n === "Set") return Array.from(o);
  if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$b(o, minLen);
}
function _arrayLikeToArray$b(arr, len) {
  if (len == null || len > arr.length) len = arr.length;
  for (var i = 0, arr2 = new Array(len); i < len; i++) {
    arr2[i] = arr[i];
  }
  return arr2;
}
function _iterableToArrayLimit$6(arr, i) {
  if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return;
  var _arr = [];
  var _n = true;
  var _d = false;
  var _e = void 0;
  try {
    for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
      _arr.push(_s.value);
      if (i && _arr.length === i) break;
    }
  } catch (err) {
    _d = true;
    _e = err;
  } finally {
    try {
      if (!_n && _i["return"] != null) _i["return"]();
    } finally {
      if (_d) throw _e;
    }
  }
  return _arr;
}
function _arrayWithHoles$6(arr) {
  if (Array.isArray(arr)) return arr;
}
function getValidInterval(_ref) {
  var _ref2 = _slicedToArray$6(_ref, 2), min2 = _ref2[0], max2 = _ref2[1];
  var validMin = min2, validMax = max2;
  if (min2 > max2) {
    validMin = max2;
    validMax = min2;
  }
  return [validMin, validMax];
}
function getFormatStep(roughStep, allowDecimals, correctionFactor) {
  if (roughStep.lte(0)) {
    return new Decimal$1(0);
  }
  var digitCount = Arithmetic.getDigitCount(roughStep.toNumber());
  var digitCountValue = new Decimal$1(10).pow(digitCount);
  var stepRatio = roughStep.div(digitCountValue);
  var stepRatioScale = digitCount !== 1 ? 0.05 : 0.1;
  var amendStepRatio = new Decimal$1(Math.ceil(stepRatio.div(stepRatioScale).toNumber())).add(correctionFactor).mul(stepRatioScale);
  var formatStep = amendStepRatio.mul(digitCountValue);
  return allowDecimals ? formatStep : new Decimal$1(Math.ceil(formatStep));
}
function getTickOfSingleValue(value, tickCount, allowDecimals) {
  var step = 1;
  var middle = new Decimal$1(value);
  if (!middle.isint() && allowDecimals) {
    var absVal = Math.abs(value);
    if (absVal < 1) {
      step = new Decimal$1(10).pow(Arithmetic.getDigitCount(value) - 1);
      middle = new Decimal$1(Math.floor(middle.div(step).toNumber())).mul(step);
    } else if (absVal > 1) {
      middle = new Decimal$1(Math.floor(value));
    }
  } else if (value === 0) {
    middle = new Decimal$1(Math.floor((tickCount - 1) / 2));
  } else if (!allowDecimals) {
    middle = new Decimal$1(Math.floor(value));
  }
  var middleIndex = Math.floor((tickCount - 1) / 2);
  var fn = compose(map(function(n) {
    return middle.add(new Decimal$1(n - middleIndex).mul(step)).toNumber();
  }), range$2);
  return fn(0, tickCount);
}
function calculateStep(min2, max2, tickCount, allowDecimals) {
  var correctionFactor = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : 0;
  if (!Number.isFinite((max2 - min2) / (tickCount - 1))) {
    return {
      step: new Decimal$1(0),
      tickMin: new Decimal$1(0),
      tickMax: new Decimal$1(0)
    };
  }
  var step = getFormatStep(new Decimal$1(max2).sub(min2).div(tickCount - 1), allowDecimals, correctionFactor);
  var middle;
  if (min2 <= 0 && max2 >= 0) {
    middle = new Decimal$1(0);
  } else {
    middle = new Decimal$1(min2).add(max2).div(2);
    middle = middle.sub(new Decimal$1(middle).mod(step));
  }
  var belowCount = Math.ceil(middle.sub(min2).div(step).toNumber());
  var upCount = Math.ceil(new Decimal$1(max2).sub(middle).div(step).toNumber());
  var scaleCount = belowCount + upCount + 1;
  if (scaleCount > tickCount) {
    return calculateStep(min2, max2, tickCount, allowDecimals, correctionFactor + 1);
  }
  if (scaleCount < tickCount) {
    upCount = max2 > 0 ? upCount + (tickCount - scaleCount) : upCount;
    belowCount = max2 > 0 ? belowCount : belowCount + (tickCount - scaleCount);
  }
  return {
    step,
    tickMin: middle.sub(new Decimal$1(belowCount).mul(step)),
    tickMax: middle.add(new Decimal$1(upCount).mul(step))
  };
}
function getNiceTickValuesFn(_ref3) {
  var _ref4 = _slicedToArray$6(_ref3, 2), min2 = _ref4[0], max2 = _ref4[1];
  var tickCount = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 6;
  var allowDecimals = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : true;
  var count = Math.max(tickCount, 2);
  var _getValidInterval = getValidInterval([min2, max2]), _getValidInterval2 = _slicedToArray$6(_getValidInterval, 2), cormin = _getValidInterval2[0], cormax = _getValidInterval2[1];
  if (cormin === -Infinity || cormax === Infinity) {
    var _values = cormax === Infinity ? [cormin].concat(_toConsumableArray$6(range$2(0, tickCount - 1).map(function() {
      return Infinity;
    }))) : [].concat(_toConsumableArray$6(range$2(0, tickCount - 1).map(function() {
      return -Infinity;
    })), [cormax]);
    return min2 > max2 ? reverse(_values) : _values;
  }
  if (cormin === cormax) {
    return getTickOfSingleValue(cormin, tickCount, allowDecimals);
  }
  var _calculateStep = calculateStep(cormin, cormax, count, allowDecimals), step = _calculateStep.step, tickMin = _calculateStep.tickMin, tickMax = _calculateStep.tickMax;
  var values = Arithmetic.rangeStep(tickMin, tickMax.add(new Decimal$1(0.1).mul(step)), step);
  return min2 > max2 ? reverse(values) : values;
}
function getTickValuesFixedDomainFn(_ref7, tickCount) {
  var _ref8 = _slicedToArray$6(_ref7, 2), min2 = _ref8[0], max2 = _ref8[1];
  var allowDecimals = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : true;
  var _getValidInterval5 = getValidInterval([min2, max2]), _getValidInterval6 = _slicedToArray$6(_getValidInterval5, 2), cormin = _getValidInterval6[0], cormax = _getValidInterval6[1];
  if (cormin === -Infinity || cormax === Infinity) {
    return [min2, max2];
  }
  if (cormin === cormax) {
    return [cormin];
  }
  var count = Math.max(tickCount, 2);
  var step = getFormatStep(new Decimal$1(cormax).sub(cormin).div(count - 1), allowDecimals, 0);
  var values = [].concat(_toConsumableArray$6(Arithmetic.rangeStep(new Decimal$1(cormin), new Decimal$1(cormax).sub(new Decimal$1(0.99).mul(step)), step)), [cormax]);
  return min2 > max2 ? reverse(values) : values;
}
var getNiceTickValues = memoize(getNiceTickValuesFn);
var getTickValuesFixedDomain = memoize(getTickValuesFixedDomainFn);
var prefix = "Invariant failed";
function invariant(condition, message2) {
  {
    throw new Error(prefix);
  }
}
var _excluded$b = ["offset", "layout", "width", "dataKey", "data", "dataPointFormatter", "xAxis", "yAxis"];
function _typeof$u(o) {
  "@babel/helpers - typeof";
  return _typeof$u = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
    return typeof o2;
  } : function(o2) {
    return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
  }, _typeof$u(o);
}
function _extends$n() {
  _extends$n = Object.assign ? Object.assign.bind() : function(target2) {
    for (var i = 1; i < arguments.length; i++) {
      var source = arguments[i];
      for (var key2 in source) {
        if (Object.prototype.hasOwnProperty.call(source, key2)) {
          target2[key2] = source[key2];
        }
      }
    }
    return target2;
  };
  return _extends$n.apply(this, arguments);
}
function _slicedToArray$5(arr, i) {
  return _arrayWithHoles$5(arr) || _iterableToArrayLimit$5(arr, i) || _unsupportedIterableToArray$a(arr, i) || _nonIterableRest$5();
}
function _nonIterableRest$5() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray$a(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return _arrayLikeToArray$a(o, minLen);
  var n = Object.prototype.toString.call(o).slice(8, -1);
  if (n === "Object" && o.constructor) n = o.constructor.name;
  if (n === "Map" || n === "Set") return Array.from(o);
  if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$a(o, minLen);
}
function _arrayLikeToArray$a(arr, len) {
  if (len == null || len > arr.length) len = arr.length;
  for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  return arr2;
}
function _iterableToArrayLimit$5(r2, l) {
  var t = null == r2 ? null : "undefined" != typeof Symbol && r2[Symbol.iterator] || r2["@@iterator"];
  if (null != t) {
    var e, n, i, u, a2 = [], f = true, o = false;
    try {
      if (i = (t = t.call(r2)).next, 0 === l) ;
      else for (; !(f = (e = i.call(t)).done) && (a2.push(e.value), a2.length !== l); f = true) ;
    } catch (r22) {
      o = true, n = r22;
    } finally {
      try {
        if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return;
      } finally {
        if (o) throw n;
      }
    }
    return a2;
  }
}
function _arrayWithHoles$5(arr) {
  if (Array.isArray(arr)) return arr;
}
function _objectWithoutProperties$b(source, excluded) {
  if (source == null) return {};
  var target2 = _objectWithoutPropertiesLoose$b(source, excluded);
  var key2, i;
  if (Object.getOwnPropertySymbols) {
    var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
    for (i = 0; i < sourceSymbolKeys.length; i++) {
      key2 = sourceSymbolKeys[i];
      if (excluded.indexOf(key2) >= 0) continue;
      if (!Object.prototype.propertyIsEnumerable.call(source, key2)) continue;
      target2[key2] = source[key2];
    }
  }
  return target2;
}
function _objectWithoutPropertiesLoose$b(source, excluded) {
  if (source == null) return {};
  var target2 = {};
  for (var key2 in source) {
    if (Object.prototype.hasOwnProperty.call(source, key2)) {
      if (excluded.indexOf(key2) >= 0) continue;
      target2[key2] = source[key2];
    }
  }
  return target2;
}
function _classCallCheck$e(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function _defineProperties$e(target2, props) {
  for (var i = 0; i < props.length; i++) {
    var descriptor = props[i];
    descriptor.enumerable = descriptor.enumerable || false;
    descriptor.configurable = true;
    if ("value" in descriptor) descriptor.writable = true;
    Object.defineProperty(target2, _toPropertyKey$u(descriptor.key), descriptor);
  }
}
function _createClass$e(Constructor, protoProps, staticProps) {
  if (protoProps) _defineProperties$e(Constructor.prototype, protoProps);
  Object.defineProperty(Constructor, "prototype", { writable: false });
  return Constructor;
}
function _callSuper$c(t, o, e) {
  return o = _getPrototypeOf$c(o), _possibleConstructorReturn$c(t, _isNativeReflectConstruct$c() ? Reflect.construct(o, e || [], _getPrototypeOf$c(t).constructor) : o.apply(t, e));
}
function _possibleConstructorReturn$c(self, call) {
  if (call && (_typeof$u(call) === "object" || typeof call === "function")) {
    return call;
  } else if (call !== void 0) {
    throw new TypeError("Derived constructors may only return object or undefined");
  }
  return _assertThisInitialized$c(self);
}
function _assertThisInitialized$c(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function _isNativeReflectConstruct$c() {
  try {
    var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {
    }));
  } catch (t2) {
  }
  return (_isNativeReflectConstruct$c = function _isNativeReflectConstruct2() {
    return !!t;
  })();
}
function _getPrototypeOf$c(o) {
  _getPrototypeOf$c = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf2(o2) {
    return o2.__proto__ || Object.getPrototypeOf(o2);
  };
  return _getPrototypeOf$c(o);
}
function _inherits$c(subClass, superClass) {
  if (typeof superClass !== "function" && superClass !== null) {
    throw new TypeError("Super expression must either be null or a function");
  }
  subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } });
  Object.defineProperty(subClass, "prototype", { writable: false });
  if (superClass) _setPrototypeOf$c(subClass, superClass);
}
function _setPrototypeOf$c(o, p) {
  _setPrototypeOf$c = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf2(o2, p2) {
    o2.__proto__ = p2;
    return o2;
  };
  return _setPrototypeOf$c(o, p);
}
function _defineProperty$u(obj, key2, value) {
  key2 = _toPropertyKey$u(key2);
  if (key2 in obj) {
    Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key2] = value;
  }
  return obj;
}
function _toPropertyKey$u(t) {
  var i = _toPrimitive$u(t, "string");
  return "symbol" == _typeof$u(i) ? i : i + "";
}
function _toPrimitive$u(t, r2) {
  if ("object" != _typeof$u(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r2);
    if ("object" != _typeof$u(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return String(t);
}
var ErrorBar = /* @__PURE__ */ function(_React$Component) {
  function ErrorBar2() {
    _classCallCheck$e(this, ErrorBar2);
    return _callSuper$c(this, ErrorBar2, arguments);
  }
  _inherits$c(ErrorBar2, _React$Component);
  return _createClass$e(ErrorBar2, [{
    key: "render",
    value: function render() {
      var _this$props = this.props, offset = _this$props.offset, layout = _this$props.layout, width = _this$props.width, dataKey = _this$props.dataKey, data = _this$props.data, dataPointFormatter = _this$props.dataPointFormatter, xAxis = _this$props.xAxis, yAxis = _this$props.yAxis, others = _objectWithoutProperties$b(_this$props, _excluded$b);
      var svgProps = filterProps(others, false);
      !!(this.props.direction === "x" && xAxis.type !== "number") ? invariant() : void 0;
      var errorBars = data.map(function(entry) {
        var _dataPointFormatter = dataPointFormatter(entry, dataKey), x2 = _dataPointFormatter.x, y2 = _dataPointFormatter.y, value = _dataPointFormatter.value, errorVal = _dataPointFormatter.errorVal;
        if (!errorVal) {
          return null;
        }
        var lineCoordinates = [];
        var lowBound, highBound;
        if (Array.isArray(errorVal)) {
          var _errorVal = _slicedToArray$5(errorVal, 2);
          lowBound = _errorVal[0];
          highBound = _errorVal[1];
        } else {
          lowBound = highBound = errorVal;
        }
        if (layout === "vertical") {
          var scale2 = xAxis.scale;
          var yMid = y2 + offset;
          var yMin = yMid + width;
          var yMax = yMid - width;
          var xMin = scale2(value - lowBound);
          var xMax = scale2(value + highBound);
          lineCoordinates.push({
            x1: xMax,
            y1: yMin,
            x2: xMax,
            y2: yMax
          });
          lineCoordinates.push({
            x1: xMin,
            y1: yMid,
            x2: xMax,
            y2: yMid
          });
          lineCoordinates.push({
            x1: xMin,
            y1: yMin,
            x2: xMin,
            y2: yMax
          });
        } else if (layout === "horizontal") {
          var _scale = yAxis.scale;
          var xMid = x2 + offset;
          var _xMin = xMid - width;
          var _xMax = xMid + width;
          var _yMin = _scale(value - lowBound);
          var _yMax = _scale(value + highBound);
          lineCoordinates.push({
            x1: _xMin,
            y1: _yMax,
            x2: _xMax,
            y2: _yMax
          });
          lineCoordinates.push({
            x1: xMid,
            y1: _yMin,
            x2: xMid,
            y2: _yMax
          });
          lineCoordinates.push({
            x1: _xMin,
            y1: _yMin,
            x2: _xMax,
            y2: _yMin
          });
        }
        return /* @__PURE__ */ React.createElement(Layer, _extends$n({
          className: "recharts-errorBar",
          key: "bar-".concat(lineCoordinates.map(function(c2) {
            return "".concat(c2.x1, "-").concat(c2.x2, "-").concat(c2.y1, "-").concat(c2.y2);
          }))
        }, svgProps), lineCoordinates.map(function(coordinates) {
          return /* @__PURE__ */ React.createElement("line", _extends$n({}, coordinates, {
            key: "line-".concat(coordinates.x1, "-").concat(coordinates.x2, "-").concat(coordinates.y1, "-").concat(coordinates.y2)
          }));
        }));
      });
      return /* @__PURE__ */ React.createElement(Layer, {
        className: "recharts-errorBars"
      }, errorBars);
    }
  }]);
}(React.Component);
_defineProperty$u(ErrorBar, "defaultProps", {
  stroke: "black",
  strokeWidth: 1.5,
  width: 5,
  offset: 0,
  layout: "horizontal"
});
_defineProperty$u(ErrorBar, "displayName", "ErrorBar");
function _typeof$t(o) {
  "@babel/helpers - typeof";
  return _typeof$t = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
    return typeof o2;
  } : function(o2) {
    return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
  }, _typeof$t(o);
}
function ownKeys$q(e, r2) {
  var t = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    r2 && (o = o.filter(function(r3) {
      return Object.getOwnPropertyDescriptor(e, r3).enumerable;
    })), t.push.apply(t, o);
  }
  return t;
}
function _objectSpread$q(e) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys$q(Object(t), true).forEach(function(r3) {
      _defineProperty$t(e, r3, t[r3]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$q(Object(t)).forEach(function(r3) {
      Object.defineProperty(e, r3, Object.getOwnPropertyDescriptor(t, r3));
    });
  }
  return e;
}
function _defineProperty$t(obj, key2, value) {
  key2 = _toPropertyKey$t(key2);
  if (key2 in obj) {
    Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key2] = value;
  }
  return obj;
}
function _toPropertyKey$t(t) {
  var i = _toPrimitive$t(t, "string");
  return "symbol" == _typeof$t(i) ? i : i + "";
}
function _toPrimitive$t(t, r2) {
  if ("object" != _typeof$t(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r2);
    if ("object" != _typeof$t(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return ("string" === r2 ? String : Number)(t);
}
var getLegendProps = function getLegendProps2(_ref) {
  var children = _ref.children, formattedGraphicalItems = _ref.formattedGraphicalItems, legendWidth = _ref.legendWidth, legendContent = _ref.legendContent;
  var legendItem = findChildByType(children, Legend);
  if (!legendItem) {
    return null;
  }
  var legendDefaultProps = Legend.defaultProps;
  var legendProps = legendDefaultProps !== void 0 ? _objectSpread$q(_objectSpread$q({}, legendDefaultProps), legendItem.props) : {};
  var legendData;
  if (legendItem.props && legendItem.props.payload) {
    legendData = legendItem.props && legendItem.props.payload;
  } else if (legendContent === "children") {
    legendData = (formattedGraphicalItems || []).reduce(function(result, _ref2) {
      var item = _ref2.item, props = _ref2.props;
      var data = props.sectors || props.data || [];
      return result.concat(data.map(function(entry) {
        return {
          type: legendItem.props.iconType || item.props.legendType,
          value: entry.name,
          color: entry.fill,
          payload: entry
        };
      }));
    }, []);
  } else {
    legendData = (formattedGraphicalItems || []).map(function(_ref3) {
      var item = _ref3.item;
      var itemDefaultProps = item.type.defaultProps;
      var itemProps = itemDefaultProps !== void 0 ? _objectSpread$q(_objectSpread$q({}, itemDefaultProps), item.props) : {};
      var dataKey = itemProps.dataKey, name = itemProps.name, legendType = itemProps.legendType, hide = itemProps.hide;
      return {
        inactive: hide,
        dataKey,
        type: legendProps.iconType || legendType || "square",
        color: getMainColorOfGraphicItem(item),
        value: name || dataKey,
        // @ts-expect-error property strokeDasharray is required in Payload but optional in props
        payload: itemProps
      };
    });
  }
  return _objectSpread$q(_objectSpread$q(_objectSpread$q({}, legendProps), Legend.getWithHeight(legendItem, legendWidth)), {}, {
    payload: legendData,
    item: legendItem
  });
};
function _typeof$s(o) {
  "@babel/helpers - typeof";
  return _typeof$s = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
    return typeof o2;
  } : function(o2) {
    return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
  }, _typeof$s(o);
}
function _toConsumableArray$5(arr) {
  return _arrayWithoutHoles$5(arr) || _iterableToArray$5(arr) || _unsupportedIterableToArray$9(arr) || _nonIterableSpread$5();
}
function _nonIterableSpread$5() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray$9(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return _arrayLikeToArray$9(o, minLen);
  var n = Object.prototype.toString.call(o).slice(8, -1);
  if (n === "Object" && o.constructor) n = o.constructor.name;
  if (n === "Map" || n === "Set") return Array.from(o);
  if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$9(o, minLen);
}
function _iterableToArray$5(iter) {
  if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _arrayWithoutHoles$5(arr) {
  if (Array.isArray(arr)) return _arrayLikeToArray$9(arr);
}
function _arrayLikeToArray$9(arr, len) {
  if (len == null || len > arr.length) len = arr.length;
  for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  return arr2;
}
function ownKeys$p(e, r2) {
  var t = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    r2 && (o = o.filter(function(r3) {
      return Object.getOwnPropertyDescriptor(e, r3).enumerable;
    })), t.push.apply(t, o);
  }
  return t;
}
function _objectSpread$p(e) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys$p(Object(t), true).forEach(function(r3) {
      _defineProperty$s(e, r3, t[r3]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$p(Object(t)).forEach(function(r3) {
      Object.defineProperty(e, r3, Object.getOwnPropertyDescriptor(t, r3));
    });
  }
  return e;
}
function _defineProperty$s(obj, key2, value) {
  key2 = _toPropertyKey$s(key2);
  if (key2 in obj) {
    Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key2] = value;
  }
  return obj;
}
function _toPropertyKey$s(t) {
  var i = _toPrimitive$s(t, "string");
  return "symbol" == _typeof$s(i) ? i : i + "";
}
function _toPrimitive$s(t, r2) {
  if ("object" != _typeof$s(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r2);
    if ("object" != _typeof$s(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return ("string" === r2 ? String : Number)(t);
}
function getValueByDataKey(obj, dataKey, defaultValue) {
  if (isNil$1(obj) || isNil$1(dataKey)) {
    return defaultValue;
  }
  if (isNumOrStr(dataKey)) {
    return get$2(obj, dataKey, defaultValue);
  }
  if (isFunction(dataKey)) {
    return dataKey(obj);
  }
  return defaultValue;
}
function getDomainOfDataByKey(data, key2, type, filterNil) {
  var flattenData = flatMap$1(data, function(entry) {
    return getValueByDataKey(entry, key2);
  });
  if (type === "number") {
    var domain = flattenData.filter(function(entry) {
      return isNumber(entry) || parseFloat(entry);
    });
    return domain.length ? [min$1(domain), max$1(domain)] : [Infinity, -Infinity];
  }
  var validateData = filterNil ? flattenData.filter(function(entry) {
    return !isNil$1(entry);
  }) : flattenData;
  return validateData.map(function(entry) {
    return isNumOrStr(entry) || entry instanceof Date ? entry : "";
  });
}
var calculateActiveTickIndex = function calculateActiveTickIndex2(coordinate) {
  var _ticks$length;
  var ticks2 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : [];
  var unsortedTicks = arguments.length > 2 ? arguments[2] : void 0;
  var axis = arguments.length > 3 ? arguments[3] : void 0;
  var index = -1;
  var len = (_ticks$length = ticks2 === null || ticks2 === void 0 ? void 0 : ticks2.length) !== null && _ticks$length !== void 0 ? _ticks$length : 0;
  if (len <= 1) {
    return 0;
  }
  if (axis && axis.axisType === "angleAxis" && Math.abs(Math.abs(axis.range[1] - axis.range[0]) - 360) <= 1e-6) {
    var range3 = axis.range;
    for (var i = 0; i < len; i++) {
      var before = i > 0 ? unsortedTicks[i - 1].coordinate : unsortedTicks[len - 1].coordinate;
      var cur = unsortedTicks[i].coordinate;
      var after = i >= len - 1 ? unsortedTicks[0].coordinate : unsortedTicks[i + 1].coordinate;
      var sameDirectionCoord = void 0;
      if (mathSign(cur - before) !== mathSign(after - cur)) {
        var diffInterval = [];
        if (mathSign(after - cur) === mathSign(range3[1] - range3[0])) {
          sameDirectionCoord = after;
          var curInRange = cur + range3[1] - range3[0];
          diffInterval[0] = Math.min(curInRange, (curInRange + before) / 2);
          diffInterval[1] = Math.max(curInRange, (curInRange + before) / 2);
        } else {
          sameDirectionCoord = before;
          var afterInRange = after + range3[1] - range3[0];
          diffInterval[0] = Math.min(cur, (afterInRange + cur) / 2);
          diffInterval[1] = Math.max(cur, (afterInRange + cur) / 2);
        }
        var sameInterval = [Math.min(cur, (sameDirectionCoord + cur) / 2), Math.max(cur, (sameDirectionCoord + cur) / 2)];
        if (coordinate > sameInterval[0] && coordinate <= sameInterval[1] || coordinate >= diffInterval[0] && coordinate <= diffInterval[1]) {
          index = unsortedTicks[i].index;
          break;
        }
      } else {
        var minValue = Math.min(before, after);
        var maxValue = Math.max(before, after);
        if (coordinate > (minValue + cur) / 2 && coordinate <= (maxValue + cur) / 2) {
          index = unsortedTicks[i].index;
          break;
        }
      }
    }
  } else {
    for (var _i = 0; _i < len; _i++) {
      if (_i === 0 && coordinate <= (ticks2[_i].coordinate + ticks2[_i + 1].coordinate) / 2 || _i > 0 && _i < len - 1 && coordinate > (ticks2[_i].coordinate + ticks2[_i - 1].coordinate) / 2 && coordinate <= (ticks2[_i].coordinate + ticks2[_i + 1].coordinate) / 2 || _i === len - 1 && coordinate > (ticks2[_i].coordinate + ticks2[_i - 1].coordinate) / 2) {
        index = ticks2[_i].index;
        break;
      }
    }
  }
  return index;
};
var getMainColorOfGraphicItem = function getMainColorOfGraphicItem2(item) {
  var _item$type;
  var _ref = item, displayName = _ref.type.displayName;
  var defaultedProps = (_item$type = item.type) !== null && _item$type !== void 0 && _item$type.defaultProps ? _objectSpread$p(_objectSpread$p({}, item.type.defaultProps), item.props) : item.props;
  var stroke = defaultedProps.stroke, fill = defaultedProps.fill;
  var result;
  switch (displayName) {
    case "Line":
      result = stroke;
      break;
    case "Area":
    case "Radar":
      result = stroke && stroke !== "none" ? stroke : fill;
      break;
    default:
      result = fill;
      break;
  }
  return result;
};
var getBarSizeList = function getBarSizeList2(_ref2) {
  var globalSize = _ref2.barSize, totalSize = _ref2.totalSize, _ref2$stackGroups = _ref2.stackGroups, stackGroups = _ref2$stackGroups === void 0 ? {} : _ref2$stackGroups;
  if (!stackGroups) {
    return {};
  }
  var result = {};
  var numericAxisIds = Object.keys(stackGroups);
  for (var i = 0, len = numericAxisIds.length; i < len; i++) {
    var sgs = stackGroups[numericAxisIds[i]].stackGroups;
    var stackIds = Object.keys(sgs);
    for (var j = 0, sLen = stackIds.length; j < sLen; j++) {
      var _sgs$stackIds$j = sgs[stackIds[j]], items = _sgs$stackIds$j.items, cateAxisId = _sgs$stackIds$j.cateAxisId;
      var barItems = items.filter(function(item) {
        return getDisplayName(item.type).indexOf("Bar") >= 0;
      });
      if (barItems && barItems.length) {
        var barItemDefaultProps = barItems[0].type.defaultProps;
        var barItemProps = barItemDefaultProps !== void 0 ? _objectSpread$p(_objectSpread$p({}, barItemDefaultProps), barItems[0].props) : barItems[0].props;
        var selfSize = barItemProps.barSize;
        var cateId = barItemProps[cateAxisId];
        if (!result[cateId]) {
          result[cateId] = [];
        }
        var barSize = isNil$1(selfSize) ? globalSize : selfSize;
        result[cateId].push({
          item: barItems[0],
          stackList: barItems.slice(1),
          barSize: isNil$1(barSize) ? void 0 : getPercentValue(barSize, totalSize, 0)
        });
      }
    }
  }
  return result;
};
var getBarPosition = function getBarPosition2(_ref3) {
  var barGap = _ref3.barGap, barCategoryGap = _ref3.barCategoryGap, bandSize = _ref3.bandSize, _ref3$sizeList = _ref3.sizeList, sizeList = _ref3$sizeList === void 0 ? [] : _ref3$sizeList, maxBarSize = _ref3.maxBarSize;
  var len = sizeList.length;
  if (len < 1) return null;
  var realBarGap = getPercentValue(barGap, bandSize, 0, true);
  var result;
  var initialValue = [];
  if (sizeList[0].barSize === +sizeList[0].barSize) {
    var useFull = false;
    var fullBarSize = bandSize / len;
    var sum = sizeList.reduce(function(res, entry) {
      return res + entry.barSize || 0;
    }, 0);
    sum += (len - 1) * realBarGap;
    if (sum >= bandSize) {
      sum -= (len - 1) * realBarGap;
      realBarGap = 0;
    }
    if (sum >= bandSize && fullBarSize > 0) {
      useFull = true;
      fullBarSize *= 0.9;
      sum = len * fullBarSize;
    }
    var offset = (bandSize - sum) / 2 >> 0;
    var prev = {
      offset: offset - realBarGap,
      size: 0
    };
    result = sizeList.reduce(function(res, entry) {
      var newPosition = {
        item: entry.item,
        position: {
          offset: prev.offset + prev.size + realBarGap,
          // @ts-expect-error the type check above does not check for type number explicitly
          size: useFull ? fullBarSize : entry.barSize
        }
      };
      var newRes = [].concat(_toConsumableArray$5(res), [newPosition]);
      prev = newRes[newRes.length - 1].position;
      if (entry.stackList && entry.stackList.length) {
        entry.stackList.forEach(function(item) {
          newRes.push({
            item,
            position: prev
          });
        });
      }
      return newRes;
    }, initialValue);
  } else {
    var _offset = getPercentValue(barCategoryGap, bandSize, 0, true);
    if (bandSize - 2 * _offset - (len - 1) * realBarGap <= 0) {
      realBarGap = 0;
    }
    var originalSize = (bandSize - 2 * _offset - (len - 1) * realBarGap) / len;
    if (originalSize > 1) {
      originalSize >>= 0;
    }
    var size = maxBarSize === +maxBarSize ? Math.min(originalSize, maxBarSize) : originalSize;
    result = sizeList.reduce(function(res, entry, i) {
      var newRes = [].concat(_toConsumableArray$5(res), [{
        item: entry.item,
        position: {
          offset: _offset + (originalSize + realBarGap) * i + (originalSize - size) / 2,
          size
        }
      }]);
      if (entry.stackList && entry.stackList.length) {
        entry.stackList.forEach(function(item) {
          newRes.push({
            item,
            position: newRes[newRes.length - 1].position
          });
        });
      }
      return newRes;
    }, initialValue);
  }
  return result;
};
var appendOffsetOfLegend = function appendOffsetOfLegend2(offset, _unused, props, legendBox) {
  var children = props.children, width = props.width, margin = props.margin;
  var legendWidth = width - (margin.left || 0) - (margin.right || 0);
  var legendProps = getLegendProps({
    children,
    legendWidth
  });
  if (legendProps) {
    var _ref4 = legendBox || {}, boxWidth = _ref4.width, boxHeight = _ref4.height;
    var align = legendProps.align, verticalAlign = legendProps.verticalAlign, layout = legendProps.layout;
    if ((layout === "vertical" || layout === "horizontal" && verticalAlign === "middle") && align !== "center" && isNumber(offset[align])) {
      return _objectSpread$p(_objectSpread$p({}, offset), {}, _defineProperty$s({}, align, offset[align] + (boxWidth || 0)));
    }
    if ((layout === "horizontal" || layout === "vertical" && align === "center") && verticalAlign !== "middle" && isNumber(offset[verticalAlign])) {
      return _objectSpread$p(_objectSpread$p({}, offset), {}, _defineProperty$s({}, verticalAlign, offset[verticalAlign] + (boxHeight || 0)));
    }
  }
  return offset;
};
var isErrorBarRelevantForAxis = function isErrorBarRelevantForAxis2(layout, axisType, direction) {
  if (isNil$1(axisType)) {
    return true;
  }
  if (layout === "horizontal") {
    return axisType === "yAxis";
  }
  if (layout === "vertical") {
    return axisType === "xAxis";
  }
  if (direction === "x") {
    return axisType === "xAxis";
  }
  if (direction === "y") {
    return axisType === "yAxis";
  }
  return true;
};
var getDomainOfErrorBars = function getDomainOfErrorBars2(data, item, dataKey, layout, axisType) {
  var children = item.props.children;
  var errorBars = findAllByType(children, ErrorBar).filter(function(errorBarChild) {
    return isErrorBarRelevantForAxis(layout, axisType, errorBarChild.props.direction);
  });
  if (errorBars && errorBars.length) {
    var keys2 = errorBars.map(function(errorBarChild) {
      return errorBarChild.props.dataKey;
    });
    return data.reduce(function(result, entry) {
      var entryValue = getValueByDataKey(entry, dataKey);
      if (isNil$1(entryValue)) return result;
      var mainValue = Array.isArray(entryValue) ? [min$1(entryValue), max$1(entryValue)] : [entryValue, entryValue];
      var errorDomain = keys2.reduce(function(prevErrorArr, k2) {
        var errorValue = getValueByDataKey(entry, k2, 0);
        var lowerValue = mainValue[0] - Math.abs(Array.isArray(errorValue) ? errorValue[0] : errorValue);
        var upperValue = mainValue[1] + Math.abs(Array.isArray(errorValue) ? errorValue[1] : errorValue);
        return [Math.min(lowerValue, prevErrorArr[0]), Math.max(upperValue, prevErrorArr[1])];
      }, [Infinity, -Infinity]);
      return [Math.min(errorDomain[0], result[0]), Math.max(errorDomain[1], result[1])];
    }, [Infinity, -Infinity]);
  }
  return null;
};
var parseErrorBarsOfAxis = function parseErrorBarsOfAxis2(data, items, dataKey, axisType, layout) {
  var domains = items.map(function(item) {
    return getDomainOfErrorBars(data, item, dataKey, layout, axisType);
  }).filter(function(entry) {
    return !isNil$1(entry);
  });
  if (domains && domains.length) {
    return domains.reduce(function(result, entry) {
      return [Math.min(result[0], entry[0]), Math.max(result[1], entry[1])];
    }, [Infinity, -Infinity]);
  }
  return null;
};
var getDomainOfItemsWithSameAxis = function getDomainOfItemsWithSameAxis2(data, items, type, layout, filterNil) {
  var domains = items.map(function(item) {
    var dataKey = item.props.dataKey;
    if (type === "number" && dataKey) {
      return getDomainOfErrorBars(data, item, dataKey, layout) || getDomainOfDataByKey(data, dataKey, type, filterNil);
    }
    return getDomainOfDataByKey(data, dataKey, type, filterNil);
  });
  if (type === "number") {
    return domains.reduce(
      // @ts-expect-error if (type === number) means that the domain is numerical type
      // - but this link is missing in the type definition
      function(result, entry) {
        return [Math.min(result[0], entry[0]), Math.max(result[1], entry[1])];
      },
      [Infinity, -Infinity]
    );
  }
  var tag2 = {};
  return domains.reduce(function(result, entry) {
    for (var i = 0, len = entry.length; i < len; i++) {
      if (!tag2[entry[i]]) {
        tag2[entry[i]] = true;
        result.push(entry[i]);
      }
    }
    return result;
  }, []);
};
var isCategoricalAxis = function isCategoricalAxis2(layout, axisType) {
  return layout === "horizontal" && axisType === "xAxis" || layout === "vertical" && axisType === "yAxis" || layout === "centric" && axisType === "angleAxis" || layout === "radial" && axisType === "radiusAxis";
};
var getCoordinatesOfGrid = function getCoordinatesOfGrid2(ticks2, minValue, maxValue, syncWithTicks) {
  if (syncWithTicks) {
    return ticks2.map(function(entry) {
      return entry.coordinate;
    });
  }
  var hasMin, hasMax;
  var values = ticks2.map(function(entry) {
    if (entry.coordinate === minValue) {
      hasMin = true;
    }
    if (entry.coordinate === maxValue) {
      hasMax = true;
    }
    return entry.coordinate;
  });
  if (!hasMin) {
    values.push(minValue);
  }
  if (!hasMax) {
    values.push(maxValue);
  }
  return values;
};
var getTicksOfAxis = function getTicksOfAxis2(axis, isGrid, isAll) {
  if (!axis) return null;
  var scale2 = axis.scale;
  var duplicateDomain = axis.duplicateDomain, type = axis.type, range3 = axis.range;
  var offsetForBand = axis.realScaleType === "scaleBand" ? scale2.bandwidth() / 2 : 2;
  var offset = (isGrid || isAll) && type === "category" && scale2.bandwidth ? scale2.bandwidth() / offsetForBand : 0;
  offset = axis.axisType === "angleAxis" && (range3 === null || range3 === void 0 ? void 0 : range3.length) >= 2 ? mathSign(range3[0] - range3[1]) * 2 * offset : offset;
  if (isGrid && (axis.ticks || axis.niceTicks)) {
    var result = (axis.ticks || axis.niceTicks).map(function(entry) {
      var scaleContent = duplicateDomain ? duplicateDomain.indexOf(entry) : entry;
      return {
        // If the scaleContent is not a number, the coordinate will be NaN.
        // That could be the case for example with a PointScale and a string as domain.
        coordinate: scale2(scaleContent) + offset,
        value: entry,
        offset
      };
    });
    return result.filter(function(row) {
      return !isNan(row.coordinate);
    });
  }
  if (axis.isCategorical && axis.categoricalDomain) {
    return axis.categoricalDomain.map(function(entry, index) {
      return {
        coordinate: scale2(entry) + offset,
        value: entry,
        index,
        offset
      };
    });
  }
  if (scale2.ticks && !isAll) {
    return scale2.ticks(axis.tickCount).map(function(entry) {
      return {
        coordinate: scale2(entry) + offset,
        value: entry,
        offset
      };
    });
  }
  return scale2.domain().map(function(entry, index) {
    return {
      coordinate: scale2(entry) + offset,
      value: duplicateDomain ? duplicateDomain[entry] : entry,
      index,
      offset
    };
  });
};
var handlerWeakMap = /* @__PURE__ */ new WeakMap();
var combineEventHandlers = function combineEventHandlers2(defaultHandler, childHandler) {
  if (typeof childHandler !== "function") {
    return defaultHandler;
  }
  if (!handlerWeakMap.has(defaultHandler)) {
    handlerWeakMap.set(defaultHandler, /* @__PURE__ */ new WeakMap());
  }
  var childWeakMap = handlerWeakMap.get(defaultHandler);
  if (childWeakMap.has(childHandler)) {
    return childWeakMap.get(childHandler);
  }
  var combineHandler = function combineHandler2() {
    defaultHandler.apply(void 0, arguments);
    childHandler.apply(void 0, arguments);
  };
  childWeakMap.set(childHandler, combineHandler);
  return combineHandler;
};
var parseScale = function parseScale2(axis, chartType, hasBar) {
  var scale2 = axis.scale, type = axis.type, layout = axis.layout, axisType = axis.axisType;
  if (scale2 === "auto") {
    if (layout === "radial" && axisType === "radiusAxis") {
      return {
        scale: band(),
        realScaleType: "band"
      };
    }
    if (layout === "radial" && axisType === "angleAxis") {
      return {
        scale: linear(),
        realScaleType: "linear"
      };
    }
    if (type === "category" && chartType && (chartType.indexOf("LineChart") >= 0 || chartType.indexOf("AreaChart") >= 0 || chartType.indexOf("ComposedChart") >= 0 && !hasBar)) {
      return {
        scale: point(),
        realScaleType: "point"
      };
    }
    if (type === "category") {
      return {
        scale: band(),
        realScaleType: "band"
      };
    }
    return {
      scale: linear(),
      realScaleType: "linear"
    };
  }
  if (isString$1(scale2)) {
    var name = "scale".concat(upperFirst$1(scale2));
    return {
      scale: (d3Scales[name] || point)(),
      realScaleType: d3Scales[name] ? name : "point"
    };
  }
  return isFunction(scale2) ? {
    scale: scale2
  } : {
    scale: point(),
    realScaleType: "point"
  };
};
var EPS = 1e-4;
var checkDomainOfScale = function checkDomainOfScale2(scale2) {
  var domain = scale2.domain();
  if (!domain || domain.length <= 2) {
    return;
  }
  var len = domain.length;
  var range3 = scale2.range();
  var minValue = Math.min(range3[0], range3[1]) - EPS;
  var maxValue = Math.max(range3[0], range3[1]) + EPS;
  var first = scale2(domain[0]);
  var last2 = scale2(domain[len - 1]);
  if (first < minValue || first > maxValue || last2 < minValue || last2 > maxValue) {
    scale2.domain([domain[0], domain[len - 1]]);
  }
};
var findPositionOfBar = function findPositionOfBar2(barPosition, child) {
  if (!barPosition) {
    return null;
  }
  for (var i = 0, len = barPosition.length; i < len; i++) {
    if (barPosition[i].item === child) {
      return barPosition[i].position;
    }
  }
  return null;
};
var truncateByDomain = function truncateByDomain2(value, domain) {
  if (!domain || domain.length !== 2 || !isNumber(domain[0]) || !isNumber(domain[1])) {
    return value;
  }
  var minValue = Math.min(domain[0], domain[1]);
  var maxValue = Math.max(domain[0], domain[1]);
  var result = [value[0], value[1]];
  if (!isNumber(value[0]) || value[0] < minValue) {
    result[0] = minValue;
  }
  if (!isNumber(value[1]) || value[1] > maxValue) {
    result[1] = maxValue;
  }
  if (result[0] > maxValue) {
    result[0] = maxValue;
  }
  if (result[1] < minValue) {
    result[1] = minValue;
  }
  return result;
};
var offsetSign = function offsetSign2(series) {
  var n = series.length;
  if (n <= 0) {
    return;
  }
  for (var j = 0, m = series[0].length; j < m; ++j) {
    var positive = 0;
    var negative = 0;
    for (var i = 0; i < n; ++i) {
      var value = isNan(series[i][j][1]) ? series[i][j][0] : series[i][j][1];
      if (value >= 0) {
        series[i][j][0] = positive;
        series[i][j][1] = positive + value;
        positive = series[i][j][1];
      } else {
        series[i][j][0] = negative;
        series[i][j][1] = negative + value;
        negative = series[i][j][1];
      }
    }
  }
};
var offsetPositive = function offsetPositive2(series) {
  var n = series.length;
  if (n <= 0) {
    return;
  }
  for (var j = 0, m = series[0].length; j < m; ++j) {
    var positive = 0;
    for (var i = 0; i < n; ++i) {
      var value = isNan(series[i][j][1]) ? series[i][j][0] : series[i][j][1];
      if (value >= 0) {
        series[i][j][0] = positive;
        series[i][j][1] = positive + value;
        positive = series[i][j][1];
      } else {
        series[i][j][0] = 0;
        series[i][j][1] = 0;
      }
    }
  }
};
var STACK_OFFSET_MAP = {
  sign: offsetSign,
  // @ts-expect-error definitelytyped types are incorrect
  expand: stackOffsetExpand,
  // @ts-expect-error definitelytyped types are incorrect
  none: stackOffsetNone,
  // @ts-expect-error definitelytyped types are incorrect
  silhouette: stackOffsetSilhouette,
  // @ts-expect-error definitelytyped types are incorrect
  wiggle: stackOffsetWiggle,
  positive: offsetPositive
};
var getStackedData = function getStackedData2(data, stackItems, offsetType) {
  var dataKeys = stackItems.map(function(item) {
    return item.props.dataKey;
  });
  var offsetAccessor = STACK_OFFSET_MAP[offsetType];
  var stack = shapeStack().keys(dataKeys).value(function(d, key2) {
    return +getValueByDataKey(d, key2, 0);
  }).order(stackOrderNone).offset(offsetAccessor);
  return stack(data);
};
var getStackGroupsByAxisId = function getStackGroupsByAxisId2(data, _items, numericAxisId, cateAxisId, offsetType, reverseStackOrder) {
  if (!data) {
    return null;
  }
  var items = reverseStackOrder ? _items.reverse() : _items;
  var parentStackGroupsInitialValue = {};
  var stackGroups = items.reduce(function(result, item) {
    var _item$type2;
    var defaultedProps = (_item$type2 = item.type) !== null && _item$type2 !== void 0 && _item$type2.defaultProps ? _objectSpread$p(_objectSpread$p({}, item.type.defaultProps), item.props) : item.props;
    var stackId = defaultedProps.stackId, hide = defaultedProps.hide;
    if (hide) {
      return result;
    }
    var axisId = defaultedProps[numericAxisId];
    var parentGroup = result[axisId] || {
      hasStack: false,
      stackGroups: {}
    };
    if (isNumOrStr(stackId)) {
      var childGroup = parentGroup.stackGroups[stackId] || {
        numericAxisId,
        cateAxisId,
        items: []
      };
      childGroup.items.push(item);
      parentGroup.hasStack = true;
      parentGroup.stackGroups[stackId] = childGroup;
    } else {
      parentGroup.stackGroups[uniqueId("_stackId_")] = {
        numericAxisId,
        cateAxisId,
        items: [item]
      };
    }
    return _objectSpread$p(_objectSpread$p({}, result), {}, _defineProperty$s({}, axisId, parentGroup));
  }, parentStackGroupsInitialValue);
  var axisStackGroupsInitialValue = {};
  return Object.keys(stackGroups).reduce(function(result, axisId) {
    var group = stackGroups[axisId];
    if (group.hasStack) {
      var stackGroupsInitialValue = {};
      group.stackGroups = Object.keys(group.stackGroups).reduce(function(res, stackId) {
        var g = group.stackGroups[stackId];
        return _objectSpread$p(_objectSpread$p({}, res), {}, _defineProperty$s({}, stackId, {
          numericAxisId,
          cateAxisId,
          items: g.items,
          stackedData: getStackedData(data, g.items, offsetType)
        }));
      }, stackGroupsInitialValue);
    }
    return _objectSpread$p(_objectSpread$p({}, result), {}, _defineProperty$s({}, axisId, group));
  }, axisStackGroupsInitialValue);
};
var getTicksOfScale = function getTicksOfScale2(scale2, opts) {
  var realScaleType = opts.realScaleType, type = opts.type, tickCount = opts.tickCount, originalDomain = opts.originalDomain, allowDecimals = opts.allowDecimals;
  var scaleType = realScaleType || opts.scale;
  if (scaleType !== "auto" && scaleType !== "linear") {
    return null;
  }
  if (tickCount && type === "number" && originalDomain && (originalDomain[0] === "auto" || originalDomain[1] === "auto")) {
    var domain = scale2.domain();
    if (!domain.length) {
      return null;
    }
    var tickValues = getNiceTickValues(domain, tickCount, allowDecimals);
    scale2.domain([min$1(tickValues), max$1(tickValues)]);
    return {
      niceTicks: tickValues
    };
  }
  if (tickCount && type === "number") {
    var _domain = scale2.domain();
    var _tickValues = getTickValuesFixedDomain(_domain, tickCount, allowDecimals);
    return {
      niceTicks: _tickValues
    };
  }
  return null;
};
function getCateCoordinateOfLine(_ref5) {
  var axis = _ref5.axis, ticks2 = _ref5.ticks, bandSize = _ref5.bandSize, entry = _ref5.entry, index = _ref5.index, dataKey = _ref5.dataKey;
  if (axis.type === "category") {
    if (!axis.allowDuplicatedCategory && axis.dataKey && !isNil$1(entry[axis.dataKey])) {
      var matchedTick = findEntryInArray(ticks2, "value", entry[axis.dataKey]);
      if (matchedTick) {
        return matchedTick.coordinate + bandSize / 2;
      }
    }
    return ticks2[index] ? ticks2[index].coordinate + bandSize / 2 : null;
  }
  var value = getValueByDataKey(entry, !isNil$1(dataKey) ? dataKey : axis.dataKey);
  return !isNil$1(value) ? axis.scale(value) : null;
}
var getCateCoordinateOfBar = function getCateCoordinateOfBar2(_ref6) {
  var axis = _ref6.axis, ticks2 = _ref6.ticks, offset = _ref6.offset, bandSize = _ref6.bandSize, entry = _ref6.entry, index = _ref6.index;
  if (axis.type === "category") {
    return ticks2[index] ? ticks2[index].coordinate + offset : null;
  }
  var value = getValueByDataKey(entry, axis.dataKey, axis.domain[index]);
  return !isNil$1(value) ? axis.scale(value) - bandSize / 2 + offset : null;
};
var getBaseValueOfBar = function getBaseValueOfBar2(_ref7) {
  var numericAxis = _ref7.numericAxis;
  var domain = numericAxis.scale.domain();
  if (numericAxis.type === "number") {
    var minValue = Math.min(domain[0], domain[1]);
    var maxValue = Math.max(domain[0], domain[1]);
    if (minValue <= 0 && maxValue >= 0) {
      return 0;
    }
    if (maxValue < 0) {
      return maxValue;
    }
    return minValue;
  }
  return domain[0];
};
var getStackedDataOfItem = function getStackedDataOfItem2(item, stackGroups) {
  var _item$type3;
  var defaultedProps = (_item$type3 = item.type) !== null && _item$type3 !== void 0 && _item$type3.defaultProps ? _objectSpread$p(_objectSpread$p({}, item.type.defaultProps), item.props) : item.props;
  var stackId = defaultedProps.stackId;
  if (isNumOrStr(stackId)) {
    var group = stackGroups[stackId];
    if (group) {
      var itemIndex = group.items.indexOf(item);
      return itemIndex >= 0 ? group.stackedData[itemIndex] : null;
    }
  }
  return null;
};
var getDomainOfSingle = function getDomainOfSingle2(data) {
  return data.reduce(function(result, entry) {
    return [min$1(entry.concat([result[0]]).filter(isNumber)), max$1(entry.concat([result[1]]).filter(isNumber))];
  }, [Infinity, -Infinity]);
};
var getDomainOfStackGroups = function getDomainOfStackGroups2(stackGroups, startIndex, endIndex) {
  return Object.keys(stackGroups).reduce(function(result, stackId) {
    var group = stackGroups[stackId];
    var stackedData = group.stackedData;
    var domain = stackedData.reduce(function(res, entry) {
      var s2 = getDomainOfSingle(entry.slice(startIndex, endIndex + 1));
      return [Math.min(res[0], s2[0]), Math.max(res[1], s2[1])];
    }, [Infinity, -Infinity]);
    return [Math.min(domain[0], result[0]), Math.max(domain[1], result[1])];
  }, [Infinity, -Infinity]).map(function(result) {
    return result === Infinity || result === -Infinity ? 0 : result;
  });
};
var MIN_VALUE_REG = /^dataMin[\s]*-[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/;
var MAX_VALUE_REG = /^dataMax[\s]*\+[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/;
var parseSpecifiedDomain = function parseSpecifiedDomain2(specifiedDomain, dataDomain, allowDataOverflow) {
  if (isFunction(specifiedDomain)) {
    return specifiedDomain(dataDomain, allowDataOverflow);
  }
  if (!Array.isArray(specifiedDomain)) {
    return dataDomain;
  }
  var domain = [];
  if (isNumber(specifiedDomain[0])) {
    domain[0] = allowDataOverflow ? specifiedDomain[0] : Math.min(specifiedDomain[0], dataDomain[0]);
  } else if (MIN_VALUE_REG.test(specifiedDomain[0])) {
    var value = +MIN_VALUE_REG.exec(specifiedDomain[0])[1];
    domain[0] = dataDomain[0] - value;
  } else if (isFunction(specifiedDomain[0])) {
    domain[0] = specifiedDomain[0](dataDomain[0]);
  } else {
    domain[0] = dataDomain[0];
  }
  if (isNumber(specifiedDomain[1])) {
    domain[1] = allowDataOverflow ? specifiedDomain[1] : Math.max(specifiedDomain[1], dataDomain[1]);
  } else if (MAX_VALUE_REG.test(specifiedDomain[1])) {
    var _value = +MAX_VALUE_REG.exec(specifiedDomain[1])[1];
    domain[1] = dataDomain[1] + _value;
  } else if (isFunction(specifiedDomain[1])) {
    domain[1] = specifiedDomain[1](dataDomain[1]);
  } else {
    domain[1] = dataDomain[1];
  }
  return domain;
};
var getBandSizeOfAxis = function getBandSizeOfAxis2(axis, ticks2, isBar) {
  if (axis && axis.scale && axis.scale.bandwidth) {
    var bandWidth = axis.scale.bandwidth();
    if (!isBar || bandWidth > 0) {
      return bandWidth;
    }
  }
  if (axis && ticks2 && ticks2.length >= 2) {
    var orderedTicks = sortBy$1(ticks2, function(o) {
      return o.coordinate;
    });
    var bandSize = Infinity;
    for (var i = 1, len = orderedTicks.length; i < len; i++) {
      var cur = orderedTicks[i];
      var prev = orderedTicks[i - 1];
      bandSize = Math.min((cur.coordinate || 0) - (prev.coordinate || 0), bandSize);
    }
    return bandSize === Infinity ? 0 : bandSize;
  }
  return isBar ? void 0 : 0;
};
var parseDomainOfCategoryAxis = function parseDomainOfCategoryAxis2(specifiedDomain, calculatedDomain, axisChild) {
  if (!specifiedDomain || !specifiedDomain.length) {
    return calculatedDomain;
  }
  if (isEqual(specifiedDomain, get$2(axisChild, "type.defaultProps.domain"))) {
    return calculatedDomain;
  }
  return specifiedDomain;
};
var getTooltipItem = function getTooltipItem2(graphicalItem, payload) {
  var defaultedProps = graphicalItem.type.defaultProps ? _objectSpread$p(_objectSpread$p({}, graphicalItem.type.defaultProps), graphicalItem.props) : graphicalItem.props;
  var dataKey = defaultedProps.dataKey, name = defaultedProps.name, unit2 = defaultedProps.unit, formatter = defaultedProps.formatter, tooltipType = defaultedProps.tooltipType, chartType = defaultedProps.chartType, hide = defaultedProps.hide;
  return _objectSpread$p(_objectSpread$p({}, filterProps(graphicalItem, false)), {}, {
    dataKey,
    unit: unit2,
    formatter,
    name: name || dataKey,
    color: getMainColorOfGraphicItem(graphicalItem),
    value: getValueByDataKey(payload, dataKey),
    type: tooltipType,
    payload,
    chartType,
    hide
  });
};
function _typeof$r(o) {
  "@babel/helpers - typeof";
  return _typeof$r = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
    return typeof o2;
  } : function(o2) {
    return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
  }, _typeof$r(o);
}
function ownKeys$o(e, r2) {
  var t = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    r2 && (o = o.filter(function(r3) {
      return Object.getOwnPropertyDescriptor(e, r3).enumerable;
    })), t.push.apply(t, o);
  }
  return t;
}
function _objectSpread$o(e) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys$o(Object(t), true).forEach(function(r3) {
      _defineProperty$r(e, r3, t[r3]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$o(Object(t)).forEach(function(r3) {
      Object.defineProperty(e, r3, Object.getOwnPropertyDescriptor(t, r3));
    });
  }
  return e;
}
function _defineProperty$r(obj, key2, value) {
  key2 = _toPropertyKey$r(key2);
  if (key2 in obj) {
    Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key2] = value;
  }
  return obj;
}
function _toPropertyKey$r(t) {
  var i = _toPrimitive$r(t, "string");
  return "symbol" == _typeof$r(i) ? i : i + "";
}
function _toPrimitive$r(t, r2) {
  if ("object" != _typeof$r(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r2);
    if ("object" != _typeof$r(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return ("string" === r2 ? String : Number)(t);
}
function _slicedToArray$4(arr, i) {
  return _arrayWithHoles$4(arr) || _iterableToArrayLimit$4(arr, i) || _unsupportedIterableToArray$8(arr, i) || _nonIterableRest$4();
}
function _nonIterableRest$4() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray$8(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return _arrayLikeToArray$8(o, minLen);
  var n = Object.prototype.toString.call(o).slice(8, -1);
  if (n === "Object" && o.constructor) n = o.constructor.name;
  if (n === "Map" || n === "Set") return Array.from(o);
  if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$8(o, minLen);
}
function _arrayLikeToArray$8(arr, len) {
  if (len == null || len > arr.length) len = arr.length;
  for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  return arr2;
}
function _iterableToArrayLimit$4(r2, l) {
  var t = null == r2 ? null : "undefined" != typeof Symbol && r2[Symbol.iterator] || r2["@@iterator"];
  if (null != t) {
    var e, n, i, u, a2 = [], f = true, o = false;
    try {
      if (i = (t = t.call(r2)).next, 0 === l) ;
      else for (; !(f = (e = i.call(t)).done) && (a2.push(e.value), a2.length !== l); f = true) ;
    } catch (r3) {
      o = true, n = r3;
    } finally {
      try {
        if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return;
      } finally {
        if (o) throw n;
      }
    }
    return a2;
  }
}
function _arrayWithHoles$4(arr) {
  if (Array.isArray(arr)) return arr;
}
var RADIAN$1 = Math.PI / 180;
var radianToDegree = function radianToDegree2(angleInRadian) {
  return angleInRadian * 180 / Math.PI;
};
var polarToCartesian = function polarToCartesian2(cx, cy, radius, angle) {
  return {
    x: cx + Math.cos(-RADIAN$1 * angle) * radius,
    y: cy + Math.sin(-RADIAN$1 * angle) * radius
  };
};
var getMaxRadius = function getMaxRadius2(width, height) {
  var offset = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {
    top: 0,
    right: 0,
    bottom: 0,
    left: 0
  };
  return Math.min(Math.abs(width - (offset.left || 0) - (offset.right || 0)), Math.abs(height - (offset.top || 0) - (offset.bottom || 0))) / 2;
};
var formatAxisMap$1 = function formatAxisMap2(props, axisMap, offset, axisType, chartName) {
  var width = props.width, height = props.height;
  var startAngle = props.startAngle, endAngle = props.endAngle;
  var cx = getPercentValue(props.cx, width, width / 2);
  var cy = getPercentValue(props.cy, height, height / 2);
  var maxRadius = getMaxRadius(width, height, offset);
  var innerRadius = getPercentValue(props.innerRadius, maxRadius, 0);
  var outerRadius = getPercentValue(props.outerRadius, maxRadius, maxRadius * 0.8);
  var ids = Object.keys(axisMap);
  return ids.reduce(function(result, id) {
    var axis = axisMap[id];
    var domain = axis.domain, reversed = axis.reversed;
    var range3;
    if (isNil$1(axis.range)) {
      if (axisType === "angleAxis") {
        range3 = [startAngle, endAngle];
      } else if (axisType === "radiusAxis") {
        range3 = [innerRadius, outerRadius];
      }
      if (reversed) {
        range3 = [range3[1], range3[0]];
      }
    } else {
      range3 = axis.range;
      var _range = range3;
      var _range2 = _slicedToArray$4(_range, 2);
      startAngle = _range2[0];
      endAngle = _range2[1];
    }
    var _parseScale = parseScale(axis, chartName), realScaleType = _parseScale.realScaleType, scale2 = _parseScale.scale;
    scale2.domain(domain).range(range3);
    checkDomainOfScale(scale2);
    var ticks2 = getTicksOfScale(scale2, _objectSpread$o(_objectSpread$o({}, axis), {}, {
      realScaleType
    }));
    var finalAxis = _objectSpread$o(_objectSpread$o(_objectSpread$o({}, axis), ticks2), {}, {
      range: range3,
      radius: outerRadius,
      realScaleType,
      scale: scale2,
      cx,
      cy,
      innerRadius,
      outerRadius,
      startAngle,
      endAngle
    });
    return _objectSpread$o(_objectSpread$o({}, result), {}, _defineProperty$r({}, id, finalAxis));
  }, {});
};
var distanceBetweenPoints = function distanceBetweenPoints2(point2, anotherPoint) {
  var x1 = point2.x, y1 = point2.y;
  var x2 = anotherPoint.x, y2 = anotherPoint.y;
  return Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2));
};
var getAngleOfPoint = function getAngleOfPoint2(_ref, _ref2) {
  var x2 = _ref.x, y2 = _ref.y;
  var cx = _ref2.cx, cy = _ref2.cy;
  var radius = distanceBetweenPoints({
    x: x2,
    y: y2
  }, {
    x: cx,
    y: cy
  });
  if (radius <= 0) {
    return {
      radius
    };
  }
  var cos2 = (x2 - cx) / radius;
  var angleInRadian = Math.acos(cos2);
  if (y2 > cy) {
    angleInRadian = 2 * Math.PI - angleInRadian;
  }
  return {
    radius,
    angle: radianToDegree(angleInRadian),
    angleInRadian
  };
};
var formatAngleOfSector = function formatAngleOfSector2(_ref3) {
  var startAngle = _ref3.startAngle, endAngle = _ref3.endAngle;
  var startCnt = Math.floor(startAngle / 360);
  var endCnt = Math.floor(endAngle / 360);
  var min2 = Math.min(startCnt, endCnt);
  return {
    startAngle: startAngle - min2 * 360,
    endAngle: endAngle - min2 * 360
  };
};
var reverseFormatAngleOfSetor = function reverseFormatAngleOfSetor2(angle, _ref4) {
  var startAngle = _ref4.startAngle, endAngle = _ref4.endAngle;
  var startCnt = Math.floor(startAngle / 360);
  var endCnt = Math.floor(endAngle / 360);
  var min2 = Math.min(startCnt, endCnt);
  return angle + min2 * 360;
};
var inRangeOfSector = function inRangeOfSector2(_ref5, sector) {
  var x2 = _ref5.x, y2 = _ref5.y;
  var _getAngleOfPoint = getAngleOfPoint({
    x: x2,
    y: y2
  }, sector), radius = _getAngleOfPoint.radius, angle = _getAngleOfPoint.angle;
  var innerRadius = sector.innerRadius, outerRadius = sector.outerRadius;
  if (radius < innerRadius || radius > outerRadius) {
    return false;
  }
  if (radius === 0) {
    return true;
  }
  var _formatAngleOfSector = formatAngleOfSector(sector), startAngle = _formatAngleOfSector.startAngle, endAngle = _formatAngleOfSector.endAngle;
  var formatAngle = angle;
  var inRange;
  if (startAngle <= endAngle) {
    while (formatAngle > endAngle) {
      formatAngle -= 360;
    }
    while (formatAngle < startAngle) {
      formatAngle += 360;
    }
    inRange = formatAngle >= startAngle && formatAngle <= endAngle;
  } else {
    while (formatAngle > startAngle) {
      formatAngle -= 360;
    }
    while (formatAngle < endAngle) {
      formatAngle += 360;
    }
    inRange = formatAngle >= endAngle && formatAngle <= startAngle;
  }
  if (inRange) {
    return _objectSpread$o(_objectSpread$o({}, sector), {}, {
      radius,
      angle: reverseFormatAngleOfSetor(formatAngle, sector)
    });
  }
  return null;
};
var getTickClassName = function getTickClassName2(tick) {
  return !/* @__PURE__ */ reactExports.isValidElement(tick) && !isFunction(tick) && typeof tick !== "boolean" ? tick.className : "";
};
function _typeof$q(o) {
  "@babel/helpers - typeof";
  return _typeof$q = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
    return typeof o2;
  } : function(o2) {
    return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
  }, _typeof$q(o);
}
var _excluded$a = ["offset"];
function _toConsumableArray$4(arr) {
  return _arrayWithoutHoles$4(arr) || _iterableToArray$4(arr) || _unsupportedIterableToArray$7(arr) || _nonIterableSpread$4();
}
function _nonIterableSpread$4() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray$7(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return _arrayLikeToArray$7(o, minLen);
  var n = Object.prototype.toString.call(o).slice(8, -1);
  if (n === "Object" && o.constructor) n = o.constructor.name;
  if (n === "Map" || n === "Set") return Array.from(o);
  if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$7(o, minLen);
}
function _iterableToArray$4(iter) {
  if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _arrayWithoutHoles$4(arr) {
  if (Array.isArray(arr)) return _arrayLikeToArray$7(arr);
}
function _arrayLikeToArray$7(arr, len) {
  if (len == null || len > arr.length) len = arr.length;
  for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  return arr2;
}
function _objectWithoutProperties$a(source, excluded) {
  if (source == null) return {};
  var target2 = _objectWithoutPropertiesLoose$a(source, excluded);
  var key2, i;
  if (Object.getOwnPropertySymbols) {
    var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
    for (i = 0; i < sourceSymbolKeys.length; i++) {
      key2 = sourceSymbolKeys[i];
      if (excluded.indexOf(key2) >= 0) continue;
      if (!Object.prototype.propertyIsEnumerable.call(source, key2)) continue;
      target2[key2] = source[key2];
    }
  }
  return target2;
}
function _objectWithoutPropertiesLoose$a(source, excluded) {
  if (source == null) return {};
  var target2 = {};
  for (var key2 in source) {
    if (Object.prototype.hasOwnProperty.call(source, key2)) {
      if (excluded.indexOf(key2) >= 0) continue;
      target2[key2] = source[key2];
    }
  }
  return target2;
}
function ownKeys$n(e, r2) {
  var t = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    r2 && (o = o.filter(function(r3) {
      return Object.getOwnPropertyDescriptor(e, r3).enumerable;
    })), t.push.apply(t, o);
  }
  return t;
}
function _objectSpread$n(e) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys$n(Object(t), true).forEach(function(r3) {
      _defineProperty$q(e, r3, t[r3]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$n(Object(t)).forEach(function(r3) {
      Object.defineProperty(e, r3, Object.getOwnPropertyDescriptor(t, r3));
    });
  }
  return e;
}
function _defineProperty$q(obj, key2, value) {
  key2 = _toPropertyKey$q(key2);
  if (key2 in obj) {
    Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key2] = value;
  }
  return obj;
}
function _toPropertyKey$q(t) {
  var i = _toPrimitive$q(t, "string");
  return "symbol" == _typeof$q(i) ? i : i + "";
}
function _toPrimitive$q(t, r2) {
  if ("object" != _typeof$q(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r2);
    if ("object" != _typeof$q(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return ("string" === r2 ? String : Number)(t);
}
function _extends$m() {
  _extends$m = Object.assign ? Object.assign.bind() : function(target2) {
    for (var i = 1; i < arguments.length; i++) {
      var source = arguments[i];
      for (var key2 in source) {
        if (Object.prototype.hasOwnProperty.call(source, key2)) {
          target2[key2] = source[key2];
        }
      }
    }
    return target2;
  };
  return _extends$m.apply(this, arguments);
}
var getLabel = function getLabel2(props) {
  var value = props.value, formatter = props.formatter;
  var label = isNil$1(props.children) ? value : props.children;
  if (isFunction(formatter)) {
    return formatter(label);
  }
  return label;
};
var getDeltaAngle$1 = function getDeltaAngle2(startAngle, endAngle) {
  var sign2 = mathSign(endAngle - startAngle);
  var deltaAngle = Math.min(Math.abs(endAngle - startAngle), 360);
  return sign2 * deltaAngle;
};
var renderRadialLabel = function renderRadialLabel2(labelProps, label, attrs) {
  var position = labelProps.position, viewBox = labelProps.viewBox, offset = labelProps.offset, className = labelProps.className;
  var _ref = viewBox, cx = _ref.cx, cy = _ref.cy, innerRadius = _ref.innerRadius, outerRadius = _ref.outerRadius, startAngle = _ref.startAngle, endAngle = _ref.endAngle, clockWise = _ref.clockWise;
  var radius = (innerRadius + outerRadius) / 2;
  var deltaAngle = getDeltaAngle$1(startAngle, endAngle);
  var sign2 = deltaAngle >= 0 ? 1 : -1;
  var labelAngle, direction;
  if (position === "insideStart") {
    labelAngle = startAngle + sign2 * offset;
    direction = clockWise;
  } else if (position === "insideEnd") {
    labelAngle = endAngle - sign2 * offset;
    direction = !clockWise;
  } else if (position === "end") {
    labelAngle = endAngle + sign2 * offset;
    direction = clockWise;
  }
  direction = deltaAngle <= 0 ? direction : !direction;
  var startPoint = polarToCartesian(cx, cy, radius, labelAngle);
  var endPoint = polarToCartesian(cx, cy, radius, labelAngle + (direction ? 1 : -1) * 359);
  var path = "M".concat(startPoint.x, ",").concat(startPoint.y, "\n    A").concat(radius, ",").concat(radius, ",0,1,").concat(direction ? 0 : 1, ",\n    ").concat(endPoint.x, ",").concat(endPoint.y);
  var id = isNil$1(labelProps.id) ? uniqueId("recharts-radial-line-") : labelProps.id;
  return /* @__PURE__ */ React.createElement("text", _extends$m({}, attrs, {
    dominantBaseline: "central",
    className: clsx("recharts-radial-bar-label", className)
  }), /* @__PURE__ */ React.createElement("defs", null, /* @__PURE__ */ React.createElement("path", {
    id,
    d: path
  })), /* @__PURE__ */ React.createElement("textPath", {
    xlinkHref: "#".concat(id)
  }, label));
};
var getAttrsOfPolarLabel = function getAttrsOfPolarLabel2(props) {
  var viewBox = props.viewBox, offset = props.offset, position = props.position;
  var _ref2 = viewBox, cx = _ref2.cx, cy = _ref2.cy, innerRadius = _ref2.innerRadius, outerRadius = _ref2.outerRadius, startAngle = _ref2.startAngle, endAngle = _ref2.endAngle;
  var midAngle = (startAngle + endAngle) / 2;
  if (position === "outside") {
    var _polarToCartesian = polarToCartesian(cx, cy, outerRadius + offset, midAngle), _x = _polarToCartesian.x, _y = _polarToCartesian.y;
    return {
      x: _x,
      y: _y,
      textAnchor: _x >= cx ? "start" : "end",
      verticalAnchor: "middle"
    };
  }
  if (position === "center") {
    return {
      x: cx,
      y: cy,
      textAnchor: "middle",
      verticalAnchor: "middle"
    };
  }
  if (position === "centerTop") {
    return {
      x: cx,
      y: cy,
      textAnchor: "middle",
      verticalAnchor: "start"
    };
  }
  if (position === "centerBottom") {
    return {
      x: cx,
      y: cy,
      textAnchor: "middle",
      verticalAnchor: "end"
    };
  }
  var r2 = (innerRadius + outerRadius) / 2;
  var _polarToCartesian2 = polarToCartesian(cx, cy, r2, midAngle), x2 = _polarToCartesian2.x, y2 = _polarToCartesian2.y;
  return {
    x: x2,
    y: y2,
    textAnchor: "middle",
    verticalAnchor: "middle"
  };
};
var getAttrsOfCartesianLabel = function getAttrsOfCartesianLabel2(props) {
  var viewBox = props.viewBox, parentViewBox = props.parentViewBox, offset = props.offset, position = props.position;
  var _ref3 = viewBox, x2 = _ref3.x, y2 = _ref3.y, width = _ref3.width, height = _ref3.height;
  var verticalSign = height >= 0 ? 1 : -1;
  var verticalOffset = verticalSign * offset;
  var verticalEnd = verticalSign > 0 ? "end" : "start";
  var verticalStart = verticalSign > 0 ? "start" : "end";
  var horizontalSign = width >= 0 ? 1 : -1;
  var horizontalOffset = horizontalSign * offset;
  var horizontalEnd = horizontalSign > 0 ? "end" : "start";
  var horizontalStart = horizontalSign > 0 ? "start" : "end";
  if (position === "top") {
    var attrs = {
      x: x2 + width / 2,
      y: y2 - verticalSign * offset,
      textAnchor: "middle",
      verticalAnchor: verticalEnd
    };
    return _objectSpread$n(_objectSpread$n({}, attrs), parentViewBox ? {
      height: Math.max(y2 - parentViewBox.y, 0),
      width
    } : {});
  }
  if (position === "bottom") {
    var _attrs = {
      x: x2 + width / 2,
      y: y2 + height + verticalOffset,
      textAnchor: "middle",
      verticalAnchor: verticalStart
    };
    return _objectSpread$n(_objectSpread$n({}, _attrs), parentViewBox ? {
      height: Math.max(parentViewBox.y + parentViewBox.height - (y2 + height), 0),
      width
    } : {});
  }
  if (position === "left") {
    var _attrs2 = {
      x: x2 - horizontalOffset,
      y: y2 + height / 2,
      textAnchor: horizontalEnd,
      verticalAnchor: "middle"
    };
    return _objectSpread$n(_objectSpread$n({}, _attrs2), parentViewBox ? {
      width: Math.max(_attrs2.x - parentViewBox.x, 0),
      height
    } : {});
  }
  if (position === "right") {
    var _attrs3 = {
      x: x2 + width + horizontalOffset,
      y: y2 + height / 2,
      textAnchor: horizontalStart,
      verticalAnchor: "middle"
    };
    return _objectSpread$n(_objectSpread$n({}, _attrs3), parentViewBox ? {
      width: Math.max(parentViewBox.x + parentViewBox.width - _attrs3.x, 0),
      height
    } : {});
  }
  var sizeAttrs = parentViewBox ? {
    width,
    height
  } : {};
  if (position === "insideLeft") {
    return _objectSpread$n({
      x: x2 + horizontalOffset,
      y: y2 + height / 2,
      textAnchor: horizontalStart,
      verticalAnchor: "middle"
    }, sizeAttrs);
  }
  if (position === "insideRight") {
    return _objectSpread$n({
      x: x2 + width - horizontalOffset,
      y: y2 + height / 2,
      textAnchor: horizontalEnd,
      verticalAnchor: "middle"
    }, sizeAttrs);
  }
  if (position === "insideTop") {
    return _objectSpread$n({
      x: x2 + width / 2,
      y: y2 + verticalOffset,
      textAnchor: "middle",
      verticalAnchor: verticalStart
    }, sizeAttrs);
  }
  if (position === "insideBottom") {
    return _objectSpread$n({
      x: x2 + width / 2,
      y: y2 + height - verticalOffset,
      textAnchor: "middle",
      verticalAnchor: verticalEnd
    }, sizeAttrs);
  }
  if (position === "insideTopLeft") {
    return _objectSpread$n({
      x: x2 + horizontalOffset,
      y: y2 + verticalOffset,
      textAnchor: horizontalStart,
      verticalAnchor: verticalStart
    }, sizeAttrs);
  }
  if (position === "insideTopRight") {
    return _objectSpread$n({
      x: x2 + width - horizontalOffset,
      y: y2 + verticalOffset,
      textAnchor: horizontalEnd,
      verticalAnchor: verticalStart
    }, sizeAttrs);
  }
  if (position === "insideBottomLeft") {
    return _objectSpread$n({
      x: x2 + horizontalOffset,
      y: y2 + height - verticalOffset,
      textAnchor: horizontalStart,
      verticalAnchor: verticalEnd
    }, sizeAttrs);
  }
  if (position === "insideBottomRight") {
    return _objectSpread$n({
      x: x2 + width - horizontalOffset,
      y: y2 + height - verticalOffset,
      textAnchor: horizontalEnd,
      verticalAnchor: verticalEnd
    }, sizeAttrs);
  }
  if (isObject$5(position) && (isNumber(position.x) || isPercent(position.x)) && (isNumber(position.y) || isPercent(position.y))) {
    return _objectSpread$n({
      x: x2 + getPercentValue(position.x, width),
      y: y2 + getPercentValue(position.y, height),
      textAnchor: "end",
      verticalAnchor: "end"
    }, sizeAttrs);
  }
  return _objectSpread$n({
    x: x2 + width / 2,
    y: y2 + height / 2,
    textAnchor: "middle",
    verticalAnchor: "middle"
  }, sizeAttrs);
};
var isPolar = function isPolar2(viewBox) {
  return "cx" in viewBox && isNumber(viewBox.cx);
};
function Label$1(_ref4) {
  var _ref4$offset = _ref4.offset, offset = _ref4$offset === void 0 ? 5 : _ref4$offset, restProps = _objectWithoutProperties$a(_ref4, _excluded$a);
  var props = _objectSpread$n({
    offset
  }, restProps);
  var viewBox = props.viewBox, position = props.position, value = props.value, children = props.children, content = props.content, _props$className = props.className, className = _props$className === void 0 ? "" : _props$className, textBreakAll = props.textBreakAll;
  if (!viewBox || isNil$1(value) && isNil$1(children) && !/* @__PURE__ */ reactExports.isValidElement(content) && !isFunction(content)) {
    return null;
  }
  if (/* @__PURE__ */ reactExports.isValidElement(content)) {
    return /* @__PURE__ */ reactExports.cloneElement(content, props);
  }
  var label;
  if (isFunction(content)) {
    label = /* @__PURE__ */ reactExports.createElement(content, props);
    if (/* @__PURE__ */ reactExports.isValidElement(label)) {
      return label;
    }
  } else {
    label = getLabel(props);
  }
  var isPolarLabel = isPolar(viewBox);
  var attrs = filterProps(props, true);
  if (isPolarLabel && (position === "insideStart" || position === "insideEnd" || position === "end")) {
    return renderRadialLabel(props, label, attrs);
  }
  var positionAttrs = isPolarLabel ? getAttrsOfPolarLabel(props) : getAttrsOfCartesianLabel(props);
  return /* @__PURE__ */ React.createElement(Text, _extends$m({
    className: clsx("recharts-label", className)
  }, attrs, positionAttrs, {
    breakAll: textBreakAll
  }), label);
}
Label$1.displayName = "Label";
var parseViewBox = function parseViewBox2(props) {
  var cx = props.cx, cy = props.cy, angle = props.angle, startAngle = props.startAngle, endAngle = props.endAngle, r2 = props.r, radius = props.radius, innerRadius = props.innerRadius, outerRadius = props.outerRadius, x2 = props.x, y2 = props.y, top = props.top, left = props.left, width = props.width, height = props.height, clockWise = props.clockWise, labelViewBox = props.labelViewBox;
  if (labelViewBox) {
    return labelViewBox;
  }
  if (isNumber(width) && isNumber(height)) {
    if (isNumber(x2) && isNumber(y2)) {
      return {
        x: x2,
        y: y2,
        width,
        height
      };
    }
    if (isNumber(top) && isNumber(left)) {
      return {
        x: top,
        y: left,
        width,
        height
      };
    }
  }
  if (isNumber(x2) && isNumber(y2)) {
    return {
      x: x2,
      y: y2,
      width: 0,
      height: 0
    };
  }
  if (isNumber(cx) && isNumber(cy)) {
    return {
      cx,
      cy,
      startAngle: startAngle || angle || 0,
      endAngle: endAngle || angle || 0,
      innerRadius: innerRadius || 0,
      outerRadius: outerRadius || radius || r2 || 0,
      clockWise
    };
  }
  if (props.viewBox) {
    return props.viewBox;
  }
  return {};
};
var parseLabel = function parseLabel2(label, viewBox) {
  if (!label) {
    return null;
  }
  if (label === true) {
    return /* @__PURE__ */ React.createElement(Label$1, {
      key: "label-implicit",
      viewBox
    });
  }
  if (isNumOrStr(label)) {
    return /* @__PURE__ */ React.createElement(Label$1, {
      key: "label-implicit",
      viewBox,
      value: label
    });
  }
  if (/* @__PURE__ */ reactExports.isValidElement(label)) {
    if (label.type === Label$1) {
      return /* @__PURE__ */ reactExports.cloneElement(label, {
        key: "label-implicit",
        viewBox
      });
    }
    return /* @__PURE__ */ React.createElement(Label$1, {
      key: "label-implicit",
      content: label,
      viewBox
    });
  }
  if (isFunction(label)) {
    return /* @__PURE__ */ React.createElement(Label$1, {
      key: "label-implicit",
      content: label,
      viewBox
    });
  }
  if (isObject$5(label)) {
    return /* @__PURE__ */ React.createElement(Label$1, _extends$m({
      viewBox
    }, label, {
      key: "label-implicit"
    }));
  }
  return null;
};
var renderCallByParent$1 = function renderCallByParent2(parentProps, viewBox) {
  var checkPropsLabel = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : true;
  if (!parentProps || !parentProps.children && checkPropsLabel && !parentProps.label) {
    return null;
  }
  var children = parentProps.children;
  var parentViewBox = parseViewBox(parentProps);
  var explicitChildren = findAllByType(children, Label$1).map(function(child, index) {
    return /* @__PURE__ */ reactExports.cloneElement(child, {
      viewBox: viewBox || parentViewBox,
      // eslint-disable-next-line react/no-array-index-key
      key: "label-".concat(index)
    });
  });
  if (!checkPropsLabel) {
    return explicitChildren;
  }
  var implicitLabel = parseLabel(parentProps.label, viewBox || parentViewBox);
  return [implicitLabel].concat(_toConsumableArray$4(explicitChildren));
};
Label$1.parseViewBox = parseViewBox;
Label$1.renderCallByParent = renderCallByParent$1;
function last(array2) {
  var length = array2 == null ? 0 : array2.length;
  return length ? array2[length - 1] : void 0;
}
var last_1 = last;
const last$1 = /* @__PURE__ */ getDefaultExportFromCjs(last_1);
function _typeof$p(o) {
  "@babel/helpers - typeof";
  return _typeof$p = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
    return typeof o2;
  } : function(o2) {
    return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
  }, _typeof$p(o);
}
var _excluded$9 = ["valueAccessor"], _excluded2$4 = ["data", "dataKey", "clockWise", "id", "textBreakAll"];
function _toConsumableArray$3(arr) {
  return _arrayWithoutHoles$3(arr) || _iterableToArray$3(arr) || _unsupportedIterableToArray$6(arr) || _nonIterableSpread$3();
}
function _nonIterableSpread$3() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray$6(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return _arrayLikeToArray$6(o, minLen);
  var n = Object.prototype.toString.call(o).slice(8, -1);
  if (n === "Object" && o.constructor) n = o.constructor.name;
  if (n === "Map" || n === "Set") return Array.from(o);
  if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$6(o, minLen);
}
function _iterableToArray$3(iter) {
  if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _arrayWithoutHoles$3(arr) {
  if (Array.isArray(arr)) return _arrayLikeToArray$6(arr);
}
function _arrayLikeToArray$6(arr, len) {
  if (len == null || len > arr.length) len = arr.length;
  for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  return arr2;
}
function _extends$l() {
  _extends$l = Object.assign ? Object.assign.bind() : function(target2) {
    for (var i = 1; i < arguments.length; i++) {
      var source = arguments[i];
      for (var key2 in source) {
        if (Object.prototype.hasOwnProperty.call(source, key2)) {
          target2[key2] = source[key2];
        }
      }
    }
    return target2;
  };
  return _extends$l.apply(this, arguments);
}
function ownKeys$m(e, r2) {
  var t = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    r2 && (o = o.filter(function(r3) {
      return Object.getOwnPropertyDescriptor(e, r3).enumerable;
    })), t.push.apply(t, o);
  }
  return t;
}
function _objectSpread$m(e) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys$m(Object(t), true).forEach(function(r3) {
      _defineProperty$p(e, r3, t[r3]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$m(Object(t)).forEach(function(r3) {
      Object.defineProperty(e, r3, Object.getOwnPropertyDescriptor(t, r3));
    });
  }
  return e;
}
function _defineProperty$p(obj, key2, value) {
  key2 = _toPropertyKey$p(key2);
  if (key2 in obj) {
    Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key2] = value;
  }
  return obj;
}
function _toPropertyKey$p(t) {
  var i = _toPrimitive$p(t, "string");
  return "symbol" == _typeof$p(i) ? i : i + "";
}
function _toPrimitive$p(t, r2) {
  if ("object" != _typeof$p(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r2);
    if ("object" != _typeof$p(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return ("string" === r2 ? String : Number)(t);
}
function _objectWithoutProperties$9(source, excluded) {
  if (source == null) return {};
  var target2 = _objectWithoutPropertiesLoose$9(source, excluded);
  var key2, i;
  if (Object.getOwnPropertySymbols) {
    var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
    for (i = 0; i < sourceSymbolKeys.length; i++) {
      key2 = sourceSymbolKeys[i];
      if (excluded.indexOf(key2) >= 0) continue;
      if (!Object.prototype.propertyIsEnumerable.call(source, key2)) continue;
      target2[key2] = source[key2];
    }
  }
  return target2;
}
function _objectWithoutPropertiesLoose$9(source, excluded) {
  if (source == null) return {};
  var target2 = {};
  for (var key2 in source) {
    if (Object.prototype.hasOwnProperty.call(source, key2)) {
      if (excluded.indexOf(key2) >= 0) continue;
      target2[key2] = source[key2];
    }
  }
  return target2;
}
var defaultAccessor = function defaultAccessor2(entry) {
  return Array.isArray(entry.value) ? last$1(entry.value) : entry.value;
};
function LabelList(_ref) {
  var _ref$valueAccessor = _ref.valueAccessor, valueAccessor = _ref$valueAccessor === void 0 ? defaultAccessor : _ref$valueAccessor, restProps = _objectWithoutProperties$9(_ref, _excluded$9);
  var data = restProps.data, dataKey = restProps.dataKey, clockWise = restProps.clockWise, id = restProps.id, textBreakAll = restProps.textBreakAll, others = _objectWithoutProperties$9(restProps, _excluded2$4);
  if (!data || !data.length) {
    return null;
  }
  return /* @__PURE__ */ React.createElement(Layer, {
    className: "recharts-label-list"
  }, data.map(function(entry, index) {
    var value = isNil$1(dataKey) ? valueAccessor(entry, index) : getValueByDataKey(entry && entry.payload, dataKey);
    var idProps = isNil$1(id) ? {} : {
      id: "".concat(id, "-").concat(index)
    };
    return /* @__PURE__ */ React.createElement(Label$1, _extends$l({}, filterProps(entry, true), others, idProps, {
      parentViewBox: entry.parentViewBox,
      value,
      textBreakAll,
      viewBox: Label$1.parseViewBox(isNil$1(clockWise) ? entry : _objectSpread$m(_objectSpread$m({}, entry), {}, {
        clockWise
      })),
      key: "label-".concat(index),
      index
    }));
  }));
}
LabelList.displayName = "LabelList";
function parseLabelList(label, data) {
  if (!label) {
    return null;
  }
  if (label === true) {
    return /* @__PURE__ */ React.createElement(LabelList, {
      key: "labelList-implicit",
      data
    });
  }
  if (/* @__PURE__ */ React.isValidElement(label) || isFunction(label)) {
    return /* @__PURE__ */ React.createElement(LabelList, {
      key: "labelList-implicit",
      data,
      content: label
    });
  }
  if (isObject$5(label)) {
    return /* @__PURE__ */ React.createElement(LabelList, _extends$l({
      data
    }, label, {
      key: "labelList-implicit"
    }));
  }
  return null;
}
function renderCallByParent(parentProps, data) {
  var checkPropsLabel = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : true;
  if (!parentProps || !parentProps.children && checkPropsLabel && !parentProps.label) {
    return null;
  }
  var children = parentProps.children;
  var explicitChildren = findAllByType(children, LabelList).map(function(child, index) {
    return /* @__PURE__ */ reactExports.cloneElement(child, {
      data,
      // eslint-disable-next-line react/no-array-index-key
      key: "labelList-".concat(index)
    });
  });
  if (!checkPropsLabel) {
    return explicitChildren;
  }
  var implicitLabelList = parseLabelList(parentProps.label, data);
  return [implicitLabelList].concat(_toConsumableArray$3(explicitChildren));
}
LabelList.renderCallByParent = renderCallByParent;
function _typeof$o(o) {
  "@babel/helpers - typeof";
  return _typeof$o = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
    return typeof o2;
  } : function(o2) {
    return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
  }, _typeof$o(o);
}
function _extends$k() {
  _extends$k = Object.assign ? Object.assign.bind() : function(target2) {
    for (var i = 1; i < arguments.length; i++) {
      var source = arguments[i];
      for (var key2 in source) {
        if (Object.prototype.hasOwnProperty.call(source, key2)) {
          target2[key2] = source[key2];
        }
      }
    }
    return target2;
  };
  return _extends$k.apply(this, arguments);
}
function ownKeys$l(e, r2) {
  var t = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    r2 && (o = o.filter(function(r3) {
      return Object.getOwnPropertyDescriptor(e, r3).enumerable;
    })), t.push.apply(t, o);
  }
  return t;
}
function _objectSpread$l(e) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys$l(Object(t), true).forEach(function(r3) {
      _defineProperty$o(e, r3, t[r3]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$l(Object(t)).forEach(function(r3) {
      Object.defineProperty(e, r3, Object.getOwnPropertyDescriptor(t, r3));
    });
  }
  return e;
}
function _defineProperty$o(obj, key2, value) {
  key2 = _toPropertyKey$o(key2);
  if (key2 in obj) {
    Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key2] = value;
  }
  return obj;
}
function _toPropertyKey$o(t) {
  var i = _toPrimitive$o(t, "string");
  return "symbol" == _typeof$o(i) ? i : i + "";
}
function _toPrimitive$o(t, r2) {
  if ("object" != _typeof$o(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r2);
    if ("object" != _typeof$o(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return ("string" === r2 ? String : Number)(t);
}
var getDeltaAngle = function getDeltaAngle3(startAngle, endAngle) {
  var sign2 = mathSign(endAngle - startAngle);
  var deltaAngle = Math.min(Math.abs(endAngle - startAngle), 359.999);
  return sign2 * deltaAngle;
};
var getTangentCircle = function getTangentCircle2(_ref) {
  var cx = _ref.cx, cy = _ref.cy, radius = _ref.radius, angle = _ref.angle, sign2 = _ref.sign, isExternal = _ref.isExternal, cornerRadius = _ref.cornerRadius, cornerIsExternal = _ref.cornerIsExternal;
  var centerRadius = cornerRadius * (isExternal ? 1 : -1) + radius;
  var theta = Math.asin(cornerRadius / centerRadius) / RADIAN$1;
  var centerAngle = cornerIsExternal ? angle : angle + sign2 * theta;
  var center = polarToCartesian(cx, cy, centerRadius, centerAngle);
  var circleTangency = polarToCartesian(cx, cy, radius, centerAngle);
  var lineTangencyAngle = cornerIsExternal ? angle - sign2 * theta : angle;
  var lineTangency = polarToCartesian(cx, cy, centerRadius * Math.cos(theta * RADIAN$1), lineTangencyAngle);
  return {
    center,
    circleTangency,
    lineTangency,
    theta
  };
};
var getSectorPath = function getSectorPath2(_ref2) {
  var cx = _ref2.cx, cy = _ref2.cy, innerRadius = _ref2.innerRadius, outerRadius = _ref2.outerRadius, startAngle = _ref2.startAngle, endAngle = _ref2.endAngle;
  var angle = getDeltaAngle(startAngle, endAngle);
  var tempEndAngle = startAngle + angle;
  var outerStartPoint = polarToCartesian(cx, cy, outerRadius, startAngle);
  var outerEndPoint = polarToCartesian(cx, cy, outerRadius, tempEndAngle);
  var path = "M ".concat(outerStartPoint.x, ",").concat(outerStartPoint.y, "\n    A ").concat(outerRadius, ",").concat(outerRadius, ",0,\n    ").concat(+(Math.abs(angle) > 180), ",").concat(+(startAngle > tempEndAngle), ",\n    ").concat(outerEndPoint.x, ",").concat(outerEndPoint.y, "\n  ");
  if (innerRadius > 0) {
    var innerStartPoint = polarToCartesian(cx, cy, innerRadius, startAngle);
    var innerEndPoint = polarToCartesian(cx, cy, innerRadius, tempEndAngle);
    path += "L ".concat(innerEndPoint.x, ",").concat(innerEndPoint.y, "\n            A ").concat(innerRadius, ",").concat(innerRadius, ",0,\n            ").concat(+(Math.abs(angle) > 180), ",").concat(+(startAngle <= tempEndAngle), ",\n            ").concat(innerStartPoint.x, ",").concat(innerStartPoint.y, " Z");
  } else {
    path += "L ".concat(cx, ",").concat(cy, " Z");
  }
  return path;
};
var getSectorWithCorner = function getSectorWithCorner2(_ref3) {
  var cx = _ref3.cx, cy = _ref3.cy, innerRadius = _ref3.innerRadius, outerRadius = _ref3.outerRadius, cornerRadius = _ref3.cornerRadius, forceCornerRadius = _ref3.forceCornerRadius, cornerIsExternal = _ref3.cornerIsExternal, startAngle = _ref3.startAngle, endAngle = _ref3.endAngle;
  var sign2 = mathSign(endAngle - startAngle);
  var _getTangentCircle = getTangentCircle({
    cx,
    cy,
    radius: outerRadius,
    angle: startAngle,
    sign: sign2,
    cornerRadius,
    cornerIsExternal
  }), soct = _getTangentCircle.circleTangency, solt = _getTangentCircle.lineTangency, sot = _getTangentCircle.theta;
  var _getTangentCircle2 = getTangentCircle({
    cx,
    cy,
    radius: outerRadius,
    angle: endAngle,
    sign: -sign2,
    cornerRadius,
    cornerIsExternal
  }), eoct = _getTangentCircle2.circleTangency, eolt = _getTangentCircle2.lineTangency, eot = _getTangentCircle2.theta;
  var outerArcAngle = cornerIsExternal ? Math.abs(startAngle - endAngle) : Math.abs(startAngle - endAngle) - sot - eot;
  if (outerArcAngle < 0) {
    if (forceCornerRadius) {
      return "M ".concat(solt.x, ",").concat(solt.y, "\n        a").concat(cornerRadius, ",").concat(cornerRadius, ",0,0,1,").concat(cornerRadius * 2, ",0\n        a").concat(cornerRadius, ",").concat(cornerRadius, ",0,0,1,").concat(-cornerRadius * 2, ",0\n      ");
    }
    return getSectorPath({
      cx,
      cy,
      innerRadius,
      outerRadius,
      startAngle,
      endAngle
    });
  }
  var path = "M ".concat(solt.x, ",").concat(solt.y, "\n    A").concat(cornerRadius, ",").concat(cornerRadius, ",0,0,").concat(+(sign2 < 0), ",").concat(soct.x, ",").concat(soct.y, "\n    A").concat(outerRadius, ",").concat(outerRadius, ",0,").concat(+(outerArcAngle > 180), ",").concat(+(sign2 < 0), ",").concat(eoct.x, ",").concat(eoct.y, "\n    A").concat(cornerRadius, ",").concat(cornerRadius, ",0,0,").concat(+(sign2 < 0), ",").concat(eolt.x, ",").concat(eolt.y, "\n  ");
  if (innerRadius > 0) {
    var _getTangentCircle3 = getTangentCircle({
      cx,
      cy,
      radius: innerRadius,
      angle: startAngle,
      sign: sign2,
      isExternal: true,
      cornerRadius,
      cornerIsExternal
    }), sict = _getTangentCircle3.circleTangency, silt = _getTangentCircle3.lineTangency, sit = _getTangentCircle3.theta;
    var _getTangentCircle4 = getTangentCircle({
      cx,
      cy,
      radius: innerRadius,
      angle: endAngle,
      sign: -sign2,
      isExternal: true,
      cornerRadius,
      cornerIsExternal
    }), eict = _getTangentCircle4.circleTangency, eilt = _getTangentCircle4.lineTangency, eit = _getTangentCircle4.theta;
    var innerArcAngle = cornerIsExternal ? Math.abs(startAngle - endAngle) : Math.abs(startAngle - endAngle) - sit - eit;
    if (innerArcAngle < 0 && cornerRadius === 0) {
      return "".concat(path, "L").concat(cx, ",").concat(cy, "Z");
    }
    path += "L".concat(eilt.x, ",").concat(eilt.y, "\n      A").concat(cornerRadius, ",").concat(cornerRadius, ",0,0,").concat(+(sign2 < 0), ",").concat(eict.x, ",").concat(eict.y, "\n      A").concat(innerRadius, ",").concat(innerRadius, ",0,").concat(+(innerArcAngle > 180), ",").concat(+(sign2 > 0), ",").concat(sict.x, ",").concat(sict.y, "\n      A").concat(cornerRadius, ",").concat(cornerRadius, ",0,0,").concat(+(sign2 < 0), ",").concat(silt.x, ",").concat(silt.y, "Z");
  } else {
    path += "L".concat(cx, ",").concat(cy, "Z");
  }
  return path;
};
var defaultProps$3 = {
  cx: 0,
  cy: 0,
  innerRadius: 0,
  outerRadius: 0,
  startAngle: 0,
  endAngle: 0,
  cornerRadius: 0,
  forceCornerRadius: false,
  cornerIsExternal: false
};
var Sector = function Sector2(sectorProps) {
  var props = _objectSpread$l(_objectSpread$l({}, defaultProps$3), sectorProps);
  var cx = props.cx, cy = props.cy, innerRadius = props.innerRadius, outerRadius = props.outerRadius, cornerRadius = props.cornerRadius, forceCornerRadius = props.forceCornerRadius, cornerIsExternal = props.cornerIsExternal, startAngle = props.startAngle, endAngle = props.endAngle, className = props.className;
  if (outerRadius < innerRadius || startAngle === endAngle) {
    return null;
  }
  var layerClass = clsx("recharts-sector", className);
  var deltaRadius = outerRadius - innerRadius;
  var cr = getPercentValue(cornerRadius, deltaRadius, 0, true);
  var path;
  if (cr > 0 && Math.abs(startAngle - endAngle) < 360) {
    path = getSectorWithCorner({
      cx,
      cy,
      innerRadius,
      outerRadius,
      cornerRadius: Math.min(cr, deltaRadius / 2),
      forceCornerRadius,
      cornerIsExternal,
      startAngle,
      endAngle
    });
  } else {
    path = getSectorPath({
      cx,
      cy,
      innerRadius,
      outerRadius,
      startAngle,
      endAngle
    });
  }
  return /* @__PURE__ */ React.createElement("path", _extends$k({}, filterProps(props, true), {
    className: layerClass,
    d: path,
    role: "img"
  }));
};
function _typeof$n(o) {
  "@babel/helpers - typeof";
  return _typeof$n = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
    return typeof o2;
  } : function(o2) {
    return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
  }, _typeof$n(o);
}
function _extends$j() {
  _extends$j = Object.assign ? Object.assign.bind() : function(target2) {
    for (var i = 1; i < arguments.length; i++) {
      var source = arguments[i];
      for (var key2 in source) {
        if (Object.prototype.hasOwnProperty.call(source, key2)) {
          target2[key2] = source[key2];
        }
      }
    }
    return target2;
  };
  return _extends$j.apply(this, arguments);
}
function ownKeys$k(e, r2) {
  var t = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    r2 && (o = o.filter(function(r3) {
      return Object.getOwnPropertyDescriptor(e, r3).enumerable;
    })), t.push.apply(t, o);
  }
  return t;
}
function _objectSpread$k(e) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys$k(Object(t), true).forEach(function(r3) {
      _defineProperty$n(e, r3, t[r3]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$k(Object(t)).forEach(function(r3) {
      Object.defineProperty(e, r3, Object.getOwnPropertyDescriptor(t, r3));
    });
  }
  return e;
}
function _defineProperty$n(obj, key2, value) {
  key2 = _toPropertyKey$n(key2);
  if (key2 in obj) {
    Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key2] = value;
  }
  return obj;
}
function _toPropertyKey$n(t) {
  var i = _toPrimitive$n(t, "string");
  return "symbol" == _typeof$n(i) ? i : i + "";
}
function _toPrimitive$n(t, r2) {
  if ("object" != _typeof$n(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r2);
    if ("object" != _typeof$n(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return ("string" === r2 ? String : Number)(t);
}
var CURVE_FACTORIES = {
  curveBasisClosed,
  curveBasisOpen,
  curveBasis,
  curveBumpX: bumpX,
  curveBumpY: bumpY,
  curveLinearClosed,
  curveLinear,
  curveMonotoneX: monotoneX,
  curveMonotoneY: monotoneY,
  curveNatural,
  curveStep,
  curveStepAfter: stepAfter,
  curveStepBefore: stepBefore
};
var defined = function defined2(p) {
  return p.x === +p.x && p.y === +p.y;
};
var getX = function getX2(p) {
  return p.x;
};
var getY = function getY2(p) {
  return p.y;
};
var getCurveFactory = function getCurveFactory2(type, layout) {
  if (isFunction(type)) {
    return type;
  }
  var name = "curve".concat(upperFirst$1(type));
  if ((name === "curveMonotone" || name === "curveBump") && layout) {
    return CURVE_FACTORIES["".concat(name).concat(layout === "vertical" ? "Y" : "X")];
  }
  return CURVE_FACTORIES[name] || curveLinear;
};
var getPath$1 = function getPath2(_ref) {
  var _ref$type = _ref.type, type = _ref$type === void 0 ? "linear" : _ref$type, _ref$points = _ref.points, points = _ref$points === void 0 ? [] : _ref$points, baseLine = _ref.baseLine, layout = _ref.layout, _ref$connectNulls = _ref.connectNulls, connectNulls = _ref$connectNulls === void 0 ? false : _ref$connectNulls;
  var curveFactory = getCurveFactory(type, layout);
  var formatPoints = connectNulls ? points.filter(function(entry) {
    return defined(entry);
  }) : points;
  var lineFunction;
  if (Array.isArray(baseLine)) {
    var formatBaseLine = connectNulls ? baseLine.filter(function(base) {
      return defined(base);
    }) : baseLine;
    var areaPoints = formatPoints.map(function(entry, index) {
      return _objectSpread$k(_objectSpread$k({}, entry), {}, {
        base: formatBaseLine[index]
      });
    });
    if (layout === "vertical") {
      lineFunction = shapeArea().y(getY).x1(getX).x0(function(d) {
        return d.base.x;
      });
    } else {
      lineFunction = shapeArea().x(getX).y1(getY).y0(function(d) {
        return d.base.y;
      });
    }
    lineFunction.defined(defined).curve(curveFactory);
    return lineFunction(areaPoints);
  }
  if (layout === "vertical" && isNumber(baseLine)) {
    lineFunction = shapeArea().y(getY).x1(getX).x0(baseLine);
  } else if (isNumber(baseLine)) {
    lineFunction = shapeArea().x(getX).y1(getY).y0(baseLine);
  } else {
    lineFunction = shapeLine().x(getX).y(getY);
  }
  lineFunction.defined(defined).curve(curveFactory);
  return lineFunction(formatPoints);
};
var Curve = function Curve2(props) {
  var className = props.className, points = props.points, path = props.path, pathRef = props.pathRef;
  if ((!points || !points.length) && !path) {
    return null;
  }
  var realPath = points && points.length ? getPath$1(props) : path;
  return /* @__PURE__ */ reactExports.createElement("path", _extends$j({}, filterProps(props, false), adaptEventHandlers(props), {
    className: clsx("recharts-curve", className),
    d: realPath,
    ref: pathRef
  }));
};
function _typeof$m(o) {
  "@babel/helpers - typeof";
  return _typeof$m = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
    return typeof o2;
  } : function(o2) {
    return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
  }, _typeof$m(o);
}
function _extends$i() {
  _extends$i = Object.assign ? Object.assign.bind() : function(target2) {
    for (var i = 1; i < arguments.length; i++) {
      var source = arguments[i];
      for (var key2 in source) {
        if (Object.prototype.hasOwnProperty.call(source, key2)) {
          target2[key2] = source[key2];
        }
      }
    }
    return target2;
  };
  return _extends$i.apply(this, arguments);
}
function _slicedToArray$3(arr, i) {
  return _arrayWithHoles$3(arr) || _iterableToArrayLimit$3(arr, i) || _unsupportedIterableToArray$5(arr, i) || _nonIterableRest$3();
}
function _nonIterableRest$3() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray$5(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return _arrayLikeToArray$5(o, minLen);
  var n = Object.prototype.toString.call(o).slice(8, -1);
  if (n === "Object" && o.constructor) n = o.constructor.name;
  if (n === "Map" || n === "Set") return Array.from(o);
  if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$5(o, minLen);
}
function _arrayLikeToArray$5(arr, len) {
  if (len == null || len > arr.length) len = arr.length;
  for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  return arr2;
}
function _iterableToArrayLimit$3(r2, l) {
  var t = null == r2 ? null : "undefined" != typeof Symbol && r2[Symbol.iterator] || r2["@@iterator"];
  if (null != t) {
    var e, n, i, u, a2 = [], f = true, o = false;
    try {
      if (i = (t = t.call(r2)).next, 0 === l) ;
      else for (; !(f = (e = i.call(t)).done) && (a2.push(e.value), a2.length !== l); f = true) ;
    } catch (r3) {
      o = true, n = r3;
    } finally {
      try {
        if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return;
      } finally {
        if (o) throw n;
      }
    }
    return a2;
  }
}
function _arrayWithHoles$3(arr) {
  if (Array.isArray(arr)) return arr;
}
function ownKeys$j(e, r2) {
  var t = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    r2 && (o = o.filter(function(r3) {
      return Object.getOwnPropertyDescriptor(e, r3).enumerable;
    })), t.push.apply(t, o);
  }
  return t;
}
function _objectSpread$j(e) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys$j(Object(t), true).forEach(function(r3) {
      _defineProperty$m(e, r3, t[r3]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$j(Object(t)).forEach(function(r3) {
      Object.defineProperty(e, r3, Object.getOwnPropertyDescriptor(t, r3));
    });
  }
  return e;
}
function _defineProperty$m(obj, key2, value) {
  key2 = _toPropertyKey$m(key2);
  if (key2 in obj) {
    Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key2] = value;
  }
  return obj;
}
function _toPropertyKey$m(t) {
  var i = _toPrimitive$m(t, "string");
  return "symbol" == _typeof$m(i) ? i : i + "";
}
function _toPrimitive$m(t, r2) {
  if ("object" != _typeof$m(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r2);
    if ("object" != _typeof$m(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return ("string" === r2 ? String : Number)(t);
}
var getRectanglePath = function getRectanglePath2(x2, y2, width, height, radius) {
  var maxRadius = Math.min(Math.abs(width) / 2, Math.abs(height) / 2);
  var ySign = height >= 0 ? 1 : -1;
  var xSign = width >= 0 ? 1 : -1;
  var clockWise = height >= 0 && width >= 0 || height < 0 && width < 0 ? 1 : 0;
  var path;
  if (maxRadius > 0 && radius instanceof Array) {
    var newRadius = [0, 0, 0, 0];
    for (var i = 0, len = 4; i < len; i++) {
      newRadius[i] = radius[i] > maxRadius ? maxRadius : radius[i];
    }
    path = "M".concat(x2, ",").concat(y2 + ySign * newRadius[0]);
    if (newRadius[0] > 0) {
      path += "A ".concat(newRadius[0], ",").concat(newRadius[0], ",0,0,").concat(clockWise, ",").concat(x2 + xSign * newRadius[0], ",").concat(y2);
    }
    path += "L ".concat(x2 + width - xSign * newRadius[1], ",").concat(y2);
    if (newRadius[1] > 0) {
      path += "A ".concat(newRadius[1], ",").concat(newRadius[1], ",0,0,").concat(clockWise, ",\n        ").concat(x2 + width, ",").concat(y2 + ySign * newRadius[1]);
    }
    path += "L ".concat(x2 + width, ",").concat(y2 + height - ySign * newRadius[2]);
    if (newRadius[2] > 0) {
      path += "A ".concat(newRadius[2], ",").concat(newRadius[2], ",0,0,").concat(clockWise, ",\n        ").concat(x2 + width - xSign * newRadius[2], ",").concat(y2 + height);
    }
    path += "L ".concat(x2 + xSign * newRadius[3], ",").concat(y2 + height);
    if (newRadius[3] > 0) {
      path += "A ".concat(newRadius[3], ",").concat(newRadius[3], ",0,0,").concat(clockWise, ",\n        ").concat(x2, ",").concat(y2 + height - ySign * newRadius[3]);
    }
    path += "Z";
  } else if (maxRadius > 0 && radius === +radius && radius > 0) {
    var _newRadius = Math.min(maxRadius, radius);
    path = "M ".concat(x2, ",").concat(y2 + ySign * _newRadius, "\n            A ").concat(_newRadius, ",").concat(_newRadius, ",0,0,").concat(clockWise, ",").concat(x2 + xSign * _newRadius, ",").concat(y2, "\n            L ").concat(x2 + width - xSign * _newRadius, ",").concat(y2, "\n            A ").concat(_newRadius, ",").concat(_newRadius, ",0,0,").concat(clockWise, ",").concat(x2 + width, ",").concat(y2 + ySign * _newRadius, "\n            L ").concat(x2 + width, ",").concat(y2 + height - ySign * _newRadius, "\n            A ").concat(_newRadius, ",").concat(_newRadius, ",0,0,").concat(clockWise, ",").concat(x2 + width - xSign * _newRadius, ",").concat(y2 + height, "\n            L ").concat(x2 + xSign * _newRadius, ",").concat(y2 + height, "\n            A ").concat(_newRadius, ",").concat(_newRadius, ",0,0,").concat(clockWise, ",").concat(x2, ",").concat(y2 + height - ySign * _newRadius, " Z");
  } else {
    path = "M ".concat(x2, ",").concat(y2, " h ").concat(width, " v ").concat(height, " h ").concat(-width, " Z");
  }
  return path;
};
var isInRectangle = function isInRectangle2(point2, rect) {
  if (!point2 || !rect) {
    return false;
  }
  var px = point2.x, py = point2.y;
  var x2 = rect.x, y2 = rect.y, width = rect.width, height = rect.height;
  if (Math.abs(width) > 0 && Math.abs(height) > 0) {
    var minX = Math.min(x2, x2 + width);
    var maxX = Math.max(x2, x2 + width);
    var minY = Math.min(y2, y2 + height);
    var maxY = Math.max(y2, y2 + height);
    return px >= minX && px <= maxX && py >= minY && py <= maxY;
  }
  return false;
};
var defaultProps$2 = {
  x: 0,
  y: 0,
  width: 0,
  height: 0,
  // The radius of border
  // The radius of four corners when radius is a number
  // The radius of left-top, right-top, right-bottom, left-bottom when radius is an array
  radius: 0,
  isAnimationActive: false,
  isUpdateAnimationActive: false,
  animationBegin: 0,
  animationDuration: 1500,
  animationEasing: "ease"
};
var Rectangle = function Rectangle2(rectangleProps) {
  var props = _objectSpread$j(_objectSpread$j({}, defaultProps$2), rectangleProps);
  var pathRef = reactExports.useRef();
  var _useState = reactExports.useState(-1), _useState2 = _slicedToArray$3(_useState, 2), totalLength = _useState2[0], setTotalLength = _useState2[1];
  reactExports.useEffect(function() {
    if (pathRef.current && pathRef.current.getTotalLength) {
      try {
        var pathTotalLength = pathRef.current.getTotalLength();
        if (pathTotalLength) {
          setTotalLength(pathTotalLength);
        }
      } catch (err) {
      }
    }
  }, []);
  var x2 = props.x, y2 = props.y, width = props.width, height = props.height, radius = props.radius, className = props.className;
  var animationEasing = props.animationEasing, animationDuration = props.animationDuration, animationBegin = props.animationBegin, isAnimationActive = props.isAnimationActive, isUpdateAnimationActive = props.isUpdateAnimationActive;
  if (x2 !== +x2 || y2 !== +y2 || width !== +width || height !== +height || width === 0 || height === 0) {
    return null;
  }
  var layerClass = clsx("recharts-rectangle", className);
  if (!isUpdateAnimationActive) {
    return /* @__PURE__ */ React.createElement("path", _extends$i({}, filterProps(props, true), {
      className: layerClass,
      d: getRectanglePath(x2, y2, width, height, radius)
    }));
  }
  return /* @__PURE__ */ React.createElement(Animate, {
    canBegin: totalLength > 0,
    from: {
      width,
      height,
      x: x2,
      y: y2
    },
    to: {
      width,
      height,
      x: x2,
      y: y2
    },
    duration: animationDuration,
    animationEasing,
    isActive: isUpdateAnimationActive
  }, function(_ref) {
    var currWidth = _ref.width, currHeight = _ref.height, currX = _ref.x, currY = _ref.y;
    return /* @__PURE__ */ React.createElement(Animate, {
      canBegin: totalLength > 0,
      from: "0px ".concat(totalLength === -1 ? 1 : totalLength, "px"),
      to: "".concat(totalLength, "px 0px"),
      attributeName: "strokeDasharray",
      begin: animationBegin,
      duration: animationDuration,
      isActive: isAnimationActive,
      easing: animationEasing
    }, /* @__PURE__ */ React.createElement("path", _extends$i({}, filterProps(props, true), {
      className: layerClass,
      d: getRectanglePath(currX, currY, currWidth, currHeight, radius),
      ref: pathRef
    })));
  });
};
var _excluded$8 = ["points", "className", "baseLinePoints", "connectNulls"];
function _extends$h() {
  _extends$h = Object.assign ? Object.assign.bind() : function(target2) {
    for (var i = 1; i < arguments.length; i++) {
      var source = arguments[i];
      for (var key2 in source) {
        if (Object.prototype.hasOwnProperty.call(source, key2)) {
          target2[key2] = source[key2];
        }
      }
    }
    return target2;
  };
  return _extends$h.apply(this, arguments);
}
function _objectWithoutProperties$8(source, excluded) {
  if (source == null) return {};
  var target2 = _objectWithoutPropertiesLoose$8(source, excluded);
  var key2, i;
  if (Object.getOwnPropertySymbols) {
    var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
    for (i = 0; i < sourceSymbolKeys.length; i++) {
      key2 = sourceSymbolKeys[i];
      if (excluded.indexOf(key2) >= 0) continue;
      if (!Object.prototype.propertyIsEnumerable.call(source, key2)) continue;
      target2[key2] = source[key2];
    }
  }
  return target2;
}
function _objectWithoutPropertiesLoose$8(source, excluded) {
  if (source == null) return {};
  var target2 = {};
  for (var key2 in source) {
    if (Object.prototype.hasOwnProperty.call(source, key2)) {
      if (excluded.indexOf(key2) >= 0) continue;
      target2[key2] = source[key2];
    }
  }
  return target2;
}
function _toConsumableArray$2(arr) {
  return _arrayWithoutHoles$2(arr) || _iterableToArray$2(arr) || _unsupportedIterableToArray$4(arr) || _nonIterableSpread$2();
}
function _nonIterableSpread$2() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray$4(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return _arrayLikeToArray$4(o, minLen);
  var n = Object.prototype.toString.call(o).slice(8, -1);
  if (n === "Object" && o.constructor) n = o.constructor.name;
  if (n === "Map" || n === "Set") return Array.from(o);
  if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$4(o, minLen);
}
function _iterableToArray$2(iter) {
  if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _arrayWithoutHoles$2(arr) {
  if (Array.isArray(arr)) return _arrayLikeToArray$4(arr);
}
function _arrayLikeToArray$4(arr, len) {
  if (len == null || len > arr.length) len = arr.length;
  for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  return arr2;
}
var isValidatePoint = function isValidatePoint2(point2) {
  return point2 && point2.x === +point2.x && point2.y === +point2.y;
};
var getParsedPoints = function getParsedPoints2() {
  var points = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : [];
  var segmentPoints = [[]];
  points.forEach(function(entry) {
    if (isValidatePoint(entry)) {
      segmentPoints[segmentPoints.length - 1].push(entry);
    } else if (segmentPoints[segmentPoints.length - 1].length > 0) {
      segmentPoints.push([]);
    }
  });
  if (isValidatePoint(points[0])) {
    segmentPoints[segmentPoints.length - 1].push(points[0]);
  }
  if (segmentPoints[segmentPoints.length - 1].length <= 0) {
    segmentPoints = segmentPoints.slice(0, -1);
  }
  return segmentPoints;
};
var getSinglePolygonPath = function getSinglePolygonPath2(points, connectNulls) {
  var segmentPoints = getParsedPoints(points);
  if (connectNulls) {
    segmentPoints = [segmentPoints.reduce(function(res, segPoints) {
      return [].concat(_toConsumableArray$2(res), _toConsumableArray$2(segPoints));
    }, [])];
  }
  var polygonPath = segmentPoints.map(function(segPoints) {
    return segPoints.reduce(function(path, point2, index) {
      return "".concat(path).concat(index === 0 ? "M" : "L").concat(point2.x, ",").concat(point2.y);
    }, "");
  }).join("");
  return segmentPoints.length === 1 ? "".concat(polygonPath, "Z") : polygonPath;
};
var getRanglePath = function getRanglePath2(points, baseLinePoints, connectNulls) {
  var outerPath = getSinglePolygonPath(points, connectNulls);
  return "".concat(outerPath.slice(-1) === "Z" ? outerPath.slice(0, -1) : outerPath, "L").concat(getSinglePolygonPath(baseLinePoints.reverse(), connectNulls).slice(1));
};
var Polygon = function Polygon2(props) {
  var points = props.points, className = props.className, baseLinePoints = props.baseLinePoints, connectNulls = props.connectNulls, others = _objectWithoutProperties$8(props, _excluded$8);
  if (!points || !points.length) {
    return null;
  }
  var layerClass = clsx("recharts-polygon", className);
  if (baseLinePoints && baseLinePoints.length) {
    var hasStroke = others.stroke && others.stroke !== "none";
    var rangePath = getRanglePath(points, baseLinePoints, connectNulls);
    return /* @__PURE__ */ React.createElement("g", {
      className: layerClass
    }, /* @__PURE__ */ React.createElement("path", _extends$h({}, filterProps(others, true), {
      fill: rangePath.slice(-1) === "Z" ? others.fill : "none",
      stroke: "none",
      d: rangePath
    })), hasStroke ? /* @__PURE__ */ React.createElement("path", _extends$h({}, filterProps(others, true), {
      fill: "none",
      d: getSinglePolygonPath(points, connectNulls)
    })) : null, hasStroke ? /* @__PURE__ */ React.createElement("path", _extends$h({}, filterProps(others, true), {
      fill: "none",
      d: getSinglePolygonPath(baseLinePoints, connectNulls)
    })) : null);
  }
  var singlePath = getSinglePolygonPath(points, connectNulls);
  return /* @__PURE__ */ React.createElement("path", _extends$h({}, filterProps(others, true), {
    fill: singlePath.slice(-1) === "Z" ? others.fill : "none",
    className: layerClass,
    d: singlePath
  }));
};
function _extends$g() {
  _extends$g = Object.assign ? Object.assign.bind() : function(target2) {
    for (var i = 1; i < arguments.length; i++) {
      var source = arguments[i];
      for (var key2 in source) {
        if (Object.prototype.hasOwnProperty.call(source, key2)) {
          target2[key2] = source[key2];
        }
      }
    }
    return target2;
  };
  return _extends$g.apply(this, arguments);
}
var Dot = function Dot2(props) {
  var cx = props.cx, cy = props.cy, r2 = props.r, className = props.className;
  var layerClass = clsx("recharts-dot", className);
  if (cx === +cx && cy === +cy && r2 === +r2) {
    return /* @__PURE__ */ reactExports.createElement("circle", _extends$g({}, filterProps(props, false), adaptEventHandlers(props), {
      className: layerClass,
      cx,
      cy,
      r: r2
    }));
  }
  return null;
};
function _typeof$l(o) {
  "@babel/helpers - typeof";
  return _typeof$l = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
    return typeof o2;
  } : function(o2) {
    return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
  }, _typeof$l(o);
}
var _excluded$7 = ["x", "y", "top", "left", "width", "height", "className"];
function _extends$f() {
  _extends$f = Object.assign ? Object.assign.bind() : function(target2) {
    for (var i = 1; i < arguments.length; i++) {
      var source = arguments[i];
      for (var key2 in source) {
        if (Object.prototype.hasOwnProperty.call(source, key2)) {
          target2[key2] = source[key2];
        }
      }
    }
    return target2;
  };
  return _extends$f.apply(this, arguments);
}
function ownKeys$i(e, r2) {
  var t = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    r2 && (o = o.filter(function(r3) {
      return Object.getOwnPropertyDescriptor(e, r3).enumerable;
    })), t.push.apply(t, o);
  }
  return t;
}
function _objectSpread$i(e) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys$i(Object(t), true).forEach(function(r3) {
      _defineProperty$l(e, r3, t[r3]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$i(Object(t)).forEach(function(r3) {
      Object.defineProperty(e, r3, Object.getOwnPropertyDescriptor(t, r3));
    });
  }
  return e;
}
function _defineProperty$l(obj, key2, value) {
  key2 = _toPropertyKey$l(key2);
  if (key2 in obj) {
    Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key2] = value;
  }
  return obj;
}
function _toPropertyKey$l(t) {
  var i = _toPrimitive$l(t, "string");
  return "symbol" == _typeof$l(i) ? i : i + "";
}
function _toPrimitive$l(t, r2) {
  if ("object" != _typeof$l(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r2);
    if ("object" != _typeof$l(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return ("string" === r2 ? String : Number)(t);
}
function _objectWithoutProperties$7(source, excluded) {
  if (source == null) return {};
  var target2 = _objectWithoutPropertiesLoose$7(source, excluded);
  var key2, i;
  if (Object.getOwnPropertySymbols) {
    var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
    for (i = 0; i < sourceSymbolKeys.length; i++) {
      key2 = sourceSymbolKeys[i];
      if (excluded.indexOf(key2) >= 0) continue;
      if (!Object.prototype.propertyIsEnumerable.call(source, key2)) continue;
      target2[key2] = source[key2];
    }
  }
  return target2;
}
function _objectWithoutPropertiesLoose$7(source, excluded) {
  if (source == null) return {};
  var target2 = {};
  for (var key2 in source) {
    if (Object.prototype.hasOwnProperty.call(source, key2)) {
      if (excluded.indexOf(key2) >= 0) continue;
      target2[key2] = source[key2];
    }
  }
  return target2;
}
var getPath = function getPath3(x2, y2, width, height, top, left) {
  return "M".concat(x2, ",").concat(top, "v").concat(height, "M").concat(left, ",").concat(y2, "h").concat(width);
};
var Cross = function Cross2(_ref) {
  var _ref$x = _ref.x, x2 = _ref$x === void 0 ? 0 : _ref$x, _ref$y = _ref.y, y2 = _ref$y === void 0 ? 0 : _ref$y, _ref$top = _ref.top, top = _ref$top === void 0 ? 0 : _ref$top, _ref$left = _ref.left, left = _ref$left === void 0 ? 0 : _ref$left, _ref$width = _ref.width, width = _ref$width === void 0 ? 0 : _ref$width, _ref$height = _ref.height, height = _ref$height === void 0 ? 0 : _ref$height, className = _ref.className, rest = _objectWithoutProperties$7(_ref, _excluded$7);
  var props = _objectSpread$i({
    x: x2,
    y: y2,
    top,
    left,
    width,
    height
  }, rest);
  if (!isNumber(x2) || !isNumber(y2) || !isNumber(width) || !isNumber(height) || !isNumber(top) || !isNumber(left)) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("path", _extends$f({}, filterProps(props, true), {
    className: clsx("recharts-cross", className),
    d: getPath(x2, y2, width, height, top, left)
  }));
};
var baseExtremum$1 = _baseExtremum, baseGt = _baseGt, baseIteratee$6 = _baseIteratee;
function maxBy(array2, iteratee) {
  return array2 && array2.length ? baseExtremum$1(array2, baseIteratee$6(iteratee), baseGt) : void 0;
}
var maxBy_1 = maxBy;
const maxBy$1 = /* @__PURE__ */ getDefaultExportFromCjs(maxBy_1);
var baseExtremum = _baseExtremum, baseIteratee$5 = _baseIteratee, baseLt = _baseLt;
function minBy(array2, iteratee) {
  return array2 && array2.length ? baseExtremum(array2, baseIteratee$5(iteratee), baseLt) : void 0;
}
var minBy_1 = minBy;
const minBy$1 = /* @__PURE__ */ getDefaultExportFromCjs(minBy_1);
var _excluded$6 = ["cx", "cy", "angle", "ticks", "axisLine"], _excluded2$3 = ["ticks", "tick", "angle", "tickFormatter", "stroke"];
function _typeof$k(o) {
  "@babel/helpers - typeof";
  return _typeof$k = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
    return typeof o2;
  } : function(o2) {
    return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
  }, _typeof$k(o);
}
function _extends$e() {
  _extends$e = Object.assign ? Object.assign.bind() : function(target2) {
    for (var i = 1; i < arguments.length; i++) {
      var source = arguments[i];
      for (var key2 in source) {
        if (Object.prototype.hasOwnProperty.call(source, key2)) {
          target2[key2] = source[key2];
        }
      }
    }
    return target2;
  };
  return _extends$e.apply(this, arguments);
}
function ownKeys$h(e, r2) {
  var t = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    r2 && (o = o.filter(function(r3) {
      return Object.getOwnPropertyDescriptor(e, r3).enumerable;
    })), t.push.apply(t, o);
  }
  return t;
}
function _objectSpread$h(e) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys$h(Object(t), true).forEach(function(r3) {
      _defineProperty$k(e, r3, t[r3]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$h(Object(t)).forEach(function(r3) {
      Object.defineProperty(e, r3, Object.getOwnPropertyDescriptor(t, r3));
    });
  }
  return e;
}
function _objectWithoutProperties$6(source, excluded) {
  if (source == null) return {};
  var target2 = _objectWithoutPropertiesLoose$6(source, excluded);
  var key2, i;
  if (Object.getOwnPropertySymbols) {
    var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
    for (i = 0; i < sourceSymbolKeys.length; i++) {
      key2 = sourceSymbolKeys[i];
      if (excluded.indexOf(key2) >= 0) continue;
      if (!Object.prototype.propertyIsEnumerable.call(source, key2)) continue;
      target2[key2] = source[key2];
    }
  }
  return target2;
}
function _objectWithoutPropertiesLoose$6(source, excluded) {
  if (source == null) return {};
  var target2 = {};
  for (var key2 in source) {
    if (Object.prototype.hasOwnProperty.call(source, key2)) {
      if (excluded.indexOf(key2) >= 0) continue;
      target2[key2] = source[key2];
    }
  }
  return target2;
}
function _classCallCheck$d(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function _defineProperties$d(target2, props) {
  for (var i = 0; i < props.length; i++) {
    var descriptor = props[i];
    descriptor.enumerable = descriptor.enumerable || false;
    descriptor.configurable = true;
    if ("value" in descriptor) descriptor.writable = true;
    Object.defineProperty(target2, _toPropertyKey$k(descriptor.key), descriptor);
  }
}
function _createClass$d(Constructor, protoProps, staticProps) {
  if (protoProps) _defineProperties$d(Constructor.prototype, protoProps);
  if (staticProps) _defineProperties$d(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", { writable: false });
  return Constructor;
}
function _callSuper$b(t, o, e) {
  return o = _getPrototypeOf$b(o), _possibleConstructorReturn$b(t, _isNativeReflectConstruct$b() ? Reflect.construct(o, e || [], _getPrototypeOf$b(t).constructor) : o.apply(t, e));
}
function _possibleConstructorReturn$b(self, call) {
  if (call && (_typeof$k(call) === "object" || typeof call === "function")) {
    return call;
  } else if (call !== void 0) {
    throw new TypeError("Derived constructors may only return object or undefined");
  }
  return _assertThisInitialized$b(self);
}
function _assertThisInitialized$b(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function _isNativeReflectConstruct$b() {
  try {
    var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {
    }));
  } catch (t2) {
  }
  return (_isNativeReflectConstruct$b = function _isNativeReflectConstruct2() {
    return !!t;
  })();
}
function _getPrototypeOf$b(o) {
  _getPrototypeOf$b = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf2(o2) {
    return o2.__proto__ || Object.getPrototypeOf(o2);
  };
  return _getPrototypeOf$b(o);
}
function _inherits$b(subClass, superClass) {
  if (typeof superClass !== "function" && superClass !== null) {
    throw new TypeError("Super expression must either be null or a function");
  }
  subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } });
  Object.defineProperty(subClass, "prototype", { writable: false });
  if (superClass) _setPrototypeOf$b(subClass, superClass);
}
function _setPrototypeOf$b(o, p) {
  _setPrototypeOf$b = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf2(o2, p2) {
    o2.__proto__ = p2;
    return o2;
  };
  return _setPrototypeOf$b(o, p);
}
function _defineProperty$k(obj, key2, value) {
  key2 = _toPropertyKey$k(key2);
  if (key2 in obj) {
    Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key2] = value;
  }
  return obj;
}
function _toPropertyKey$k(t) {
  var i = _toPrimitive$k(t, "string");
  return "symbol" == _typeof$k(i) ? i : i + "";
}
function _toPrimitive$k(t, r2) {
  if ("object" != _typeof$k(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r2);
    if ("object" != _typeof$k(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return ("string" === r2 ? String : Number)(t);
}
var PolarRadiusAxis = /* @__PURE__ */ function(_PureComponent) {
  function PolarRadiusAxis2() {
    _classCallCheck$d(this, PolarRadiusAxis2);
    return _callSuper$b(this, PolarRadiusAxis2, arguments);
  }
  _inherits$b(PolarRadiusAxis2, _PureComponent);
  return _createClass$d(PolarRadiusAxis2, [{
    key: "getTickValueCoord",
    value: (
      /**
       * Calculate the coordinate of tick
       * @param  {Number} coordinate The radius of tick
       * @return {Object} (x, y)
       */
      function getTickValueCoord(_ref) {
        var coordinate = _ref.coordinate;
        var _this$props = this.props, angle = _this$props.angle, cx = _this$props.cx, cy = _this$props.cy;
        return polarToCartesian(cx, cy, coordinate, angle);
      }
    )
  }, {
    key: "getTickTextAnchor",
    value: function getTickTextAnchor() {
      var orientation = this.props.orientation;
      var textAnchor;
      switch (orientation) {
        case "left":
          textAnchor = "end";
          break;
        case "right":
          textAnchor = "start";
          break;
        default:
          textAnchor = "middle";
          break;
      }
      return textAnchor;
    }
  }, {
    key: "getViewBox",
    value: function getViewBox() {
      var _this$props2 = this.props, cx = _this$props2.cx, cy = _this$props2.cy, angle = _this$props2.angle, ticks2 = _this$props2.ticks;
      var maxRadiusTick = maxBy$1(ticks2, function(entry) {
        return entry.coordinate || 0;
      });
      var minRadiusTick = minBy$1(ticks2, function(entry) {
        return entry.coordinate || 0;
      });
      return {
        cx,
        cy,
        startAngle: angle,
        endAngle: angle,
        innerRadius: minRadiusTick.coordinate || 0,
        outerRadius: maxRadiusTick.coordinate || 0
      };
    }
  }, {
    key: "renderAxisLine",
    value: function renderAxisLine() {
      var _this$props3 = this.props, cx = _this$props3.cx, cy = _this$props3.cy, angle = _this$props3.angle, ticks2 = _this$props3.ticks, axisLine = _this$props3.axisLine, others = _objectWithoutProperties$6(_this$props3, _excluded$6);
      var extent = ticks2.reduce(function(result, entry) {
        return [Math.min(result[0], entry.coordinate), Math.max(result[1], entry.coordinate)];
      }, [Infinity, -Infinity]);
      var point0 = polarToCartesian(cx, cy, extent[0], angle);
      var point1 = polarToCartesian(cx, cy, extent[1], angle);
      var props = _objectSpread$h(_objectSpread$h(_objectSpread$h({}, filterProps(others, false)), {}, {
        fill: "none"
      }, filterProps(axisLine, false)), {}, {
        x1: point0.x,
        y1: point0.y,
        x2: point1.x,
        y2: point1.y
      });
      return /* @__PURE__ */ React.createElement("line", _extends$e({
        className: "recharts-polar-radius-axis-line"
      }, props));
    }
  }, {
    key: "renderTicks",
    value: function renderTicks() {
      var _this = this;
      var _this$props4 = this.props, ticks2 = _this$props4.ticks, tick = _this$props4.tick, angle = _this$props4.angle, tickFormatter = _this$props4.tickFormatter, stroke = _this$props4.stroke, others = _objectWithoutProperties$6(_this$props4, _excluded2$3);
      var textAnchor = this.getTickTextAnchor();
      var axisProps = filterProps(others, false);
      var customTickProps = filterProps(tick, false);
      var items = ticks2.map(function(entry, i) {
        var coord = _this.getTickValueCoord(entry);
        var tickProps = _objectSpread$h(_objectSpread$h(_objectSpread$h(_objectSpread$h({
          textAnchor,
          transform: "rotate(".concat(90 - angle, ", ").concat(coord.x, ", ").concat(coord.y, ")")
        }, axisProps), {}, {
          stroke: "none",
          fill: stroke
        }, customTickProps), {}, {
          index: i
        }, coord), {}, {
          payload: entry
        });
        return /* @__PURE__ */ React.createElement(Layer, _extends$e({
          className: clsx("recharts-polar-radius-axis-tick", getTickClassName(tick)),
          key: "tick-".concat(entry.coordinate)
        }, adaptEventsOfChild(_this.props, entry, i)), PolarRadiusAxis2.renderTickItem(tick, tickProps, tickFormatter ? tickFormatter(entry.value, i) : entry.value));
      });
      return /* @__PURE__ */ React.createElement(Layer, {
        className: "recharts-polar-radius-axis-ticks"
      }, items);
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props5 = this.props, ticks2 = _this$props5.ticks, axisLine = _this$props5.axisLine, tick = _this$props5.tick;
      if (!ticks2 || !ticks2.length) {
        return null;
      }
      return /* @__PURE__ */ React.createElement(Layer, {
        className: clsx("recharts-polar-radius-axis", this.props.className)
      }, axisLine && this.renderAxisLine(), tick && this.renderTicks(), Label$1.renderCallByParent(this.props, this.getViewBox()));
    }
  }], [{
    key: "renderTickItem",
    value: function renderTickItem(option, props, value) {
      var tickItem;
      if (/* @__PURE__ */ React.isValidElement(option)) {
        tickItem = /* @__PURE__ */ React.cloneElement(option, props);
      } else if (isFunction(option)) {
        tickItem = option(props);
      } else {
        tickItem = /* @__PURE__ */ React.createElement(Text, _extends$e({}, props, {
          className: "recharts-polar-radius-axis-tick-value"
        }), value);
      }
      return tickItem;
    }
  }]);
}(reactExports.PureComponent);
_defineProperty$k(PolarRadiusAxis, "displayName", "PolarRadiusAxis");
_defineProperty$k(PolarRadiusAxis, "axisType", "radiusAxis");
_defineProperty$k(PolarRadiusAxis, "defaultProps", {
  type: "number",
  radiusAxisId: 0,
  cx: 0,
  cy: 0,
  angle: 0,
  orientation: "right",
  stroke: "#ccc",
  axisLine: true,
  tick: true,
  tickCount: 5,
  allowDataOverflow: false,
  scale: "auto",
  allowDuplicatedCategory: true
});
function _typeof$j(o) {
  "@babel/helpers - typeof";
  return _typeof$j = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
    return typeof o2;
  } : function(o2) {
    return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
  }, _typeof$j(o);
}
function _extends$d() {
  _extends$d = Object.assign ? Object.assign.bind() : function(target2) {
    for (var i = 1; i < arguments.length; i++) {
      var source = arguments[i];
      for (var key2 in source) {
        if (Object.prototype.hasOwnProperty.call(source, key2)) {
          target2[key2] = source[key2];
        }
      }
    }
    return target2;
  };
  return _extends$d.apply(this, arguments);
}
function ownKeys$g(e, r2) {
  var t = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    r2 && (o = o.filter(function(r3) {
      return Object.getOwnPropertyDescriptor(e, r3).enumerable;
    })), t.push.apply(t, o);
  }
  return t;
}
function _objectSpread$g(e) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys$g(Object(t), true).forEach(function(r3) {
      _defineProperty$j(e, r3, t[r3]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$g(Object(t)).forEach(function(r3) {
      Object.defineProperty(e, r3, Object.getOwnPropertyDescriptor(t, r3));
    });
  }
  return e;
}
function _classCallCheck$c(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function _defineProperties$c(target2, props) {
  for (var i = 0; i < props.length; i++) {
    var descriptor = props[i];
    descriptor.enumerable = descriptor.enumerable || false;
    descriptor.configurable = true;
    if ("value" in descriptor) descriptor.writable = true;
    Object.defineProperty(target2, _toPropertyKey$j(descriptor.key), descriptor);
  }
}
function _createClass$c(Constructor, protoProps, staticProps) {
  if (protoProps) _defineProperties$c(Constructor.prototype, protoProps);
  if (staticProps) _defineProperties$c(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", { writable: false });
  return Constructor;
}
function _callSuper$a(t, o, e) {
  return o = _getPrototypeOf$a(o), _possibleConstructorReturn$a(t, _isNativeReflectConstruct$a() ? Reflect.construct(o, e || [], _getPrototypeOf$a(t).constructor) : o.apply(t, e));
}
function _possibleConstructorReturn$a(self, call) {
  if (call && (_typeof$j(call) === "object" || typeof call === "function")) {
    return call;
  } else if (call !== void 0) {
    throw new TypeError("Derived constructors may only return object or undefined");
  }
  return _assertThisInitialized$a(self);
}
function _assertThisInitialized$a(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function _isNativeReflectConstruct$a() {
  try {
    var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {
    }));
  } catch (t2) {
  }
  return (_isNativeReflectConstruct$a = function _isNativeReflectConstruct2() {
    return !!t;
  })();
}
function _getPrototypeOf$a(o) {
  _getPrototypeOf$a = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf2(o2) {
    return o2.__proto__ || Object.getPrototypeOf(o2);
  };
  return _getPrototypeOf$a(o);
}
function _inherits$a(subClass, superClass) {
  if (typeof superClass !== "function" && superClass !== null) {
    throw new TypeError("Super expression must either be null or a function");
  }
  subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } });
  Object.defineProperty(subClass, "prototype", { writable: false });
  if (superClass) _setPrototypeOf$a(subClass, superClass);
}
function _setPrototypeOf$a(o, p) {
  _setPrototypeOf$a = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf2(o2, p2) {
    o2.__proto__ = p2;
    return o2;
  };
  return _setPrototypeOf$a(o, p);
}
function _defineProperty$j(obj, key2, value) {
  key2 = _toPropertyKey$j(key2);
  if (key2 in obj) {
    Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key2] = value;
  }
  return obj;
}
function _toPropertyKey$j(t) {
  var i = _toPrimitive$j(t, "string");
  return "symbol" == _typeof$j(i) ? i : i + "";
}
function _toPrimitive$j(t, r2) {
  if ("object" != _typeof$j(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r2);
    if ("object" != _typeof$j(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return ("string" === r2 ? String : Number)(t);
}
var RADIAN = Math.PI / 180;
var eps = 1e-5;
var PolarAngleAxis = /* @__PURE__ */ function(_PureComponent) {
  function PolarAngleAxis2() {
    _classCallCheck$c(this, PolarAngleAxis2);
    return _callSuper$a(this, PolarAngleAxis2, arguments);
  }
  _inherits$a(PolarAngleAxis2, _PureComponent);
  return _createClass$c(PolarAngleAxis2, [{
    key: "getTickLineCoord",
    value: (
      /**
       * Calculate the coordinate of line endpoint
       * @param  {Object} data The Data if ticks
       * @return {Object} (x0, y0): The start point of text,
       *                  (x1, y1): The end point close to text,
       *                  (x2, y2): The end point close to axis
       */
      function getTickLineCoord(data) {
        var _this$props = this.props, cx = _this$props.cx, cy = _this$props.cy, radius = _this$props.radius, orientation = _this$props.orientation, tickSize = _this$props.tickSize;
        var tickLineSize = tickSize || 8;
        var p1 = polarToCartesian(cx, cy, radius, data.coordinate);
        var p2 = polarToCartesian(cx, cy, radius + (orientation === "inner" ? -1 : 1) * tickLineSize, data.coordinate);
        return {
          x1: p1.x,
          y1: p1.y,
          x2: p2.x,
          y2: p2.y
        };
      }
    )
    /**
     * Get the text-anchor of each tick
     * @param  {Object} data Data of ticks
     * @return {String} text-anchor
     */
  }, {
    key: "getTickTextAnchor",
    value: function getTickTextAnchor(data) {
      var orientation = this.props.orientation;
      var cos2 = Math.cos(-data.coordinate * RADIAN);
      var textAnchor;
      if (cos2 > eps) {
        textAnchor = orientation === "outer" ? "start" : "end";
      } else if (cos2 < -eps) {
        textAnchor = orientation === "outer" ? "end" : "start";
      } else {
        textAnchor = "middle";
      }
      return textAnchor;
    }
  }, {
    key: "renderAxisLine",
    value: function renderAxisLine() {
      var _this$props2 = this.props, cx = _this$props2.cx, cy = _this$props2.cy, radius = _this$props2.radius, axisLine = _this$props2.axisLine, axisLineType = _this$props2.axisLineType;
      var props = _objectSpread$g(_objectSpread$g({}, filterProps(this.props, false)), {}, {
        fill: "none"
      }, filterProps(axisLine, false));
      if (axisLineType === "circle") {
        return /* @__PURE__ */ React.createElement(Dot, _extends$d({
          className: "recharts-polar-angle-axis-line"
        }, props, {
          cx,
          cy,
          r: radius
        }));
      }
      var ticks2 = this.props.ticks;
      var points = ticks2.map(function(entry) {
        return polarToCartesian(cx, cy, radius, entry.coordinate);
      });
      return /* @__PURE__ */ React.createElement(Polygon, _extends$d({
        className: "recharts-polar-angle-axis-line"
      }, props, {
        points
      }));
    }
  }, {
    key: "renderTicks",
    value: function renderTicks() {
      var _this = this;
      var _this$props3 = this.props, ticks2 = _this$props3.ticks, tick = _this$props3.tick, tickLine = _this$props3.tickLine, tickFormatter = _this$props3.tickFormatter, stroke = _this$props3.stroke;
      var axisProps = filterProps(this.props, false);
      var customTickProps = filterProps(tick, false);
      var tickLineProps = _objectSpread$g(_objectSpread$g({}, axisProps), {}, {
        fill: "none"
      }, filterProps(tickLine, false));
      var items = ticks2.map(function(entry, i) {
        var lineCoord = _this.getTickLineCoord(entry);
        var textAnchor = _this.getTickTextAnchor(entry);
        var tickProps = _objectSpread$g(_objectSpread$g(_objectSpread$g({
          textAnchor
        }, axisProps), {}, {
          stroke: "none",
          fill: stroke
        }, customTickProps), {}, {
          index: i,
          payload: entry,
          x: lineCoord.x2,
          y: lineCoord.y2
        });
        return /* @__PURE__ */ React.createElement(Layer, _extends$d({
          className: clsx("recharts-polar-angle-axis-tick", getTickClassName(tick)),
          key: "tick-".concat(entry.coordinate)
        }, adaptEventsOfChild(_this.props, entry, i)), tickLine && /* @__PURE__ */ React.createElement("line", _extends$d({
          className: "recharts-polar-angle-axis-tick-line"
        }, tickLineProps, lineCoord)), tick && PolarAngleAxis2.renderTickItem(tick, tickProps, tickFormatter ? tickFormatter(entry.value, i) : entry.value));
      });
      return /* @__PURE__ */ React.createElement(Layer, {
        className: "recharts-polar-angle-axis-ticks"
      }, items);
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props4 = this.props, ticks2 = _this$props4.ticks, radius = _this$props4.radius, axisLine = _this$props4.axisLine;
      if (radius <= 0 || !ticks2 || !ticks2.length) {
        return null;
      }
      return /* @__PURE__ */ React.createElement(Layer, {
        className: clsx("recharts-polar-angle-axis", this.props.className)
      }, axisLine && this.renderAxisLine(), this.renderTicks());
    }
  }], [{
    key: "renderTickItem",
    value: function renderTickItem(option, props, value) {
      var tickItem;
      if (/* @__PURE__ */ React.isValidElement(option)) {
        tickItem = /* @__PURE__ */ React.cloneElement(option, props);
      } else if (isFunction(option)) {
        tickItem = option(props);
      } else {
        tickItem = /* @__PURE__ */ React.createElement(Text, _extends$d({}, props, {
          className: "recharts-polar-angle-axis-tick-value"
        }), value);
      }
      return tickItem;
    }
  }]);
}(reactExports.PureComponent);
_defineProperty$j(PolarAngleAxis, "displayName", "PolarAngleAxis");
_defineProperty$j(PolarAngleAxis, "axisType", "angleAxis");
_defineProperty$j(PolarAngleAxis, "defaultProps", {
  type: "category",
  angleAxisId: 0,
  scale: "auto",
  cx: 0,
  cy: 0,
  orientation: "outer",
  axisLine: true,
  tickLine: true,
  tickSize: 8,
  tick: true,
  hide: false,
  allowDuplicatedCategory: true
});
var overArg = _overArg;
var getPrototype$1 = overArg(Object.getPrototypeOf, Object);
var _getPrototype = getPrototype$1;
var baseGetTag$1 = _baseGetTag, getPrototype = _getPrototype, isObjectLike$1 = isObjectLike_1;
var objectTag = "[object Object]";
var funcProto = Function.prototype, objectProto = Object.prototype;
var funcToString = funcProto.toString;
var hasOwnProperty = objectProto.hasOwnProperty;
var objectCtorString = funcToString.call(Object);
function isPlainObject(value) {
  if (!isObjectLike$1(value) || baseGetTag$1(value) != objectTag) {
    return false;
  }
  var proto = getPrototype(value);
  if (proto === null) {
    return true;
  }
  var Ctor = hasOwnProperty.call(proto, "constructor") && proto.constructor;
  return typeof Ctor == "function" && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString;
}
var isPlainObject_1 = isPlainObject;
const isPlainObject$1 = /* @__PURE__ */ getDefaultExportFromCjs(isPlainObject_1);
var baseGetTag = _baseGetTag, isObjectLike = isObjectLike_1;
var boolTag = "[object Boolean]";
function isBoolean(value) {
  return value === true || value === false || isObjectLike(value) && baseGetTag(value) == boolTag;
}
var isBoolean_1 = isBoolean;
const isBoolean$1 = /* @__PURE__ */ getDefaultExportFromCjs(isBoolean_1);
function _typeof$i(o) {
  "@babel/helpers - typeof";
  return _typeof$i = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
    return typeof o2;
  } : function(o2) {
    return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
  }, _typeof$i(o);
}
function _extends$c() {
  _extends$c = Object.assign ? Object.assign.bind() : function(target2) {
    for (var i = 1; i < arguments.length; i++) {
      var source = arguments[i];
      for (var key2 in source) {
        if (Object.prototype.hasOwnProperty.call(source, key2)) {
          target2[key2] = source[key2];
        }
      }
    }
    return target2;
  };
  return _extends$c.apply(this, arguments);
}
function _slicedToArray$2(arr, i) {
  return _arrayWithHoles$2(arr) || _iterableToArrayLimit$2(arr, i) || _unsupportedIterableToArray$3(arr, i) || _nonIterableRest$2();
}
function _nonIterableRest$2() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray$3(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return _arrayLikeToArray$3(o, minLen);
  var n = Object.prototype.toString.call(o).slice(8, -1);
  if (n === "Object" && o.constructor) n = o.constructor.name;
  if (n === "Map" || n === "Set") return Array.from(o);
  if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$3(o, minLen);
}
function _arrayLikeToArray$3(arr, len) {
  if (len == null || len > arr.length) len = arr.length;
  for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  return arr2;
}
function _iterableToArrayLimit$2(r2, l) {
  var t = null == r2 ? null : "undefined" != typeof Symbol && r2[Symbol.iterator] || r2["@@iterator"];
  if (null != t) {
    var e, n, i, u, a2 = [], f = true, o = false;
    try {
      if (i = (t = t.call(r2)).next, 0 === l) ;
      else for (; !(f = (e = i.call(t)).done) && (a2.push(e.value), a2.length !== l); f = true) ;
    } catch (r3) {
      o = true, n = r3;
    } finally {
      try {
        if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return;
      } finally {
        if (o) throw n;
      }
    }
    return a2;
  }
}
function _arrayWithHoles$2(arr) {
  if (Array.isArray(arr)) return arr;
}
function ownKeys$f(e, r2) {
  var t = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    r2 && (o = o.filter(function(r3) {
      return Object.getOwnPropertyDescriptor(e, r3).enumerable;
    })), t.push.apply(t, o);
  }
  return t;
}
function _objectSpread$f(e) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys$f(Object(t), true).forEach(function(r3) {
      _defineProperty$i(e, r3, t[r3]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$f(Object(t)).forEach(function(r3) {
      Object.defineProperty(e, r3, Object.getOwnPropertyDescriptor(t, r3));
    });
  }
  return e;
}
function _defineProperty$i(obj, key2, value) {
  key2 = _toPropertyKey$i(key2);
  if (key2 in obj) {
    Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key2] = value;
  }
  return obj;
}
function _toPropertyKey$i(t) {
  var i = _toPrimitive$i(t, "string");
  return "symbol" == _typeof$i(i) ? i : i + "";
}
function _toPrimitive$i(t, r2) {
  if ("object" != _typeof$i(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r2);
    if ("object" != _typeof$i(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return ("string" === r2 ? String : Number)(t);
}
var getTrapezoidPath = function getTrapezoidPath2(x2, y2, upperWidth, lowerWidth, height) {
  var widthGap = upperWidth - lowerWidth;
  var path;
  path = "M ".concat(x2, ",").concat(y2);
  path += "L ".concat(x2 + upperWidth, ",").concat(y2);
  path += "L ".concat(x2 + upperWidth - widthGap / 2, ",").concat(y2 + height);
  path += "L ".concat(x2 + upperWidth - widthGap / 2 - lowerWidth, ",").concat(y2 + height);
  path += "L ".concat(x2, ",").concat(y2, " Z");
  return path;
};
var defaultProps$1 = {
  x: 0,
  y: 0,
  upperWidth: 0,
  lowerWidth: 0,
  height: 0,
  isUpdateAnimationActive: false,
  animationBegin: 0,
  animationDuration: 1500,
  animationEasing: "ease"
};
var Trapezoid = function Trapezoid2(props) {
  var trapezoidProps = _objectSpread$f(_objectSpread$f({}, defaultProps$1), props);
  var pathRef = reactExports.useRef();
  var _useState = reactExports.useState(-1), _useState2 = _slicedToArray$2(_useState, 2), totalLength = _useState2[0], setTotalLength = _useState2[1];
  reactExports.useEffect(function() {
    if (pathRef.current && pathRef.current.getTotalLength) {
      try {
        var pathTotalLength = pathRef.current.getTotalLength();
        if (pathTotalLength) {
          setTotalLength(pathTotalLength);
        }
      } catch (err) {
      }
    }
  }, []);
  var x2 = trapezoidProps.x, y2 = trapezoidProps.y, upperWidth = trapezoidProps.upperWidth, lowerWidth = trapezoidProps.lowerWidth, height = trapezoidProps.height, className = trapezoidProps.className;
  var animationEasing = trapezoidProps.animationEasing, animationDuration = trapezoidProps.animationDuration, animationBegin = trapezoidProps.animationBegin, isUpdateAnimationActive = trapezoidProps.isUpdateAnimationActive;
  if (x2 !== +x2 || y2 !== +y2 || upperWidth !== +upperWidth || lowerWidth !== +lowerWidth || height !== +height || upperWidth === 0 && lowerWidth === 0 || height === 0) {
    return null;
  }
  var layerClass = clsx("recharts-trapezoid", className);
  if (!isUpdateAnimationActive) {
    return /* @__PURE__ */ React.createElement("g", null, /* @__PURE__ */ React.createElement("path", _extends$c({}, filterProps(trapezoidProps, true), {
      className: layerClass,
      d: getTrapezoidPath(x2, y2, upperWidth, lowerWidth, height)
    })));
  }
  return /* @__PURE__ */ React.createElement(Animate, {
    canBegin: totalLength > 0,
    from: {
      upperWidth: 0,
      lowerWidth: 0,
      height,
      x: x2,
      y: y2
    },
    to: {
      upperWidth,
      lowerWidth,
      height,
      x: x2,
      y: y2
    },
    duration: animationDuration,
    animationEasing,
    isActive: isUpdateAnimationActive
  }, function(_ref) {
    var currUpperWidth = _ref.upperWidth, currLowerWidth = _ref.lowerWidth, currHeight = _ref.height, currX = _ref.x, currY = _ref.y;
    return /* @__PURE__ */ React.createElement(Animate, {
      canBegin: totalLength > 0,
      from: "0px ".concat(totalLength === -1 ? 1 : totalLength, "px"),
      to: "".concat(totalLength, "px 0px"),
      attributeName: "strokeDasharray",
      begin: animationBegin,
      duration: animationDuration,
      easing: animationEasing
    }, /* @__PURE__ */ React.createElement("path", _extends$c({}, filterProps(trapezoidProps, true), {
      className: layerClass,
      d: getTrapezoidPath(currX, currY, currUpperWidth, currLowerWidth, currHeight),
      ref: pathRef
    })));
  });
};
var _excluded$5 = ["option", "shapeType", "propTransformer", "activeClassName", "isActive"];
function _typeof$h(o) {
  "@babel/helpers - typeof";
  return _typeof$h = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
    return typeof o2;
  } : function(o2) {
    return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
  }, _typeof$h(o);
}
function _objectWithoutProperties$5(source, excluded) {
  if (source == null) return {};
  var target2 = _objectWithoutPropertiesLoose$5(source, excluded);
  var key2, i;
  if (Object.getOwnPropertySymbols) {
    var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
    for (i = 0; i < sourceSymbolKeys.length; i++) {
      key2 = sourceSymbolKeys[i];
      if (excluded.indexOf(key2) >= 0) continue;
      if (!Object.prototype.propertyIsEnumerable.call(source, key2)) continue;
      target2[key2] = source[key2];
    }
  }
  return target2;
}
function _objectWithoutPropertiesLoose$5(source, excluded) {
  if (source == null) return {};
  var target2 = {};
  for (var key2 in source) {
    if (Object.prototype.hasOwnProperty.call(source, key2)) {
      if (excluded.indexOf(key2) >= 0) continue;
      target2[key2] = source[key2];
    }
  }
  return target2;
}
function ownKeys$e(e, r2) {
  var t = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    r2 && (o = o.filter(function(r3) {
      return Object.getOwnPropertyDescriptor(e, r3).enumerable;
    })), t.push.apply(t, o);
  }
  return t;
}
function _objectSpread$e(e) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys$e(Object(t), true).forEach(function(r3) {
      _defineProperty$h(e, r3, t[r3]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$e(Object(t)).forEach(function(r3) {
      Object.defineProperty(e, r3, Object.getOwnPropertyDescriptor(t, r3));
    });
  }
  return e;
}
function _defineProperty$h(obj, key2, value) {
  key2 = _toPropertyKey$h(key2);
  if (key2 in obj) {
    Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key2] = value;
  }
  return obj;
}
function _toPropertyKey$h(t) {
  var i = _toPrimitive$h(t, "string");
  return "symbol" == _typeof$h(i) ? i : i + "";
}
function _toPrimitive$h(t, r2) {
  if ("object" != _typeof$h(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r2);
    if ("object" != _typeof$h(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return ("string" === r2 ? String : Number)(t);
}
function defaultPropTransformer(option, props) {
  return _objectSpread$e(_objectSpread$e({}, props), option);
}
function isSymbolsProps(shapeType, _elementProps) {
  return shapeType === "symbols";
}
function ShapeSelector(_ref) {
  var shapeType = _ref.shapeType, elementProps = _ref.elementProps;
  switch (shapeType) {
    case "rectangle":
      return /* @__PURE__ */ React.createElement(Rectangle, elementProps);
    case "trapezoid":
      return /* @__PURE__ */ React.createElement(Trapezoid, elementProps);
    case "sector":
      return /* @__PURE__ */ React.createElement(Sector, elementProps);
    case "symbols":
      if (isSymbolsProps(shapeType)) {
        return /* @__PURE__ */ React.createElement(Symbols, elementProps);
      }
      break;
    default:
      return null;
  }
}
function getPropsFromShapeOption(option) {
  if (/* @__PURE__ */ reactExports.isValidElement(option)) {
    return option.props;
  }
  return option;
}
function Shape(_ref2) {
  var option = _ref2.option, shapeType = _ref2.shapeType, _ref2$propTransformer = _ref2.propTransformer, propTransformer = _ref2$propTransformer === void 0 ? defaultPropTransformer : _ref2$propTransformer, _ref2$activeClassName = _ref2.activeClassName, activeClassName = _ref2$activeClassName === void 0 ? "recharts-active-shape" : _ref2$activeClassName, isActive = _ref2.isActive, props = _objectWithoutProperties$5(_ref2, _excluded$5);
  var shape;
  if (/* @__PURE__ */ reactExports.isValidElement(option)) {
    shape = /* @__PURE__ */ reactExports.cloneElement(option, _objectSpread$e(_objectSpread$e({}, props), getPropsFromShapeOption(option)));
  } else if (isFunction(option)) {
    shape = option(props);
  } else if (isPlainObject$1(option) && !isBoolean$1(option)) {
    var nextProps = propTransformer(option, props);
    shape = /* @__PURE__ */ React.createElement(ShapeSelector, {
      shapeType,
      elementProps: nextProps
    });
  } else {
    var elementProps = props;
    shape = /* @__PURE__ */ React.createElement(ShapeSelector, {
      shapeType,
      elementProps
    });
  }
  if (isActive) {
    return /* @__PURE__ */ React.createElement(Layer, {
      className: activeClassName
    }, shape);
  }
  return shape;
}
function isFunnel(graphicalItem, _item) {
  return _item != null && "trapezoids" in graphicalItem.props;
}
function isPie(graphicalItem, _item) {
  return _item != null && "sectors" in graphicalItem.props;
}
function isScatter(graphicalItem, _item) {
  return _item != null && "points" in graphicalItem.props;
}
function compareFunnel(shapeData, activeTooltipItem) {
  var _activeTooltipItem$la, _activeTooltipItem$la2;
  var xMatches = shapeData.x === (activeTooltipItem === null || activeTooltipItem === void 0 || (_activeTooltipItem$la = activeTooltipItem.labelViewBox) === null || _activeTooltipItem$la === void 0 ? void 0 : _activeTooltipItem$la.x) || shapeData.x === activeTooltipItem.x;
  var yMatches = shapeData.y === (activeTooltipItem === null || activeTooltipItem === void 0 || (_activeTooltipItem$la2 = activeTooltipItem.labelViewBox) === null || _activeTooltipItem$la2 === void 0 ? void 0 : _activeTooltipItem$la2.y) || shapeData.y === activeTooltipItem.y;
  return xMatches && yMatches;
}
function comparePie(shapeData, activeTooltipItem) {
  var startAngleMatches = shapeData.endAngle === activeTooltipItem.endAngle;
  var endAngleMatches = shapeData.startAngle === activeTooltipItem.startAngle;
  return startAngleMatches && endAngleMatches;
}
function compareScatter(shapeData, activeTooltipItem) {
  var xMatches = shapeData.x === activeTooltipItem.x;
  var yMatches = shapeData.y === activeTooltipItem.y;
  var zMatches = shapeData.z === activeTooltipItem.z;
  return xMatches && yMatches && zMatches;
}
function getComparisonFn(graphicalItem, activeItem) {
  var comparison;
  if (isFunnel(graphicalItem, activeItem)) {
    comparison = compareFunnel;
  } else if (isPie(graphicalItem, activeItem)) {
    comparison = comparePie;
  } else if (isScatter(graphicalItem, activeItem)) {
    comparison = compareScatter;
  }
  return comparison;
}
function getShapeDataKey(graphicalItem, activeItem) {
  var shapeKey;
  if (isFunnel(graphicalItem, activeItem)) {
    shapeKey = "trapezoids";
  } else if (isPie(graphicalItem, activeItem)) {
    shapeKey = "sectors";
  } else if (isScatter(graphicalItem, activeItem)) {
    shapeKey = "points";
  }
  return shapeKey;
}
function getActiveShapeTooltipPayload(graphicalItem, activeItem) {
  if (isFunnel(graphicalItem, activeItem)) {
    var _activeItem$tooltipPa;
    return (_activeItem$tooltipPa = activeItem.tooltipPayload) === null || _activeItem$tooltipPa === void 0 || (_activeItem$tooltipPa = _activeItem$tooltipPa[0]) === null || _activeItem$tooltipPa === void 0 || (_activeItem$tooltipPa = _activeItem$tooltipPa.payload) === null || _activeItem$tooltipPa === void 0 ? void 0 : _activeItem$tooltipPa.payload;
  }
  if (isPie(graphicalItem, activeItem)) {
    var _activeItem$tooltipPa2;
    return (_activeItem$tooltipPa2 = activeItem.tooltipPayload) === null || _activeItem$tooltipPa2 === void 0 || (_activeItem$tooltipPa2 = _activeItem$tooltipPa2[0]) === null || _activeItem$tooltipPa2 === void 0 || (_activeItem$tooltipPa2 = _activeItem$tooltipPa2.payload) === null || _activeItem$tooltipPa2 === void 0 ? void 0 : _activeItem$tooltipPa2.payload;
  }
  if (isScatter(graphicalItem, activeItem)) {
    return activeItem.payload;
  }
  return {};
}
function getActiveShapeIndexForTooltip(_ref3) {
  var activeTooltipItem = _ref3.activeTooltipItem, graphicalItem = _ref3.graphicalItem, itemData = _ref3.itemData;
  var shapeKey = getShapeDataKey(graphicalItem, activeTooltipItem);
  var tooltipPayload = getActiveShapeTooltipPayload(graphicalItem, activeTooltipItem);
  var activeItemMatches = itemData.filter(function(datum, dataIndex) {
    var valuesMatch = isEqual(tooltipPayload, datum);
    var mouseCoordinateMatches = graphicalItem.props[shapeKey].filter(function(shapeData) {
      var comparison = getComparisonFn(graphicalItem, activeTooltipItem);
      return comparison(shapeData, activeTooltipItem);
    });
    var indexOfMouseCoordinates = graphicalItem.props[shapeKey].indexOf(mouseCoordinateMatches[mouseCoordinateMatches.length - 1]);
    var coordinatesMatch = dataIndex === indexOfMouseCoordinates;
    return valuesMatch && coordinatesMatch;
  });
  var activeIndex = itemData.indexOf(activeItemMatches[activeItemMatches.length - 1]);
  return activeIndex;
}
var _Pie;
function _typeof$g(o) {
  "@babel/helpers - typeof";
  return _typeof$g = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
    return typeof o2;
  } : function(o2) {
    return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
  }, _typeof$g(o);
}
function _extends$b() {
  _extends$b = Object.assign ? Object.assign.bind() : function(target2) {
    for (var i = 1; i < arguments.length; i++) {
      var source = arguments[i];
      for (var key2 in source) {
        if (Object.prototype.hasOwnProperty.call(source, key2)) {
          target2[key2] = source[key2];
        }
      }
    }
    return target2;
  };
  return _extends$b.apply(this, arguments);
}
function ownKeys$d(e, r2) {
  var t = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    r2 && (o = o.filter(function(r3) {
      return Object.getOwnPropertyDescriptor(e, r3).enumerable;
    })), t.push.apply(t, o);
  }
  return t;
}
function _objectSpread$d(e) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys$d(Object(t), true).forEach(function(r3) {
      _defineProperty$g(e, r3, t[r3]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$d(Object(t)).forEach(function(r3) {
      Object.defineProperty(e, r3, Object.getOwnPropertyDescriptor(t, r3));
    });
  }
  return e;
}
function _classCallCheck$b(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function _defineProperties$b(target2, props) {
  for (var i = 0; i < props.length; i++) {
    var descriptor = props[i];
    descriptor.enumerable = descriptor.enumerable || false;
    descriptor.configurable = true;
    if ("value" in descriptor) descriptor.writable = true;
    Object.defineProperty(target2, _toPropertyKey$g(descriptor.key), descriptor);
  }
}
function _createClass$b(Constructor, protoProps, staticProps) {
  if (protoProps) _defineProperties$b(Constructor.prototype, protoProps);
  if (staticProps) _defineProperties$b(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", { writable: false });
  return Constructor;
}
function _callSuper$9(t, o, e) {
  return o = _getPrototypeOf$9(o), _possibleConstructorReturn$9(t, _isNativeReflectConstruct$9() ? Reflect.construct(o, e || [], _getPrototypeOf$9(t).constructor) : o.apply(t, e));
}
function _possibleConstructorReturn$9(self, call) {
  if (call && (_typeof$g(call) === "object" || typeof call === "function")) {
    return call;
  } else if (call !== void 0) {
    throw new TypeError("Derived constructors may only return object or undefined");
  }
  return _assertThisInitialized$9(self);
}
function _assertThisInitialized$9(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function _isNativeReflectConstruct$9() {
  try {
    var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {
    }));
  } catch (t2) {
  }
  return (_isNativeReflectConstruct$9 = function _isNativeReflectConstruct2() {
    return !!t;
  })();
}
function _getPrototypeOf$9(o) {
  _getPrototypeOf$9 = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf2(o2) {
    return o2.__proto__ || Object.getPrototypeOf(o2);
  };
  return _getPrototypeOf$9(o);
}
function _inherits$9(subClass, superClass) {
  if (typeof superClass !== "function" && superClass !== null) {
    throw new TypeError("Super expression must either be null or a function");
  }
  subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } });
  Object.defineProperty(subClass, "prototype", { writable: false });
  if (superClass) _setPrototypeOf$9(subClass, superClass);
}
function _setPrototypeOf$9(o, p) {
  _setPrototypeOf$9 = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf2(o2, p2) {
    o2.__proto__ = p2;
    return o2;
  };
  return _setPrototypeOf$9(o, p);
}
function _defineProperty$g(obj, key2, value) {
  key2 = _toPropertyKey$g(key2);
  if (key2 in obj) {
    Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key2] = value;
  }
  return obj;
}
function _toPropertyKey$g(t) {
  var i = _toPrimitive$g(t, "string");
  return "symbol" == _typeof$g(i) ? i : i + "";
}
function _toPrimitive$g(t, r2) {
  if ("object" != _typeof$g(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r2);
    if ("object" != _typeof$g(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return String(t);
}
var Pie = /* @__PURE__ */ function(_PureComponent) {
  function Pie2(props) {
    var _this;
    _classCallCheck$b(this, Pie2);
    _this = _callSuper$9(this, Pie2, [props]);
    _defineProperty$g(_this, "pieRef", null);
    _defineProperty$g(_this, "sectorRefs", []);
    _defineProperty$g(_this, "id", uniqueId("recharts-pie-"));
    _defineProperty$g(_this, "handleAnimationEnd", function() {
      var onAnimationEnd = _this.props.onAnimationEnd;
      _this.setState({
        isAnimationFinished: true
      });
      if (isFunction(onAnimationEnd)) {
        onAnimationEnd();
      }
    });
    _defineProperty$g(_this, "handleAnimationStart", function() {
      var onAnimationStart = _this.props.onAnimationStart;
      _this.setState({
        isAnimationFinished: false
      });
      if (isFunction(onAnimationStart)) {
        onAnimationStart();
      }
    });
    _this.state = {
      isAnimationFinished: !props.isAnimationActive,
      prevIsAnimationActive: props.isAnimationActive,
      prevAnimationId: props.animationId,
      sectorToFocus: 0
    };
    return _this;
  }
  _inherits$9(Pie2, _PureComponent);
  return _createClass$b(Pie2, [{
    key: "isActiveIndex",
    value: function isActiveIndex(i) {
      var activeIndex = this.props.activeIndex;
      if (Array.isArray(activeIndex)) {
        return activeIndex.indexOf(i) !== -1;
      }
      return i === activeIndex;
    }
  }, {
    key: "hasActiveIndex",
    value: function hasActiveIndex() {
      var activeIndex = this.props.activeIndex;
      return Array.isArray(activeIndex) ? activeIndex.length !== 0 : activeIndex || activeIndex === 0;
    }
  }, {
    key: "renderLabels",
    value: function renderLabels(sectors) {
      var isAnimationActive = this.props.isAnimationActive;
      if (isAnimationActive && !this.state.isAnimationFinished) {
        return null;
      }
      var _this$props = this.props, label = _this$props.label, labelLine = _this$props.labelLine, dataKey = _this$props.dataKey, valueKey = _this$props.valueKey;
      var pieProps = filterProps(this.props, false);
      var customLabelProps = filterProps(label, false);
      var customLabelLineProps = filterProps(labelLine, false);
      var offsetRadius = label && label.offsetRadius || 20;
      var labels = sectors.map(function(entry, i) {
        var midAngle = (entry.startAngle + entry.endAngle) / 2;
        var endPoint = polarToCartesian(entry.cx, entry.cy, entry.outerRadius + offsetRadius, midAngle);
        var labelProps = _objectSpread$d(_objectSpread$d(_objectSpread$d(_objectSpread$d({}, pieProps), entry), {}, {
          stroke: "none"
        }, customLabelProps), {}, {
          index: i,
          textAnchor: Pie2.getTextAnchor(endPoint.x, entry.cx)
        }, endPoint);
        var lineProps = _objectSpread$d(_objectSpread$d(_objectSpread$d(_objectSpread$d({}, pieProps), entry), {}, {
          fill: "none",
          stroke: entry.fill
        }, customLabelLineProps), {}, {
          index: i,
          points: [polarToCartesian(entry.cx, entry.cy, entry.outerRadius, midAngle), endPoint]
        });
        var realDataKey = dataKey;
        if (isNil$1(dataKey) && isNil$1(valueKey)) {
          realDataKey = "value";
        } else if (isNil$1(dataKey)) {
          realDataKey = valueKey;
        }
        return (
          // eslint-disable-next-line react/no-array-index-key
          /* @__PURE__ */ React.createElement(Layer, {
            key: "label-".concat(entry.startAngle, "-").concat(entry.endAngle, "-").concat(entry.midAngle, "-").concat(i)
          }, labelLine && Pie2.renderLabelLineItem(labelLine, lineProps, "line"), Pie2.renderLabelItem(label, labelProps, getValueByDataKey(entry, realDataKey)))
        );
      });
      return /* @__PURE__ */ React.createElement(Layer, {
        className: "recharts-pie-labels"
      }, labels);
    }
  }, {
    key: "renderSectorsStatically",
    value: function renderSectorsStatically(sectors) {
      var _this2 = this;
      var _this$props2 = this.props, activeShape = _this$props2.activeShape, blendStroke = _this$props2.blendStroke, inactiveShapeProp = _this$props2.inactiveShape;
      return sectors.map(function(entry, i) {
        if ((entry === null || entry === void 0 ? void 0 : entry.startAngle) === 0 && (entry === null || entry === void 0 ? void 0 : entry.endAngle) === 0 && sectors.length !== 1) return null;
        var isActive = _this2.isActiveIndex(i);
        var inactiveShape = inactiveShapeProp && _this2.hasActiveIndex() ? inactiveShapeProp : null;
        var sectorOptions = isActive ? activeShape : inactiveShape;
        var sectorProps = _objectSpread$d(_objectSpread$d({}, entry), {}, {
          stroke: blendStroke ? entry.fill : entry.stroke,
          tabIndex: -1
        });
        return /* @__PURE__ */ React.createElement(Layer, _extends$b({
          ref: function ref(_ref) {
            if (_ref && !_this2.sectorRefs.includes(_ref)) {
              _this2.sectorRefs.push(_ref);
            }
          },
          tabIndex: -1,
          className: "recharts-pie-sector"
        }, adaptEventsOfChild(_this2.props, entry, i), {
          // eslint-disable-next-line react/no-array-index-key
          key: "sector-".concat(entry === null || entry === void 0 ? void 0 : entry.startAngle, "-").concat(entry === null || entry === void 0 ? void 0 : entry.endAngle, "-").concat(entry.midAngle, "-").concat(i)
        }), /* @__PURE__ */ React.createElement(Shape, _extends$b({
          option: sectorOptions,
          isActive,
          shapeType: "sector"
        }, sectorProps)));
      });
    }
  }, {
    key: "renderSectorsWithAnimation",
    value: function renderSectorsWithAnimation() {
      var _this3 = this;
      var _this$props3 = this.props, sectors = _this$props3.sectors, isAnimationActive = _this$props3.isAnimationActive, animationBegin = _this$props3.animationBegin, animationDuration = _this$props3.animationDuration, animationEasing = _this$props3.animationEasing, animationId = _this$props3.animationId;
      var _this$state = this.state, prevSectors = _this$state.prevSectors, prevIsAnimationActive = _this$state.prevIsAnimationActive;
      return /* @__PURE__ */ React.createElement(Animate, {
        begin: animationBegin,
        duration: animationDuration,
        isActive: isAnimationActive,
        easing: animationEasing,
        from: {
          t: 0
        },
        to: {
          t: 1
        },
        key: "pie-".concat(animationId, "-").concat(prevIsAnimationActive),
        onAnimationStart: this.handleAnimationStart,
        onAnimationEnd: this.handleAnimationEnd
      }, function(_ref2) {
        var t = _ref2.t;
        var stepData = [];
        var first = sectors && sectors[0];
        var curAngle = first.startAngle;
        sectors.forEach(function(entry, index) {
          var prev = prevSectors && prevSectors[index];
          var paddingAngle = index > 0 ? get$2(entry, "paddingAngle", 0) : 0;
          if (prev) {
            var angleIp = interpolateNumber$2(prev.endAngle - prev.startAngle, entry.endAngle - entry.startAngle);
            var latest = _objectSpread$d(_objectSpread$d({}, entry), {}, {
              startAngle: curAngle + paddingAngle,
              endAngle: curAngle + angleIp(t) + paddingAngle
            });
            stepData.push(latest);
            curAngle = latest.endAngle;
          } else {
            var endAngle = entry.endAngle, startAngle = entry.startAngle;
            var interpolatorAngle = interpolateNumber$2(0, endAngle - startAngle);
            var deltaAngle = interpolatorAngle(t);
            var _latest = _objectSpread$d(_objectSpread$d({}, entry), {}, {
              startAngle: curAngle + paddingAngle,
              endAngle: curAngle + deltaAngle + paddingAngle
            });
            stepData.push(_latest);
            curAngle = _latest.endAngle;
          }
        });
        return /* @__PURE__ */ React.createElement(Layer, null, _this3.renderSectorsStatically(stepData));
      });
    }
  }, {
    key: "attachKeyboardHandlers",
    value: function attachKeyboardHandlers(pieRef) {
      var _this4 = this;
      pieRef.onkeydown = function(e) {
        if (!e.altKey) {
          switch (e.key) {
            case "ArrowLeft": {
              var next = ++_this4.state.sectorToFocus % _this4.sectorRefs.length;
              _this4.sectorRefs[next].focus();
              _this4.setState({
                sectorToFocus: next
              });
              break;
            }
            case "ArrowRight": {
              var _next = --_this4.state.sectorToFocus < 0 ? _this4.sectorRefs.length - 1 : _this4.state.sectorToFocus % _this4.sectorRefs.length;
              _this4.sectorRefs[_next].focus();
              _this4.setState({
                sectorToFocus: _next
              });
              break;
            }
            case "Escape": {
              _this4.sectorRefs[_this4.state.sectorToFocus].blur();
              _this4.setState({
                sectorToFocus: 0
              });
              break;
            }
          }
        }
      };
    }
  }, {
    key: "renderSectors",
    value: function renderSectors() {
      var _this$props4 = this.props, sectors = _this$props4.sectors, isAnimationActive = _this$props4.isAnimationActive;
      var prevSectors = this.state.prevSectors;
      if (isAnimationActive && sectors && sectors.length && (!prevSectors || !isEqual(prevSectors, sectors))) {
        return this.renderSectorsWithAnimation();
      }
      return this.renderSectorsStatically(sectors);
    }
  }, {
    key: "componentDidMount",
    value: function componentDidMount() {
      if (this.pieRef) {
        this.attachKeyboardHandlers(this.pieRef);
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this5 = this;
      var _this$props5 = this.props, hide = _this$props5.hide, sectors = _this$props5.sectors, className = _this$props5.className, label = _this$props5.label, cx = _this$props5.cx, cy = _this$props5.cy, innerRadius = _this$props5.innerRadius, outerRadius = _this$props5.outerRadius, isAnimationActive = _this$props5.isAnimationActive;
      var isAnimationFinished = this.state.isAnimationFinished;
      if (hide || !sectors || !sectors.length || !isNumber(cx) || !isNumber(cy) || !isNumber(innerRadius) || !isNumber(outerRadius)) {
        return null;
      }
      var layerClass = clsx("recharts-pie", className);
      return /* @__PURE__ */ React.createElement(Layer, {
        tabIndex: this.props.rootTabIndex,
        className: layerClass,
        ref: function ref(_ref3) {
          _this5.pieRef = _ref3;
        }
      }, this.renderSectors(), label && this.renderLabels(sectors), Label$1.renderCallByParent(this.props, null, false), (!isAnimationActive || isAnimationFinished) && LabelList.renderCallByParent(this.props, sectors, false));
    }
  }], [{
    key: "getDerivedStateFromProps",
    value: function getDerivedStateFromProps(nextProps, prevState) {
      if (prevState.prevIsAnimationActive !== nextProps.isAnimationActive) {
        return {
          prevIsAnimationActive: nextProps.isAnimationActive,
          prevAnimationId: nextProps.animationId,
          curSectors: nextProps.sectors,
          prevSectors: [],
          isAnimationFinished: true
        };
      }
      if (nextProps.isAnimationActive && nextProps.animationId !== prevState.prevAnimationId) {
        return {
          prevAnimationId: nextProps.animationId,
          curSectors: nextProps.sectors,
          prevSectors: prevState.curSectors,
          isAnimationFinished: true
        };
      }
      if (nextProps.sectors !== prevState.curSectors) {
        return {
          curSectors: nextProps.sectors,
          isAnimationFinished: true
        };
      }
      return null;
    }
  }, {
    key: "getTextAnchor",
    value: function getTextAnchor(x2, cx) {
      if (x2 > cx) {
        return "start";
      }
      if (x2 < cx) {
        return "end";
      }
      return "middle";
    }
  }, {
    key: "renderLabelLineItem",
    value: function renderLabelLineItem(option, props, key2) {
      if (/* @__PURE__ */ React.isValidElement(option)) {
        return /* @__PURE__ */ React.cloneElement(option, props);
      }
      if (isFunction(option)) {
        return option(props);
      }
      var className = clsx("recharts-pie-label-line", typeof option !== "boolean" ? option.className : "");
      return /* @__PURE__ */ React.createElement(Curve, _extends$b({}, props, {
        key: key2,
        type: "linear",
        className
      }));
    }
  }, {
    key: "renderLabelItem",
    value: function renderLabelItem(option, props, value) {
      if (/* @__PURE__ */ React.isValidElement(option)) {
        return /* @__PURE__ */ React.cloneElement(option, props);
      }
      var label = value;
      if (isFunction(option)) {
        label = option(props);
        if (/* @__PURE__ */ React.isValidElement(label)) {
          return label;
        }
      }
      var className = clsx("recharts-pie-label-text", typeof option !== "boolean" && !isFunction(option) ? option.className : "");
      return /* @__PURE__ */ React.createElement(Text, _extends$b({}, props, {
        alignmentBaseline: "middle",
        className
      }), label);
    }
  }]);
}(reactExports.PureComponent);
_Pie = Pie;
_defineProperty$g(Pie, "displayName", "Pie");
_defineProperty$g(Pie, "defaultProps", {
  stroke: "#fff",
  fill: "#808080",
  legendType: "rect",
  cx: "50%",
  cy: "50%",
  startAngle: 0,
  endAngle: 360,
  innerRadius: 0,
  outerRadius: "80%",
  paddingAngle: 0,
  labelLine: true,
  hide: false,
  minAngle: 0,
  isAnimationActive: !Global.isSsr,
  animationBegin: 400,
  animationDuration: 1500,
  animationEasing: "ease",
  nameKey: "name",
  blendStroke: false,
  rootTabIndex: 0
});
_defineProperty$g(Pie, "parseDeltaAngle", function(startAngle, endAngle) {
  var sign2 = mathSign(endAngle - startAngle);
  var deltaAngle = Math.min(Math.abs(endAngle - startAngle), 360);
  return sign2 * deltaAngle;
});
_defineProperty$g(Pie, "getRealPieData", function(itemProps) {
  var data = itemProps.data, children = itemProps.children;
  var presentationProps = filterProps(itemProps, false);
  var cells = findAllByType(children, Cell);
  if (data && data.length) {
    return data.map(function(entry, index) {
      return _objectSpread$d(_objectSpread$d(_objectSpread$d({
        payload: entry
      }, presentationProps), entry), cells && cells[index] && cells[index].props);
    });
  }
  if (cells && cells.length) {
    return cells.map(function(cell) {
      return _objectSpread$d(_objectSpread$d({}, presentationProps), cell.props);
    });
  }
  return [];
});
_defineProperty$g(Pie, "parseCoordinateOfPie", function(itemProps, offset) {
  var top = offset.top, left = offset.left, width = offset.width, height = offset.height;
  var maxPieRadius = getMaxRadius(width, height);
  var cx = left + getPercentValue(itemProps.cx, width, width / 2);
  var cy = top + getPercentValue(itemProps.cy, height, height / 2);
  var innerRadius = getPercentValue(itemProps.innerRadius, maxPieRadius, 0);
  var outerRadius = getPercentValue(itemProps.outerRadius, maxPieRadius, maxPieRadius * 0.8);
  var maxRadius = itemProps.maxRadius || Math.sqrt(width * width + height * height) / 2;
  return {
    cx,
    cy,
    innerRadius,
    outerRadius,
    maxRadius
  };
});
_defineProperty$g(Pie, "getComposedData", function(_ref4) {
  var item = _ref4.item, offset = _ref4.offset;
  var itemProps = item.type.defaultProps !== void 0 ? _objectSpread$d(_objectSpread$d({}, item.type.defaultProps), item.props) : item.props;
  var pieData = _Pie.getRealPieData(itemProps);
  if (!pieData || !pieData.length) {
    return null;
  }
  var cornerRadius = itemProps.cornerRadius, startAngle = itemProps.startAngle, endAngle = itemProps.endAngle, paddingAngle = itemProps.paddingAngle, dataKey = itemProps.dataKey, nameKey = itemProps.nameKey, valueKey = itemProps.valueKey, tooltipType = itemProps.tooltipType;
  var minAngle = Math.abs(itemProps.minAngle);
  var coordinate = _Pie.parseCoordinateOfPie(itemProps, offset);
  var deltaAngle = _Pie.parseDeltaAngle(startAngle, endAngle);
  var absDeltaAngle = Math.abs(deltaAngle);
  var realDataKey = dataKey;
  if (isNil$1(dataKey) && isNil$1(valueKey)) {
    warn(false, 'Use "dataKey" to specify the value of pie,\n      the props "valueKey" will be deprecated in 1.1.0');
    realDataKey = "value";
  } else if (isNil$1(dataKey)) {
    warn(false, 'Use "dataKey" to specify the value of pie,\n      the props "valueKey" will be deprecated in 1.1.0');
    realDataKey = valueKey;
  }
  var notZeroItemCount = pieData.filter(function(entry) {
    return getValueByDataKey(entry, realDataKey, 0) !== 0;
  }).length;
  var totalPadingAngle = (absDeltaAngle >= 360 ? notZeroItemCount : notZeroItemCount - 1) * paddingAngle;
  var realTotalAngle = absDeltaAngle - notZeroItemCount * minAngle - totalPadingAngle;
  var sum = pieData.reduce(function(result, entry) {
    var val = getValueByDataKey(entry, realDataKey, 0);
    return result + (isNumber(val) ? val : 0);
  }, 0);
  var sectors;
  if (sum > 0) {
    var prev;
    sectors = pieData.map(function(entry, i) {
      var val = getValueByDataKey(entry, realDataKey, 0);
      var name = getValueByDataKey(entry, nameKey, i);
      var percent2 = (isNumber(val) ? val : 0) / sum;
      var tempStartAngle;
      if (i) {
        tempStartAngle = prev.endAngle + mathSign(deltaAngle) * paddingAngle * (val !== 0 ? 1 : 0);
      } else {
        tempStartAngle = startAngle;
      }
      var tempEndAngle = tempStartAngle + mathSign(deltaAngle) * ((val !== 0 ? minAngle : 0) + percent2 * realTotalAngle);
      var midAngle = (tempStartAngle + tempEndAngle) / 2;
      var middleRadius = (coordinate.innerRadius + coordinate.outerRadius) / 2;
      var tooltipPayload = [{
        name,
        value: val,
        payload: entry,
        dataKey: realDataKey,
        type: tooltipType
      }];
      var tooltipPosition = polarToCartesian(coordinate.cx, coordinate.cy, middleRadius, midAngle);
      prev = _objectSpread$d(_objectSpread$d(_objectSpread$d({
        percent: percent2,
        cornerRadius,
        name,
        tooltipPayload,
        midAngle,
        middleRadius,
        tooltipPosition
      }, entry), coordinate), {}, {
        value: getValueByDataKey(entry, realDataKey),
        startAngle: tempStartAngle,
        endAngle: tempEndAngle,
        payload: entry,
        paddingAngle: mathSign(deltaAngle) * paddingAngle
      });
      return prev;
    });
  }
  return _objectSpread$d(_objectSpread$d({}, coordinate), {}, {
    sectors,
    data: pieData
  });
});
var nativeCeil = Math.ceil, nativeMax$1 = Math.max;
function baseRange$1(start, end, step, fromRight) {
  var index = -1, length = nativeMax$1(nativeCeil((end - start) / (step || 1)), 0), result = Array(length);
  while (length--) {
    result[fromRight ? length : ++index] = start;
    start += step;
  }
  return result;
}
var _baseRange = baseRange$1;
var toNumber = toNumber_1;
var INFINITY = 1 / 0, MAX_INTEGER = 17976931348623157e292;
function toFinite$2(value) {
  if (!value) {
    return value === 0 ? value : 0;
  }
  value = toNumber(value);
  if (value === INFINITY || value === -INFINITY) {
    var sign2 = value < 0 ? -1 : 1;
    return sign2 * MAX_INTEGER;
  }
  return value === value ? value : 0;
}
var toFinite_1 = toFinite$2;
var baseRange = _baseRange, isIterateeCall$2 = _isIterateeCall, toFinite$1 = toFinite_1;
function createRange$1(fromRight) {
  return function(start, end, step) {
    if (step && typeof step != "number" && isIterateeCall$2(start, end, step)) {
      end = step = void 0;
    }
    start = toFinite$1(start);
    if (end === void 0) {
      end = start;
      start = 0;
    } else {
      end = toFinite$1(end);
    }
    step = step === void 0 ? start < end ? 1 : -1 : toFinite$1(step);
    return baseRange(start, end, step, fromRight);
  };
}
var _createRange = createRange$1;
var createRange = _createRange;
var range = createRange();
var range_1 = range;
const range$1 = /* @__PURE__ */ getDefaultExportFromCjs(range_1);
function _typeof$f(o) {
  "@babel/helpers - typeof";
  return _typeof$f = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
    return typeof o2;
  } : function(o2) {
    return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
  }, _typeof$f(o);
}
function ownKeys$c(e, r2) {
  var t = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    r2 && (o = o.filter(function(r3) {
      return Object.getOwnPropertyDescriptor(e, r3).enumerable;
    })), t.push.apply(t, o);
  }
  return t;
}
function _objectSpread$c(e) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys$c(Object(t), true).forEach(function(r3) {
      _defineProperty$f(e, r3, t[r3]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$c(Object(t)).forEach(function(r3) {
      Object.defineProperty(e, r3, Object.getOwnPropertyDescriptor(t, r3));
    });
  }
  return e;
}
function _defineProperty$f(obj, key2, value) {
  key2 = _toPropertyKey$f(key2);
  if (key2 in obj) {
    Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key2] = value;
  }
  return obj;
}
function _toPropertyKey$f(t) {
  var i = _toPrimitive$f(t, "string");
  return "symbol" == _typeof$f(i) ? i : i + "";
}
function _toPrimitive$f(t, r2) {
  if ("object" != _typeof$f(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r2);
    if ("object" != _typeof$f(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return ("string" === r2 ? String : Number)(t);
}
var PREFIX_LIST = ["Webkit", "Moz", "O", "ms"];
var generatePrefixStyle = function generatePrefixStyle2(name, value) {
  var camelName = name.replace(/(\w)/, function(v) {
    return v.toUpperCase();
  });
  var result = PREFIX_LIST.reduce(function(res, entry) {
    return _objectSpread$c(_objectSpread$c({}, res), {}, _defineProperty$f({}, entry + camelName, value));
  }, {});
  result[name] = value;
  return result;
};
function _typeof$e(o) {
  "@babel/helpers - typeof";
  return _typeof$e = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
    return typeof o2;
  } : function(o2) {
    return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
  }, _typeof$e(o);
}
function _extends$a() {
  _extends$a = Object.assign ? Object.assign.bind() : function(target2) {
    for (var i = 1; i < arguments.length; i++) {
      var source = arguments[i];
      for (var key2 in source) {
        if (Object.prototype.hasOwnProperty.call(source, key2)) {
          target2[key2] = source[key2];
        }
      }
    }
    return target2;
  };
  return _extends$a.apply(this, arguments);
}
function ownKeys$b(e, r2) {
  var t = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    r2 && (o = o.filter(function(r3) {
      return Object.getOwnPropertyDescriptor(e, r3).enumerable;
    })), t.push.apply(t, o);
  }
  return t;
}
function _objectSpread$b(e) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys$b(Object(t), true).forEach(function(r3) {
      _defineProperty$e(e, r3, t[r3]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$b(Object(t)).forEach(function(r3) {
      Object.defineProperty(e, r3, Object.getOwnPropertyDescriptor(t, r3));
    });
  }
  return e;
}
function _classCallCheck$a(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function _defineProperties$a(target2, props) {
  for (var i = 0; i < props.length; i++) {
    var descriptor = props[i];
    descriptor.enumerable = descriptor.enumerable || false;
    descriptor.configurable = true;
    if ("value" in descriptor) descriptor.writable = true;
    Object.defineProperty(target2, _toPropertyKey$e(descriptor.key), descriptor);
  }
}
function _createClass$a(Constructor, protoProps, staticProps) {
  if (protoProps) _defineProperties$a(Constructor.prototype, protoProps);
  if (staticProps) _defineProperties$a(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", { writable: false });
  return Constructor;
}
function _callSuper$8(t, o, e) {
  return o = _getPrototypeOf$8(o), _possibleConstructorReturn$8(t, _isNativeReflectConstruct$8() ? Reflect.construct(o, e || [], _getPrototypeOf$8(t).constructor) : o.apply(t, e));
}
function _possibleConstructorReturn$8(self, call) {
  if (call && (_typeof$e(call) === "object" || typeof call === "function")) {
    return call;
  } else if (call !== void 0) {
    throw new TypeError("Derived constructors may only return object or undefined");
  }
  return _assertThisInitialized$8(self);
}
function _assertThisInitialized$8(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function _isNativeReflectConstruct$8() {
  try {
    var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {
    }));
  } catch (t2) {
  }
  return (_isNativeReflectConstruct$8 = function _isNativeReflectConstruct2() {
    return !!t;
  })();
}
function _getPrototypeOf$8(o) {
  _getPrototypeOf$8 = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf2(o2) {
    return o2.__proto__ || Object.getPrototypeOf(o2);
  };
  return _getPrototypeOf$8(o);
}
function _inherits$8(subClass, superClass) {
  if (typeof superClass !== "function" && superClass !== null) {
    throw new TypeError("Super expression must either be null or a function");
  }
  subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } });
  Object.defineProperty(subClass, "prototype", { writable: false });
  if (superClass) _setPrototypeOf$8(subClass, superClass);
}
function _setPrototypeOf$8(o, p) {
  _setPrototypeOf$8 = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf2(o2, p2) {
    o2.__proto__ = p2;
    return o2;
  };
  return _setPrototypeOf$8(o, p);
}
function _defineProperty$e(obj, key2, value) {
  key2 = _toPropertyKey$e(key2);
  if (key2 in obj) {
    Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key2] = value;
  }
  return obj;
}
function _toPropertyKey$e(t) {
  var i = _toPrimitive$e(t, "string");
  return "symbol" == _typeof$e(i) ? i : i + "";
}
function _toPrimitive$e(t, r2) {
  if ("object" != _typeof$e(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r2);
    if ("object" != _typeof$e(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return String(t);
}
var createScale = function createScale2(_ref) {
  var data = _ref.data, startIndex = _ref.startIndex, endIndex = _ref.endIndex, x2 = _ref.x, width = _ref.width, travellerWidth = _ref.travellerWidth;
  if (!data || !data.length) {
    return {};
  }
  var len = data.length;
  var scale2 = point().domain(range$1(0, len)).range([x2, x2 + width - travellerWidth]);
  var scaleValues = scale2.domain().map(function(entry) {
    return scale2(entry);
  });
  return {
    isTextActive: false,
    isSlideMoving: false,
    isTravellerMoving: false,
    isTravellerFocused: false,
    startX: scale2(startIndex),
    endX: scale2(endIndex),
    scale: scale2,
    scaleValues
  };
};
var isTouch = function isTouch2(e) {
  return e.changedTouches && !!e.changedTouches.length;
};
var Brush = /* @__PURE__ */ function(_PureComponent) {
  function Brush2(props) {
    var _this;
    _classCallCheck$a(this, Brush2);
    _this = _callSuper$8(this, Brush2, [props]);
    _defineProperty$e(_this, "handleDrag", function(e) {
      if (_this.leaveTimer) {
        clearTimeout(_this.leaveTimer);
        _this.leaveTimer = null;
      }
      if (_this.state.isTravellerMoving) {
        _this.handleTravellerMove(e);
      } else if (_this.state.isSlideMoving) {
        _this.handleSlideDrag(e);
      }
    });
    _defineProperty$e(_this, "handleTouchMove", function(e) {
      if (e.changedTouches != null && e.changedTouches.length > 0) {
        _this.handleDrag(e.changedTouches[0]);
      }
    });
    _defineProperty$e(_this, "handleDragEnd", function() {
      _this.setState({
        isTravellerMoving: false,
        isSlideMoving: false
      }, function() {
        var _this$props = _this.props, endIndex = _this$props.endIndex, onDragEnd = _this$props.onDragEnd, startIndex = _this$props.startIndex;
        onDragEnd === null || onDragEnd === void 0 || onDragEnd({
          endIndex,
          startIndex
        });
      });
      _this.detachDragEndListener();
    });
    _defineProperty$e(_this, "handleLeaveWrapper", function() {
      if (_this.state.isTravellerMoving || _this.state.isSlideMoving) {
        _this.leaveTimer = window.setTimeout(_this.handleDragEnd, _this.props.leaveTimeOut);
      }
    });
    _defineProperty$e(_this, "handleEnterSlideOrTraveller", function() {
      _this.setState({
        isTextActive: true
      });
    });
    _defineProperty$e(_this, "handleLeaveSlideOrTraveller", function() {
      _this.setState({
        isTextActive: false
      });
    });
    _defineProperty$e(_this, "handleSlideDragStart", function(e) {
      var event = isTouch(e) ? e.changedTouches[0] : e;
      _this.setState({
        isTravellerMoving: false,
        isSlideMoving: true,
        slideMoveStartX: event.pageX
      });
      _this.attachDragEndListener();
    });
    _this.travellerDragStartHandlers = {
      startX: _this.handleTravellerDragStart.bind(_this, "startX"),
      endX: _this.handleTravellerDragStart.bind(_this, "endX")
    };
    _this.state = {};
    return _this;
  }
  _inherits$8(Brush2, _PureComponent);
  return _createClass$a(Brush2, [{
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      if (this.leaveTimer) {
        clearTimeout(this.leaveTimer);
        this.leaveTimer = null;
      }
      this.detachDragEndListener();
    }
  }, {
    key: "getIndex",
    value: function getIndex(_ref2) {
      var startX = _ref2.startX, endX = _ref2.endX;
      var scaleValues = this.state.scaleValues;
      var _this$props2 = this.props, gap = _this$props2.gap, data = _this$props2.data;
      var lastIndex = data.length - 1;
      var min2 = Math.min(startX, endX);
      var max2 = Math.max(startX, endX);
      var minIndex = Brush2.getIndexInRange(scaleValues, min2);
      var maxIndex = Brush2.getIndexInRange(scaleValues, max2);
      return {
        startIndex: minIndex - minIndex % gap,
        endIndex: maxIndex === lastIndex ? lastIndex : maxIndex - maxIndex % gap
      };
    }
  }, {
    key: "getTextOfTick",
    value: function getTextOfTick(index) {
      var _this$props3 = this.props, data = _this$props3.data, tickFormatter = _this$props3.tickFormatter, dataKey = _this$props3.dataKey;
      var text = getValueByDataKey(data[index], dataKey, index);
      return isFunction(tickFormatter) ? tickFormatter(text, index) : text;
    }
  }, {
    key: "attachDragEndListener",
    value: function attachDragEndListener() {
      window.addEventListener("mouseup", this.handleDragEnd, true);
      window.addEventListener("touchend", this.handleDragEnd, true);
      window.addEventListener("mousemove", this.handleDrag, true);
    }
  }, {
    key: "detachDragEndListener",
    value: function detachDragEndListener() {
      window.removeEventListener("mouseup", this.handleDragEnd, true);
      window.removeEventListener("touchend", this.handleDragEnd, true);
      window.removeEventListener("mousemove", this.handleDrag, true);
    }
  }, {
    key: "handleSlideDrag",
    value: function handleSlideDrag(e) {
      var _this$state = this.state, slideMoveStartX = _this$state.slideMoveStartX, startX = _this$state.startX, endX = _this$state.endX;
      var _this$props4 = this.props, x2 = _this$props4.x, width = _this$props4.width, travellerWidth = _this$props4.travellerWidth, startIndex = _this$props4.startIndex, endIndex = _this$props4.endIndex, onChange = _this$props4.onChange;
      var delta = e.pageX - slideMoveStartX;
      if (delta > 0) {
        delta = Math.min(delta, x2 + width - travellerWidth - endX, x2 + width - travellerWidth - startX);
      } else if (delta < 0) {
        delta = Math.max(delta, x2 - startX, x2 - endX);
      }
      var newIndex = this.getIndex({
        startX: startX + delta,
        endX: endX + delta
      });
      if ((newIndex.startIndex !== startIndex || newIndex.endIndex !== endIndex) && onChange) {
        onChange(newIndex);
      }
      this.setState({
        startX: startX + delta,
        endX: endX + delta,
        slideMoveStartX: e.pageX
      });
    }
  }, {
    key: "handleTravellerDragStart",
    value: function handleTravellerDragStart(id, e) {
      var event = isTouch(e) ? e.changedTouches[0] : e;
      this.setState({
        isSlideMoving: false,
        isTravellerMoving: true,
        movingTravellerId: id,
        brushMoveStartX: event.pageX
      });
      this.attachDragEndListener();
    }
  }, {
    key: "handleTravellerMove",
    value: function handleTravellerMove(e) {
      var _this$state2 = this.state, brushMoveStartX = _this$state2.brushMoveStartX, movingTravellerId = _this$state2.movingTravellerId, endX = _this$state2.endX, startX = _this$state2.startX;
      var prevValue = this.state[movingTravellerId];
      var _this$props5 = this.props, x2 = _this$props5.x, width = _this$props5.width, travellerWidth = _this$props5.travellerWidth, onChange = _this$props5.onChange, gap = _this$props5.gap, data = _this$props5.data;
      var params = {
        startX: this.state.startX,
        endX: this.state.endX
      };
      var delta = e.pageX - brushMoveStartX;
      if (delta > 0) {
        delta = Math.min(delta, x2 + width - travellerWidth - prevValue);
      } else if (delta < 0) {
        delta = Math.max(delta, x2 - prevValue);
      }
      params[movingTravellerId] = prevValue + delta;
      var newIndex = this.getIndex(params);
      var startIndex = newIndex.startIndex, endIndex = newIndex.endIndex;
      var isFullGap = function isFullGap2() {
        var lastIndex = data.length - 1;
        if (movingTravellerId === "startX" && (endX > startX ? startIndex % gap === 0 : endIndex % gap === 0) || endX < startX && endIndex === lastIndex || movingTravellerId === "endX" && (endX > startX ? endIndex % gap === 0 : startIndex % gap === 0) || endX > startX && endIndex === lastIndex) {
          return true;
        }
        return false;
      };
      this.setState(_defineProperty$e(_defineProperty$e({}, movingTravellerId, prevValue + delta), "brushMoveStartX", e.pageX), function() {
        if (onChange) {
          if (isFullGap()) {
            onChange(newIndex);
          }
        }
      });
    }
  }, {
    key: "handleTravellerMoveKeyboard",
    value: function handleTravellerMoveKeyboard(direction, id) {
      var _this2 = this;
      var _this$state3 = this.state, scaleValues = _this$state3.scaleValues, startX = _this$state3.startX, endX = _this$state3.endX;
      var currentScaleValue = this.state[id];
      var currentIndex = scaleValues.indexOf(currentScaleValue);
      if (currentIndex === -1) {
        return;
      }
      var newIndex = currentIndex + direction;
      if (newIndex === -1 || newIndex >= scaleValues.length) {
        return;
      }
      var newScaleValue = scaleValues[newIndex];
      if (id === "startX" && newScaleValue >= endX || id === "endX" && newScaleValue <= startX) {
        return;
      }
      this.setState(_defineProperty$e({}, id, newScaleValue), function() {
        _this2.props.onChange(_this2.getIndex({
          startX: _this2.state.startX,
          endX: _this2.state.endX
        }));
      });
    }
  }, {
    key: "renderBackground",
    value: function renderBackground() {
      var _this$props6 = this.props, x2 = _this$props6.x, y2 = _this$props6.y, width = _this$props6.width, height = _this$props6.height, fill = _this$props6.fill, stroke = _this$props6.stroke;
      return /* @__PURE__ */ React.createElement("rect", {
        stroke,
        fill,
        x: x2,
        y: y2,
        width,
        height
      });
    }
  }, {
    key: "renderPanorama",
    value: function renderPanorama() {
      var _this$props7 = this.props, x2 = _this$props7.x, y2 = _this$props7.y, width = _this$props7.width, height = _this$props7.height, data = _this$props7.data, children = _this$props7.children, padding = _this$props7.padding;
      var chartElement = reactExports.Children.only(children);
      if (!chartElement) {
        return null;
      }
      return /* @__PURE__ */ React.cloneElement(chartElement, {
        x: x2,
        y: y2,
        width,
        height,
        margin: padding,
        compact: true,
        data
      });
    }
  }, {
    key: "renderTravellerLayer",
    value: function renderTravellerLayer(travellerX, id) {
      var _data$startIndex, _data$endIndex, _this3 = this;
      var _this$props8 = this.props, y2 = _this$props8.y, travellerWidth = _this$props8.travellerWidth, height = _this$props8.height, traveller = _this$props8.traveller, ariaLabel = _this$props8.ariaLabel, data = _this$props8.data, startIndex = _this$props8.startIndex, endIndex = _this$props8.endIndex;
      var x2 = Math.max(travellerX, this.props.x);
      var travellerProps = _objectSpread$b(_objectSpread$b({}, filterProps(this.props, false)), {}, {
        x: x2,
        y: y2,
        width: travellerWidth,
        height
      });
      var ariaLabelBrush = ariaLabel || "Min value: ".concat((_data$startIndex = data[startIndex]) === null || _data$startIndex === void 0 ? void 0 : _data$startIndex.name, ", Max value: ").concat((_data$endIndex = data[endIndex]) === null || _data$endIndex === void 0 ? void 0 : _data$endIndex.name);
      return /* @__PURE__ */ React.createElement(Layer, {
        tabIndex: 0,
        role: "slider",
        "aria-label": ariaLabelBrush,
        "aria-valuenow": travellerX,
        className: "recharts-brush-traveller",
        onMouseEnter: this.handleEnterSlideOrTraveller,
        onMouseLeave: this.handleLeaveSlideOrTraveller,
        onMouseDown: this.travellerDragStartHandlers[id],
        onTouchStart: this.travellerDragStartHandlers[id],
        onKeyDown: function onKeyDown(e) {
          if (!["ArrowLeft", "ArrowRight"].includes(e.key)) {
            return;
          }
          e.preventDefault();
          e.stopPropagation();
          _this3.handleTravellerMoveKeyboard(e.key === "ArrowRight" ? 1 : -1, id);
        },
        onFocus: function onFocus() {
          _this3.setState({
            isTravellerFocused: true
          });
        },
        onBlur: function onBlur() {
          _this3.setState({
            isTravellerFocused: false
          });
        },
        style: {
          cursor: "col-resize"
        }
      }, Brush2.renderTraveller(traveller, travellerProps));
    }
  }, {
    key: "renderSlide",
    value: function renderSlide(startX, endX) {
      var _this$props9 = this.props, y2 = _this$props9.y, height = _this$props9.height, stroke = _this$props9.stroke, travellerWidth = _this$props9.travellerWidth;
      var x2 = Math.min(startX, endX) + travellerWidth;
      var width = Math.max(Math.abs(endX - startX) - travellerWidth, 0);
      return /* @__PURE__ */ React.createElement("rect", {
        className: "recharts-brush-slide",
        onMouseEnter: this.handleEnterSlideOrTraveller,
        onMouseLeave: this.handleLeaveSlideOrTraveller,
        onMouseDown: this.handleSlideDragStart,
        onTouchStart: this.handleSlideDragStart,
        style: {
          cursor: "move"
        },
        stroke: "none",
        fill: stroke,
        fillOpacity: 0.2,
        x: x2,
        y: y2,
        width,
        height
      });
    }
  }, {
    key: "renderText",
    value: function renderText() {
      var _this$props10 = this.props, startIndex = _this$props10.startIndex, endIndex = _this$props10.endIndex, y2 = _this$props10.y, height = _this$props10.height, travellerWidth = _this$props10.travellerWidth, stroke = _this$props10.stroke;
      var _this$state4 = this.state, startX = _this$state4.startX, endX = _this$state4.endX;
      var offset = 5;
      var attrs = {
        pointerEvents: "none",
        fill: stroke
      };
      return /* @__PURE__ */ React.createElement(Layer, {
        className: "recharts-brush-texts"
      }, /* @__PURE__ */ React.createElement(Text, _extends$a({
        textAnchor: "end",
        verticalAnchor: "middle",
        x: Math.min(startX, endX) - offset,
        y: y2 + height / 2
      }, attrs), this.getTextOfTick(startIndex)), /* @__PURE__ */ React.createElement(Text, _extends$a({
        textAnchor: "start",
        verticalAnchor: "middle",
        x: Math.max(startX, endX) + travellerWidth + offset,
        y: y2 + height / 2
      }, attrs), this.getTextOfTick(endIndex)));
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props11 = this.props, data = _this$props11.data, className = _this$props11.className, children = _this$props11.children, x2 = _this$props11.x, y2 = _this$props11.y, width = _this$props11.width, height = _this$props11.height, alwaysShowText = _this$props11.alwaysShowText;
      var _this$state5 = this.state, startX = _this$state5.startX, endX = _this$state5.endX, isTextActive = _this$state5.isTextActive, isSlideMoving = _this$state5.isSlideMoving, isTravellerMoving = _this$state5.isTravellerMoving, isTravellerFocused = _this$state5.isTravellerFocused;
      if (!data || !data.length || !isNumber(x2) || !isNumber(y2) || !isNumber(width) || !isNumber(height) || width <= 0 || height <= 0) {
        return null;
      }
      var layerClass = clsx("recharts-brush", className);
      var isPanoramic = React.Children.count(children) === 1;
      var style = generatePrefixStyle("userSelect", "none");
      return /* @__PURE__ */ React.createElement(Layer, {
        className: layerClass,
        onMouseLeave: this.handleLeaveWrapper,
        onTouchMove: this.handleTouchMove,
        style
      }, this.renderBackground(), isPanoramic && this.renderPanorama(), this.renderSlide(startX, endX), this.renderTravellerLayer(startX, "startX"), this.renderTravellerLayer(endX, "endX"), (isTextActive || isSlideMoving || isTravellerMoving || isTravellerFocused || alwaysShowText) && this.renderText());
    }
  }], [{
    key: "renderDefaultTraveller",
    value: function renderDefaultTraveller(props) {
      var x2 = props.x, y2 = props.y, width = props.width, height = props.height, stroke = props.stroke;
      var lineY = Math.floor(y2 + height / 2) - 1;
      return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("rect", {
        x: x2,
        y: y2,
        width,
        height,
        fill: stroke,
        stroke: "none"
      }), /* @__PURE__ */ React.createElement("line", {
        x1: x2 + 1,
        y1: lineY,
        x2: x2 + width - 1,
        y2: lineY,
        fill: "none",
        stroke: "#fff"
      }), /* @__PURE__ */ React.createElement("line", {
        x1: x2 + 1,
        y1: lineY + 2,
        x2: x2 + width - 1,
        y2: lineY + 2,
        fill: "none",
        stroke: "#fff"
      }));
    }
  }, {
    key: "renderTraveller",
    value: function renderTraveller(option, props) {
      var rectangle;
      if (/* @__PURE__ */ React.isValidElement(option)) {
        rectangle = /* @__PURE__ */ React.cloneElement(option, props);
      } else if (isFunction(option)) {
        rectangle = option(props);
      } else {
        rectangle = Brush2.renderDefaultTraveller(props);
      }
      return rectangle;
    }
  }, {
    key: "getDerivedStateFromProps",
    value: function getDerivedStateFromProps(nextProps, prevState) {
      var data = nextProps.data, width = nextProps.width, x2 = nextProps.x, travellerWidth = nextProps.travellerWidth, updateId = nextProps.updateId, startIndex = nextProps.startIndex, endIndex = nextProps.endIndex;
      if (data !== prevState.prevData || updateId !== prevState.prevUpdateId) {
        return _objectSpread$b({
          prevData: data,
          prevTravellerWidth: travellerWidth,
          prevUpdateId: updateId,
          prevX: x2,
          prevWidth: width
        }, data && data.length ? createScale({
          data,
          width,
          x: x2,
          travellerWidth,
          startIndex,
          endIndex
        }) : {
          scale: null,
          scaleValues: null
        });
      }
      if (prevState.scale && (width !== prevState.prevWidth || x2 !== prevState.prevX || travellerWidth !== prevState.prevTravellerWidth)) {
        prevState.scale.range([x2, x2 + width - travellerWidth]);
        var scaleValues = prevState.scale.domain().map(function(entry) {
          return prevState.scale(entry);
        });
        return {
          prevData: data,
          prevTravellerWidth: travellerWidth,
          prevUpdateId: updateId,
          prevX: x2,
          prevWidth: width,
          startX: prevState.scale(nextProps.startIndex),
          endX: prevState.scale(nextProps.endIndex),
          scaleValues
        };
      }
      return null;
    }
  }, {
    key: "getIndexInRange",
    value: function getIndexInRange(valueRange, x2) {
      var len = valueRange.length;
      var start = 0;
      var end = len - 1;
      while (end - start > 1) {
        var middle = Math.floor((start + end) / 2);
        if (valueRange[middle] > x2) {
          end = middle;
        } else {
          start = middle;
        }
      }
      return x2 >= valueRange[end] ? end : start;
    }
  }]);
}(reactExports.PureComponent);
_defineProperty$e(Brush, "displayName", "Brush");
_defineProperty$e(Brush, "defaultProps", {
  height: 40,
  travellerWidth: 5,
  gap: 1,
  fill: "#fff",
  stroke: "#666",
  padding: {
    top: 1,
    right: 1,
    bottom: 1,
    left: 1
  },
  leaveTimeOut: 1e3,
  alwaysShowText: false
});
var baseEach$1 = _baseEach;
function baseSome$1(collection, predicate) {
  var result;
  baseEach$1(collection, function(value, index, collection2) {
    result = predicate(value, index, collection2);
    return !result;
  });
  return !!result;
}
var _baseSome = baseSome$1;
var arraySome = _arraySome, baseIteratee$4 = _baseIteratee, baseSome = _baseSome, isArray$1 = isArray_1, isIterateeCall$1 = _isIterateeCall;
function some(collection, predicate, guard) {
  var func = isArray$1(collection) ? arraySome : baseSome;
  if (guard && isIterateeCall$1(collection, predicate, guard)) {
    predicate = void 0;
  }
  return func(collection, baseIteratee$4(predicate));
}
var some_1 = some;
const some$1 = /* @__PURE__ */ getDefaultExportFromCjs(some_1);
var ifOverflowMatches = function ifOverflowMatches2(props, value) {
  var alwaysShow = props.alwaysShow;
  var ifOverflow = props.ifOverflow;
  if (alwaysShow) {
    ifOverflow = "extendDomain";
  }
  return ifOverflow === value;
};
var defineProperty = _defineProperty$B;
function baseAssignValue$1(object2, key2, value) {
  if (key2 == "__proto__" && defineProperty) {
    defineProperty(object2, key2, {
      "configurable": true,
      "enumerable": true,
      "value": value,
      "writable": true
    });
  } else {
    object2[key2] = value;
  }
}
var _baseAssignValue = baseAssignValue$1;
var baseAssignValue = _baseAssignValue, baseForOwn = _baseForOwn, baseIteratee$3 = _baseIteratee;
function mapValues(object2, iteratee) {
  var result = {};
  iteratee = baseIteratee$3(iteratee);
  baseForOwn(object2, function(value, key2, object3) {
    baseAssignValue(result, key2, iteratee(value, key2, object3));
  });
  return result;
}
var mapValues_1 = mapValues;
const mapValues$1 = /* @__PURE__ */ getDefaultExportFromCjs(mapValues_1);
function arrayEvery$1(array2, predicate) {
  var index = -1, length = array2 == null ? 0 : array2.length;
  while (++index < length) {
    if (!predicate(array2[index], index, array2)) {
      return false;
    }
  }
  return true;
}
var _arrayEvery = arrayEvery$1;
var baseEach = _baseEach;
function baseEvery$1(collection, predicate) {
  var result = true;
  baseEach(collection, function(value, index, collection2) {
    result = !!predicate(value, index, collection2);
    return result;
  });
  return result;
}
var _baseEvery = baseEvery$1;
var arrayEvery = _arrayEvery, baseEvery = _baseEvery, baseIteratee$2 = _baseIteratee, isArray = isArray_1, isIterateeCall = _isIterateeCall;
function every(collection, predicate, guard) {
  var func = isArray(collection) ? arrayEvery : baseEvery;
  if (guard && isIterateeCall(collection, predicate, guard)) {
    predicate = void 0;
  }
  return func(collection, baseIteratee$2(predicate));
}
var every_1 = every;
const every$1 = /* @__PURE__ */ getDefaultExportFromCjs(every_1);
var _excluded$4 = ["x", "y"];
function _typeof$d(o) {
  "@babel/helpers - typeof";
  return _typeof$d = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
    return typeof o2;
  } : function(o2) {
    return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
  }, _typeof$d(o);
}
function _extends$9() {
  _extends$9 = Object.assign ? Object.assign.bind() : function(target2) {
    for (var i = 1; i < arguments.length; i++) {
      var source = arguments[i];
      for (var key2 in source) {
        if (Object.prototype.hasOwnProperty.call(source, key2)) {
          target2[key2] = source[key2];
        }
      }
    }
    return target2;
  };
  return _extends$9.apply(this, arguments);
}
function ownKeys$a(e, r2) {
  var t = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    r2 && (o = o.filter(function(r22) {
      return Object.getOwnPropertyDescriptor(e, r22).enumerable;
    })), t.push.apply(t, o);
  }
  return t;
}
function _objectSpread$a(e) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys$a(Object(t), true).forEach(function(r22) {
      _defineProperty$d(e, r22, t[r22]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$a(Object(t)).forEach(function(r22) {
      Object.defineProperty(e, r22, Object.getOwnPropertyDescriptor(t, r22));
    });
  }
  return e;
}
function _defineProperty$d(obj, key2, value) {
  key2 = _toPropertyKey$d(key2);
  if (key2 in obj) {
    Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key2] = value;
  }
  return obj;
}
function _toPropertyKey$d(t) {
  var i = _toPrimitive$d(t, "string");
  return "symbol" == _typeof$d(i) ? i : i + "";
}
function _toPrimitive$d(t, r2) {
  if ("object" != _typeof$d(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r2);
    if ("object" != _typeof$d(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return ("string" === r2 ? String : Number)(t);
}
function _objectWithoutProperties$4(source, excluded) {
  if (source == null) return {};
  var target2 = _objectWithoutPropertiesLoose$4(source, excluded);
  var key2, i;
  if (Object.getOwnPropertySymbols) {
    var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
    for (i = 0; i < sourceSymbolKeys.length; i++) {
      key2 = sourceSymbolKeys[i];
      if (excluded.indexOf(key2) >= 0) continue;
      if (!Object.prototype.propertyIsEnumerable.call(source, key2)) continue;
      target2[key2] = source[key2];
    }
  }
  return target2;
}
function _objectWithoutPropertiesLoose$4(source, excluded) {
  if (source == null) return {};
  var target2 = {};
  for (var key2 in source) {
    if (Object.prototype.hasOwnProperty.call(source, key2)) {
      if (excluded.indexOf(key2) >= 0) continue;
      target2[key2] = source[key2];
    }
  }
  return target2;
}
function typeguardBarRectangleProps(_ref, props) {
  var xProp = _ref.x, yProp = _ref.y, option = _objectWithoutProperties$4(_ref, _excluded$4);
  var xValue = "".concat(xProp);
  var x2 = parseInt(xValue, 10);
  var yValue = "".concat(yProp);
  var y2 = parseInt(yValue, 10);
  var heightValue = "".concat(props.height || option.height);
  var height = parseInt(heightValue, 10);
  var widthValue = "".concat(props.width || option.width);
  var width = parseInt(widthValue, 10);
  return _objectSpread$a(_objectSpread$a(_objectSpread$a(_objectSpread$a(_objectSpread$a({}, props), option), x2 ? {
    x: x2
  } : {}), y2 ? {
    y: y2
  } : {}), {}, {
    height,
    width,
    name: props.name,
    radius: props.radius
  });
}
function BarRectangle(props) {
  return /* @__PURE__ */ React.createElement(Shape, _extends$9({
    shapeType: "rectangle",
    propTransformer: typeguardBarRectangleProps,
    activeClassName: "recharts-active-bar"
  }, props));
}
var minPointSizeCallback = function minPointSizeCallback2(minPointSize) {
  var defaultValue = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 0;
  return function(value, index) {
    if (typeof minPointSize === "number") return minPointSize;
    var isValueNumberOrNil = isNumber(value) || isNullish(value);
    if (isValueNumberOrNil) {
      return minPointSize(value, index);
    }
    !isValueNumberOrNil ? invariant() : void 0;
    return defaultValue;
  };
};
var _excluded$3 = ["value", "background"];
var _Bar;
function _typeof$c(o) {
  "@babel/helpers - typeof";
  return _typeof$c = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
    return typeof o2;
  } : function(o2) {
    return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
  }, _typeof$c(o);
}
function _objectWithoutProperties$3(source, excluded) {
  if (source == null) return {};
  var target2 = _objectWithoutPropertiesLoose$3(source, excluded);
  var key2, i;
  if (Object.getOwnPropertySymbols) {
    var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
    for (i = 0; i < sourceSymbolKeys.length; i++) {
      key2 = sourceSymbolKeys[i];
      if (excluded.indexOf(key2) >= 0) continue;
      if (!Object.prototype.propertyIsEnumerable.call(source, key2)) continue;
      target2[key2] = source[key2];
    }
  }
  return target2;
}
function _objectWithoutPropertiesLoose$3(source, excluded) {
  if (source == null) return {};
  var target2 = {};
  for (var key2 in source) {
    if (Object.prototype.hasOwnProperty.call(source, key2)) {
      if (excluded.indexOf(key2) >= 0) continue;
      target2[key2] = source[key2];
    }
  }
  return target2;
}
function _extends$8() {
  _extends$8 = Object.assign ? Object.assign.bind() : function(target2) {
    for (var i = 1; i < arguments.length; i++) {
      var source = arguments[i];
      for (var key2 in source) {
        if (Object.prototype.hasOwnProperty.call(source, key2)) {
          target2[key2] = source[key2];
        }
      }
    }
    return target2;
  };
  return _extends$8.apply(this, arguments);
}
function ownKeys$9(e, r2) {
  var t = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    r2 && (o = o.filter(function(r3) {
      return Object.getOwnPropertyDescriptor(e, r3).enumerable;
    })), t.push.apply(t, o);
  }
  return t;
}
function _objectSpread$9(e) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys$9(Object(t), true).forEach(function(r3) {
      _defineProperty$c(e, r3, t[r3]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$9(Object(t)).forEach(function(r3) {
      Object.defineProperty(e, r3, Object.getOwnPropertyDescriptor(t, r3));
    });
  }
  return e;
}
function _classCallCheck$9(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function _defineProperties$9(target2, props) {
  for (var i = 0; i < props.length; i++) {
    var descriptor = props[i];
    descriptor.enumerable = descriptor.enumerable || false;
    descriptor.configurable = true;
    if ("value" in descriptor) descriptor.writable = true;
    Object.defineProperty(target2, _toPropertyKey$c(descriptor.key), descriptor);
  }
}
function _createClass$9(Constructor, protoProps, staticProps) {
  if (protoProps) _defineProperties$9(Constructor.prototype, protoProps);
  if (staticProps) _defineProperties$9(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", { writable: false });
  return Constructor;
}
function _callSuper$7(t, o, e) {
  return o = _getPrototypeOf$7(o), _possibleConstructorReturn$7(t, _isNativeReflectConstruct$7() ? Reflect.construct(o, e || [], _getPrototypeOf$7(t).constructor) : o.apply(t, e));
}
function _possibleConstructorReturn$7(self, call) {
  if (call && (_typeof$c(call) === "object" || typeof call === "function")) {
    return call;
  } else if (call !== void 0) {
    throw new TypeError("Derived constructors may only return object or undefined");
  }
  return _assertThisInitialized$7(self);
}
function _assertThisInitialized$7(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function _isNativeReflectConstruct$7() {
  try {
    var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {
    }));
  } catch (t2) {
  }
  return (_isNativeReflectConstruct$7 = function _isNativeReflectConstruct2() {
    return !!t;
  })();
}
function _getPrototypeOf$7(o) {
  _getPrototypeOf$7 = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf2(o2) {
    return o2.__proto__ || Object.getPrototypeOf(o2);
  };
  return _getPrototypeOf$7(o);
}
function _inherits$7(subClass, superClass) {
  if (typeof superClass !== "function" && superClass !== null) {
    throw new TypeError("Super expression must either be null or a function");
  }
  subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } });
  Object.defineProperty(subClass, "prototype", { writable: false });
  if (superClass) _setPrototypeOf$7(subClass, superClass);
}
function _setPrototypeOf$7(o, p) {
  _setPrototypeOf$7 = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf2(o2, p2) {
    o2.__proto__ = p2;
    return o2;
  };
  return _setPrototypeOf$7(o, p);
}
function _defineProperty$c(obj, key2, value) {
  key2 = _toPropertyKey$c(key2);
  if (key2 in obj) {
    Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key2] = value;
  }
  return obj;
}
function _toPropertyKey$c(t) {
  var i = _toPrimitive$c(t, "string");
  return "symbol" == _typeof$c(i) ? i : i + "";
}
function _toPrimitive$c(t, r2) {
  if ("object" != _typeof$c(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r2);
    if ("object" != _typeof$c(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return String(t);
}
var Bar = /* @__PURE__ */ function(_PureComponent) {
  function Bar2() {
    var _this;
    _classCallCheck$9(this, Bar2);
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    _this = _callSuper$7(this, Bar2, [].concat(args));
    _defineProperty$c(_this, "state", {
      isAnimationFinished: false
    });
    _defineProperty$c(_this, "id", uniqueId("recharts-bar-"));
    _defineProperty$c(_this, "handleAnimationEnd", function() {
      var onAnimationEnd = _this.props.onAnimationEnd;
      _this.setState({
        isAnimationFinished: true
      });
      if (onAnimationEnd) {
        onAnimationEnd();
      }
    });
    _defineProperty$c(_this, "handleAnimationStart", function() {
      var onAnimationStart = _this.props.onAnimationStart;
      _this.setState({
        isAnimationFinished: false
      });
      if (onAnimationStart) {
        onAnimationStart();
      }
    });
    return _this;
  }
  _inherits$7(Bar2, _PureComponent);
  return _createClass$9(Bar2, [{
    key: "renderRectanglesStatically",
    value: function renderRectanglesStatically(data) {
      var _this2 = this;
      var _this$props = this.props, shape = _this$props.shape, dataKey = _this$props.dataKey, activeIndex = _this$props.activeIndex, activeBar = _this$props.activeBar;
      var baseProps = filterProps(this.props, false);
      return data && data.map(function(entry, i) {
        var isActive = i === activeIndex;
        var option = isActive ? activeBar : shape;
        var props = _objectSpread$9(_objectSpread$9(_objectSpread$9({}, baseProps), entry), {}, {
          isActive,
          option,
          index: i,
          dataKey,
          onAnimationStart: _this2.handleAnimationStart,
          onAnimationEnd: _this2.handleAnimationEnd
        });
        return /* @__PURE__ */ React.createElement(Layer, _extends$8({
          className: "recharts-bar-rectangle"
        }, adaptEventsOfChild(_this2.props, entry, i), {
          // https://github.com/recharts/recharts/issues/5415
          // eslint-disable-next-line react/no-array-index-key
          key: "rectangle-".concat(entry === null || entry === void 0 ? void 0 : entry.x, "-").concat(entry === null || entry === void 0 ? void 0 : entry.y, "-").concat(entry === null || entry === void 0 ? void 0 : entry.value, "-").concat(i)
        }), /* @__PURE__ */ React.createElement(BarRectangle, props));
      });
    }
  }, {
    key: "renderRectanglesWithAnimation",
    value: function renderRectanglesWithAnimation() {
      var _this3 = this;
      var _this$props2 = this.props, data = _this$props2.data, layout = _this$props2.layout, isAnimationActive = _this$props2.isAnimationActive, animationBegin = _this$props2.animationBegin, animationDuration = _this$props2.animationDuration, animationEasing = _this$props2.animationEasing, animationId = _this$props2.animationId;
      var prevData = this.state.prevData;
      return /* @__PURE__ */ React.createElement(Animate, {
        begin: animationBegin,
        duration: animationDuration,
        isActive: isAnimationActive,
        easing: animationEasing,
        from: {
          t: 0
        },
        to: {
          t: 1
        },
        key: "bar-".concat(animationId),
        onAnimationEnd: this.handleAnimationEnd,
        onAnimationStart: this.handleAnimationStart
      }, function(_ref) {
        var t = _ref.t;
        var stepData = data.map(function(entry, index) {
          var prev = prevData && prevData[index];
          if (prev) {
            var interpolatorX = interpolateNumber$2(prev.x, entry.x);
            var interpolatorY = interpolateNumber$2(prev.y, entry.y);
            var interpolatorWidth = interpolateNumber$2(prev.width, entry.width);
            var interpolatorHeight = interpolateNumber$2(prev.height, entry.height);
            return _objectSpread$9(_objectSpread$9({}, entry), {}, {
              x: interpolatorX(t),
              y: interpolatorY(t),
              width: interpolatorWidth(t),
              height: interpolatorHeight(t)
            });
          }
          if (layout === "horizontal") {
            var _interpolatorHeight = interpolateNumber$2(0, entry.height);
            var h = _interpolatorHeight(t);
            return _objectSpread$9(_objectSpread$9({}, entry), {}, {
              y: entry.y + entry.height - h,
              height: h
            });
          }
          var interpolator = interpolateNumber$2(0, entry.width);
          var w = interpolator(t);
          return _objectSpread$9(_objectSpread$9({}, entry), {}, {
            width: w
          });
        });
        return /* @__PURE__ */ React.createElement(Layer, null, _this3.renderRectanglesStatically(stepData));
      });
    }
  }, {
    key: "renderRectangles",
    value: function renderRectangles() {
      var _this$props3 = this.props, data = _this$props3.data, isAnimationActive = _this$props3.isAnimationActive;
      var prevData = this.state.prevData;
      if (isAnimationActive && data && data.length && (!prevData || !isEqual(prevData, data))) {
        return this.renderRectanglesWithAnimation();
      }
      return this.renderRectanglesStatically(data);
    }
  }, {
    key: "renderBackground",
    value: function renderBackground() {
      var _this4 = this;
      var _this$props4 = this.props, data = _this$props4.data, dataKey = _this$props4.dataKey, activeIndex = _this$props4.activeIndex;
      var backgroundProps = filterProps(this.props.background, false);
      return data.map(function(entry, i) {
        entry.value;
        var background = entry.background, rest = _objectWithoutProperties$3(entry, _excluded$3);
        if (!background) {
          return null;
        }
        var props = _objectSpread$9(_objectSpread$9(_objectSpread$9(_objectSpread$9(_objectSpread$9({}, rest), {}, {
          fill: "#eee"
        }, background), backgroundProps), adaptEventsOfChild(_this4.props, entry, i)), {}, {
          onAnimationStart: _this4.handleAnimationStart,
          onAnimationEnd: _this4.handleAnimationEnd,
          dataKey,
          index: i,
          className: "recharts-bar-background-rectangle"
        });
        return /* @__PURE__ */ React.createElement(BarRectangle, _extends$8({
          key: "background-bar-".concat(i),
          option: _this4.props.background,
          isActive: i === activeIndex
        }, props));
      });
    }
  }, {
    key: "renderErrorBar",
    value: function renderErrorBar(needClip, clipPathId) {
      if (this.props.isAnimationActive && !this.state.isAnimationFinished) {
        return null;
      }
      var _this$props5 = this.props, data = _this$props5.data, xAxis = _this$props5.xAxis, yAxis = _this$props5.yAxis, layout = _this$props5.layout, children = _this$props5.children;
      var errorBarItems = findAllByType(children, ErrorBar);
      if (!errorBarItems) {
        return null;
      }
      var offset = layout === "vertical" ? data[0].height / 2 : data[0].width / 2;
      var dataPointFormatter = function dataPointFormatter2(dataPoint, dataKey) {
        var value = Array.isArray(dataPoint.value) ? dataPoint.value[1] : dataPoint.value;
        return {
          x: dataPoint.x,
          y: dataPoint.y,
          value,
          errorVal: getValueByDataKey(dataPoint, dataKey)
        };
      };
      var errorBarProps = {
        clipPath: needClip ? "url(#clipPath-".concat(clipPathId, ")") : null
      };
      return /* @__PURE__ */ React.createElement(Layer, errorBarProps, errorBarItems.map(function(item) {
        return /* @__PURE__ */ React.cloneElement(item, {
          key: "error-bar-".concat(clipPathId, "-").concat(item.props.dataKey),
          data,
          xAxis,
          yAxis,
          layout,
          offset,
          dataPointFormatter
        });
      }));
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props6 = this.props, hide = _this$props6.hide, data = _this$props6.data, className = _this$props6.className, xAxis = _this$props6.xAxis, yAxis = _this$props6.yAxis, left = _this$props6.left, top = _this$props6.top, width = _this$props6.width, height = _this$props6.height, isAnimationActive = _this$props6.isAnimationActive, background = _this$props6.background, id = _this$props6.id;
      if (hide || !data || !data.length) {
        return null;
      }
      var isAnimationFinished = this.state.isAnimationFinished;
      var layerClass = clsx("recharts-bar", className);
      var needClipX = xAxis && xAxis.allowDataOverflow;
      var needClipY = yAxis && yAxis.allowDataOverflow;
      var needClip = needClipX || needClipY;
      var clipPathId = isNil$1(id) ? this.id : id;
      return /* @__PURE__ */ React.createElement(Layer, {
        className: layerClass
      }, needClipX || needClipY ? /* @__PURE__ */ React.createElement("defs", null, /* @__PURE__ */ React.createElement("clipPath", {
        id: "clipPath-".concat(clipPathId)
      }, /* @__PURE__ */ React.createElement("rect", {
        x: needClipX ? left : left - width / 2,
        y: needClipY ? top : top - height / 2,
        width: needClipX ? width : width * 2,
        height: needClipY ? height : height * 2
      }))) : null, /* @__PURE__ */ React.createElement(Layer, {
        className: "recharts-bar-rectangles",
        clipPath: needClip ? "url(#clipPath-".concat(clipPathId, ")") : null
      }, background ? this.renderBackground() : null, this.renderRectangles()), this.renderErrorBar(needClip, clipPathId), (!isAnimationActive || isAnimationFinished) && LabelList.renderCallByParent(this.props, data));
    }
  }], [{
    key: "getDerivedStateFromProps",
    value: function getDerivedStateFromProps(nextProps, prevState) {
      if (nextProps.animationId !== prevState.prevAnimationId) {
        return {
          prevAnimationId: nextProps.animationId,
          curData: nextProps.data,
          prevData: prevState.curData
        };
      }
      if (nextProps.data !== prevState.curData) {
        return {
          curData: nextProps.data
        };
      }
      return null;
    }
  }]);
}(reactExports.PureComponent);
_Bar = Bar;
_defineProperty$c(Bar, "displayName", "Bar");
_defineProperty$c(Bar, "defaultProps", {
  xAxisId: 0,
  yAxisId: 0,
  legendType: "rect",
  minPointSize: 0,
  hide: false,
  data: [],
  layout: "vertical",
  activeBar: false,
  isAnimationActive: !Global.isSsr,
  animationBegin: 0,
  animationDuration: 400,
  animationEasing: "ease"
});
_defineProperty$c(Bar, "getComposedData", function(_ref2) {
  var props = _ref2.props, item = _ref2.item, barPosition = _ref2.barPosition, bandSize = _ref2.bandSize, xAxis = _ref2.xAxis, yAxis = _ref2.yAxis, xAxisTicks = _ref2.xAxisTicks, yAxisTicks = _ref2.yAxisTicks, stackedData = _ref2.stackedData, dataStartIndex = _ref2.dataStartIndex, displayedData = _ref2.displayedData, offset = _ref2.offset;
  var pos = findPositionOfBar(barPosition, item);
  if (!pos) {
    return null;
  }
  var layout = props.layout;
  var itemDefaultProps = item.type.defaultProps;
  var itemProps = itemDefaultProps !== void 0 ? _objectSpread$9(_objectSpread$9({}, itemDefaultProps), item.props) : item.props;
  var dataKey = itemProps.dataKey, children = itemProps.children, minPointSizeProp = itemProps.minPointSize;
  var numericAxis = layout === "horizontal" ? yAxis : xAxis;
  var stackedDomain = stackedData ? numericAxis.scale.domain() : null;
  var baseValue = getBaseValueOfBar({
    numericAxis
  });
  var cells = findAllByType(children, Cell);
  var rects = displayedData.map(function(entry, index) {
    var value, x2, y2, width, height, background;
    if (stackedData) {
      value = truncateByDomain(stackedData[dataStartIndex + index], stackedDomain);
    } else {
      value = getValueByDataKey(entry, dataKey);
      if (!Array.isArray(value)) {
        value = [baseValue, value];
      }
    }
    var minPointSize = minPointSizeCallback(minPointSizeProp, _Bar.defaultProps.minPointSize)(value[1], index);
    if (layout === "horizontal") {
      var _ref4;
      var _ref3 = [yAxis.scale(value[0]), yAxis.scale(value[1])], baseValueScale = _ref3[0], currentValueScale = _ref3[1];
      x2 = getCateCoordinateOfBar({
        axis: xAxis,
        ticks: xAxisTicks,
        bandSize,
        offset: pos.offset,
        entry,
        index
      });
      y2 = (_ref4 = currentValueScale !== null && currentValueScale !== void 0 ? currentValueScale : baseValueScale) !== null && _ref4 !== void 0 ? _ref4 : void 0;
      width = pos.size;
      var computedHeight = baseValueScale - currentValueScale;
      height = Number.isNaN(computedHeight) ? 0 : computedHeight;
      background = {
        x: x2,
        y: yAxis.y,
        width,
        height: yAxis.height
      };
      if (Math.abs(minPointSize) > 0 && Math.abs(height) < Math.abs(minPointSize)) {
        var delta = mathSign(height || minPointSize) * (Math.abs(minPointSize) - Math.abs(height));
        y2 -= delta;
        height += delta;
      }
    } else {
      var _ref5 = [xAxis.scale(value[0]), xAxis.scale(value[1])], _baseValueScale = _ref5[0], _currentValueScale = _ref5[1];
      x2 = _baseValueScale;
      y2 = getCateCoordinateOfBar({
        axis: yAxis,
        ticks: yAxisTicks,
        bandSize,
        offset: pos.offset,
        entry,
        index
      });
      width = _currentValueScale - _baseValueScale;
      height = pos.size;
      background = {
        x: xAxis.x,
        y: y2,
        width: xAxis.width,
        height
      };
      if (Math.abs(minPointSize) > 0 && Math.abs(width) < Math.abs(minPointSize)) {
        var _delta = mathSign(width || minPointSize) * (Math.abs(minPointSize) - Math.abs(width));
        width += _delta;
      }
    }
    return _objectSpread$9(_objectSpread$9(_objectSpread$9({}, entry), {}, {
      x: x2,
      y: y2,
      width,
      height,
      value: stackedData ? value : value[1],
      payload: entry,
      background
    }, cells && cells[index] && cells[index].props), {}, {
      tooltipPayload: [getTooltipItem(item, entry)],
      tooltipPosition: {
        x: x2 + width / 2,
        y: y2 + height / 2
      }
    });
  });
  return _objectSpread$9({
    data: rects,
    layout
  }, offset);
});
function _typeof$b(o) {
  "@babel/helpers - typeof";
  return _typeof$b = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
    return typeof o2;
  } : function(o2) {
    return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
  }, _typeof$b(o);
}
function _classCallCheck$8(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function _defineProperties$8(target2, props) {
  for (var i = 0; i < props.length; i++) {
    var descriptor = props[i];
    descriptor.enumerable = descriptor.enumerable || false;
    descriptor.configurable = true;
    if ("value" in descriptor) descriptor.writable = true;
    Object.defineProperty(target2, _toPropertyKey$b(descriptor.key), descriptor);
  }
}
function _createClass$8(Constructor, protoProps, staticProps) {
  if (protoProps) _defineProperties$8(Constructor.prototype, protoProps);
  if (staticProps) _defineProperties$8(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", { writable: false });
  return Constructor;
}
function ownKeys$8(e, r2) {
  var t = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    r2 && (o = o.filter(function(r3) {
      return Object.getOwnPropertyDescriptor(e, r3).enumerable;
    })), t.push.apply(t, o);
  }
  return t;
}
function _objectSpread$8(e) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys$8(Object(t), true).forEach(function(r3) {
      _defineProperty$b(e, r3, t[r3]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$8(Object(t)).forEach(function(r3) {
      Object.defineProperty(e, r3, Object.getOwnPropertyDescriptor(t, r3));
    });
  }
  return e;
}
function _defineProperty$b(obj, key2, value) {
  key2 = _toPropertyKey$b(key2);
  if (key2 in obj) {
    Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key2] = value;
  }
  return obj;
}
function _toPropertyKey$b(t) {
  var i = _toPrimitive$b(t, "string");
  return "symbol" == _typeof$b(i) ? i : i + "";
}
function _toPrimitive$b(t, r2) {
  if ("object" != _typeof$b(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r2);
    if ("object" != _typeof$b(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return ("string" === r2 ? String : Number)(t);
}
var formatAxisMap = function formatAxisMap3(props, axisMap, offset, axisType, chartName) {
  var width = props.width, height = props.height, layout = props.layout, children = props.children;
  var ids = Object.keys(axisMap);
  var steps = {
    left: offset.left,
    leftMirror: offset.left,
    right: width - offset.right,
    rightMirror: width - offset.right,
    top: offset.top,
    topMirror: offset.top,
    bottom: height - offset.bottom,
    bottomMirror: height - offset.bottom
  };
  var hasBar = !!findChildByType(children, Bar);
  return ids.reduce(function(result, id) {
    var axis = axisMap[id];
    var orientation = axis.orientation, domain = axis.domain, _axis$padding = axis.padding, padding = _axis$padding === void 0 ? {} : _axis$padding, mirror = axis.mirror, reversed = axis.reversed;
    var offsetKey = "".concat(orientation).concat(mirror ? "Mirror" : "");
    var calculatedPadding, range3, x2, y2, needSpace;
    if (axis.type === "number" && (axis.padding === "gap" || axis.padding === "no-gap")) {
      var diff = domain[1] - domain[0];
      var smallestDistanceBetweenValues = Infinity;
      var sortedValues = axis.categoricalDomain.sort(compareValues);
      sortedValues.forEach(function(value, index) {
        if (index > 0) {
          smallestDistanceBetweenValues = Math.min((value || 0) - (sortedValues[index - 1] || 0), smallestDistanceBetweenValues);
        }
      });
      if (Number.isFinite(smallestDistanceBetweenValues)) {
        var smallestDistanceInPercent = smallestDistanceBetweenValues / diff;
        var rangeWidth = axis.layout === "vertical" ? offset.height : offset.width;
        if (axis.padding === "gap") {
          calculatedPadding = smallestDistanceInPercent * rangeWidth / 2;
        }
        if (axis.padding === "no-gap") {
          var gap = getPercentValue(props.barCategoryGap, smallestDistanceInPercent * rangeWidth);
          var halfBand = smallestDistanceInPercent * rangeWidth / 2;
          calculatedPadding = halfBand - gap - (halfBand - gap) / rangeWidth * gap;
        }
      }
    }
    if (axisType === "xAxis") {
      range3 = [offset.left + (padding.left || 0) + (calculatedPadding || 0), offset.left + offset.width - (padding.right || 0) - (calculatedPadding || 0)];
    } else if (axisType === "yAxis") {
      range3 = layout === "horizontal" ? [offset.top + offset.height - (padding.bottom || 0), offset.top + (padding.top || 0)] : [offset.top + (padding.top || 0) + (calculatedPadding || 0), offset.top + offset.height - (padding.bottom || 0) - (calculatedPadding || 0)];
    } else {
      range3 = axis.range;
    }
    if (reversed) {
      range3 = [range3[1], range3[0]];
    }
    var _parseScale = parseScale(axis, chartName, hasBar), scale2 = _parseScale.scale, realScaleType = _parseScale.realScaleType;
    scale2.domain(domain).range(range3);
    checkDomainOfScale(scale2);
    var ticks2 = getTicksOfScale(scale2, _objectSpread$8(_objectSpread$8({}, axis), {}, {
      realScaleType
    }));
    if (axisType === "xAxis") {
      needSpace = orientation === "top" && !mirror || orientation === "bottom" && mirror;
      x2 = offset.left;
      y2 = steps[offsetKey] - needSpace * axis.height;
    } else if (axisType === "yAxis") {
      needSpace = orientation === "left" && !mirror || orientation === "right" && mirror;
      x2 = steps[offsetKey] - needSpace * axis.width;
      y2 = offset.top;
    }
    var finalAxis = _objectSpread$8(_objectSpread$8(_objectSpread$8({}, axis), ticks2), {}, {
      realScaleType,
      x: x2,
      y: y2,
      scale: scale2,
      width: axisType === "xAxis" ? offset.width : axis.width,
      height: axisType === "yAxis" ? offset.height : axis.height
    });
    finalAxis.bandSize = getBandSizeOfAxis(finalAxis, ticks2);
    if (!axis.hide && axisType === "xAxis") {
      steps[offsetKey] += (needSpace ? -1 : 1) * finalAxis.height;
    } else if (!axis.hide) {
      steps[offsetKey] += (needSpace ? -1 : 1) * finalAxis.width;
    }
    return _objectSpread$8(_objectSpread$8({}, result), {}, _defineProperty$b({}, id, finalAxis));
  }, {});
};
var rectWithPoints = function rectWithPoints2(_ref, _ref2) {
  var x1 = _ref.x, y1 = _ref.y;
  var x2 = _ref2.x, y2 = _ref2.y;
  return {
    x: Math.min(x1, x2),
    y: Math.min(y1, y2),
    width: Math.abs(x2 - x1),
    height: Math.abs(y2 - y1)
  };
};
var rectWithCoords = function rectWithCoords2(_ref3) {
  var x1 = _ref3.x1, y1 = _ref3.y1, x2 = _ref3.x2, y2 = _ref3.y2;
  return rectWithPoints({
    x: x1,
    y: y1
  }, {
    x: x2,
    y: y2
  });
};
var ScaleHelper = /* @__PURE__ */ function() {
  function ScaleHelper2(scale2) {
    _classCallCheck$8(this, ScaleHelper2);
    this.scale = scale2;
  }
  return _createClass$8(ScaleHelper2, [{
    key: "domain",
    get: function get2() {
      return this.scale.domain;
    }
  }, {
    key: "range",
    get: function get2() {
      return this.scale.range;
    }
  }, {
    key: "rangeMin",
    get: function get2() {
      return this.range()[0];
    }
  }, {
    key: "rangeMax",
    get: function get2() {
      return this.range()[1];
    }
  }, {
    key: "bandwidth",
    get: function get2() {
      return this.scale.bandwidth;
    }
  }, {
    key: "apply",
    value: function apply2(value) {
      var _ref4 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}, bandAware = _ref4.bandAware, position = _ref4.position;
      if (value === void 0) {
        return void 0;
      }
      if (position) {
        switch (position) {
          case "start": {
            return this.scale(value);
          }
          case "middle": {
            var offset = this.bandwidth ? this.bandwidth() / 2 : 0;
            return this.scale(value) + offset;
          }
          case "end": {
            var _offset = this.bandwidth ? this.bandwidth() : 0;
            return this.scale(value) + _offset;
          }
          default: {
            return this.scale(value);
          }
        }
      }
      if (bandAware) {
        var _offset2 = this.bandwidth ? this.bandwidth() / 2 : 0;
        return this.scale(value) + _offset2;
      }
      return this.scale(value);
    }
  }, {
    key: "isInRange",
    value: function isInRange(value) {
      var range3 = this.range();
      var first = range3[0];
      var last2 = range3[range3.length - 1];
      return first <= last2 ? value >= first && value <= last2 : value >= last2 && value <= first;
    }
  }], [{
    key: "create",
    value: function create(obj) {
      return new ScaleHelper2(obj);
    }
  }]);
}();
_defineProperty$b(ScaleHelper, "EPS", 1e-4);
var createLabeledScales = function createLabeledScales2(options2) {
  var scales = Object.keys(options2).reduce(function(res, key2) {
    return _objectSpread$8(_objectSpread$8({}, res), {}, _defineProperty$b({}, key2, ScaleHelper.create(options2[key2])));
  }, {});
  return _objectSpread$8(_objectSpread$8({}, scales), {}, {
    apply: function apply2(coord) {
      var _ref5 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}, bandAware = _ref5.bandAware, position = _ref5.position;
      return mapValues$1(coord, function(value, label) {
        return scales[label].apply(value, {
          bandAware,
          position
        });
      });
    },
    isInRange: function isInRange(coord) {
      return every$1(coord, function(value, label) {
        return scales[label].isInRange(value);
      });
    }
  });
};
function normalizeAngle(angle) {
  return (angle % 180 + 180) % 180;
}
var getAngledRectangleWidth = function getAngledRectangleWidth2(_ref6) {
  var width = _ref6.width, height = _ref6.height;
  var angle = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 0;
  var normalizedAngle = normalizeAngle(angle);
  var angleRadians = normalizedAngle * Math.PI / 180;
  var angleThreshold = Math.atan(height / width);
  var angledWidth = angleRadians > angleThreshold && angleRadians < Math.PI - angleThreshold ? height / Math.sin(angleRadians) : width / Math.cos(angleRadians);
  return Math.abs(angledWidth);
};
var baseIteratee$1 = _baseIteratee, isArrayLike = isArrayLike_1, keys = keys_1;
function createFind$1(findIndexFunc) {
  return function(collection, predicate, fromIndex) {
    var iterable = Object(collection);
    if (!isArrayLike(collection)) {
      var iteratee = baseIteratee$1(predicate);
      collection = keys(collection);
      predicate = function(key2) {
        return iteratee(iterable[key2], key2, iterable);
      };
    }
    var index = findIndexFunc(collection, predicate, fromIndex);
    return index > -1 ? iterable[iteratee ? collection[index] : index] : void 0;
  };
}
var _createFind = createFind$1;
var toFinite = toFinite_1;
function toInteger$1(value) {
  var result = toFinite(value), remainder = result % 1;
  return result === result ? remainder ? result - remainder : result : 0;
}
var toInteger_1 = toInteger$1;
var baseFindIndex = _baseFindIndex, baseIteratee = _baseIteratee, toInteger = toInteger_1;
var nativeMax = Math.max;
function findIndex$2(array2, predicate, fromIndex) {
  var length = array2 == null ? 0 : array2.length;
  if (!length) {
    return -1;
  }
  var index = fromIndex == null ? 0 : toInteger(fromIndex);
  if (index < 0) {
    index = nativeMax(length + index, 0);
  }
  return baseFindIndex(array2, baseIteratee(predicate), index);
}
var findIndex_1 = findIndex$2;
var createFind = _createFind, findIndex$1 = findIndex_1;
var find = createFind(findIndex$1);
var find_1 = find;
const find$1 = /* @__PURE__ */ getDefaultExportFromCjs(find_1);
var calculateViewBox = memoize$3(function(offset) {
  return {
    x: offset.left,
    y: offset.top,
    width: offset.width,
    height: offset.height
  };
}, function(offset) {
  return ["l", offset.left, "t", offset.top, "w", offset.width, "h", offset.height].join("");
});
var XAxisContext = /* @__PURE__ */ reactExports.createContext(void 0);
var YAxisContext = /* @__PURE__ */ reactExports.createContext(void 0);
var ViewBoxContext = /* @__PURE__ */ reactExports.createContext(void 0);
var OffsetContext = /* @__PURE__ */ reactExports.createContext({});
var ClipPathIdContext = /* @__PURE__ */ reactExports.createContext(void 0);
var ChartHeightContext = /* @__PURE__ */ reactExports.createContext(0);
var ChartWidthContext = /* @__PURE__ */ reactExports.createContext(0);
var ChartLayoutContextProvider = function ChartLayoutContextProvider2(props) {
  var _props$state = props.state, xAxisMap = _props$state.xAxisMap, yAxisMap = _props$state.yAxisMap, offset = _props$state.offset, clipPathId = props.clipPathId, children = props.children, width = props.width, height = props.height;
  var viewBox = calculateViewBox(offset);
  return /* @__PURE__ */ React.createElement(XAxisContext.Provider, {
    value: xAxisMap
  }, /* @__PURE__ */ React.createElement(YAxisContext.Provider, {
    value: yAxisMap
  }, /* @__PURE__ */ React.createElement(OffsetContext.Provider, {
    value: offset
  }, /* @__PURE__ */ React.createElement(ViewBoxContext.Provider, {
    value: viewBox
  }, /* @__PURE__ */ React.createElement(ClipPathIdContext.Provider, {
    value: clipPathId
  }, /* @__PURE__ */ React.createElement(ChartHeightContext.Provider, {
    value: height
  }, /* @__PURE__ */ React.createElement(ChartWidthContext.Provider, {
    value: width
  }, children)))))));
};
var useClipPathId = function useClipPathId2() {
  return reactExports.useContext(ClipPathIdContext);
};
var useXAxisOrThrow = function useXAxisOrThrow2(xAxisId) {
  var xAxisMap = reactExports.useContext(XAxisContext);
  !(xAxisMap != null) ? invariant() : void 0;
  var xAxis = xAxisMap[xAxisId];
  !(xAxis != null) ? invariant() : void 0;
  return xAxis;
};
var useArbitraryXAxis = function useArbitraryXAxis2() {
  var xAxisMap = reactExports.useContext(XAxisContext);
  return getAnyElementOfObject(xAxisMap);
};
var useYAxisWithFiniteDomainOrRandom = function useYAxisWithFiniteDomainOrRandom2() {
  var yAxisMap = reactExports.useContext(YAxisContext);
  var yAxisWithFiniteDomain = find$1(yAxisMap, function(axis) {
    return every$1(axis.domain, Number.isFinite);
  });
  return yAxisWithFiniteDomain || getAnyElementOfObject(yAxisMap);
};
var useYAxisOrThrow = function useYAxisOrThrow2(yAxisId) {
  var yAxisMap = reactExports.useContext(YAxisContext);
  !(yAxisMap != null) ? invariant() : void 0;
  var yAxis = yAxisMap[yAxisId];
  !(yAxis != null) ? invariant() : void 0;
  return yAxis;
};
var useViewBox = function useViewBox2() {
  var viewBox = reactExports.useContext(ViewBoxContext);
  return viewBox;
};
var useOffset = function useOffset2() {
  return reactExports.useContext(OffsetContext);
};
var useChartWidth = function useChartWidth2() {
  return reactExports.useContext(ChartWidthContext);
};
var useChartHeight = function useChartHeight2() {
  return reactExports.useContext(ChartHeightContext);
};
function _typeof$a(o) {
  "@babel/helpers - typeof";
  return _typeof$a = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
    return typeof o2;
  } : function(o2) {
    return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
  }, _typeof$a(o);
}
function _classCallCheck$7(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function _defineProperties$7(target2, props) {
  for (var i = 0; i < props.length; i++) {
    var descriptor = props[i];
    descriptor.enumerable = descriptor.enumerable || false;
    descriptor.configurable = true;
    if ("value" in descriptor) descriptor.writable = true;
    Object.defineProperty(target2, _toPropertyKey$a(descriptor.key), descriptor);
  }
}
function _createClass$7(Constructor, protoProps, staticProps) {
  if (protoProps) _defineProperties$7(Constructor.prototype, protoProps);
  Object.defineProperty(Constructor, "prototype", { writable: false });
  return Constructor;
}
function _callSuper$6(t, o, e) {
  return o = _getPrototypeOf$6(o), _possibleConstructorReturn$6(t, _isNativeReflectConstruct$6() ? Reflect.construct(o, e || [], _getPrototypeOf$6(t).constructor) : o.apply(t, e));
}
function _possibleConstructorReturn$6(self, call) {
  if (call && (_typeof$a(call) === "object" || typeof call === "function")) {
    return call;
  } else if (call !== void 0) {
    throw new TypeError("Derived constructors may only return object or undefined");
  }
  return _assertThisInitialized$6(self);
}
function _assertThisInitialized$6(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function _isNativeReflectConstruct$6() {
  try {
    var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {
    }));
  } catch (t2) {
  }
  return (_isNativeReflectConstruct$6 = function _isNativeReflectConstruct2() {
    return !!t;
  })();
}
function _getPrototypeOf$6(o) {
  _getPrototypeOf$6 = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf2(o2) {
    return o2.__proto__ || Object.getPrototypeOf(o2);
  };
  return _getPrototypeOf$6(o);
}
function _inherits$6(subClass, superClass) {
  if (typeof superClass !== "function" && superClass !== null) {
    throw new TypeError("Super expression must either be null or a function");
  }
  subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } });
  Object.defineProperty(subClass, "prototype", { writable: false });
  if (superClass) _setPrototypeOf$6(subClass, superClass);
}
function _setPrototypeOf$6(o, p) {
  _setPrototypeOf$6 = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf2(o2, p2) {
    o2.__proto__ = p2;
    return o2;
  };
  return _setPrototypeOf$6(o, p);
}
function ownKeys$7(e, r2) {
  var t = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    r2 && (o = o.filter(function(r3) {
      return Object.getOwnPropertyDescriptor(e, r3).enumerable;
    })), t.push.apply(t, o);
  }
  return t;
}
function _objectSpread$7(e) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys$7(Object(t), true).forEach(function(r3) {
      _defineProperty$a(e, r3, t[r3]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$7(Object(t)).forEach(function(r3) {
      Object.defineProperty(e, r3, Object.getOwnPropertyDescriptor(t, r3));
    });
  }
  return e;
}
function _defineProperty$a(obj, key2, value) {
  key2 = _toPropertyKey$a(key2);
  if (key2 in obj) {
    Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key2] = value;
  }
  return obj;
}
function _toPropertyKey$a(t) {
  var i = _toPrimitive$a(t, "string");
  return "symbol" == _typeof$a(i) ? i : i + "";
}
function _toPrimitive$a(t, r2) {
  if ("object" != _typeof$a(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r2);
    if ("object" != _typeof$a(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return String(t);
}
function _slicedToArray$1(arr, i) {
  return _arrayWithHoles$1(arr) || _iterableToArrayLimit$1(arr, i) || _unsupportedIterableToArray$2(arr, i) || _nonIterableRest$1();
}
function _nonIterableRest$1() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray$2(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return _arrayLikeToArray$2(o, minLen);
  var n = Object.prototype.toString.call(o).slice(8, -1);
  if (n === "Object" && o.constructor) n = o.constructor.name;
  if (n === "Map" || n === "Set") return Array.from(o);
  if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$2(o, minLen);
}
function _arrayLikeToArray$2(arr, len) {
  if (len == null || len > arr.length) len = arr.length;
  for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  return arr2;
}
function _iterableToArrayLimit$1(r2, l) {
  var t = null == r2 ? null : "undefined" != typeof Symbol && r2[Symbol.iterator] || r2["@@iterator"];
  if (null != t) {
    var e, n, i, u, a2 = [], f = true, o = false;
    try {
      if (i = (t = t.call(r2)).next, 0 === l) ;
      else for (; !(f = (e = i.call(t)).done) && (a2.push(e.value), a2.length !== l); f = true) ;
    } catch (r3) {
      o = true, n = r3;
    } finally {
      try {
        if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return;
      } finally {
        if (o) throw n;
      }
    }
    return a2;
  }
}
function _arrayWithHoles$1(arr) {
  if (Array.isArray(arr)) return arr;
}
function _extends$7() {
  _extends$7 = Object.assign ? Object.assign.bind() : function(target2) {
    for (var i = 1; i < arguments.length; i++) {
      var source = arguments[i];
      for (var key2 in source) {
        if (Object.prototype.hasOwnProperty.call(source, key2)) {
          target2[key2] = source[key2];
        }
      }
    }
    return target2;
  };
  return _extends$7.apply(this, arguments);
}
var renderLine = function renderLine2(option, props) {
  var line;
  if (/* @__PURE__ */ React.isValidElement(option)) {
    line = /* @__PURE__ */ React.cloneElement(option, props);
  } else if (isFunction(option)) {
    line = option(props);
  } else {
    line = /* @__PURE__ */ React.createElement("line", _extends$7({}, props, {
      className: "recharts-reference-line-line"
    }));
  }
  return line;
};
var getEndPoints = function getEndPoints2(scales, isFixedX, isFixedY, isSegment, viewBox, position, xAxisOrientation, yAxisOrientation, props) {
  var x2 = viewBox.x, y2 = viewBox.y, width = viewBox.width, height = viewBox.height;
  if (isFixedY) {
    var yCoord = props.y;
    var coord = scales.y.apply(yCoord, {
      position
    });
    if (ifOverflowMatches(props, "discard") && !scales.y.isInRange(coord)) {
      return null;
    }
    var points = [{
      x: x2 + width,
      y: coord
    }, {
      x: x2,
      y: coord
    }];
    return yAxisOrientation === "left" ? points.reverse() : points;
  }
  if (isFixedX) {
    var xCoord = props.x;
    var _coord = scales.x.apply(xCoord, {
      position
    });
    if (ifOverflowMatches(props, "discard") && !scales.x.isInRange(_coord)) {
      return null;
    }
    var _points = [{
      x: _coord,
      y: y2 + height
    }, {
      x: _coord,
      y: y2
    }];
    return xAxisOrientation === "top" ? _points.reverse() : _points;
  }
  if (isSegment) {
    var segment = props.segment;
    var _points2 = segment.map(function(p) {
      return scales.apply(p, {
        position
      });
    });
    if (ifOverflowMatches(props, "discard") && some$1(_points2, function(p) {
      return !scales.isInRange(p);
    })) {
      return null;
    }
    return _points2;
  }
  return null;
};
function ReferenceLineImpl(props) {
  var fixedX = props.x, fixedY = props.y, segment = props.segment, xAxisId = props.xAxisId, yAxisId = props.yAxisId, shape = props.shape, className = props.className, alwaysShow = props.alwaysShow;
  var clipPathId = useClipPathId();
  var xAxis = useXAxisOrThrow(xAxisId);
  var yAxis = useYAxisOrThrow(yAxisId);
  var viewBox = useViewBox();
  if (!clipPathId || !viewBox) {
    return null;
  }
  warn(alwaysShow === void 0, 'The alwaysShow prop is deprecated. Please use ifOverflow="extendDomain" instead.');
  var scales = createLabeledScales({
    x: xAxis.scale,
    y: yAxis.scale
  });
  var isX = isNumOrStr(fixedX);
  var isY = isNumOrStr(fixedY);
  var isSegment = segment && segment.length === 2;
  var endPoints = getEndPoints(scales, isX, isY, isSegment, viewBox, props.position, xAxis.orientation, yAxis.orientation, props);
  if (!endPoints) {
    return null;
  }
  var _endPoints = _slicedToArray$1(endPoints, 2), _endPoints$ = _endPoints[0], x1 = _endPoints$.x, y1 = _endPoints$.y, _endPoints$2 = _endPoints[1], x2 = _endPoints$2.x, y2 = _endPoints$2.y;
  var clipPath = ifOverflowMatches(props, "hidden") ? "url(#".concat(clipPathId, ")") : void 0;
  var lineProps = _objectSpread$7(_objectSpread$7({
    clipPath
  }, filterProps(props, true)), {}, {
    x1,
    y1,
    x2,
    y2
  });
  return /* @__PURE__ */ React.createElement(Layer, {
    className: clsx("recharts-reference-line", className)
  }, renderLine(shape, lineProps), Label$1.renderCallByParent(props, rectWithCoords({
    x1,
    y1,
    x2,
    y2
  })));
}
var ReferenceLine = /* @__PURE__ */ function(_React$Component) {
  function ReferenceLine2() {
    _classCallCheck$7(this, ReferenceLine2);
    return _callSuper$6(this, ReferenceLine2, arguments);
  }
  _inherits$6(ReferenceLine2, _React$Component);
  return _createClass$7(ReferenceLine2, [{
    key: "render",
    value: function render() {
      return /* @__PURE__ */ React.createElement(ReferenceLineImpl, this.props);
    }
  }]);
}(React.Component);
_defineProperty$a(ReferenceLine, "displayName", "ReferenceLine");
_defineProperty$a(ReferenceLine, "defaultProps", {
  isFront: false,
  ifOverflow: "discard",
  xAxisId: 0,
  yAxisId: 0,
  fill: "none",
  stroke: "#ccc",
  fillOpacity: 1,
  strokeWidth: 1,
  position: "middle"
});
function _extends$6() {
  _extends$6 = Object.assign ? Object.assign.bind() : function(target2) {
    for (var i = 1; i < arguments.length; i++) {
      var source = arguments[i];
      for (var key2 in source) {
        if (Object.prototype.hasOwnProperty.call(source, key2)) {
          target2[key2] = source[key2];
        }
      }
    }
    return target2;
  };
  return _extends$6.apply(this, arguments);
}
function _typeof$9(o) {
  "@babel/helpers - typeof";
  return _typeof$9 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
    return typeof o2;
  } : function(o2) {
    return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
  }, _typeof$9(o);
}
function ownKeys$6(e, r2) {
  var t = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    r2 && (o = o.filter(function(r3) {
      return Object.getOwnPropertyDescriptor(e, r3).enumerable;
    })), t.push.apply(t, o);
  }
  return t;
}
function _objectSpread$6(e) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys$6(Object(t), true).forEach(function(r3) {
      _defineProperty$9(e, r3, t[r3]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$6(Object(t)).forEach(function(r3) {
      Object.defineProperty(e, r3, Object.getOwnPropertyDescriptor(t, r3));
    });
  }
  return e;
}
function _classCallCheck$6(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function _defineProperties$6(target2, props) {
  for (var i = 0; i < props.length; i++) {
    var descriptor = props[i];
    descriptor.enumerable = descriptor.enumerable || false;
    descriptor.configurable = true;
    if ("value" in descriptor) descriptor.writable = true;
    Object.defineProperty(target2, _toPropertyKey$9(descriptor.key), descriptor);
  }
}
function _createClass$6(Constructor, protoProps, staticProps) {
  if (protoProps) _defineProperties$6(Constructor.prototype, protoProps);
  Object.defineProperty(Constructor, "prototype", { writable: false });
  return Constructor;
}
function _callSuper$5(t, o, e) {
  return o = _getPrototypeOf$5(o), _possibleConstructorReturn$5(t, _isNativeReflectConstruct$5() ? Reflect.construct(o, e || [], _getPrototypeOf$5(t).constructor) : o.apply(t, e));
}
function _possibleConstructorReturn$5(self, call) {
  if (call && (_typeof$9(call) === "object" || typeof call === "function")) {
    return call;
  } else if (call !== void 0) {
    throw new TypeError("Derived constructors may only return object or undefined");
  }
  return _assertThisInitialized$5(self);
}
function _assertThisInitialized$5(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function _isNativeReflectConstruct$5() {
  try {
    var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {
    }));
  } catch (t2) {
  }
  return (_isNativeReflectConstruct$5 = function _isNativeReflectConstruct2() {
    return !!t;
  })();
}
function _getPrototypeOf$5(o) {
  _getPrototypeOf$5 = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf2(o2) {
    return o2.__proto__ || Object.getPrototypeOf(o2);
  };
  return _getPrototypeOf$5(o);
}
function _inherits$5(subClass, superClass) {
  if (typeof superClass !== "function" && superClass !== null) {
    throw new TypeError("Super expression must either be null or a function");
  }
  subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } });
  Object.defineProperty(subClass, "prototype", { writable: false });
  if (superClass) _setPrototypeOf$5(subClass, superClass);
}
function _setPrototypeOf$5(o, p) {
  _setPrototypeOf$5 = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf2(o2, p2) {
    o2.__proto__ = p2;
    return o2;
  };
  return _setPrototypeOf$5(o, p);
}
function _defineProperty$9(obj, key2, value) {
  key2 = _toPropertyKey$9(key2);
  if (key2 in obj) {
    Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key2] = value;
  }
  return obj;
}
function _toPropertyKey$9(t) {
  var i = _toPrimitive$9(t, "string");
  return "symbol" == _typeof$9(i) ? i : i + "";
}
function _toPrimitive$9(t, r2) {
  if ("object" != _typeof$9(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r2);
    if ("object" != _typeof$9(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return String(t);
}
var getCoordinate = function getCoordinate2(props) {
  var x2 = props.x, y2 = props.y, xAxis = props.xAxis, yAxis = props.yAxis;
  var scales = createLabeledScales({
    x: xAxis.scale,
    y: yAxis.scale
  });
  var result = scales.apply({
    x: x2,
    y: y2
  }, {
    bandAware: true
  });
  if (ifOverflowMatches(props, "discard") && !scales.isInRange(result)) {
    return null;
  }
  return result;
};
var ReferenceDot = /* @__PURE__ */ function(_React$Component) {
  function ReferenceDot2() {
    _classCallCheck$6(this, ReferenceDot2);
    return _callSuper$5(this, ReferenceDot2, arguments);
  }
  _inherits$5(ReferenceDot2, _React$Component);
  return _createClass$6(ReferenceDot2, [{
    key: "render",
    value: function render() {
      var _this$props = this.props, x2 = _this$props.x, y2 = _this$props.y, r2 = _this$props.r, alwaysShow = _this$props.alwaysShow, clipPathId = _this$props.clipPathId;
      var isX = isNumOrStr(x2);
      var isY = isNumOrStr(y2);
      warn(alwaysShow === void 0, 'The alwaysShow prop is deprecated. Please use ifOverflow="extendDomain" instead.');
      if (!isX || !isY) {
        return null;
      }
      var coordinate = getCoordinate(this.props);
      if (!coordinate) {
        return null;
      }
      var cx = coordinate.x, cy = coordinate.y;
      var _this$props2 = this.props, shape = _this$props2.shape, className = _this$props2.className;
      var clipPath = ifOverflowMatches(this.props, "hidden") ? "url(#".concat(clipPathId, ")") : void 0;
      var dotProps = _objectSpread$6(_objectSpread$6({
        clipPath
      }, filterProps(this.props, true)), {}, {
        cx,
        cy
      });
      return /* @__PURE__ */ React.createElement(Layer, {
        className: clsx("recharts-reference-dot", className)
      }, ReferenceDot2.renderDot(shape, dotProps), Label$1.renderCallByParent(this.props, {
        x: cx - r2,
        y: cy - r2,
        width: 2 * r2,
        height: 2 * r2
      }));
    }
  }]);
}(React.Component);
_defineProperty$9(ReferenceDot, "displayName", "ReferenceDot");
_defineProperty$9(ReferenceDot, "defaultProps", {
  isFront: false,
  ifOverflow: "discard",
  xAxisId: 0,
  yAxisId: 0,
  r: 10,
  fill: "#fff",
  stroke: "#ccc",
  fillOpacity: 1,
  strokeWidth: 1
});
_defineProperty$9(ReferenceDot, "renderDot", function(option, props) {
  var dot;
  if (/* @__PURE__ */ React.isValidElement(option)) {
    dot = /* @__PURE__ */ React.cloneElement(option, props);
  } else if (isFunction(option)) {
    dot = option(props);
  } else {
    dot = /* @__PURE__ */ React.createElement(Dot, _extends$6({}, props, {
      cx: props.cx,
      cy: props.cy,
      className: "recharts-reference-dot-dot"
    }));
  }
  return dot;
});
function _extends$5() {
  _extends$5 = Object.assign ? Object.assign.bind() : function(target2) {
    for (var i = 1; i < arguments.length; i++) {
      var source = arguments[i];
      for (var key2 in source) {
        if (Object.prototype.hasOwnProperty.call(source, key2)) {
          target2[key2] = source[key2];
        }
      }
    }
    return target2;
  };
  return _extends$5.apply(this, arguments);
}
function _typeof$8(o) {
  "@babel/helpers - typeof";
  return _typeof$8 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
    return typeof o2;
  } : function(o2) {
    return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
  }, _typeof$8(o);
}
function ownKeys$5(e, r2) {
  var t = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    r2 && (o = o.filter(function(r3) {
      return Object.getOwnPropertyDescriptor(e, r3).enumerable;
    })), t.push.apply(t, o);
  }
  return t;
}
function _objectSpread$5(e) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys$5(Object(t), true).forEach(function(r3) {
      _defineProperty$8(e, r3, t[r3]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$5(Object(t)).forEach(function(r3) {
      Object.defineProperty(e, r3, Object.getOwnPropertyDescriptor(t, r3));
    });
  }
  return e;
}
function _classCallCheck$5(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function _defineProperties$5(target2, props) {
  for (var i = 0; i < props.length; i++) {
    var descriptor = props[i];
    descriptor.enumerable = descriptor.enumerable || false;
    descriptor.configurable = true;
    if ("value" in descriptor) descriptor.writable = true;
    Object.defineProperty(target2, _toPropertyKey$8(descriptor.key), descriptor);
  }
}
function _createClass$5(Constructor, protoProps, staticProps) {
  if (protoProps) _defineProperties$5(Constructor.prototype, protoProps);
  Object.defineProperty(Constructor, "prototype", { writable: false });
  return Constructor;
}
function _callSuper$4(t, o, e) {
  return o = _getPrototypeOf$4(o), _possibleConstructorReturn$4(t, _isNativeReflectConstruct$4() ? Reflect.construct(o, e || [], _getPrototypeOf$4(t).constructor) : o.apply(t, e));
}
function _possibleConstructorReturn$4(self, call) {
  if (call && (_typeof$8(call) === "object" || typeof call === "function")) {
    return call;
  } else if (call !== void 0) {
    throw new TypeError("Derived constructors may only return object or undefined");
  }
  return _assertThisInitialized$4(self);
}
function _assertThisInitialized$4(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function _isNativeReflectConstruct$4() {
  try {
    var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {
    }));
  } catch (t2) {
  }
  return (_isNativeReflectConstruct$4 = function _isNativeReflectConstruct2() {
    return !!t;
  })();
}
function _getPrototypeOf$4(o) {
  _getPrototypeOf$4 = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf2(o2) {
    return o2.__proto__ || Object.getPrototypeOf(o2);
  };
  return _getPrototypeOf$4(o);
}
function _inherits$4(subClass, superClass) {
  if (typeof superClass !== "function" && superClass !== null) {
    throw new TypeError("Super expression must either be null or a function");
  }
  subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } });
  Object.defineProperty(subClass, "prototype", { writable: false });
  if (superClass) _setPrototypeOf$4(subClass, superClass);
}
function _setPrototypeOf$4(o, p) {
  _setPrototypeOf$4 = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf2(o2, p2) {
    o2.__proto__ = p2;
    return o2;
  };
  return _setPrototypeOf$4(o, p);
}
function _defineProperty$8(obj, key2, value) {
  key2 = _toPropertyKey$8(key2);
  if (key2 in obj) {
    Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key2] = value;
  }
  return obj;
}
function _toPropertyKey$8(t) {
  var i = _toPrimitive$8(t, "string");
  return "symbol" == _typeof$8(i) ? i : i + "";
}
function _toPrimitive$8(t, r2) {
  if ("object" != _typeof$8(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r2);
    if ("object" != _typeof$8(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return String(t);
}
var getRect = function getRect2(hasX1, hasX2, hasY1, hasY2, props) {
  var xValue1 = props.x1, xValue2 = props.x2, yValue1 = props.y1, yValue2 = props.y2, xAxis = props.xAxis, yAxis = props.yAxis;
  if (!xAxis || !yAxis) return null;
  var scales = createLabeledScales({
    x: xAxis.scale,
    y: yAxis.scale
  });
  var p1 = {
    x: hasX1 ? scales.x.apply(xValue1, {
      position: "start"
    }) : scales.x.rangeMin,
    y: hasY1 ? scales.y.apply(yValue1, {
      position: "start"
    }) : scales.y.rangeMin
  };
  var p2 = {
    x: hasX2 ? scales.x.apply(xValue2, {
      position: "end"
    }) : scales.x.rangeMax,
    y: hasY2 ? scales.y.apply(yValue2, {
      position: "end"
    }) : scales.y.rangeMax
  };
  if (ifOverflowMatches(props, "discard") && (!scales.isInRange(p1) || !scales.isInRange(p2))) {
    return null;
  }
  return rectWithPoints(p1, p2);
};
var ReferenceArea = /* @__PURE__ */ function(_React$Component) {
  function ReferenceArea2() {
    _classCallCheck$5(this, ReferenceArea2);
    return _callSuper$4(this, ReferenceArea2, arguments);
  }
  _inherits$4(ReferenceArea2, _React$Component);
  return _createClass$5(ReferenceArea2, [{
    key: "render",
    value: function render() {
      var _this$props = this.props, x1 = _this$props.x1, x2 = _this$props.x2, y1 = _this$props.y1, y2 = _this$props.y2, className = _this$props.className, alwaysShow = _this$props.alwaysShow, clipPathId = _this$props.clipPathId;
      warn(alwaysShow === void 0, 'The alwaysShow prop is deprecated. Please use ifOverflow="extendDomain" instead.');
      var hasX1 = isNumOrStr(x1);
      var hasX2 = isNumOrStr(x2);
      var hasY1 = isNumOrStr(y1);
      var hasY2 = isNumOrStr(y2);
      var shape = this.props.shape;
      if (!hasX1 && !hasX2 && !hasY1 && !hasY2 && !shape) {
        return null;
      }
      var rect = getRect(hasX1, hasX2, hasY1, hasY2, this.props);
      if (!rect && !shape) {
        return null;
      }
      var clipPath = ifOverflowMatches(this.props, "hidden") ? "url(#".concat(clipPathId, ")") : void 0;
      return /* @__PURE__ */ React.createElement(Layer, {
        className: clsx("recharts-reference-area", className)
      }, ReferenceArea2.renderRect(shape, _objectSpread$5(_objectSpread$5({
        clipPath
      }, filterProps(this.props, true)), rect)), Label$1.renderCallByParent(this.props, rect));
    }
  }]);
}(React.Component);
_defineProperty$8(ReferenceArea, "displayName", "ReferenceArea");
_defineProperty$8(ReferenceArea, "defaultProps", {
  isFront: false,
  ifOverflow: "discard",
  xAxisId: 0,
  yAxisId: 0,
  r: 10,
  fill: "#ccc",
  fillOpacity: 0.5,
  stroke: "none",
  strokeWidth: 1
});
_defineProperty$8(ReferenceArea, "renderRect", function(option, props) {
  var rect;
  if (/* @__PURE__ */ React.isValidElement(option)) {
    rect = /* @__PURE__ */ React.cloneElement(option, props);
  } else if (isFunction(option)) {
    rect = option(props);
  } else {
    rect = /* @__PURE__ */ React.createElement(Rectangle, _extends$5({}, props, {
      className: "recharts-reference-area-rect"
    }));
  }
  return rect;
});
function getEveryNthWithCondition(array2, n, isValid2) {
  if (n < 1) {
    return [];
  }
  if (n === 1 && isValid2 === void 0) {
    return array2;
  }
  var result = [];
  for (var i = 0; i < array2.length; i += n) {
    {
      result.push(array2[i]);
    }
  }
  return result;
}
function getAngledTickWidth(contentSize, unitSize, angle) {
  var size = {
    width: contentSize.width + unitSize.width,
    height: contentSize.height + unitSize.height
  };
  return getAngledRectangleWidth(size, angle);
}
function getTickBoundaries(viewBox, sign2, sizeKey) {
  var isWidth = sizeKey === "width";
  var x2 = viewBox.x, y2 = viewBox.y, width = viewBox.width, height = viewBox.height;
  if (sign2 === 1) {
    return {
      start: isWidth ? x2 : y2,
      end: isWidth ? x2 + width : y2 + height
    };
  }
  return {
    start: isWidth ? x2 + width : y2 + height,
    end: isWidth ? x2 : y2
  };
}
function isVisible(sign2, tickPosition, getSize, start, end) {
  if (sign2 * tickPosition < sign2 * start || sign2 * tickPosition > sign2 * end) {
    return false;
  }
  var size = getSize();
  return sign2 * (tickPosition - sign2 * size / 2 - start) >= 0 && sign2 * (tickPosition + sign2 * size / 2 - end) <= 0;
}
function getNumberIntervalTicks(ticks2, interval) {
  return getEveryNthWithCondition(ticks2, interval + 1);
}
function getEquidistantTicks(sign2, boundaries, getTickSize, ticks2, minTickGap) {
  var result = (ticks2 || []).slice();
  var initialStart = boundaries.start, end = boundaries.end;
  var index = 0;
  var stepsize = 1;
  var start = initialStart;
  var _loop = function _loop2() {
    var entry = ticks2 === null || ticks2 === void 0 ? void 0 : ticks2[index];
    if (entry === void 0) {
      return {
        v: getEveryNthWithCondition(ticks2, stepsize)
      };
    }
    var i = index;
    var size;
    var getSize = function getSize2() {
      if (size === void 0) {
        size = getTickSize(entry, i);
      }
      return size;
    };
    var tickCoord = entry.coordinate;
    var isShow = index === 0 || isVisible(sign2, tickCoord, getSize, start, end);
    if (!isShow) {
      index = 0;
      start = initialStart;
      stepsize += 1;
    }
    if (isShow) {
      start = tickCoord + sign2 * (getSize() / 2 + minTickGap);
      index += stepsize;
    }
  }, _ret;
  while (stepsize <= result.length) {
    _ret = _loop();
    if (_ret) return _ret.v;
  }
  return [];
}
function _typeof$7(o) {
  "@babel/helpers - typeof";
  return _typeof$7 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
    return typeof o2;
  } : function(o2) {
    return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
  }, _typeof$7(o);
}
function ownKeys$4(e, r2) {
  var t = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    r2 && (o = o.filter(function(r3) {
      return Object.getOwnPropertyDescriptor(e, r3).enumerable;
    })), t.push.apply(t, o);
  }
  return t;
}
function _objectSpread$4(e) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys$4(Object(t), true).forEach(function(r3) {
      _defineProperty$7(e, r3, t[r3]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$4(Object(t)).forEach(function(r3) {
      Object.defineProperty(e, r3, Object.getOwnPropertyDescriptor(t, r3));
    });
  }
  return e;
}
function _defineProperty$7(obj, key2, value) {
  key2 = _toPropertyKey$7(key2);
  if (key2 in obj) {
    Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key2] = value;
  }
  return obj;
}
function _toPropertyKey$7(t) {
  var i = _toPrimitive$7(t, "string");
  return "symbol" == _typeof$7(i) ? i : i + "";
}
function _toPrimitive$7(t, r2) {
  if ("object" != _typeof$7(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r2);
    if ("object" != _typeof$7(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return ("string" === r2 ? String : Number)(t);
}
function getTicksEnd(sign2, boundaries, getTickSize, ticks2, minTickGap) {
  var result = (ticks2 || []).slice();
  var len = result.length;
  var start = boundaries.start;
  var end = boundaries.end;
  var _loop = function _loop2(i2) {
    var entry = result[i2];
    var size;
    var getSize = function getSize2() {
      if (size === void 0) {
        size = getTickSize(entry, i2);
      }
      return size;
    };
    if (i2 === len - 1) {
      var gap = sign2 * (entry.coordinate + sign2 * getSize() / 2 - end);
      result[i2] = entry = _objectSpread$4(_objectSpread$4({}, entry), {}, {
        tickCoord: gap > 0 ? entry.coordinate - gap * sign2 : entry.coordinate
      });
    } else {
      result[i2] = entry = _objectSpread$4(_objectSpread$4({}, entry), {}, {
        tickCoord: entry.coordinate
      });
    }
    var isShow = isVisible(sign2, entry.tickCoord, getSize, start, end);
    if (isShow) {
      end = entry.tickCoord - sign2 * (getSize() / 2 + minTickGap);
      result[i2] = _objectSpread$4(_objectSpread$4({}, entry), {}, {
        isShow: true
      });
    }
  };
  for (var i = len - 1; i >= 0; i--) {
    _loop(i);
  }
  return result;
}
function getTicksStart(sign2, boundaries, getTickSize, ticks2, minTickGap, preserveEnd) {
  var result = (ticks2 || []).slice();
  var len = result.length;
  var start = boundaries.start, end = boundaries.end;
  if (preserveEnd) {
    var tail = ticks2[len - 1];
    var tailSize = getTickSize(tail, len - 1);
    var tailGap = sign2 * (tail.coordinate + sign2 * tailSize / 2 - end);
    result[len - 1] = tail = _objectSpread$4(_objectSpread$4({}, tail), {}, {
      tickCoord: tailGap > 0 ? tail.coordinate - tailGap * sign2 : tail.coordinate
    });
    var isTailShow = isVisible(sign2, tail.tickCoord, function() {
      return tailSize;
    }, start, end);
    if (isTailShow) {
      end = tail.tickCoord - sign2 * (tailSize / 2 + minTickGap);
      result[len - 1] = _objectSpread$4(_objectSpread$4({}, tail), {}, {
        isShow: true
      });
    }
  }
  var count = preserveEnd ? len - 1 : len;
  var _loop2 = function _loop22(i2) {
    var entry = result[i2];
    var size;
    var getSize = function getSize2() {
      if (size === void 0) {
        size = getTickSize(entry, i2);
      }
      return size;
    };
    if (i2 === 0) {
      var gap = sign2 * (entry.coordinate - sign2 * getSize() / 2 - start);
      result[i2] = entry = _objectSpread$4(_objectSpread$4({}, entry), {}, {
        tickCoord: gap < 0 ? entry.coordinate - gap * sign2 : entry.coordinate
      });
    } else {
      result[i2] = entry = _objectSpread$4(_objectSpread$4({}, entry), {}, {
        tickCoord: entry.coordinate
      });
    }
    var isShow = isVisible(sign2, entry.tickCoord, getSize, start, end);
    if (isShow) {
      start = entry.tickCoord + sign2 * (getSize() / 2 + minTickGap);
      result[i2] = _objectSpread$4(_objectSpread$4({}, entry), {}, {
        isShow: true
      });
    }
  };
  for (var i = 0; i < count; i++) {
    _loop2(i);
  }
  return result;
}
function getTicks(props, fontSize, letterSpacing) {
  var tick = props.tick, ticks2 = props.ticks, viewBox = props.viewBox, minTickGap = props.minTickGap, orientation = props.orientation, interval = props.interval, tickFormatter = props.tickFormatter, unit2 = props.unit, angle = props.angle;
  if (!ticks2 || !ticks2.length || !tick) {
    return [];
  }
  if (isNumber(interval) || Global.isSsr) {
    return getNumberIntervalTicks(ticks2, typeof interval === "number" && isNumber(interval) ? interval : 0);
  }
  var candidates = [];
  var sizeKey = orientation === "top" || orientation === "bottom" ? "width" : "height";
  var unitSize = unit2 && sizeKey === "width" ? getStringSize(unit2, {
    fontSize,
    letterSpacing
  }) : {
    width: 0,
    height: 0
  };
  var getTickSize = function getTickSize2(content, index) {
    var value = isFunction(tickFormatter) ? tickFormatter(content.value, index) : content.value;
    return sizeKey === "width" ? getAngledTickWidth(getStringSize(value, {
      fontSize,
      letterSpacing
    }), unitSize, angle) : getStringSize(value, {
      fontSize,
      letterSpacing
    })[sizeKey];
  };
  var sign2 = ticks2.length >= 2 ? mathSign(ticks2[1].coordinate - ticks2[0].coordinate) : 1;
  var boundaries = getTickBoundaries(viewBox, sign2, sizeKey);
  if (interval === "equidistantPreserveStart") {
    return getEquidistantTicks(sign2, boundaries, getTickSize, ticks2, minTickGap);
  }
  if (interval === "preserveStart" || interval === "preserveStartEnd") {
    candidates = getTicksStart(sign2, boundaries, getTickSize, ticks2, minTickGap, interval === "preserveStartEnd");
  } else {
    candidates = getTicksEnd(sign2, boundaries, getTickSize, ticks2, minTickGap);
  }
  return candidates.filter(function(entry) {
    return entry.isShow;
  });
}
var _excluded$2 = ["viewBox"], _excluded2$2 = ["viewBox"], _excluded3 = ["ticks"];
function _typeof$6(o) {
  "@babel/helpers - typeof";
  return _typeof$6 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
    return typeof o2;
  } : function(o2) {
    return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
  }, _typeof$6(o);
}
function _extends$4() {
  _extends$4 = Object.assign ? Object.assign.bind() : function(target2) {
    for (var i = 1; i < arguments.length; i++) {
      var source = arguments[i];
      for (var key2 in source) {
        if (Object.prototype.hasOwnProperty.call(source, key2)) {
          target2[key2] = source[key2];
        }
      }
    }
    return target2;
  };
  return _extends$4.apply(this, arguments);
}
function ownKeys$3(e, r2) {
  var t = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    r2 && (o = o.filter(function(r3) {
      return Object.getOwnPropertyDescriptor(e, r3).enumerable;
    })), t.push.apply(t, o);
  }
  return t;
}
function _objectSpread$3(e) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys$3(Object(t), true).forEach(function(r3) {
      _defineProperty$6(e, r3, t[r3]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$3(Object(t)).forEach(function(r3) {
      Object.defineProperty(e, r3, Object.getOwnPropertyDescriptor(t, r3));
    });
  }
  return e;
}
function _objectWithoutProperties$2(source, excluded) {
  if (source == null) return {};
  var target2 = _objectWithoutPropertiesLoose$2(source, excluded);
  var key2, i;
  if (Object.getOwnPropertySymbols) {
    var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
    for (i = 0; i < sourceSymbolKeys.length; i++) {
      key2 = sourceSymbolKeys[i];
      if (excluded.indexOf(key2) >= 0) continue;
      if (!Object.prototype.propertyIsEnumerable.call(source, key2)) continue;
      target2[key2] = source[key2];
    }
  }
  return target2;
}
function _objectWithoutPropertiesLoose$2(source, excluded) {
  if (source == null) return {};
  var target2 = {};
  for (var key2 in source) {
    if (Object.prototype.hasOwnProperty.call(source, key2)) {
      if (excluded.indexOf(key2) >= 0) continue;
      target2[key2] = source[key2];
    }
  }
  return target2;
}
function _classCallCheck$4(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function _defineProperties$4(target2, props) {
  for (var i = 0; i < props.length; i++) {
    var descriptor = props[i];
    descriptor.enumerable = descriptor.enumerable || false;
    descriptor.configurable = true;
    if ("value" in descriptor) descriptor.writable = true;
    Object.defineProperty(target2, _toPropertyKey$6(descriptor.key), descriptor);
  }
}
function _createClass$4(Constructor, protoProps, staticProps) {
  if (protoProps) _defineProperties$4(Constructor.prototype, protoProps);
  if (staticProps) _defineProperties$4(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", { writable: false });
  return Constructor;
}
function _callSuper$3(t, o, e) {
  return o = _getPrototypeOf$3(o), _possibleConstructorReturn$3(t, _isNativeReflectConstruct$3() ? Reflect.construct(o, e || [], _getPrototypeOf$3(t).constructor) : o.apply(t, e));
}
function _possibleConstructorReturn$3(self, call) {
  if (call && (_typeof$6(call) === "object" || typeof call === "function")) {
    return call;
  } else if (call !== void 0) {
    throw new TypeError("Derived constructors may only return object or undefined");
  }
  return _assertThisInitialized$3(self);
}
function _assertThisInitialized$3(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function _isNativeReflectConstruct$3() {
  try {
    var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {
    }));
  } catch (t2) {
  }
  return (_isNativeReflectConstruct$3 = function _isNativeReflectConstruct2() {
    return !!t;
  })();
}
function _getPrototypeOf$3(o) {
  _getPrototypeOf$3 = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf2(o2) {
    return o2.__proto__ || Object.getPrototypeOf(o2);
  };
  return _getPrototypeOf$3(o);
}
function _inherits$3(subClass, superClass) {
  if (typeof superClass !== "function" && superClass !== null) {
    throw new TypeError("Super expression must either be null or a function");
  }
  subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } });
  Object.defineProperty(subClass, "prototype", { writable: false });
  if (superClass) _setPrototypeOf$3(subClass, superClass);
}
function _setPrototypeOf$3(o, p) {
  _setPrototypeOf$3 = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf2(o2, p2) {
    o2.__proto__ = p2;
    return o2;
  };
  return _setPrototypeOf$3(o, p);
}
function _defineProperty$6(obj, key2, value) {
  key2 = _toPropertyKey$6(key2);
  if (key2 in obj) {
    Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key2] = value;
  }
  return obj;
}
function _toPropertyKey$6(t) {
  var i = _toPrimitive$6(t, "string");
  return "symbol" == _typeof$6(i) ? i : i + "";
}
function _toPrimitive$6(t, r2) {
  if ("object" != _typeof$6(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r2);
    if ("object" != _typeof$6(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return String(t);
}
var CartesianAxis = /* @__PURE__ */ function(_Component) {
  function CartesianAxis2(props) {
    var _this;
    _classCallCheck$4(this, CartesianAxis2);
    _this = _callSuper$3(this, CartesianAxis2, [props]);
    _this.state = {
      fontSize: "",
      letterSpacing: ""
    };
    return _this;
  }
  _inherits$3(CartesianAxis2, _Component);
  return _createClass$4(CartesianAxis2, [{
    key: "shouldComponentUpdate",
    value: function shouldComponentUpdate(_ref, nextState) {
      var viewBox = _ref.viewBox, restProps = _objectWithoutProperties$2(_ref, _excluded$2);
      var _this$props = this.props, viewBoxOld = _this$props.viewBox, restPropsOld = _objectWithoutProperties$2(_this$props, _excluded2$2);
      return !shallowEqual(viewBox, viewBoxOld) || !shallowEqual(restProps, restPropsOld) || !shallowEqual(nextState, this.state);
    }
  }, {
    key: "componentDidMount",
    value: function componentDidMount() {
      var htmlLayer = this.layerReference;
      if (!htmlLayer) return;
      var tick = htmlLayer.getElementsByClassName("recharts-cartesian-axis-tick-value")[0];
      if (tick) {
        this.setState({
          fontSize: window.getComputedStyle(tick).fontSize,
          letterSpacing: window.getComputedStyle(tick).letterSpacing
        });
      }
    }
    /**
     * Calculate the coordinates of endpoints in ticks
     * @param  {Object} data The data of a simple tick
     * @return {Object} (x1, y1): The coordinate of endpoint close to tick text
     *  (x2, y2): The coordinate of endpoint close to axis
     */
  }, {
    key: "getTickLineCoord",
    value: function getTickLineCoord(data) {
      var _this$props2 = this.props, x2 = _this$props2.x, y2 = _this$props2.y, width = _this$props2.width, height = _this$props2.height, orientation = _this$props2.orientation, tickSize = _this$props2.tickSize, mirror = _this$props2.mirror, tickMargin = _this$props2.tickMargin;
      var x1, x22, y1, y22, tx, ty;
      var sign2 = mirror ? -1 : 1;
      var finalTickSize = data.tickSize || tickSize;
      var tickCoord = isNumber(data.tickCoord) ? data.tickCoord : data.coordinate;
      switch (orientation) {
        case "top":
          x1 = x22 = data.coordinate;
          y22 = y2 + +!mirror * height;
          y1 = y22 - sign2 * finalTickSize;
          ty = y1 - sign2 * tickMargin;
          tx = tickCoord;
          break;
        case "left":
          y1 = y22 = data.coordinate;
          x22 = x2 + +!mirror * width;
          x1 = x22 - sign2 * finalTickSize;
          tx = x1 - sign2 * tickMargin;
          ty = tickCoord;
          break;
        case "right":
          y1 = y22 = data.coordinate;
          x22 = x2 + +mirror * width;
          x1 = x22 + sign2 * finalTickSize;
          tx = x1 + sign2 * tickMargin;
          ty = tickCoord;
          break;
        default:
          x1 = x22 = data.coordinate;
          y22 = y2 + +mirror * height;
          y1 = y22 + sign2 * finalTickSize;
          ty = y1 + sign2 * tickMargin;
          tx = tickCoord;
          break;
      }
      return {
        line: {
          x1,
          y1,
          x2: x22,
          y2: y22
        },
        tick: {
          x: tx,
          y: ty
        }
      };
    }
  }, {
    key: "getTickTextAnchor",
    value: function getTickTextAnchor() {
      var _this$props3 = this.props, orientation = _this$props3.orientation, mirror = _this$props3.mirror;
      var textAnchor;
      switch (orientation) {
        case "left":
          textAnchor = mirror ? "start" : "end";
          break;
        case "right":
          textAnchor = mirror ? "end" : "start";
          break;
        default:
          textAnchor = "middle";
          break;
      }
      return textAnchor;
    }
  }, {
    key: "getTickVerticalAnchor",
    value: function getTickVerticalAnchor() {
      var _this$props4 = this.props, orientation = _this$props4.orientation, mirror = _this$props4.mirror;
      var verticalAnchor = "end";
      switch (orientation) {
        case "left":
        case "right":
          verticalAnchor = "middle";
          break;
        case "top":
          verticalAnchor = mirror ? "start" : "end";
          break;
        default:
          verticalAnchor = mirror ? "end" : "start";
          break;
      }
      return verticalAnchor;
    }
  }, {
    key: "renderAxisLine",
    value: function renderAxisLine() {
      var _this$props5 = this.props, x2 = _this$props5.x, y2 = _this$props5.y, width = _this$props5.width, height = _this$props5.height, orientation = _this$props5.orientation, mirror = _this$props5.mirror, axisLine = _this$props5.axisLine;
      var props = _objectSpread$3(_objectSpread$3(_objectSpread$3({}, filterProps(this.props, false)), filterProps(axisLine, false)), {}, {
        fill: "none"
      });
      if (orientation === "top" || orientation === "bottom") {
        var needHeight = +(orientation === "top" && !mirror || orientation === "bottom" && mirror);
        props = _objectSpread$3(_objectSpread$3({}, props), {}, {
          x1: x2,
          y1: y2 + needHeight * height,
          x2: x2 + width,
          y2: y2 + needHeight * height
        });
      } else {
        var needWidth = +(orientation === "left" && !mirror || orientation === "right" && mirror);
        props = _objectSpread$3(_objectSpread$3({}, props), {}, {
          x1: x2 + needWidth * width,
          y1: y2,
          x2: x2 + needWidth * width,
          y2: y2 + height
        });
      }
      return /* @__PURE__ */ React.createElement("line", _extends$4({}, props, {
        className: clsx("recharts-cartesian-axis-line", get$2(axisLine, "className"))
      }));
    }
  }, {
    key: "renderTicks",
    value: (
      /**
       * render the ticks
       * @param {Array} ticks The ticks to actually render (overrides what was passed in props)
       * @param {string} fontSize Fontsize to consider for tick spacing
       * @param {string} letterSpacing Letterspacing to consider for tick spacing
       * @return {ReactComponent} renderedTicks
       */
      function renderTicks(ticks2, fontSize, letterSpacing) {
        var _this2 = this;
        var _this$props6 = this.props, tickLine = _this$props6.tickLine, stroke = _this$props6.stroke, tick = _this$props6.tick, tickFormatter = _this$props6.tickFormatter, unit2 = _this$props6.unit;
        var finalTicks = getTicks(_objectSpread$3(_objectSpread$3({}, this.props), {}, {
          ticks: ticks2
        }), fontSize, letterSpacing);
        var textAnchor = this.getTickTextAnchor();
        var verticalAnchor = this.getTickVerticalAnchor();
        var axisProps = filterProps(this.props, false);
        var customTickProps = filterProps(tick, false);
        var tickLineProps = _objectSpread$3(_objectSpread$3({}, axisProps), {}, {
          fill: "none"
        }, filterProps(tickLine, false));
        var items = finalTicks.map(function(entry, i) {
          var _this2$getTickLineCoo = _this2.getTickLineCoord(entry), lineCoord = _this2$getTickLineCoo.line, tickCoord = _this2$getTickLineCoo.tick;
          var tickProps = _objectSpread$3(_objectSpread$3(_objectSpread$3(_objectSpread$3({
            textAnchor,
            verticalAnchor
          }, axisProps), {}, {
            stroke: "none",
            fill: stroke
          }, customTickProps), tickCoord), {}, {
            index: i,
            payload: entry,
            visibleTicksCount: finalTicks.length,
            tickFormatter
          });
          return /* @__PURE__ */ React.createElement(Layer, _extends$4({
            className: "recharts-cartesian-axis-tick",
            key: "tick-".concat(entry.value, "-").concat(entry.coordinate, "-").concat(entry.tickCoord)
          }, adaptEventsOfChild(_this2.props, entry, i)), tickLine && /* @__PURE__ */ React.createElement("line", _extends$4({}, tickLineProps, lineCoord, {
            className: clsx("recharts-cartesian-axis-tick-line", get$2(tickLine, "className"))
          })), tick && CartesianAxis2.renderTickItem(tick, tickProps, "".concat(isFunction(tickFormatter) ? tickFormatter(entry.value, i) : entry.value).concat(unit2 || "")));
        });
        return /* @__PURE__ */ React.createElement("g", {
          className: "recharts-cartesian-axis-ticks"
        }, items);
      }
    )
  }, {
    key: "render",
    value: function render() {
      var _this3 = this;
      var _this$props7 = this.props, axisLine = _this$props7.axisLine, width = _this$props7.width, height = _this$props7.height, ticksGenerator = _this$props7.ticksGenerator, className = _this$props7.className, hide = _this$props7.hide;
      if (hide) {
        return null;
      }
      var _this$props8 = this.props, ticks2 = _this$props8.ticks, noTicksProps = _objectWithoutProperties$2(_this$props8, _excluded3);
      var finalTicks = ticks2;
      if (isFunction(ticksGenerator)) {
        finalTicks = ticks2 && ticks2.length > 0 ? ticksGenerator(this.props) : ticksGenerator(noTicksProps);
      }
      if (width <= 0 || height <= 0 || !finalTicks || !finalTicks.length) {
        return null;
      }
      return /* @__PURE__ */ React.createElement(Layer, {
        className: clsx("recharts-cartesian-axis", className),
        ref: function ref(_ref2) {
          _this3.layerReference = _ref2;
        }
      }, axisLine && this.renderAxisLine(), this.renderTicks(finalTicks, this.state.fontSize, this.state.letterSpacing), Label$1.renderCallByParent(this.props));
    }
  }], [{
    key: "renderTickItem",
    value: function renderTickItem(option, props, value) {
      var tickItem;
      var combinedClassName = clsx(props.className, "recharts-cartesian-axis-tick-value");
      if (/* @__PURE__ */ React.isValidElement(option)) {
        tickItem = /* @__PURE__ */ React.cloneElement(option, _objectSpread$3(_objectSpread$3({}, props), {}, {
          className: combinedClassName
        }));
      } else if (isFunction(option)) {
        tickItem = option(_objectSpread$3(_objectSpread$3({}, props), {}, {
          className: combinedClassName
        }));
      } else {
        tickItem = /* @__PURE__ */ React.createElement(Text, _extends$4({}, props, {
          className: "recharts-cartesian-axis-tick-value"
        }), value);
      }
      return tickItem;
    }
  }]);
}(reactExports.Component);
_defineProperty$6(CartesianAxis, "displayName", "CartesianAxis");
_defineProperty$6(CartesianAxis, "defaultProps", {
  x: 0,
  y: 0,
  width: 0,
  height: 0,
  viewBox: {
    x: 0,
    y: 0,
    width: 0,
    height: 0
  },
  // The orientation of axis
  orientation: "bottom",
  // The ticks
  ticks: [],
  stroke: "#666",
  tickLine: true,
  axisLine: true,
  tick: true,
  mirror: false,
  minTickGap: 5,
  // The width or height of tick
  tickSize: 6,
  tickMargin: 2,
  interval: "preserveEnd"
});
var _excluded$1 = ["x1", "y1", "x2", "y2", "key"], _excluded2$1 = ["offset"];
function _typeof$5(o) {
  "@babel/helpers - typeof";
  return _typeof$5 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
    return typeof o2;
  } : function(o2) {
    return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
  }, _typeof$5(o);
}
function ownKeys$2(e, r2) {
  var t = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    r2 && (o = o.filter(function(r3) {
      return Object.getOwnPropertyDescriptor(e, r3).enumerable;
    })), t.push.apply(t, o);
  }
  return t;
}
function _objectSpread$2(e) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys$2(Object(t), true).forEach(function(r3) {
      _defineProperty$5(e, r3, t[r3]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$2(Object(t)).forEach(function(r3) {
      Object.defineProperty(e, r3, Object.getOwnPropertyDescriptor(t, r3));
    });
  }
  return e;
}
function _defineProperty$5(obj, key2, value) {
  key2 = _toPropertyKey$5(key2);
  if (key2 in obj) {
    Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key2] = value;
  }
  return obj;
}
function _toPropertyKey$5(t) {
  var i = _toPrimitive$5(t, "string");
  return "symbol" == _typeof$5(i) ? i : i + "";
}
function _toPrimitive$5(t, r2) {
  if ("object" != _typeof$5(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r2);
    if ("object" != _typeof$5(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return ("string" === r2 ? String : Number)(t);
}
function _extends$3() {
  _extends$3 = Object.assign ? Object.assign.bind() : function(target2) {
    for (var i = 1; i < arguments.length; i++) {
      var source = arguments[i];
      for (var key2 in source) {
        if (Object.prototype.hasOwnProperty.call(source, key2)) {
          target2[key2] = source[key2];
        }
      }
    }
    return target2;
  };
  return _extends$3.apply(this, arguments);
}
function _objectWithoutProperties$1(source, excluded) {
  if (source == null) return {};
  var target2 = _objectWithoutPropertiesLoose$1(source, excluded);
  var key2, i;
  if (Object.getOwnPropertySymbols) {
    var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
    for (i = 0; i < sourceSymbolKeys.length; i++) {
      key2 = sourceSymbolKeys[i];
      if (excluded.indexOf(key2) >= 0) continue;
      if (!Object.prototype.propertyIsEnumerable.call(source, key2)) continue;
      target2[key2] = source[key2];
    }
  }
  return target2;
}
function _objectWithoutPropertiesLoose$1(source, excluded) {
  if (source == null) return {};
  var target2 = {};
  for (var key2 in source) {
    if (Object.prototype.hasOwnProperty.call(source, key2)) {
      if (excluded.indexOf(key2) >= 0) continue;
      target2[key2] = source[key2];
    }
  }
  return target2;
}
var Background = function Background2(props) {
  var fill = props.fill;
  if (!fill || fill === "none") {
    return null;
  }
  var fillOpacity = props.fillOpacity, x2 = props.x, y2 = props.y, width = props.width, height = props.height, ry = props.ry;
  return /* @__PURE__ */ React.createElement("rect", {
    x: x2,
    y: y2,
    ry,
    width,
    height,
    stroke: "none",
    fill,
    fillOpacity,
    className: "recharts-cartesian-grid-bg"
  });
};
function renderLineItem(option, props) {
  var lineItem;
  if (/* @__PURE__ */ React.isValidElement(option)) {
    lineItem = /* @__PURE__ */ React.cloneElement(option, props);
  } else if (isFunction(option)) {
    lineItem = option(props);
  } else {
    var x1 = props.x1, y1 = props.y1, x2 = props.x2, y2 = props.y2, key2 = props.key, others = _objectWithoutProperties$1(props, _excluded$1);
    var _filterProps = filterProps(others, false);
    _filterProps.offset;
    var restOfFilteredProps = _objectWithoutProperties$1(_filterProps, _excluded2$1);
    lineItem = /* @__PURE__ */ React.createElement("line", _extends$3({}, restOfFilteredProps, {
      x1,
      y1,
      x2,
      y2,
      fill: "none",
      key: key2
    }));
  }
  return lineItem;
}
function HorizontalGridLines(props) {
  var x2 = props.x, width = props.width, _props$horizontal = props.horizontal, horizontal = _props$horizontal === void 0 ? true : _props$horizontal, horizontalPoints = props.horizontalPoints;
  if (!horizontal || !horizontalPoints || !horizontalPoints.length) {
    return null;
  }
  var items = horizontalPoints.map(function(entry, i) {
    var lineItemProps = _objectSpread$2(_objectSpread$2({}, props), {}, {
      x1: x2,
      y1: entry,
      x2: x2 + width,
      y2: entry,
      key: "line-".concat(i),
      index: i
    });
    return renderLineItem(horizontal, lineItemProps);
  });
  return /* @__PURE__ */ React.createElement("g", {
    className: "recharts-cartesian-grid-horizontal"
  }, items);
}
function VerticalGridLines(props) {
  var y2 = props.y, height = props.height, _props$vertical = props.vertical, vertical = _props$vertical === void 0 ? true : _props$vertical, verticalPoints = props.verticalPoints;
  if (!vertical || !verticalPoints || !verticalPoints.length) {
    return null;
  }
  var items = verticalPoints.map(function(entry, i) {
    var lineItemProps = _objectSpread$2(_objectSpread$2({}, props), {}, {
      x1: entry,
      y1: y2,
      x2: entry,
      y2: y2 + height,
      key: "line-".concat(i),
      index: i
    });
    return renderLineItem(vertical, lineItemProps);
  });
  return /* @__PURE__ */ React.createElement("g", {
    className: "recharts-cartesian-grid-vertical"
  }, items);
}
function HorizontalStripes(props) {
  var horizontalFill = props.horizontalFill, fillOpacity = props.fillOpacity, x2 = props.x, y2 = props.y, width = props.width, height = props.height, horizontalPoints = props.horizontalPoints, _props$horizontal2 = props.horizontal, horizontal = _props$horizontal2 === void 0 ? true : _props$horizontal2;
  if (!horizontal || !horizontalFill || !horizontalFill.length) {
    return null;
  }
  var roundedSortedHorizontalPoints = horizontalPoints.map(function(e) {
    return Math.round(e + y2 - y2);
  }).sort(function(a2, b) {
    return a2 - b;
  });
  if (y2 !== roundedSortedHorizontalPoints[0]) {
    roundedSortedHorizontalPoints.unshift(0);
  }
  var items = roundedSortedHorizontalPoints.map(function(entry, i) {
    var lastStripe = !roundedSortedHorizontalPoints[i + 1];
    var lineHeight = lastStripe ? y2 + height - entry : roundedSortedHorizontalPoints[i + 1] - entry;
    if (lineHeight <= 0) {
      return null;
    }
    var colorIndex = i % horizontalFill.length;
    return /* @__PURE__ */ React.createElement("rect", {
      key: "react-".concat(i),
      y: entry,
      x: x2,
      height: lineHeight,
      width,
      stroke: "none",
      fill: horizontalFill[colorIndex],
      fillOpacity,
      className: "recharts-cartesian-grid-bg"
    });
  });
  return /* @__PURE__ */ React.createElement("g", {
    className: "recharts-cartesian-gridstripes-horizontal"
  }, items);
}
function VerticalStripes(props) {
  var _props$vertical2 = props.vertical, vertical = _props$vertical2 === void 0 ? true : _props$vertical2, verticalFill = props.verticalFill, fillOpacity = props.fillOpacity, x2 = props.x, y2 = props.y, width = props.width, height = props.height, verticalPoints = props.verticalPoints;
  if (!vertical || !verticalFill || !verticalFill.length) {
    return null;
  }
  var roundedSortedVerticalPoints = verticalPoints.map(function(e) {
    return Math.round(e + x2 - x2);
  }).sort(function(a2, b) {
    return a2 - b;
  });
  if (x2 !== roundedSortedVerticalPoints[0]) {
    roundedSortedVerticalPoints.unshift(0);
  }
  var items = roundedSortedVerticalPoints.map(function(entry, i) {
    var lastStripe = !roundedSortedVerticalPoints[i + 1];
    var lineWidth = lastStripe ? x2 + width - entry : roundedSortedVerticalPoints[i + 1] - entry;
    if (lineWidth <= 0) {
      return null;
    }
    var colorIndex = i % verticalFill.length;
    return /* @__PURE__ */ React.createElement("rect", {
      key: "react-".concat(i),
      x: entry,
      y: y2,
      width: lineWidth,
      height,
      stroke: "none",
      fill: verticalFill[colorIndex],
      fillOpacity,
      className: "recharts-cartesian-grid-bg"
    });
  });
  return /* @__PURE__ */ React.createElement("g", {
    className: "recharts-cartesian-gridstripes-vertical"
  }, items);
}
var defaultVerticalCoordinatesGenerator = function defaultVerticalCoordinatesGenerator2(_ref, syncWithTicks) {
  var xAxis = _ref.xAxis, width = _ref.width, height = _ref.height, offset = _ref.offset;
  return getCoordinatesOfGrid(getTicks(_objectSpread$2(_objectSpread$2(_objectSpread$2({}, CartesianAxis.defaultProps), xAxis), {}, {
    ticks: getTicksOfAxis(xAxis, true),
    viewBox: {
      x: 0,
      y: 0,
      width,
      height
    }
  })), offset.left, offset.left + offset.width, syncWithTicks);
};
var defaultHorizontalCoordinatesGenerator = function defaultHorizontalCoordinatesGenerator2(_ref2, syncWithTicks) {
  var yAxis = _ref2.yAxis, width = _ref2.width, height = _ref2.height, offset = _ref2.offset;
  return getCoordinatesOfGrid(getTicks(_objectSpread$2(_objectSpread$2(_objectSpread$2({}, CartesianAxis.defaultProps), yAxis), {}, {
    ticks: getTicksOfAxis(yAxis, true),
    viewBox: {
      x: 0,
      y: 0,
      width,
      height
    }
  })), offset.top, offset.top + offset.height, syncWithTicks);
};
var defaultProps = {
  horizontal: true,
  vertical: true,
  stroke: "#ccc",
  fill: "none",
  // The fill of colors of grid lines
  verticalFill: [],
  horizontalFill: []
};
function CartesianGrid(props) {
  var _props$stroke, _props$fill, _props$horizontal3, _props$horizontalFill, _props$vertical3, _props$verticalFill;
  var chartWidth = useChartWidth();
  var chartHeight = useChartHeight();
  var offset = useOffset();
  var propsIncludingDefaults = _objectSpread$2(_objectSpread$2({}, props), {}, {
    stroke: (_props$stroke = props.stroke) !== null && _props$stroke !== void 0 ? _props$stroke : defaultProps.stroke,
    fill: (_props$fill = props.fill) !== null && _props$fill !== void 0 ? _props$fill : defaultProps.fill,
    horizontal: (_props$horizontal3 = props.horizontal) !== null && _props$horizontal3 !== void 0 ? _props$horizontal3 : defaultProps.horizontal,
    horizontalFill: (_props$horizontalFill = props.horizontalFill) !== null && _props$horizontalFill !== void 0 ? _props$horizontalFill : defaultProps.horizontalFill,
    vertical: (_props$vertical3 = props.vertical) !== null && _props$vertical3 !== void 0 ? _props$vertical3 : defaultProps.vertical,
    verticalFill: (_props$verticalFill = props.verticalFill) !== null && _props$verticalFill !== void 0 ? _props$verticalFill : defaultProps.verticalFill,
    x: isNumber(props.x) ? props.x : offset.left,
    y: isNumber(props.y) ? props.y : offset.top,
    width: isNumber(props.width) ? props.width : offset.width,
    height: isNumber(props.height) ? props.height : offset.height
  });
  var x2 = propsIncludingDefaults.x, y2 = propsIncludingDefaults.y, width = propsIncludingDefaults.width, height = propsIncludingDefaults.height, syncWithTicks = propsIncludingDefaults.syncWithTicks, horizontalValues = propsIncludingDefaults.horizontalValues, verticalValues = propsIncludingDefaults.verticalValues;
  var xAxis = useArbitraryXAxis();
  var yAxis = useYAxisWithFiniteDomainOrRandom();
  if (!isNumber(width) || width <= 0 || !isNumber(height) || height <= 0 || !isNumber(x2) || x2 !== +x2 || !isNumber(y2) || y2 !== +y2) {
    return null;
  }
  var verticalCoordinatesGenerator = propsIncludingDefaults.verticalCoordinatesGenerator || defaultVerticalCoordinatesGenerator;
  var horizontalCoordinatesGenerator = propsIncludingDefaults.horizontalCoordinatesGenerator || defaultHorizontalCoordinatesGenerator;
  var horizontalPoints = propsIncludingDefaults.horizontalPoints, verticalPoints = propsIncludingDefaults.verticalPoints;
  if ((!horizontalPoints || !horizontalPoints.length) && isFunction(horizontalCoordinatesGenerator)) {
    var isHorizontalValues = horizontalValues && horizontalValues.length;
    var generatorResult = horizontalCoordinatesGenerator({
      yAxis: yAxis ? _objectSpread$2(_objectSpread$2({}, yAxis), {}, {
        ticks: isHorizontalValues ? horizontalValues : yAxis.ticks
      }) : void 0,
      width: chartWidth,
      height: chartHeight,
      offset
    }, isHorizontalValues ? true : syncWithTicks);
    warn(Array.isArray(generatorResult), "horizontalCoordinatesGenerator should return Array but instead it returned [".concat(_typeof$5(generatorResult), "]"));
    if (Array.isArray(generatorResult)) {
      horizontalPoints = generatorResult;
    }
  }
  if ((!verticalPoints || !verticalPoints.length) && isFunction(verticalCoordinatesGenerator)) {
    var isVerticalValues = verticalValues && verticalValues.length;
    var _generatorResult = verticalCoordinatesGenerator({
      xAxis: xAxis ? _objectSpread$2(_objectSpread$2({}, xAxis), {}, {
        ticks: isVerticalValues ? verticalValues : xAxis.ticks
      }) : void 0,
      width: chartWidth,
      height: chartHeight,
      offset
    }, isVerticalValues ? true : syncWithTicks);
    warn(Array.isArray(_generatorResult), "verticalCoordinatesGenerator should return Array but instead it returned [".concat(_typeof$5(_generatorResult), "]"));
    if (Array.isArray(_generatorResult)) {
      verticalPoints = _generatorResult;
    }
  }
  return /* @__PURE__ */ React.createElement("g", {
    className: "recharts-cartesian-grid"
  }, /* @__PURE__ */ React.createElement(Background, {
    fill: propsIncludingDefaults.fill,
    fillOpacity: propsIncludingDefaults.fillOpacity,
    x: propsIncludingDefaults.x,
    y: propsIncludingDefaults.y,
    width: propsIncludingDefaults.width,
    height: propsIncludingDefaults.height,
    ry: propsIncludingDefaults.ry
  }), /* @__PURE__ */ React.createElement(HorizontalGridLines, _extends$3({}, propsIncludingDefaults, {
    offset,
    horizontalPoints,
    xAxis,
    yAxis
  })), /* @__PURE__ */ React.createElement(VerticalGridLines, _extends$3({}, propsIncludingDefaults, {
    offset,
    verticalPoints,
    xAxis,
    yAxis
  })), /* @__PURE__ */ React.createElement(HorizontalStripes, _extends$3({}, propsIncludingDefaults, {
    horizontalPoints
  })), /* @__PURE__ */ React.createElement(VerticalStripes, _extends$3({}, propsIncludingDefaults, {
    verticalPoints
  })));
}
CartesianGrid.displayName = "CartesianGrid";
function _typeof$4(o) {
  "@babel/helpers - typeof";
  return _typeof$4 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
    return typeof o2;
  } : function(o2) {
    return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
  }, _typeof$4(o);
}
function _classCallCheck$3(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function _defineProperties$3(target2, props) {
  for (var i = 0; i < props.length; i++) {
    var descriptor = props[i];
    descriptor.enumerable = descriptor.enumerable || false;
    descriptor.configurable = true;
    if ("value" in descriptor) descriptor.writable = true;
    Object.defineProperty(target2, _toPropertyKey$4(descriptor.key), descriptor);
  }
}
function _createClass$3(Constructor, protoProps, staticProps) {
  if (protoProps) _defineProperties$3(Constructor.prototype, protoProps);
  Object.defineProperty(Constructor, "prototype", { writable: false });
  return Constructor;
}
function _callSuper$2(t, o, e) {
  return o = _getPrototypeOf$2(o), _possibleConstructorReturn$2(t, _isNativeReflectConstruct$2() ? Reflect.construct(o, e || [], _getPrototypeOf$2(t).constructor) : o.apply(t, e));
}
function _possibleConstructorReturn$2(self, call) {
  if (call && (_typeof$4(call) === "object" || typeof call === "function")) {
    return call;
  } else if (call !== void 0) {
    throw new TypeError("Derived constructors may only return object or undefined");
  }
  return _assertThisInitialized$2(self);
}
function _assertThisInitialized$2(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function _isNativeReflectConstruct$2() {
  try {
    var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {
    }));
  } catch (t2) {
  }
  return (_isNativeReflectConstruct$2 = function _isNativeReflectConstruct2() {
    return !!t;
  })();
}
function _getPrototypeOf$2(o) {
  _getPrototypeOf$2 = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf2(o2) {
    return o2.__proto__ || Object.getPrototypeOf(o2);
  };
  return _getPrototypeOf$2(o);
}
function _inherits$2(subClass, superClass) {
  if (typeof superClass !== "function" && superClass !== null) {
    throw new TypeError("Super expression must either be null or a function");
  }
  subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } });
  Object.defineProperty(subClass, "prototype", { writable: false });
  if (superClass) _setPrototypeOf$2(subClass, superClass);
}
function _setPrototypeOf$2(o, p) {
  _setPrototypeOf$2 = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf2(o2, p2) {
    o2.__proto__ = p2;
    return o2;
  };
  return _setPrototypeOf$2(o, p);
}
function _defineProperty$4(obj, key2, value) {
  key2 = _toPropertyKey$4(key2);
  if (key2 in obj) {
    Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key2] = value;
  }
  return obj;
}
function _toPropertyKey$4(t) {
  var i = _toPrimitive$4(t, "string");
  return "symbol" == _typeof$4(i) ? i : i + "";
}
function _toPrimitive$4(t, r2) {
  if ("object" != _typeof$4(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r2);
    if ("object" != _typeof$4(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return String(t);
}
function _extends$2() {
  _extends$2 = Object.assign ? Object.assign.bind() : function(target2) {
    for (var i = 1; i < arguments.length; i++) {
      var source = arguments[i];
      for (var key2 in source) {
        if (Object.prototype.hasOwnProperty.call(source, key2)) {
          target2[key2] = source[key2];
        }
      }
    }
    return target2;
  };
  return _extends$2.apply(this, arguments);
}
function XAxisImpl(_ref) {
  var xAxisId = _ref.xAxisId;
  var width = useChartWidth();
  var height = useChartHeight();
  var axisOptions = useXAxisOrThrow(xAxisId);
  if (axisOptions == null) {
    return null;
  }
  return (
    // @ts-expect-error the axisOptions type is not exactly what CartesianAxis is expecting.
    /* @__PURE__ */ reactExports.createElement(CartesianAxis, _extends$2({}, axisOptions, {
      className: clsx("recharts-".concat(axisOptions.axisType, " ").concat(axisOptions.axisType), axisOptions.className),
      viewBox: {
        x: 0,
        y: 0,
        width,
        height
      },
      ticksGenerator: function ticksGenerator(axis) {
        return getTicksOfAxis(axis, true);
      }
    }))
  );
}
var XAxis = /* @__PURE__ */ function(_React$Component) {
  function XAxis2() {
    _classCallCheck$3(this, XAxis2);
    return _callSuper$2(this, XAxis2, arguments);
  }
  _inherits$2(XAxis2, _React$Component);
  return _createClass$3(XAxis2, [{
    key: "render",
    value: function render() {
      return /* @__PURE__ */ reactExports.createElement(XAxisImpl, this.props);
    }
  }]);
}(reactExports.Component);
_defineProperty$4(XAxis, "displayName", "XAxis");
_defineProperty$4(XAxis, "defaultProps", {
  allowDecimals: true,
  hide: false,
  orientation: "bottom",
  width: 0,
  height: 30,
  mirror: false,
  xAxisId: 0,
  tickCount: 5,
  type: "category",
  padding: {
    left: 0,
    right: 0
  },
  allowDataOverflow: false,
  scale: "auto",
  reversed: false,
  allowDuplicatedCategory: true
});
function _typeof$3(o) {
  "@babel/helpers - typeof";
  return _typeof$3 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
    return typeof o2;
  } : function(o2) {
    return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
  }, _typeof$3(o);
}
function _classCallCheck$2(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function _defineProperties$2(target2, props) {
  for (var i = 0; i < props.length; i++) {
    var descriptor = props[i];
    descriptor.enumerable = descriptor.enumerable || false;
    descriptor.configurable = true;
    if ("value" in descriptor) descriptor.writable = true;
    Object.defineProperty(target2, _toPropertyKey$3(descriptor.key), descriptor);
  }
}
function _createClass$2(Constructor, protoProps, staticProps) {
  if (protoProps) _defineProperties$2(Constructor.prototype, protoProps);
  Object.defineProperty(Constructor, "prototype", { writable: false });
  return Constructor;
}
function _callSuper$1(t, o, e) {
  return o = _getPrototypeOf$1(o), _possibleConstructorReturn$1(t, _isNativeReflectConstruct$1() ? Reflect.construct(o, e || [], _getPrototypeOf$1(t).constructor) : o.apply(t, e));
}
function _possibleConstructorReturn$1(self, call) {
  if (call && (_typeof$3(call) === "object" || typeof call === "function")) {
    return call;
  } else if (call !== void 0) {
    throw new TypeError("Derived constructors may only return object or undefined");
  }
  return _assertThisInitialized$1(self);
}
function _assertThisInitialized$1(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function _isNativeReflectConstruct$1() {
  try {
    var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {
    }));
  } catch (t2) {
  }
  return (_isNativeReflectConstruct$1 = function _isNativeReflectConstruct2() {
    return !!t;
  })();
}
function _getPrototypeOf$1(o) {
  _getPrototypeOf$1 = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf2(o2) {
    return o2.__proto__ || Object.getPrototypeOf(o2);
  };
  return _getPrototypeOf$1(o);
}
function _inherits$1(subClass, superClass) {
  if (typeof superClass !== "function" && superClass !== null) {
    throw new TypeError("Super expression must either be null or a function");
  }
  subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } });
  Object.defineProperty(subClass, "prototype", { writable: false });
  if (superClass) _setPrototypeOf$1(subClass, superClass);
}
function _setPrototypeOf$1(o, p) {
  _setPrototypeOf$1 = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf2(o2, p2) {
    o2.__proto__ = p2;
    return o2;
  };
  return _setPrototypeOf$1(o, p);
}
function _defineProperty$3(obj, key2, value) {
  key2 = _toPropertyKey$3(key2);
  if (key2 in obj) {
    Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key2] = value;
  }
  return obj;
}
function _toPropertyKey$3(t) {
  var i = _toPrimitive$3(t, "string");
  return "symbol" == _typeof$3(i) ? i : i + "";
}
function _toPrimitive$3(t, r2) {
  if ("object" != _typeof$3(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r2);
    if ("object" != _typeof$3(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return String(t);
}
function _extends$1() {
  _extends$1 = Object.assign ? Object.assign.bind() : function(target2) {
    for (var i = 1; i < arguments.length; i++) {
      var source = arguments[i];
      for (var key2 in source) {
        if (Object.prototype.hasOwnProperty.call(source, key2)) {
          target2[key2] = source[key2];
        }
      }
    }
    return target2;
  };
  return _extends$1.apply(this, arguments);
}
var YAxisImpl = function YAxisImpl2(_ref) {
  var yAxisId = _ref.yAxisId;
  var width = useChartWidth();
  var height = useChartHeight();
  var axisOptions = useYAxisOrThrow(yAxisId);
  if (axisOptions == null) {
    return null;
  }
  return (
    // @ts-expect-error the axisOptions type is not exactly what CartesianAxis is expecting.
    /* @__PURE__ */ reactExports.createElement(CartesianAxis, _extends$1({}, axisOptions, {
      className: clsx("recharts-".concat(axisOptions.axisType, " ").concat(axisOptions.axisType), axisOptions.className),
      viewBox: {
        x: 0,
        y: 0,
        width,
        height
      },
      ticksGenerator: function ticksGenerator(axis) {
        return getTicksOfAxis(axis, true);
      }
    }))
  );
};
var YAxis = /* @__PURE__ */ function(_React$Component) {
  function YAxis2() {
    _classCallCheck$2(this, YAxis2);
    return _callSuper$1(this, YAxis2, arguments);
  }
  _inherits$1(YAxis2, _React$Component);
  return _createClass$2(YAxis2, [{
    key: "render",
    value: function render() {
      return /* @__PURE__ */ reactExports.createElement(YAxisImpl, this.props);
    }
  }]);
}(reactExports.Component);
_defineProperty$3(YAxis, "displayName", "YAxis");
_defineProperty$3(YAxis, "defaultProps", {
  allowDuplicatedCategory: true,
  allowDecimals: true,
  hide: false,
  orientation: "left",
  width: 60,
  height: 0,
  mirror: false,
  yAxisId: 0,
  tickCount: 5,
  type: "number",
  padding: {
    top: 0,
    bottom: 0
  },
  allowDataOverflow: false,
  scale: "auto",
  reversed: false
});
function _toConsumableArray$1(arr) {
  return _arrayWithoutHoles$1(arr) || _iterableToArray$1(arr) || _unsupportedIterableToArray$1(arr) || _nonIterableSpread$1();
}
function _nonIterableSpread$1() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray$1(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return _arrayLikeToArray$1(o, minLen);
  var n = Object.prototype.toString.call(o).slice(8, -1);
  if (n === "Object" && o.constructor) n = o.constructor.name;
  if (n === "Map" || n === "Set") return Array.from(o);
  if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$1(o, minLen);
}
function _iterableToArray$1(iter) {
  if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _arrayWithoutHoles$1(arr) {
  if (Array.isArray(arr)) return _arrayLikeToArray$1(arr);
}
function _arrayLikeToArray$1(arr, len) {
  if (len == null || len > arr.length) len = arr.length;
  for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  return arr2;
}
var detectReferenceElementsDomain = function detectReferenceElementsDomain2(children, domain, axisId, axisType, specifiedTicks) {
  var lines = findAllByType(children, ReferenceLine);
  var dots = findAllByType(children, ReferenceDot);
  var elements = [].concat(_toConsumableArray$1(lines), _toConsumableArray$1(dots));
  var areas = findAllByType(children, ReferenceArea);
  var idKey = "".concat(axisType, "Id");
  var valueKey = axisType[0];
  var finalDomain = domain;
  if (elements.length) {
    finalDomain = elements.reduce(function(result, el) {
      if (el.props[idKey] === axisId && ifOverflowMatches(el.props, "extendDomain") && isNumber(el.props[valueKey])) {
        var value = el.props[valueKey];
        return [Math.min(result[0], value), Math.max(result[1], value)];
      }
      return result;
    }, finalDomain);
  }
  if (areas.length) {
    var key1 = "".concat(valueKey, "1");
    var key2 = "".concat(valueKey, "2");
    finalDomain = areas.reduce(function(result, el) {
      if (el.props[idKey] === axisId && ifOverflowMatches(el.props, "extendDomain") && isNumber(el.props[key1]) && isNumber(el.props[key2])) {
        var value1 = el.props[key1];
        var value2 = el.props[key2];
        return [Math.min(result[0], value1, value2), Math.max(result[1], value1, value2)];
      }
      return result;
    }, finalDomain);
  }
  if (specifiedTicks && specifiedTicks.length) {
    finalDomain = specifiedTicks.reduce(function(result, tick) {
      if (isNumber(tick)) {
        return [Math.min(result[0], tick), Math.max(result[1], tick)];
      }
      return result;
    }, finalDomain);
  }
  return finalDomain;
};
var eventemitter3 = { exports: {} };
(function(module) {
  var has = Object.prototype.hasOwnProperty, prefix2 = "~";
  function Events() {
  }
  if (Object.create) {
    Events.prototype = /* @__PURE__ */ Object.create(null);
    if (!new Events().__proto__) prefix2 = false;
  }
  function EE(fn, context, once) {
    this.fn = fn;
    this.context = context;
    this.once = once || false;
  }
  function addListener(emitter, event, fn, context, once) {
    if (typeof fn !== "function") {
      throw new TypeError("The listener must be a function");
    }
    var listener = new EE(fn, context || emitter, once), evt = prefix2 ? prefix2 + event : event;
    if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
    else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
    else emitter._events[evt] = [emitter._events[evt], listener];
    return emitter;
  }
  function clearEvent(emitter, evt) {
    if (--emitter._eventsCount === 0) emitter._events = new Events();
    else delete emitter._events[evt];
  }
  function EventEmitter2() {
    this._events = new Events();
    this._eventsCount = 0;
  }
  EventEmitter2.prototype.eventNames = function eventNames() {
    var names = [], events, name;
    if (this._eventsCount === 0) return names;
    for (name in events = this._events) {
      if (has.call(events, name)) names.push(prefix2 ? name.slice(1) : name);
    }
    if (Object.getOwnPropertySymbols) {
      return names.concat(Object.getOwnPropertySymbols(events));
    }
    return names;
  };
  EventEmitter2.prototype.listeners = function listeners(event) {
    var evt = prefix2 ? prefix2 + event : event, handlers = this._events[evt];
    if (!handlers) return [];
    if (handlers.fn) return [handlers.fn];
    for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
      ee[i] = handlers[i].fn;
    }
    return ee;
  };
  EventEmitter2.prototype.listenerCount = function listenerCount(event) {
    var evt = prefix2 ? prefix2 + event : event, listeners = this._events[evt];
    if (!listeners) return 0;
    if (listeners.fn) return 1;
    return listeners.length;
  };
  EventEmitter2.prototype.emit = function emit2(event, a1, a2, a3, a4, a5) {
    var evt = prefix2 ? prefix2 + event : event;
    if (!this._events[evt]) return false;
    var listeners = this._events[evt], len = arguments.length, args, i;
    if (listeners.fn) {
      if (listeners.once) this.removeListener(event, listeners.fn, void 0, true);
      switch (len) {
        case 1:
          return listeners.fn.call(listeners.context), true;
        case 2:
          return listeners.fn.call(listeners.context, a1), true;
        case 3:
          return listeners.fn.call(listeners.context, a1, a2), true;
        case 4:
          return listeners.fn.call(listeners.context, a1, a2, a3), true;
        case 5:
          return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
        case 6:
          return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
      }
      for (i = 1, args = new Array(len - 1); i < len; i++) {
        args[i - 1] = arguments[i];
      }
      listeners.fn.apply(listeners.context, args);
    } else {
      var length = listeners.length, j;
      for (i = 0; i < length; i++) {
        if (listeners[i].once) this.removeListener(event, listeners[i].fn, void 0, true);
        switch (len) {
          case 1:
            listeners[i].fn.call(listeners[i].context);
            break;
          case 2:
            listeners[i].fn.call(listeners[i].context, a1);
            break;
          case 3:
            listeners[i].fn.call(listeners[i].context, a1, a2);
            break;
          case 4:
            listeners[i].fn.call(listeners[i].context, a1, a2, a3);
            break;
          default:
            if (!args) for (j = 1, args = new Array(len - 1); j < len; j++) {
              args[j - 1] = arguments[j];
            }
            listeners[i].fn.apply(listeners[i].context, args);
        }
      }
    }
    return true;
  };
  EventEmitter2.prototype.on = function on(event, fn, context) {
    return addListener(this, event, fn, context, false);
  };
  EventEmitter2.prototype.once = function once(event, fn, context) {
    return addListener(this, event, fn, context, true);
  };
  EventEmitter2.prototype.removeListener = function removeListener(event, fn, context, once) {
    var evt = prefix2 ? prefix2 + event : event;
    if (!this._events[evt]) return this;
    if (!fn) {
      clearEvent(this, evt);
      return this;
    }
    var listeners = this._events[evt];
    if (listeners.fn) {
      if (listeners.fn === fn && (!once || listeners.once) && (!context || listeners.context === context)) {
        clearEvent(this, evt);
      }
    } else {
      for (var i = 0, events = [], length = listeners.length; i < length; i++) {
        if (listeners[i].fn !== fn || once && !listeners[i].once || context && listeners[i].context !== context) {
          events.push(listeners[i]);
        }
      }
      if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
      else clearEvent(this, evt);
    }
    return this;
  };
  EventEmitter2.prototype.removeAllListeners = function removeAllListeners(event) {
    var evt;
    if (event) {
      evt = prefix2 ? prefix2 + event : event;
      if (this._events[evt]) clearEvent(this, evt);
    } else {
      this._events = new Events();
      this._eventsCount = 0;
    }
    return this;
  };
  EventEmitter2.prototype.off = EventEmitter2.prototype.removeListener;
  EventEmitter2.prototype.addListener = EventEmitter2.prototype.on;
  EventEmitter2.prefixed = prefix2;
  EventEmitter2.EventEmitter = EventEmitter2;
  {
    module.exports = EventEmitter2;
  }
})(eventemitter3);
var eventemitter3Exports = eventemitter3.exports;
const EventEmitter = /* @__PURE__ */ getDefaultExportFromCjs(eventemitter3Exports);
var eventCenter = new EventEmitter();
var SYNC_EVENT = "recharts.syncMouseEvents";
function _typeof$2(o) {
  "@babel/helpers - typeof";
  return _typeof$2 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
    return typeof o2;
  } : function(o2) {
    return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
  }, _typeof$2(o);
}
function _classCallCheck$1(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function _defineProperties$1(target2, props) {
  for (var i = 0; i < props.length; i++) {
    var descriptor = props[i];
    descriptor.enumerable = descriptor.enumerable || false;
    descriptor.configurable = true;
    if ("value" in descriptor) descriptor.writable = true;
    Object.defineProperty(target2, _toPropertyKey$2(descriptor.key), descriptor);
  }
}
function _createClass$1(Constructor, protoProps, staticProps) {
  if (protoProps) _defineProperties$1(Constructor.prototype, protoProps);
  Object.defineProperty(Constructor, "prototype", { writable: false });
  return Constructor;
}
function _defineProperty$2(obj, key2, value) {
  key2 = _toPropertyKey$2(key2);
  if (key2 in obj) {
    Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key2] = value;
  }
  return obj;
}
function _toPropertyKey$2(t) {
  var i = _toPrimitive$2(t, "string");
  return "symbol" == _typeof$2(i) ? i : i + "";
}
function _toPrimitive$2(t, r2) {
  if ("object" != _typeof$2(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r2);
    if ("object" != _typeof$2(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return String(t);
}
var AccessibilityManager = /* @__PURE__ */ function() {
  function AccessibilityManager2() {
    _classCallCheck$1(this, AccessibilityManager2);
    _defineProperty$2(this, "activeIndex", 0);
    _defineProperty$2(this, "coordinateList", []);
    _defineProperty$2(this, "layout", "horizontal");
  }
  return _createClass$1(AccessibilityManager2, [{
    key: "setDetails",
    value: function setDetails(_ref) {
      var _ref2;
      var _ref$coordinateList = _ref.coordinateList, coordinateList = _ref$coordinateList === void 0 ? null : _ref$coordinateList, _ref$container = _ref.container, container = _ref$container === void 0 ? null : _ref$container, _ref$layout = _ref.layout, layout = _ref$layout === void 0 ? null : _ref$layout, _ref$offset = _ref.offset, offset = _ref$offset === void 0 ? null : _ref$offset, _ref$mouseHandlerCall = _ref.mouseHandlerCallback, mouseHandlerCallback = _ref$mouseHandlerCall === void 0 ? null : _ref$mouseHandlerCall;
      this.coordinateList = (_ref2 = coordinateList !== null && coordinateList !== void 0 ? coordinateList : this.coordinateList) !== null && _ref2 !== void 0 ? _ref2 : [];
      this.container = container !== null && container !== void 0 ? container : this.container;
      this.layout = layout !== null && layout !== void 0 ? layout : this.layout;
      this.offset = offset !== null && offset !== void 0 ? offset : this.offset;
      this.mouseHandlerCallback = mouseHandlerCallback !== null && mouseHandlerCallback !== void 0 ? mouseHandlerCallback : this.mouseHandlerCallback;
      this.activeIndex = Math.min(Math.max(this.activeIndex, 0), this.coordinateList.length - 1);
    }
  }, {
    key: "focus",
    value: function focus() {
      this.spoofMouse();
    }
  }, {
    key: "keyboardEvent",
    value: function keyboardEvent(e) {
      if (this.coordinateList.length === 0) {
        return;
      }
      switch (e.key) {
        case "ArrowRight": {
          if (this.layout !== "horizontal") {
            return;
          }
          this.activeIndex = Math.min(this.activeIndex + 1, this.coordinateList.length - 1);
          this.spoofMouse();
          break;
        }
        case "ArrowLeft": {
          if (this.layout !== "horizontal") {
            return;
          }
          this.activeIndex = Math.max(this.activeIndex - 1, 0);
          this.spoofMouse();
          break;
        }
      }
    }
  }, {
    key: "setIndex",
    value: function setIndex(newIndex) {
      this.activeIndex = newIndex;
    }
  }, {
    key: "spoofMouse",
    value: function spoofMouse() {
      var _window, _window2;
      if (this.layout !== "horizontal") {
        return;
      }
      if (this.coordinateList.length === 0) {
        return;
      }
      var _this$container$getBo = this.container.getBoundingClientRect(), x2 = _this$container$getBo.x, y2 = _this$container$getBo.y, height = _this$container$getBo.height;
      var coordinate = this.coordinateList[this.activeIndex].coordinate;
      var scrollOffsetX = ((_window = window) === null || _window === void 0 ? void 0 : _window.scrollX) || 0;
      var scrollOffsetY = ((_window2 = window) === null || _window2 === void 0 ? void 0 : _window2.scrollY) || 0;
      var pageX = x2 + coordinate + scrollOffsetX;
      var pageY = y2 + this.offset.top + height / 2 + scrollOffsetY;
      this.mouseHandlerCallback({
        pageX,
        pageY
      });
    }
  }]);
}();
function isDomainSpecifiedByUser(domain, allowDataOverflow, axisType) {
  if (axisType === "number" && allowDataOverflow === true && Array.isArray(domain)) {
    var domainStart = domain === null || domain === void 0 ? void 0 : domain[0];
    var domainEnd = domain === null || domain === void 0 ? void 0 : domain[1];
    if (!!domainStart && !!domainEnd && isNumber(domainStart) && isNumber(domainEnd)) {
      return true;
    }
  }
  return false;
}
function getCursorRectangle(layout, activeCoordinate, offset, tooltipAxisBandSize) {
  var halfSize = tooltipAxisBandSize / 2;
  return {
    stroke: "none",
    fill: "#ccc",
    x: layout === "horizontal" ? activeCoordinate.x - halfSize : offset.left + 0.5,
    y: layout === "horizontal" ? offset.top + 0.5 : activeCoordinate.y - halfSize,
    width: layout === "horizontal" ? tooltipAxisBandSize : offset.width - 1,
    height: layout === "horizontal" ? offset.height - 1 : tooltipAxisBandSize
  };
}
function getRadialCursorPoints(activeCoordinate) {
  var cx = activeCoordinate.cx, cy = activeCoordinate.cy, radius = activeCoordinate.radius, startAngle = activeCoordinate.startAngle, endAngle = activeCoordinate.endAngle;
  var startPoint = polarToCartesian(cx, cy, radius, startAngle);
  var endPoint = polarToCartesian(cx, cy, radius, endAngle);
  return {
    points: [startPoint, endPoint],
    cx,
    cy,
    radius,
    startAngle,
    endAngle
  };
}
function getCursorPoints(layout, activeCoordinate, offset) {
  var x1, y1, x2, y2;
  if (layout === "horizontal") {
    x1 = activeCoordinate.x;
    x2 = x1;
    y1 = offset.top;
    y2 = offset.top + offset.height;
  } else if (layout === "vertical") {
    y1 = activeCoordinate.y;
    y2 = y1;
    x1 = offset.left;
    x2 = offset.left + offset.width;
  } else if (activeCoordinate.cx != null && activeCoordinate.cy != null) {
    if (layout === "centric") {
      var cx = activeCoordinate.cx, cy = activeCoordinate.cy, innerRadius = activeCoordinate.innerRadius, outerRadius = activeCoordinate.outerRadius, angle = activeCoordinate.angle;
      var innerPoint = polarToCartesian(cx, cy, innerRadius, angle);
      var outerPoint = polarToCartesian(cx, cy, outerRadius, angle);
      x1 = innerPoint.x;
      y1 = innerPoint.y;
      x2 = outerPoint.x;
      y2 = outerPoint.y;
    } else {
      return getRadialCursorPoints(activeCoordinate);
    }
  }
  return [{
    x: x1,
    y: y1
  }, {
    x: x2,
    y: y2
  }];
}
function _typeof$1(o) {
  "@babel/helpers - typeof";
  return _typeof$1 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
    return typeof o2;
  } : function(o2) {
    return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
  }, _typeof$1(o);
}
function ownKeys$1(e, r2) {
  var t = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    r2 && (o = o.filter(function(r3) {
      return Object.getOwnPropertyDescriptor(e, r3).enumerable;
    })), t.push.apply(t, o);
  }
  return t;
}
function _objectSpread$1(e) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys$1(Object(t), true).forEach(function(r3) {
      _defineProperty$1(e, r3, t[r3]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$1(Object(t)).forEach(function(r3) {
      Object.defineProperty(e, r3, Object.getOwnPropertyDescriptor(t, r3));
    });
  }
  return e;
}
function _defineProperty$1(obj, key2, value) {
  key2 = _toPropertyKey$1(key2);
  if (key2 in obj) {
    Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key2] = value;
  }
  return obj;
}
function _toPropertyKey$1(t) {
  var i = _toPrimitive$1(t, "string");
  return "symbol" == _typeof$1(i) ? i : i + "";
}
function _toPrimitive$1(t, r2) {
  if ("object" != _typeof$1(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r2);
    if ("object" != _typeof$1(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return ("string" === r2 ? String : Number)(t);
}
function Cursor(props) {
  var _element$props$cursor, _defaultProps;
  var element = props.element, tooltipEventType = props.tooltipEventType, isActive = props.isActive, activeCoordinate = props.activeCoordinate, activePayload = props.activePayload, offset = props.offset, activeTooltipIndex = props.activeTooltipIndex, tooltipAxisBandSize = props.tooltipAxisBandSize, layout = props.layout, chartName = props.chartName;
  var elementPropsCursor = (_element$props$cursor = element.props.cursor) !== null && _element$props$cursor !== void 0 ? _element$props$cursor : (_defaultProps = element.type.defaultProps) === null || _defaultProps === void 0 ? void 0 : _defaultProps.cursor;
  if (!element || !elementPropsCursor || !isActive || !activeCoordinate || chartName !== "ScatterChart" && tooltipEventType !== "axis") {
    return null;
  }
  var restProps;
  var cursorComp = Curve;
  if (chartName === "ScatterChart") {
    restProps = activeCoordinate;
    cursorComp = Cross;
  } else if (chartName === "BarChart") {
    restProps = getCursorRectangle(layout, activeCoordinate, offset, tooltipAxisBandSize);
    cursorComp = Rectangle;
  } else if (layout === "radial") {
    var _getRadialCursorPoint = getRadialCursorPoints(activeCoordinate), cx = _getRadialCursorPoint.cx, cy = _getRadialCursorPoint.cy, radius = _getRadialCursorPoint.radius, startAngle = _getRadialCursorPoint.startAngle, endAngle = _getRadialCursorPoint.endAngle;
    restProps = {
      cx,
      cy,
      startAngle,
      endAngle,
      innerRadius: radius,
      outerRadius: radius
    };
    cursorComp = Sector;
  } else {
    restProps = {
      points: getCursorPoints(layout, activeCoordinate, offset)
    };
    cursorComp = Curve;
  }
  var cursorProps = _objectSpread$1(_objectSpread$1(_objectSpread$1(_objectSpread$1({
    stroke: "#ccc",
    pointerEvents: "none"
  }, offset), restProps), filterProps(elementPropsCursor, false)), {}, {
    payload: activePayload,
    payloadIndex: activeTooltipIndex,
    className: clsx("recharts-tooltip-cursor", elementPropsCursor.className)
  });
  return /* @__PURE__ */ reactExports.isValidElement(elementPropsCursor) ? /* @__PURE__ */ reactExports.cloneElement(elementPropsCursor, cursorProps) : /* @__PURE__ */ reactExports.createElement(cursorComp, cursorProps);
}
var _excluded = ["item"], _excluded2 = ["children", "className", "width", "height", "style", "compact", "title", "desc"];
function _typeof(o) {
  "@babel/helpers - typeof";
  return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
    return typeof o2;
  } : function(o2) {
    return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
  }, _typeof(o);
}
function _extends() {
  _extends = Object.assign ? Object.assign.bind() : function(target2) {
    for (var i = 1; i < arguments.length; i++) {
      var source = arguments[i];
      for (var key2 in source) {
        if (Object.prototype.hasOwnProperty.call(source, key2)) {
          target2[key2] = source[key2];
        }
      }
    }
    return target2;
  };
  return _extends.apply(this, arguments);
}
function _slicedToArray(arr, i) {
  return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
}
function _nonIterableRest() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _iterableToArrayLimit(r2, l) {
  var t = null == r2 ? null : "undefined" != typeof Symbol && r2[Symbol.iterator] || r2["@@iterator"];
  if (null != t) {
    var e, n, i, u, a2 = [], f = true, o = false;
    try {
      if (i = (t = t.call(r2)).next, 0 === l) ;
      else for (; !(f = (e = i.call(t)).done) && (a2.push(e.value), a2.length !== l); f = true) ;
    } catch (r22) {
      o = true, n = r22;
    } finally {
      try {
        if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return;
      } finally {
        if (o) throw n;
      }
    }
    return a2;
  }
}
function _arrayWithHoles(arr) {
  if (Array.isArray(arr)) return arr;
}
function _objectWithoutProperties(source, excluded) {
  if (source == null) return {};
  var target2 = _objectWithoutPropertiesLoose(source, excluded);
  var key2, i;
  if (Object.getOwnPropertySymbols) {
    var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
    for (i = 0; i < sourceSymbolKeys.length; i++) {
      key2 = sourceSymbolKeys[i];
      if (excluded.indexOf(key2) >= 0) continue;
      if (!Object.prototype.propertyIsEnumerable.call(source, key2)) continue;
      target2[key2] = source[key2];
    }
  }
  return target2;
}
function _objectWithoutPropertiesLoose(source, excluded) {
  if (source == null) return {};
  var target2 = {};
  for (var key2 in source) {
    if (Object.prototype.hasOwnProperty.call(source, key2)) {
      if (excluded.indexOf(key2) >= 0) continue;
      target2[key2] = source[key2];
    }
  }
  return target2;
}
function _classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function _defineProperties(target2, props) {
  for (var i = 0; i < props.length; i++) {
    var descriptor = props[i];
    descriptor.enumerable = descriptor.enumerable || false;
    descriptor.configurable = true;
    if ("value" in descriptor) descriptor.writable = true;
    Object.defineProperty(target2, _toPropertyKey(descriptor.key), descriptor);
  }
}
function _createClass(Constructor, protoProps, staticProps) {
  if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  Object.defineProperty(Constructor, "prototype", { writable: false });
  return Constructor;
}
function _callSuper(t, o, e) {
  return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
}
function _possibleConstructorReturn(self, call) {
  if (call && (_typeof(call) === "object" || typeof call === "function")) {
    return call;
  } else if (call !== void 0) {
    throw new TypeError("Derived constructors may only return object or undefined");
  }
  return _assertThisInitialized(self);
}
function _assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self;
}
function _isNativeReflectConstruct() {
  try {
    var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {
    }));
  } catch (t2) {
  }
  return (_isNativeReflectConstruct = function _isNativeReflectConstruct2() {
    return !!t;
  })();
}
function _getPrototypeOf(o) {
  _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf2(o2) {
    return o2.__proto__ || Object.getPrototypeOf(o2);
  };
  return _getPrototypeOf(o);
}
function _inherits(subClass, superClass) {
  if (typeof superClass !== "function" && superClass !== null) {
    throw new TypeError("Super expression must either be null or a function");
  }
  subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } });
  Object.defineProperty(subClass, "prototype", { writable: false });
  if (superClass) _setPrototypeOf(subClass, superClass);
}
function _setPrototypeOf(o, p) {
  _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf2(o2, p2) {
    o2.__proto__ = p2;
    return o2;
  };
  return _setPrototypeOf(o, p);
}
function _toConsumableArray(arr) {
  return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
}
function _nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return _arrayLikeToArray(o, minLen);
  var n = Object.prototype.toString.call(o).slice(8, -1);
  if (n === "Object" && o.constructor) n = o.constructor.name;
  if (n === "Map" || n === "Set") return Array.from(o);
  if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _iterableToArray(iter) {
  if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _arrayWithoutHoles(arr) {
  if (Array.isArray(arr)) return _arrayLikeToArray(arr);
}
function _arrayLikeToArray(arr, len) {
  if (len == null || len > arr.length) len = arr.length;
  for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  return arr2;
}
function ownKeys(e, r2) {
  var t = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    r2 && (o = o.filter(function(r22) {
      return Object.getOwnPropertyDescriptor(e, r22).enumerable;
    })), t.push.apply(t, o);
  }
  return t;
}
function _objectSpread(e) {
  for (var r2 = 1; r2 < arguments.length; r2++) {
    var t = null != arguments[r2] ? arguments[r2] : {};
    r2 % 2 ? ownKeys(Object(t), true).forEach(function(r22) {
      _defineProperty(e, r22, t[r22]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r22) {
      Object.defineProperty(e, r22, Object.getOwnPropertyDescriptor(t, r22));
    });
  }
  return e;
}
function _defineProperty(obj, key2, value) {
  key2 = _toPropertyKey(key2);
  if (key2 in obj) {
    Object.defineProperty(obj, key2, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key2] = value;
  }
  return obj;
}
function _toPropertyKey(t) {
  var i = _toPrimitive(t, "string");
  return "symbol" == _typeof(i) ? i : i + "";
}
function _toPrimitive(t, r2) {
  if ("object" != _typeof(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r2);
    if ("object" != _typeof(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return ("string" === r2 ? String : Number)(t);
}
var ORIENT_MAP = {
  xAxis: ["bottom", "top"],
  yAxis: ["left", "right"]
};
var FULL_WIDTH_AND_HEIGHT = {
  width: "100%",
  height: "100%"
};
var originCoordinate = {
  x: 0,
  y: 0
};
function renderAsIs(element) {
  return element;
}
var calculateTooltipPos = function calculateTooltipPos2(rangeObj, layout) {
  if (layout === "horizontal") {
    return rangeObj.x;
  }
  if (layout === "vertical") {
    return rangeObj.y;
  }
  if (layout === "centric") {
    return rangeObj.angle;
  }
  return rangeObj.radius;
};
var getActiveCoordinate = function getActiveCoordinate2(layout, tooltipTicks, activeIndex, rangeObj) {
  var entry = tooltipTicks.find(function(tick) {
    return tick && tick.index === activeIndex;
  });
  if (entry) {
    if (layout === "horizontal") {
      return {
        x: entry.coordinate,
        y: rangeObj.y
      };
    }
    if (layout === "vertical") {
      return {
        x: rangeObj.x,
        y: entry.coordinate
      };
    }
    if (layout === "centric") {
      var _angle = entry.coordinate;
      var _radius = rangeObj.radius;
      return _objectSpread(_objectSpread(_objectSpread({}, rangeObj), polarToCartesian(rangeObj.cx, rangeObj.cy, _radius, _angle)), {}, {
        angle: _angle,
        radius: _radius
      });
    }
    var radius = entry.coordinate;
    var angle = rangeObj.angle;
    return _objectSpread(_objectSpread(_objectSpread({}, rangeObj), polarToCartesian(rangeObj.cx, rangeObj.cy, radius, angle)), {}, {
      angle,
      radius
    });
  }
  return originCoordinate;
};
var getDisplayedData = function getDisplayedData2(data, _ref) {
  var graphicalItems = _ref.graphicalItems, dataStartIndex = _ref.dataStartIndex, dataEndIndex = _ref.dataEndIndex;
  var itemsData = (graphicalItems !== null && graphicalItems !== void 0 ? graphicalItems : []).reduce(function(result, child) {
    var itemData = child.props.data;
    if (itemData && itemData.length) {
      return [].concat(_toConsumableArray(result), _toConsumableArray(itemData));
    }
    return result;
  }, []);
  if (itemsData.length > 0) {
    return itemsData;
  }
  if (data && data.length && isNumber(dataStartIndex) && isNumber(dataEndIndex)) {
    return data.slice(dataStartIndex, dataEndIndex + 1);
  }
  return [];
};
function getDefaultDomainByAxisType(axisType) {
  return axisType === "number" ? [0, "auto"] : void 0;
}
var getTooltipContent = function getTooltipContent2(state, chartData, activeIndex, activeLabel) {
  var graphicalItems = state.graphicalItems, tooltipAxis = state.tooltipAxis;
  var displayedData = getDisplayedData(chartData, state);
  if (activeIndex < 0 || !graphicalItems || !graphicalItems.length || activeIndex >= displayedData.length) {
    return null;
  }
  return graphicalItems.reduce(function(result, child) {
    var _child$props$data;
    var data = (_child$props$data = child.props.data) !== null && _child$props$data !== void 0 ? _child$props$data : chartData;
    if (data && state.dataStartIndex + state.dataEndIndex !== 0 && // https://github.com/recharts/recharts/issues/4717
    // The data is sliced only when the active index is within the start/end index range.
    state.dataEndIndex - state.dataStartIndex >= activeIndex) {
      data = data.slice(state.dataStartIndex, state.dataEndIndex + 1);
    }
    var payload;
    if (tooltipAxis.dataKey && !tooltipAxis.allowDuplicatedCategory) {
      var entries = data === void 0 ? displayedData : data;
      payload = findEntryInArray(entries, tooltipAxis.dataKey, activeLabel);
    } else {
      payload = data && data[activeIndex] || displayedData[activeIndex];
    }
    if (!payload) {
      return result;
    }
    return [].concat(_toConsumableArray(result), [getTooltipItem(child, payload)]);
  }, []);
};
var getTooltipData = function getTooltipData2(state, chartData, layout, rangeObj) {
  var rangeData = rangeObj || {
    x: state.chartX,
    y: state.chartY
  };
  var pos = calculateTooltipPos(rangeData, layout);
  var ticks2 = state.orderedTooltipTicks, axis = state.tooltipAxis, tooltipTicks = state.tooltipTicks;
  var activeIndex = calculateActiveTickIndex(pos, ticks2, tooltipTicks, axis);
  if (activeIndex >= 0 && tooltipTicks) {
    var activeLabel = tooltipTicks[activeIndex] && tooltipTicks[activeIndex].value;
    var activePayload = getTooltipContent(state, chartData, activeIndex, activeLabel);
    var activeCoordinate = getActiveCoordinate(layout, ticks2, activeIndex, rangeData);
    return {
      activeTooltipIndex: activeIndex,
      activeLabel,
      activePayload,
      activeCoordinate
    };
  }
  return null;
};
var getAxisMapByAxes = function getAxisMapByAxes2(props, _ref2) {
  var axes = _ref2.axes, graphicalItems = _ref2.graphicalItems, axisType = _ref2.axisType, axisIdKey = _ref2.axisIdKey, stackGroups = _ref2.stackGroups, dataStartIndex = _ref2.dataStartIndex, dataEndIndex = _ref2.dataEndIndex;
  var layout = props.layout, children = props.children, stackOffset = props.stackOffset;
  var isCategorical = isCategoricalAxis(layout, axisType);
  return axes.reduce(function(result, child) {
    var _childProps$domain2;
    var childProps = child.type.defaultProps !== void 0 ? _objectSpread(_objectSpread({}, child.type.defaultProps), child.props) : child.props;
    var type = childProps.type, dataKey = childProps.dataKey, allowDataOverflow = childProps.allowDataOverflow, allowDuplicatedCategory = childProps.allowDuplicatedCategory, scale2 = childProps.scale, ticks2 = childProps.ticks, includeHidden = childProps.includeHidden;
    var axisId = childProps[axisIdKey];
    if (result[axisId]) {
      return result;
    }
    var displayedData = getDisplayedData(props.data, {
      graphicalItems: graphicalItems.filter(function(item) {
        var _defaultProps;
        var itemAxisId = axisIdKey in item.props ? item.props[axisIdKey] : (_defaultProps = item.type.defaultProps) === null || _defaultProps === void 0 ? void 0 : _defaultProps[axisIdKey];
        return itemAxisId === axisId;
      }),
      dataStartIndex,
      dataEndIndex
    });
    var len = displayedData.length;
    var domain, duplicateDomain, categoricalDomain;
    if (isDomainSpecifiedByUser(childProps.domain, allowDataOverflow, type)) {
      domain = parseSpecifiedDomain(childProps.domain, null, allowDataOverflow);
      if (isCategorical && (type === "number" || scale2 !== "auto")) {
        categoricalDomain = getDomainOfDataByKey(displayedData, dataKey, "category");
      }
    }
    var defaultDomain = getDefaultDomainByAxisType(type);
    if (!domain || domain.length === 0) {
      var _childProps$domain;
      var childDomain = (_childProps$domain = childProps.domain) !== null && _childProps$domain !== void 0 ? _childProps$domain : defaultDomain;
      if (dataKey) {
        domain = getDomainOfDataByKey(displayedData, dataKey, type);
        if (type === "category" && isCategorical) {
          var duplicate = hasDuplicate(domain);
          if (allowDuplicatedCategory && duplicate) {
            duplicateDomain = domain;
            domain = range$1(0, len);
          } else if (!allowDuplicatedCategory) {
            domain = parseDomainOfCategoryAxis(childDomain, domain, child).reduce(function(finalDomain, entry) {
              return finalDomain.indexOf(entry) >= 0 ? finalDomain : [].concat(_toConsumableArray(finalDomain), [entry]);
            }, []);
          }
        } else if (type === "category") {
          if (!allowDuplicatedCategory) {
            domain = parseDomainOfCategoryAxis(childDomain, domain, child).reduce(function(finalDomain, entry) {
              return finalDomain.indexOf(entry) >= 0 || entry === "" || isNil$1(entry) ? finalDomain : [].concat(_toConsumableArray(finalDomain), [entry]);
            }, []);
          } else {
            domain = domain.filter(function(entry) {
              return entry !== "" && !isNil$1(entry);
            });
          }
        } else if (type === "number") {
          var errorBarsDomain = parseErrorBarsOfAxis(displayedData, graphicalItems.filter(function(item) {
            var _defaultProps2, _defaultProps3;
            var itemAxisId = axisIdKey in item.props ? item.props[axisIdKey] : (_defaultProps2 = item.type.defaultProps) === null || _defaultProps2 === void 0 ? void 0 : _defaultProps2[axisIdKey];
            var itemHide = "hide" in item.props ? item.props.hide : (_defaultProps3 = item.type.defaultProps) === null || _defaultProps3 === void 0 ? void 0 : _defaultProps3.hide;
            return itemAxisId === axisId && (includeHidden || !itemHide);
          }), dataKey, axisType, layout);
          if (errorBarsDomain) {
            domain = errorBarsDomain;
          }
        }
        if (isCategorical && (type === "number" || scale2 !== "auto")) {
          categoricalDomain = getDomainOfDataByKey(displayedData, dataKey, "category");
        }
      } else if (isCategorical) {
        domain = range$1(0, len);
      } else if (stackGroups && stackGroups[axisId] && stackGroups[axisId].hasStack && type === "number") {
        domain = stackOffset === "expand" ? [0, 1] : getDomainOfStackGroups(stackGroups[axisId].stackGroups, dataStartIndex, dataEndIndex);
      } else {
        domain = getDomainOfItemsWithSameAxis(displayedData, graphicalItems.filter(function(item) {
          var itemAxisId = axisIdKey in item.props ? item.props[axisIdKey] : item.type.defaultProps[axisIdKey];
          var itemHide = "hide" in item.props ? item.props.hide : item.type.defaultProps.hide;
          return itemAxisId === axisId && (includeHidden || !itemHide);
        }), type, layout, true);
      }
      if (type === "number") {
        domain = detectReferenceElementsDomain(children, domain, axisId, axisType, ticks2);
        if (childDomain) {
          domain = parseSpecifiedDomain(childDomain, domain, allowDataOverflow);
        }
      } else if (type === "category" && childDomain) {
        var axisDomain = childDomain;
        var isDomainValid = domain.every(function(entry) {
          return axisDomain.indexOf(entry) >= 0;
        });
        if (isDomainValid) {
          domain = axisDomain;
        }
      }
    }
    return _objectSpread(_objectSpread({}, result), {}, _defineProperty({}, axisId, _objectSpread(_objectSpread({}, childProps), {}, {
      axisType,
      domain,
      categoricalDomain,
      duplicateDomain,
      originalDomain: (_childProps$domain2 = childProps.domain) !== null && _childProps$domain2 !== void 0 ? _childProps$domain2 : defaultDomain,
      isCategorical,
      layout
    })));
  }, {});
};
var getAxisMapByItems = function getAxisMapByItems2(props, _ref3) {
  var graphicalItems = _ref3.graphicalItems, Axis = _ref3.Axis, axisType = _ref3.axisType, axisIdKey = _ref3.axisIdKey, stackGroups = _ref3.stackGroups, dataStartIndex = _ref3.dataStartIndex, dataEndIndex = _ref3.dataEndIndex;
  var layout = props.layout, children = props.children;
  var displayedData = getDisplayedData(props.data, {
    graphicalItems,
    dataStartIndex,
    dataEndIndex
  });
  var len = displayedData.length;
  var isCategorical = isCategoricalAxis(layout, axisType);
  var index = -1;
  return graphicalItems.reduce(function(result, child) {
    var childProps = child.type.defaultProps !== void 0 ? _objectSpread(_objectSpread({}, child.type.defaultProps), child.props) : child.props;
    var axisId = childProps[axisIdKey];
    var originalDomain = getDefaultDomainByAxisType("number");
    if (!result[axisId]) {
      index++;
      var domain;
      if (isCategorical) {
        domain = range$1(0, len);
      } else if (stackGroups && stackGroups[axisId] && stackGroups[axisId].hasStack) {
        domain = getDomainOfStackGroups(stackGroups[axisId].stackGroups, dataStartIndex, dataEndIndex);
        domain = detectReferenceElementsDomain(children, domain, axisId, axisType);
      } else {
        domain = parseSpecifiedDomain(originalDomain, getDomainOfItemsWithSameAxis(displayedData, graphicalItems.filter(function(item) {
          var _defaultProps4, _defaultProps5;
          var itemAxisId = axisIdKey in item.props ? item.props[axisIdKey] : (_defaultProps4 = item.type.defaultProps) === null || _defaultProps4 === void 0 ? void 0 : _defaultProps4[axisIdKey];
          var itemHide = "hide" in item.props ? item.props.hide : (_defaultProps5 = item.type.defaultProps) === null || _defaultProps5 === void 0 ? void 0 : _defaultProps5.hide;
          return itemAxisId === axisId && !itemHide;
        }), "number", layout), Axis.defaultProps.allowDataOverflow);
        domain = detectReferenceElementsDomain(children, domain, axisId, axisType);
      }
      return _objectSpread(_objectSpread({}, result), {}, _defineProperty({}, axisId, _objectSpread(_objectSpread({
        axisType
      }, Axis.defaultProps), {}, {
        hide: true,
        orientation: get$2(ORIENT_MAP, "".concat(axisType, ".").concat(index % 2), null),
        domain,
        originalDomain,
        isCategorical,
        layout
        // specify scale when no Axis
        // scale: isCategorical ? 'band' : 'linear',
      })));
    }
    return result;
  }, {});
};
var getAxisMap = function getAxisMap2(props, _ref4) {
  var _ref4$axisType = _ref4.axisType, axisType = _ref4$axisType === void 0 ? "xAxis" : _ref4$axisType, AxisComp = _ref4.AxisComp, graphicalItems = _ref4.graphicalItems, stackGroups = _ref4.stackGroups, dataStartIndex = _ref4.dataStartIndex, dataEndIndex = _ref4.dataEndIndex;
  var children = props.children;
  var axisIdKey = "".concat(axisType, "Id");
  var axes = findAllByType(children, AxisComp);
  var axisMap = {};
  if (axes && axes.length) {
    axisMap = getAxisMapByAxes(props, {
      axes,
      graphicalItems,
      axisType,
      axisIdKey,
      stackGroups,
      dataStartIndex,
      dataEndIndex
    });
  } else if (graphicalItems && graphicalItems.length) {
    axisMap = getAxisMapByItems(props, {
      Axis: AxisComp,
      graphicalItems,
      axisType,
      axisIdKey,
      stackGroups,
      dataStartIndex,
      dataEndIndex
    });
  }
  return axisMap;
};
var tooltipTicksGenerator = function tooltipTicksGenerator2(axisMap) {
  var axis = getAnyElementOfObject(axisMap);
  var tooltipTicks = getTicksOfAxis(axis, false, true);
  return {
    tooltipTicks,
    orderedTooltipTicks: sortBy$1(tooltipTicks, function(o) {
      return o.coordinate;
    }),
    tooltipAxis: axis,
    tooltipAxisBandSize: getBandSizeOfAxis(axis, tooltipTicks)
  };
};
var createDefaultState = function createDefaultState2(props) {
  var children = props.children, defaultShowTooltip = props.defaultShowTooltip;
  var brushItem = findChildByType(children, Brush);
  var startIndex = 0;
  var endIndex = 0;
  if (props.data && props.data.length !== 0) {
    endIndex = props.data.length - 1;
  }
  if (brushItem && brushItem.props) {
    if (brushItem.props.startIndex >= 0) {
      startIndex = brushItem.props.startIndex;
    }
    if (brushItem.props.endIndex >= 0) {
      endIndex = brushItem.props.endIndex;
    }
  }
  return {
    chartX: 0,
    chartY: 0,
    dataStartIndex: startIndex,
    dataEndIndex: endIndex,
    activeTooltipIndex: -1,
    isTooltipActive: Boolean(defaultShowTooltip)
  };
};
var hasGraphicalBarItem = function hasGraphicalBarItem2(graphicalItems) {
  if (!graphicalItems || !graphicalItems.length) {
    return false;
  }
  return graphicalItems.some(function(item) {
    var name = getDisplayName(item && item.type);
    return name && name.indexOf("Bar") >= 0;
  });
};
var getAxisNameByLayout = function getAxisNameByLayout2(layout) {
  if (layout === "horizontal") {
    return {
      numericAxisName: "yAxis",
      cateAxisName: "xAxis"
    };
  }
  if (layout === "vertical") {
    return {
      numericAxisName: "xAxis",
      cateAxisName: "yAxis"
    };
  }
  if (layout === "centric") {
    return {
      numericAxisName: "radiusAxis",
      cateAxisName: "angleAxis"
    };
  }
  return {
    numericAxisName: "angleAxis",
    cateAxisName: "radiusAxis"
  };
};
var calculateOffset = function calculateOffset2(_ref5, prevLegendBBox) {
  var props = _ref5.props, graphicalItems = _ref5.graphicalItems, _ref5$xAxisMap = _ref5.xAxisMap, xAxisMap = _ref5$xAxisMap === void 0 ? {} : _ref5$xAxisMap, _ref5$yAxisMap = _ref5.yAxisMap, yAxisMap = _ref5$yAxisMap === void 0 ? {} : _ref5$yAxisMap;
  var width = props.width, height = props.height, children = props.children;
  var margin = props.margin || {};
  var brushItem = findChildByType(children, Brush);
  var legendItem = findChildByType(children, Legend);
  var offsetH = Object.keys(yAxisMap).reduce(function(result, id) {
    var entry = yAxisMap[id];
    var orientation = entry.orientation;
    if (!entry.mirror && !entry.hide) {
      return _objectSpread(_objectSpread({}, result), {}, _defineProperty({}, orientation, result[orientation] + entry.width));
    }
    return result;
  }, {
    left: margin.left || 0,
    right: margin.right || 0
  });
  var offsetV = Object.keys(xAxisMap).reduce(function(result, id) {
    var entry = xAxisMap[id];
    var orientation = entry.orientation;
    if (!entry.mirror && !entry.hide) {
      return _objectSpread(_objectSpread({}, result), {}, _defineProperty({}, orientation, get$2(result, "".concat(orientation)) + entry.height));
    }
    return result;
  }, {
    top: margin.top || 0,
    bottom: margin.bottom || 0
  });
  var offset = _objectSpread(_objectSpread({}, offsetV), offsetH);
  var brushBottom = offset.bottom;
  if (brushItem) {
    offset.bottom += brushItem.props.height || Brush.defaultProps.height;
  }
  if (legendItem && prevLegendBBox) {
    offset = appendOffsetOfLegend(offset, graphicalItems, props, prevLegendBBox);
  }
  var offsetWidth = width - offset.left - offset.right;
  var offsetHeight = height - offset.top - offset.bottom;
  return _objectSpread(_objectSpread({
    brushBottom
  }, offset), {}, {
    // never return negative values for height and width
    width: Math.max(offsetWidth, 0),
    height: Math.max(offsetHeight, 0)
  });
};
var getCartesianAxisSize = function getCartesianAxisSize2(axisObj, axisName) {
  if (axisName === "xAxis") {
    return axisObj[axisName].width;
  }
  if (axisName === "yAxis") {
    return axisObj[axisName].height;
  }
  return void 0;
};
var generateCategoricalChart = function generateCategoricalChart2(_ref6) {
  var chartName = _ref6.chartName, GraphicalChild = _ref6.GraphicalChild, _ref6$defaultTooltipE = _ref6.defaultTooltipEventType, defaultTooltipEventType = _ref6$defaultTooltipE === void 0 ? "axis" : _ref6$defaultTooltipE, _ref6$validateTooltip = _ref6.validateTooltipEventTypes, validateTooltipEventTypes = _ref6$validateTooltip === void 0 ? ["axis"] : _ref6$validateTooltip, axisComponents = _ref6.axisComponents, legendContent = _ref6.legendContent, formatAxisMap4 = _ref6.formatAxisMap, defaultProps2 = _ref6.defaultProps;
  var getFormatItems = function getFormatItems2(props, currentState) {
    var graphicalItems = currentState.graphicalItems, stackGroups = currentState.stackGroups, offset = currentState.offset, updateId = currentState.updateId, dataStartIndex = currentState.dataStartIndex, dataEndIndex = currentState.dataEndIndex;
    var barSize = props.barSize, layout = props.layout, barGap = props.barGap, barCategoryGap = props.barCategoryGap, globalMaxBarSize = props.maxBarSize;
    var _getAxisNameByLayout = getAxisNameByLayout(layout), numericAxisName = _getAxisNameByLayout.numericAxisName, cateAxisName = _getAxisNameByLayout.cateAxisName;
    var hasBar = hasGraphicalBarItem(graphicalItems);
    var formattedItems = [];
    graphicalItems.forEach(function(item, index) {
      var displayedData = getDisplayedData(props.data, {
        graphicalItems: [item],
        dataStartIndex,
        dataEndIndex
      });
      var itemProps = item.type.defaultProps !== void 0 ? _objectSpread(_objectSpread({}, item.type.defaultProps), item.props) : item.props;
      var dataKey = itemProps.dataKey, childMaxBarSize = itemProps.maxBarSize;
      var numericAxisId = itemProps["".concat(numericAxisName, "Id")];
      var cateAxisId = itemProps["".concat(cateAxisName, "Id")];
      var axisObjInitialValue = {};
      var axisObj = axisComponents.reduce(function(result, entry) {
        var axisMap = currentState["".concat(entry.axisType, "Map")];
        var id = itemProps["".concat(entry.axisType, "Id")];
        !(axisMap && axisMap[id] || entry.axisType === "zAxis") ? invariant() : void 0;
        var axis = axisMap[id];
        return _objectSpread(_objectSpread({}, result), {}, _defineProperty(_defineProperty({}, entry.axisType, axis), "".concat(entry.axisType, "Ticks"), getTicksOfAxis(axis)));
      }, axisObjInitialValue);
      var cateAxis = axisObj[cateAxisName];
      var cateTicks = axisObj["".concat(cateAxisName, "Ticks")];
      var stackedData = stackGroups && stackGroups[numericAxisId] && stackGroups[numericAxisId].hasStack && getStackedDataOfItem(item, stackGroups[numericAxisId].stackGroups);
      var itemIsBar = getDisplayName(item.type).indexOf("Bar") >= 0;
      var bandSize = getBandSizeOfAxis(cateAxis, cateTicks);
      var barPosition = [];
      var sizeList = hasBar && getBarSizeList({
        barSize,
        stackGroups,
        totalSize: getCartesianAxisSize(axisObj, cateAxisName)
      });
      if (itemIsBar) {
        var _ref7, _getBandSizeOfAxis;
        var maxBarSize = isNil$1(childMaxBarSize) ? globalMaxBarSize : childMaxBarSize;
        var barBandSize = (_ref7 = (_getBandSizeOfAxis = getBandSizeOfAxis(cateAxis, cateTicks, true)) !== null && _getBandSizeOfAxis !== void 0 ? _getBandSizeOfAxis : maxBarSize) !== null && _ref7 !== void 0 ? _ref7 : 0;
        barPosition = getBarPosition({
          barGap,
          barCategoryGap,
          bandSize: barBandSize !== bandSize ? barBandSize : bandSize,
          sizeList: sizeList[cateAxisId],
          maxBarSize
        });
        if (barBandSize !== bandSize) {
          barPosition = barPosition.map(function(pos) {
            return _objectSpread(_objectSpread({}, pos), {}, {
              position: _objectSpread(_objectSpread({}, pos.position), {}, {
                offset: pos.position.offset - barBandSize / 2
              })
            });
          });
        }
      }
      var composedFn = item && item.type && item.type.getComposedData;
      if (composedFn) {
        formattedItems.push({
          props: _objectSpread(_objectSpread({}, composedFn(_objectSpread(_objectSpread({}, axisObj), {}, {
            displayedData,
            props,
            dataKey,
            item,
            bandSize,
            barPosition,
            offset,
            stackedData,
            layout,
            dataStartIndex,
            dataEndIndex
          }))), {}, _defineProperty(_defineProperty(_defineProperty({
            key: item.key || "item-".concat(index)
          }, numericAxisName, axisObj[numericAxisName]), cateAxisName, axisObj[cateAxisName]), "animationId", updateId)),
          childIndex: parseChildIndex(item, props.children),
          item
        });
      }
    });
    return formattedItems;
  };
  var updateStateOfAxisMapsOffsetAndStackGroups = function updateStateOfAxisMapsOffsetAndStackGroups2(_ref8, prevState) {
    var props = _ref8.props, dataStartIndex = _ref8.dataStartIndex, dataEndIndex = _ref8.dataEndIndex, updateId = _ref8.updateId;
    if (!validateWidthHeight({
      props
    })) {
      return null;
    }
    var children = props.children, layout = props.layout, stackOffset = props.stackOffset, data = props.data, reverseStackOrder = props.reverseStackOrder;
    var _getAxisNameByLayout2 = getAxisNameByLayout(layout), numericAxisName = _getAxisNameByLayout2.numericAxisName, cateAxisName = _getAxisNameByLayout2.cateAxisName;
    var graphicalItems = findAllByType(children, GraphicalChild);
    var stackGroups = getStackGroupsByAxisId(data, graphicalItems, "".concat(numericAxisName, "Id"), "".concat(cateAxisName, "Id"), stackOffset, reverseStackOrder);
    var axisObj = axisComponents.reduce(function(result, entry) {
      var name = "".concat(entry.axisType, "Map");
      return _objectSpread(_objectSpread({}, result), {}, _defineProperty({}, name, getAxisMap(props, _objectSpread(_objectSpread({}, entry), {}, {
        graphicalItems,
        stackGroups: entry.axisType === numericAxisName && stackGroups,
        dataStartIndex,
        dataEndIndex
      }))));
    }, {});
    var offset = calculateOffset(_objectSpread(_objectSpread({}, axisObj), {}, {
      props,
      graphicalItems
    }), prevState === null || prevState === void 0 ? void 0 : prevState.legendBBox);
    Object.keys(axisObj).forEach(function(key2) {
      axisObj[key2] = formatAxisMap4(props, axisObj[key2], offset, key2.replace("Map", ""), chartName);
    });
    var cateAxisMap = axisObj["".concat(cateAxisName, "Map")];
    var ticksObj = tooltipTicksGenerator(cateAxisMap);
    var formattedGraphicalItems = getFormatItems(props, _objectSpread(_objectSpread({}, axisObj), {}, {
      dataStartIndex,
      dataEndIndex,
      updateId,
      graphicalItems,
      stackGroups,
      offset
    }));
    return _objectSpread(_objectSpread({
      formattedGraphicalItems,
      graphicalItems,
      offset,
      stackGroups
    }, ticksObj), axisObj);
  };
  var CategoricalChartWrapper = /* @__PURE__ */ function(_Component) {
    function CategoricalChartWrapper2(_props) {
      var _props$id, _props$throttleDelay;
      var _this;
      _classCallCheck(this, CategoricalChartWrapper2);
      _this = _callSuper(this, CategoricalChartWrapper2, [_props]);
      _defineProperty(_this, "eventEmitterSymbol", Symbol("rechartsEventEmitter"));
      _defineProperty(_this, "accessibilityManager", new AccessibilityManager());
      _defineProperty(_this, "handleLegendBBoxUpdate", function(box) {
        if (box) {
          var _this$state = _this.state, dataStartIndex = _this$state.dataStartIndex, dataEndIndex = _this$state.dataEndIndex, updateId = _this$state.updateId;
          _this.setState(_objectSpread({
            legendBBox: box
          }, updateStateOfAxisMapsOffsetAndStackGroups({
            props: _this.props,
            dataStartIndex,
            dataEndIndex,
            updateId
          }, _objectSpread(_objectSpread({}, _this.state), {}, {
            legendBBox: box
          }))));
        }
      });
      _defineProperty(_this, "handleReceiveSyncEvent", function(cId, data, emitter) {
        if (_this.props.syncId === cId) {
          if (emitter === _this.eventEmitterSymbol && typeof _this.props.syncMethod !== "function") {
            return;
          }
          _this.applySyncEvent(data);
        }
      });
      _defineProperty(_this, "handleBrushChange", function(_ref9) {
        var startIndex = _ref9.startIndex, endIndex = _ref9.endIndex;
        if (startIndex !== _this.state.dataStartIndex || endIndex !== _this.state.dataEndIndex) {
          var updateId = _this.state.updateId;
          _this.setState(function() {
            return _objectSpread({
              dataStartIndex: startIndex,
              dataEndIndex: endIndex
            }, updateStateOfAxisMapsOffsetAndStackGroups({
              props: _this.props,
              dataStartIndex: startIndex,
              dataEndIndex: endIndex,
              updateId
            }, _this.state));
          });
          _this.triggerSyncEvent({
            dataStartIndex: startIndex,
            dataEndIndex: endIndex
          });
        }
      });
      _defineProperty(_this, "handleMouseEnter", function(e) {
        var mouse = _this.getMouseInfo(e);
        if (mouse) {
          var _nextState = _objectSpread(_objectSpread({}, mouse), {}, {
            isTooltipActive: true
          });
          _this.setState(_nextState);
          _this.triggerSyncEvent(_nextState);
          var onMouseEnter = _this.props.onMouseEnter;
          if (isFunction(onMouseEnter)) {
            onMouseEnter(_nextState, e);
          }
        }
      });
      _defineProperty(_this, "triggeredAfterMouseMove", function(e) {
        var mouse = _this.getMouseInfo(e);
        var nextState = mouse ? _objectSpread(_objectSpread({}, mouse), {}, {
          isTooltipActive: true
        }) : {
          isTooltipActive: false
        };
        _this.setState(nextState);
        _this.triggerSyncEvent(nextState);
        var onMouseMove = _this.props.onMouseMove;
        if (isFunction(onMouseMove)) {
          onMouseMove(nextState, e);
        }
      });
      _defineProperty(_this, "handleItemMouseEnter", function(el) {
        _this.setState(function() {
          return {
            isTooltipActive: true,
            activeItem: el,
            activePayload: el.tooltipPayload,
            activeCoordinate: el.tooltipPosition || {
              x: el.cx,
              y: el.cy
            }
          };
        });
      });
      _defineProperty(_this, "handleItemMouseLeave", function() {
        _this.setState(function() {
          return {
            isTooltipActive: false
          };
        });
      });
      _defineProperty(_this, "handleMouseMove", function(e) {
        e.persist();
        _this.throttleTriggeredAfterMouseMove(e);
      });
      _defineProperty(_this, "handleMouseLeave", function(e) {
        _this.throttleTriggeredAfterMouseMove.cancel();
        var nextState = {
          isTooltipActive: false
        };
        _this.setState(nextState);
        _this.triggerSyncEvent(nextState);
        var onMouseLeave = _this.props.onMouseLeave;
        if (isFunction(onMouseLeave)) {
          onMouseLeave(nextState, e);
        }
      });
      _defineProperty(_this, "handleOuterEvent", function(e) {
        var eventName = getReactEventByType(e);
        var event = get$2(_this.props, "".concat(eventName));
        if (eventName && isFunction(event)) {
          var _mouse;
          var mouse;
          if (/.*touch.*/i.test(eventName)) {
            mouse = _this.getMouseInfo(e.changedTouches[0]);
          } else {
            mouse = _this.getMouseInfo(e);
          }
          event((_mouse = mouse) !== null && _mouse !== void 0 ? _mouse : {}, e);
        }
      });
      _defineProperty(_this, "handleClick", function(e) {
        var mouse = _this.getMouseInfo(e);
        if (mouse) {
          var _nextState2 = _objectSpread(_objectSpread({}, mouse), {}, {
            isTooltipActive: true
          });
          _this.setState(_nextState2);
          _this.triggerSyncEvent(_nextState2);
          var onClick = _this.props.onClick;
          if (isFunction(onClick)) {
            onClick(_nextState2, e);
          }
        }
      });
      _defineProperty(_this, "handleMouseDown", function(e) {
        var onMouseDown = _this.props.onMouseDown;
        if (isFunction(onMouseDown)) {
          var _nextState3 = _this.getMouseInfo(e);
          onMouseDown(_nextState3, e);
        }
      });
      _defineProperty(_this, "handleMouseUp", function(e) {
        var onMouseUp = _this.props.onMouseUp;
        if (isFunction(onMouseUp)) {
          var _nextState4 = _this.getMouseInfo(e);
          onMouseUp(_nextState4, e);
        }
      });
      _defineProperty(_this, "handleTouchMove", function(e) {
        if (e.changedTouches != null && e.changedTouches.length > 0) {
          _this.throttleTriggeredAfterMouseMove(e.changedTouches[0]);
        }
      });
      _defineProperty(_this, "handleTouchStart", function(e) {
        if (e.changedTouches != null && e.changedTouches.length > 0) {
          _this.handleMouseDown(e.changedTouches[0]);
        }
      });
      _defineProperty(_this, "handleTouchEnd", function(e) {
        if (e.changedTouches != null && e.changedTouches.length > 0) {
          _this.handleMouseUp(e.changedTouches[0]);
        }
      });
      _defineProperty(_this, "handleDoubleClick", function(e) {
        var onDoubleClick = _this.props.onDoubleClick;
        if (isFunction(onDoubleClick)) {
          var _nextState5 = _this.getMouseInfo(e);
          onDoubleClick(_nextState5, e);
        }
      });
      _defineProperty(_this, "handleContextMenu", function(e) {
        var onContextMenu = _this.props.onContextMenu;
        if (isFunction(onContextMenu)) {
          var _nextState6 = _this.getMouseInfo(e);
          onContextMenu(_nextState6, e);
        }
      });
      _defineProperty(_this, "triggerSyncEvent", function(data) {
        if (_this.props.syncId !== void 0) {
          eventCenter.emit(SYNC_EVENT, _this.props.syncId, data, _this.eventEmitterSymbol);
        }
      });
      _defineProperty(_this, "applySyncEvent", function(data) {
        var _this$props = _this.props, layout = _this$props.layout, syncMethod = _this$props.syncMethod;
        var updateId = _this.state.updateId;
        var dataStartIndex = data.dataStartIndex, dataEndIndex = data.dataEndIndex;
        if (data.dataStartIndex !== void 0 || data.dataEndIndex !== void 0) {
          _this.setState(_objectSpread({
            dataStartIndex,
            dataEndIndex
          }, updateStateOfAxisMapsOffsetAndStackGroups({
            props: _this.props,
            dataStartIndex,
            dataEndIndex,
            updateId
          }, _this.state)));
        } else if (data.activeTooltipIndex !== void 0) {
          var chartX = data.chartX, chartY = data.chartY;
          var activeTooltipIndex = data.activeTooltipIndex;
          var _this$state2 = _this.state, offset = _this$state2.offset, tooltipTicks = _this$state2.tooltipTicks;
          if (!offset) {
            return;
          }
          if (typeof syncMethod === "function") {
            activeTooltipIndex = syncMethod(tooltipTicks, data);
          } else if (syncMethod === "value") {
            activeTooltipIndex = -1;
            for (var i = 0; i < tooltipTicks.length; i++) {
              if (tooltipTicks[i].value === data.activeLabel) {
                activeTooltipIndex = i;
                break;
              }
            }
          }
          var viewBox = _objectSpread(_objectSpread({}, offset), {}, {
            x: offset.left,
            y: offset.top
          });
          var validateChartX = Math.min(chartX, viewBox.x + viewBox.width);
          var validateChartY = Math.min(chartY, viewBox.y + viewBox.height);
          var activeLabel = tooltipTicks[activeTooltipIndex] && tooltipTicks[activeTooltipIndex].value;
          var activePayload = getTooltipContent(_this.state, _this.props.data, activeTooltipIndex);
          var activeCoordinate = tooltipTicks[activeTooltipIndex] ? {
            x: layout === "horizontal" ? tooltipTicks[activeTooltipIndex].coordinate : validateChartX,
            y: layout === "horizontal" ? validateChartY : tooltipTicks[activeTooltipIndex].coordinate
          } : originCoordinate;
          _this.setState(_objectSpread(_objectSpread({}, data), {}, {
            activeLabel,
            activeCoordinate,
            activePayload,
            activeTooltipIndex
          }));
        } else {
          _this.setState(data);
        }
      });
      _defineProperty(_this, "renderCursor", function(element) {
        var _element$props$active;
        var _this$state3 = _this.state, isTooltipActive = _this$state3.isTooltipActive, activeCoordinate = _this$state3.activeCoordinate, activePayload = _this$state3.activePayload, offset = _this$state3.offset, activeTooltipIndex = _this$state3.activeTooltipIndex, tooltipAxisBandSize = _this$state3.tooltipAxisBandSize;
        var tooltipEventType = _this.getTooltipEventType();
        var isActive = (_element$props$active = element.props.active) !== null && _element$props$active !== void 0 ? _element$props$active : isTooltipActive;
        var layout = _this.props.layout;
        var key2 = element.key || "_recharts-cursor";
        return /* @__PURE__ */ React.createElement(Cursor, {
          key: key2,
          activeCoordinate,
          activePayload,
          activeTooltipIndex,
          chartName,
          element,
          isActive,
          layout,
          offset,
          tooltipAxisBandSize,
          tooltipEventType
        });
      });
      _defineProperty(_this, "renderPolarAxis", function(element, displayName, index) {
        var axisType = get$2(element, "type.axisType");
        var axisMap = get$2(_this.state, "".concat(axisType, "Map"));
        var elementDefaultProps = element.type.defaultProps;
        var elementProps = elementDefaultProps !== void 0 ? _objectSpread(_objectSpread({}, elementDefaultProps), element.props) : element.props;
        var axisOption = axisMap && axisMap[elementProps["".concat(axisType, "Id")]];
        return /* @__PURE__ */ reactExports.cloneElement(element, _objectSpread(_objectSpread({}, axisOption), {}, {
          className: clsx(axisType, axisOption.className),
          key: element.key || "".concat(displayName, "-").concat(index),
          ticks: getTicksOfAxis(axisOption, true)
        }));
      });
      _defineProperty(_this, "renderPolarGrid", function(element) {
        var _element$props = element.props, radialLines = _element$props.radialLines, polarAngles = _element$props.polarAngles, polarRadius = _element$props.polarRadius;
        var _this$state4 = _this.state, radiusAxisMap = _this$state4.radiusAxisMap, angleAxisMap = _this$state4.angleAxisMap;
        var radiusAxis = getAnyElementOfObject(radiusAxisMap);
        var angleAxis = getAnyElementOfObject(angleAxisMap);
        var cx = angleAxis.cx, cy = angleAxis.cy, innerRadius = angleAxis.innerRadius, outerRadius = angleAxis.outerRadius;
        return /* @__PURE__ */ reactExports.cloneElement(element, {
          polarAngles: Array.isArray(polarAngles) ? polarAngles : getTicksOfAxis(angleAxis, true).map(function(entry) {
            return entry.coordinate;
          }),
          polarRadius: Array.isArray(polarRadius) ? polarRadius : getTicksOfAxis(radiusAxis, true).map(function(entry) {
            return entry.coordinate;
          }),
          cx,
          cy,
          innerRadius,
          outerRadius,
          key: element.key || "polar-grid",
          radialLines
        });
      });
      _defineProperty(_this, "renderLegend", function() {
        var formattedGraphicalItems = _this.state.formattedGraphicalItems;
        var _this$props2 = _this.props, children = _this$props2.children, width = _this$props2.width, height = _this$props2.height;
        var margin = _this.props.margin || {};
        var legendWidth = width - (margin.left || 0) - (margin.right || 0);
        var props = getLegendProps({
          children,
          formattedGraphicalItems,
          legendWidth,
          legendContent
        });
        if (!props) {
          return null;
        }
        var item = props.item, otherProps = _objectWithoutProperties(props, _excluded);
        return /* @__PURE__ */ reactExports.cloneElement(item, _objectSpread(_objectSpread({}, otherProps), {}, {
          chartWidth: width,
          chartHeight: height,
          margin,
          onBBoxUpdate: _this.handleLegendBBoxUpdate
        }));
      });
      _defineProperty(_this, "renderTooltip", function() {
        var _tooltipItem$props$ac;
        var _this$props3 = _this.props, children = _this$props3.children, accessibilityLayer = _this$props3.accessibilityLayer;
        var tooltipItem = findChildByType(children, Tooltip);
        if (!tooltipItem) {
          return null;
        }
        var _this$state5 = _this.state, isTooltipActive = _this$state5.isTooltipActive, activeCoordinate = _this$state5.activeCoordinate, activePayload = _this$state5.activePayload, activeLabel = _this$state5.activeLabel, offset = _this$state5.offset;
        var isActive = (_tooltipItem$props$ac = tooltipItem.props.active) !== null && _tooltipItem$props$ac !== void 0 ? _tooltipItem$props$ac : isTooltipActive;
        return /* @__PURE__ */ reactExports.cloneElement(tooltipItem, {
          viewBox: _objectSpread(_objectSpread({}, offset), {}, {
            x: offset.left,
            y: offset.top
          }),
          active: isActive,
          label: activeLabel,
          payload: isActive ? activePayload : [],
          coordinate: activeCoordinate,
          accessibilityLayer
        });
      });
      _defineProperty(_this, "renderBrush", function(element) {
        var _this$props4 = _this.props, margin = _this$props4.margin, data = _this$props4.data;
        var _this$state6 = _this.state, offset = _this$state6.offset, dataStartIndex = _this$state6.dataStartIndex, dataEndIndex = _this$state6.dataEndIndex, updateId = _this$state6.updateId;
        return /* @__PURE__ */ reactExports.cloneElement(element, {
          key: element.key || "_recharts-brush",
          onChange: combineEventHandlers(_this.handleBrushChange, element.props.onChange),
          data,
          x: isNumber(element.props.x) ? element.props.x : offset.left,
          y: isNumber(element.props.y) ? element.props.y : offset.top + offset.height + offset.brushBottom - (margin.bottom || 0),
          width: isNumber(element.props.width) ? element.props.width : offset.width,
          startIndex: dataStartIndex,
          endIndex: dataEndIndex,
          updateId: "brush-".concat(updateId)
        });
      });
      _defineProperty(_this, "renderReferenceElement", function(element, displayName, index) {
        if (!element) {
          return null;
        }
        var _this2 = _this, clipPathId = _this2.clipPathId;
        var _this$state7 = _this.state, xAxisMap = _this$state7.xAxisMap, yAxisMap = _this$state7.yAxisMap, offset = _this$state7.offset;
        var elementDefaultProps = element.type.defaultProps || {};
        var _element$props2 = element.props, _element$props2$xAxis = _element$props2.xAxisId, xAxisId = _element$props2$xAxis === void 0 ? elementDefaultProps.xAxisId : _element$props2$xAxis, _element$props2$yAxis = _element$props2.yAxisId, yAxisId = _element$props2$yAxis === void 0 ? elementDefaultProps.yAxisId : _element$props2$yAxis;
        return /* @__PURE__ */ reactExports.cloneElement(element, {
          key: element.key || "".concat(displayName, "-").concat(index),
          xAxis: xAxisMap[xAxisId],
          yAxis: yAxisMap[yAxisId],
          viewBox: {
            x: offset.left,
            y: offset.top,
            width: offset.width,
            height: offset.height
          },
          clipPathId
        });
      });
      _defineProperty(_this, "renderActivePoints", function(_ref10) {
        var item = _ref10.item, activePoint = _ref10.activePoint, basePoint = _ref10.basePoint, childIndex = _ref10.childIndex, isRange = _ref10.isRange;
        var result = [];
        var key2 = item.props.key;
        var itemItemProps = item.item.type.defaultProps !== void 0 ? _objectSpread(_objectSpread({}, item.item.type.defaultProps), item.item.props) : item.item.props;
        var activeDot = itemItemProps.activeDot, dataKey = itemItemProps.dataKey;
        var dotProps = _objectSpread(_objectSpread({
          index: childIndex,
          dataKey,
          cx: activePoint.x,
          cy: activePoint.y,
          r: 4,
          fill: getMainColorOfGraphicItem(item.item),
          strokeWidth: 2,
          stroke: "#fff",
          payload: activePoint.payload,
          value: activePoint.value
        }, filterProps(activeDot, false)), adaptEventHandlers(activeDot));
        result.push(CategoricalChartWrapper2.renderActiveDot(activeDot, dotProps, "".concat(key2, "-activePoint-").concat(childIndex)));
        if (basePoint) {
          result.push(CategoricalChartWrapper2.renderActiveDot(activeDot, _objectSpread(_objectSpread({}, dotProps), {}, {
            cx: basePoint.x,
            cy: basePoint.y
          }), "".concat(key2, "-basePoint-").concat(childIndex)));
        } else if (isRange) {
          result.push(null);
        }
        return result;
      });
      _defineProperty(_this, "renderGraphicChild", function(element, displayName, index) {
        var item = _this.filterFormatItem(element, displayName, index);
        if (!item) {
          return null;
        }
        var tooltipEventType = _this.getTooltipEventType();
        var _this$state8 = _this.state, isTooltipActive = _this$state8.isTooltipActive, tooltipAxis = _this$state8.tooltipAxis, activeTooltipIndex = _this$state8.activeTooltipIndex, activeLabel = _this$state8.activeLabel;
        var children = _this.props.children;
        var tooltipItem = findChildByType(children, Tooltip);
        var _item$props = item.props, points = _item$props.points, isRange = _item$props.isRange, baseLine = _item$props.baseLine;
        var itemItemProps = item.item.type.defaultProps !== void 0 ? _objectSpread(_objectSpread({}, item.item.type.defaultProps), item.item.props) : item.item.props;
        var activeDot = itemItemProps.activeDot, hide = itemItemProps.hide, activeBar = itemItemProps.activeBar, activeShape = itemItemProps.activeShape;
        var hasActive = Boolean(!hide && isTooltipActive && tooltipItem && (activeDot || activeBar || activeShape));
        var itemEvents = {};
        if (tooltipEventType !== "axis" && tooltipItem && tooltipItem.props.trigger === "click") {
          itemEvents = {
            onClick: combineEventHandlers(_this.handleItemMouseEnter, element.props.onClick)
          };
        } else if (tooltipEventType !== "axis") {
          itemEvents = {
            onMouseLeave: combineEventHandlers(_this.handleItemMouseLeave, element.props.onMouseLeave),
            onMouseEnter: combineEventHandlers(_this.handleItemMouseEnter, element.props.onMouseEnter)
          };
        }
        var graphicalItem = /* @__PURE__ */ reactExports.cloneElement(element, _objectSpread(_objectSpread({}, item.props), itemEvents));
        function findWithPayload(entry) {
          return typeof tooltipAxis.dataKey === "function" ? tooltipAxis.dataKey(entry.payload) : null;
        }
        if (hasActive) {
          if (activeTooltipIndex >= 0) {
            var activePoint, basePoint;
            if (tooltipAxis.dataKey && !tooltipAxis.allowDuplicatedCategory) {
              var specifiedKey = typeof tooltipAxis.dataKey === "function" ? findWithPayload : "payload.".concat(tooltipAxis.dataKey.toString());
              activePoint = findEntryInArray(points, specifiedKey, activeLabel);
              basePoint = isRange && baseLine && findEntryInArray(baseLine, specifiedKey, activeLabel);
            } else {
              activePoint = points === null || points === void 0 ? void 0 : points[activeTooltipIndex];
              basePoint = isRange && baseLine && baseLine[activeTooltipIndex];
            }
            if (activeShape || activeBar) {
              var activeIndex = element.props.activeIndex !== void 0 ? element.props.activeIndex : activeTooltipIndex;
              return [/* @__PURE__ */ reactExports.cloneElement(element, _objectSpread(_objectSpread(_objectSpread({}, item.props), itemEvents), {}, {
                activeIndex
              })), null, null];
            }
            if (!isNil$1(activePoint)) {
              return [graphicalItem].concat(_toConsumableArray(_this.renderActivePoints({
                item,
                activePoint,
                basePoint,
                childIndex: activeTooltipIndex,
                isRange
              })));
            }
          } else {
            var _this$getItemByXY;
            var _ref11 = (_this$getItemByXY = _this.getItemByXY(_this.state.activeCoordinate)) !== null && _this$getItemByXY !== void 0 ? _this$getItemByXY : {
              graphicalItem
            }, _ref11$graphicalItem = _ref11.graphicalItem, _ref11$graphicalItem$ = _ref11$graphicalItem.item, xyItem = _ref11$graphicalItem$ === void 0 ? element : _ref11$graphicalItem$, childIndex = _ref11$graphicalItem.childIndex;
            var elementProps = _objectSpread(_objectSpread(_objectSpread({}, item.props), itemEvents), {}, {
              activeIndex: childIndex
            });
            return [/* @__PURE__ */ reactExports.cloneElement(xyItem, elementProps), null, null];
          }
        }
        if (isRange) {
          return [graphicalItem, null, null];
        }
        return [graphicalItem, null];
      });
      _defineProperty(_this, "renderCustomized", function(element, displayName, index) {
        return /* @__PURE__ */ reactExports.cloneElement(element, _objectSpread(_objectSpread({
          key: "recharts-customized-".concat(index)
        }, _this.props), _this.state));
      });
      _defineProperty(_this, "renderMap", {
        CartesianGrid: {
          handler: renderAsIs,
          once: true
        },
        ReferenceArea: {
          handler: _this.renderReferenceElement
        },
        ReferenceLine: {
          handler: renderAsIs
        },
        ReferenceDot: {
          handler: _this.renderReferenceElement
        },
        XAxis: {
          handler: renderAsIs
        },
        YAxis: {
          handler: renderAsIs
        },
        Brush: {
          handler: _this.renderBrush,
          once: true
        },
        Bar: {
          handler: _this.renderGraphicChild
        },
        Line: {
          handler: _this.renderGraphicChild
        },
        Area: {
          handler: _this.renderGraphicChild
        },
        Radar: {
          handler: _this.renderGraphicChild
        },
        RadialBar: {
          handler: _this.renderGraphicChild
        },
        Scatter: {
          handler: _this.renderGraphicChild
        },
        Pie: {
          handler: _this.renderGraphicChild
        },
        Funnel: {
          handler: _this.renderGraphicChild
        },
        Tooltip: {
          handler: _this.renderCursor,
          once: true
        },
        PolarGrid: {
          handler: _this.renderPolarGrid,
          once: true
        },
        PolarAngleAxis: {
          handler: _this.renderPolarAxis
        },
        PolarRadiusAxis: {
          handler: _this.renderPolarAxis
        },
        Customized: {
          handler: _this.renderCustomized
        }
      });
      _this.clipPathId = "".concat((_props$id = _props.id) !== null && _props$id !== void 0 ? _props$id : uniqueId("recharts"), "-clip");
      _this.throttleTriggeredAfterMouseMove = throttle$1(_this.triggeredAfterMouseMove, (_props$throttleDelay = _props.throttleDelay) !== null && _props$throttleDelay !== void 0 ? _props$throttleDelay : 1e3 / 60);
      _this.state = {};
      return _this;
    }
    _inherits(CategoricalChartWrapper2, _Component);
    return _createClass(CategoricalChartWrapper2, [{
      key: "componentDidMount",
      value: function componentDidMount() {
        var _this$props$margin$le, _this$props$margin$to;
        this.addListener();
        this.accessibilityManager.setDetails({
          container: this.container,
          offset: {
            left: (_this$props$margin$le = this.props.margin.left) !== null && _this$props$margin$le !== void 0 ? _this$props$margin$le : 0,
            top: (_this$props$margin$to = this.props.margin.top) !== null && _this$props$margin$to !== void 0 ? _this$props$margin$to : 0
          },
          coordinateList: this.state.tooltipTicks,
          mouseHandlerCallback: this.triggeredAfterMouseMove,
          layout: this.props.layout
        });
        this.displayDefaultTooltip();
      }
    }, {
      key: "displayDefaultTooltip",
      value: function displayDefaultTooltip() {
        var _this$props5 = this.props, children = _this$props5.children, data = _this$props5.data, height = _this$props5.height, layout = _this$props5.layout;
        var tooltipElem = findChildByType(children, Tooltip);
        if (!tooltipElem) {
          return;
        }
        var defaultIndex = tooltipElem.props.defaultIndex;
        if (typeof defaultIndex !== "number" || defaultIndex < 0 || defaultIndex > this.state.tooltipTicks.length - 1) {
          return;
        }
        var activeLabel = this.state.tooltipTicks[defaultIndex] && this.state.tooltipTicks[defaultIndex].value;
        var activePayload = getTooltipContent(this.state, data, defaultIndex, activeLabel);
        var independentAxisCoord = this.state.tooltipTicks[defaultIndex].coordinate;
        var dependentAxisCoord = (this.state.offset.top + height) / 2;
        var isHorizontal = layout === "horizontal";
        var activeCoordinate = isHorizontal ? {
          x: independentAxisCoord,
          y: dependentAxisCoord
        } : {
          y: independentAxisCoord,
          x: dependentAxisCoord
        };
        var scatterPlotElement = this.state.formattedGraphicalItems.find(function(_ref12) {
          var item = _ref12.item;
          return item.type.name === "Scatter";
        });
        if (scatterPlotElement) {
          activeCoordinate = _objectSpread(_objectSpread({}, activeCoordinate), scatterPlotElement.props.points[defaultIndex].tooltipPosition);
          activePayload = scatterPlotElement.props.points[defaultIndex].tooltipPayload;
        }
        var nextState = {
          activeTooltipIndex: defaultIndex,
          isTooltipActive: true,
          activeLabel,
          activePayload,
          activeCoordinate
        };
        this.setState(nextState);
        this.renderCursor(tooltipElem);
        this.accessibilityManager.setIndex(defaultIndex);
      }
    }, {
      key: "getSnapshotBeforeUpdate",
      value: function getSnapshotBeforeUpdate(prevProps, prevState) {
        if (!this.props.accessibilityLayer) {
          return null;
        }
        if (this.state.tooltipTicks !== prevState.tooltipTicks) {
          this.accessibilityManager.setDetails({
            coordinateList: this.state.tooltipTicks
          });
        }
        if (this.props.layout !== prevProps.layout) {
          this.accessibilityManager.setDetails({
            layout: this.props.layout
          });
        }
        if (this.props.margin !== prevProps.margin) {
          var _this$props$margin$le2, _this$props$margin$to2;
          this.accessibilityManager.setDetails({
            offset: {
              left: (_this$props$margin$le2 = this.props.margin.left) !== null && _this$props$margin$le2 !== void 0 ? _this$props$margin$le2 : 0,
              top: (_this$props$margin$to2 = this.props.margin.top) !== null && _this$props$margin$to2 !== void 0 ? _this$props$margin$to2 : 0
            }
          });
        }
        return null;
      }
    }, {
      key: "componentDidUpdate",
      value: function componentDidUpdate(prevProps) {
        if (!isChildrenEqual([findChildByType(prevProps.children, Tooltip)], [findChildByType(this.props.children, Tooltip)])) {
          this.displayDefaultTooltip();
        }
      }
    }, {
      key: "componentWillUnmount",
      value: function componentWillUnmount() {
        this.removeListener();
        this.throttleTriggeredAfterMouseMove.cancel();
      }
    }, {
      key: "getTooltipEventType",
      value: function getTooltipEventType() {
        var tooltipItem = findChildByType(this.props.children, Tooltip);
        if (tooltipItem && typeof tooltipItem.props.shared === "boolean") {
          var eventType = tooltipItem.props.shared ? "axis" : "item";
          return validateTooltipEventTypes.indexOf(eventType) >= 0 ? eventType : defaultTooltipEventType;
        }
        return defaultTooltipEventType;
      }
      /**
       * Get the information of mouse in chart, return null when the mouse is not in the chart
       * @param  {MousePointer} event    The event object
       * @return {Object}          Mouse data
       */
    }, {
      key: "getMouseInfo",
      value: function getMouseInfo(event) {
        if (!this.container) {
          return null;
        }
        var element = this.container;
        var boundingRect = element.getBoundingClientRect();
        var containerOffset = getOffset(boundingRect);
        var e = {
          chartX: Math.round(event.pageX - containerOffset.left),
          chartY: Math.round(event.pageY - containerOffset.top)
        };
        var scale2 = boundingRect.width / element.offsetWidth || 1;
        var rangeObj = this.inRange(e.chartX, e.chartY, scale2);
        if (!rangeObj) {
          return null;
        }
        var _this$state9 = this.state, xAxisMap = _this$state9.xAxisMap, yAxisMap = _this$state9.yAxisMap;
        var tooltipEventType = this.getTooltipEventType();
        var toolTipData = getTooltipData(this.state, this.props.data, this.props.layout, rangeObj);
        if (tooltipEventType !== "axis" && xAxisMap && yAxisMap) {
          var xScale = getAnyElementOfObject(xAxisMap).scale;
          var yScale = getAnyElementOfObject(yAxisMap).scale;
          var xValue = xScale && xScale.invert ? xScale.invert(e.chartX) : null;
          var yValue = yScale && yScale.invert ? yScale.invert(e.chartY) : null;
          return _objectSpread(_objectSpread({}, e), {}, {
            xValue,
            yValue
          }, toolTipData);
        }
        if (toolTipData) {
          return _objectSpread(_objectSpread({}, e), toolTipData);
        }
        return null;
      }
    }, {
      key: "inRange",
      value: function inRange(x2, y2) {
        var scale2 = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : 1;
        var layout = this.props.layout;
        var scaledX = x2 / scale2, scaledY = y2 / scale2;
        if (layout === "horizontal" || layout === "vertical") {
          var offset = this.state.offset;
          var isInRange = scaledX >= offset.left && scaledX <= offset.left + offset.width && scaledY >= offset.top && scaledY <= offset.top + offset.height;
          return isInRange ? {
            x: scaledX,
            y: scaledY
          } : null;
        }
        var _this$state10 = this.state, angleAxisMap = _this$state10.angleAxisMap, radiusAxisMap = _this$state10.radiusAxisMap;
        if (angleAxisMap && radiusAxisMap) {
          var angleAxis = getAnyElementOfObject(angleAxisMap);
          return inRangeOfSector({
            x: scaledX,
            y: scaledY
          }, angleAxis);
        }
        return null;
      }
    }, {
      key: "parseEventsOfWrapper",
      value: function parseEventsOfWrapper() {
        var children = this.props.children;
        var tooltipEventType = this.getTooltipEventType();
        var tooltipItem = findChildByType(children, Tooltip);
        var tooltipEvents = {};
        if (tooltipItem && tooltipEventType === "axis") {
          if (tooltipItem.props.trigger === "click") {
            tooltipEvents = {
              onClick: this.handleClick
            };
          } else {
            tooltipEvents = {
              onMouseEnter: this.handleMouseEnter,
              onDoubleClick: this.handleDoubleClick,
              onMouseMove: this.handleMouseMove,
              onMouseLeave: this.handleMouseLeave,
              onTouchMove: this.handleTouchMove,
              onTouchStart: this.handleTouchStart,
              onTouchEnd: this.handleTouchEnd,
              onContextMenu: this.handleContextMenu
            };
          }
        }
        var outerEvents = adaptEventHandlers(this.props, this.handleOuterEvent);
        return _objectSpread(_objectSpread({}, outerEvents), tooltipEvents);
      }
    }, {
      key: "addListener",
      value: function addListener() {
        eventCenter.on(SYNC_EVENT, this.handleReceiveSyncEvent);
      }
    }, {
      key: "removeListener",
      value: function removeListener() {
        eventCenter.removeListener(SYNC_EVENT, this.handleReceiveSyncEvent);
      }
    }, {
      key: "filterFormatItem",
      value: function filterFormatItem(item, displayName, childIndex) {
        var formattedGraphicalItems = this.state.formattedGraphicalItems;
        for (var i = 0, len = formattedGraphicalItems.length; i < len; i++) {
          var entry = formattedGraphicalItems[i];
          if (entry.item === item || entry.props.key === item.key || displayName === getDisplayName(entry.item.type) && childIndex === entry.childIndex) {
            return entry;
          }
        }
        return null;
      }
    }, {
      key: "renderClipPath",
      value: function renderClipPath() {
        var clipPathId = this.clipPathId;
        var _this$state$offset = this.state.offset, left = _this$state$offset.left, top = _this$state$offset.top, height = _this$state$offset.height, width = _this$state$offset.width;
        return /* @__PURE__ */ React.createElement("defs", null, /* @__PURE__ */ React.createElement("clipPath", {
          id: clipPathId
        }, /* @__PURE__ */ React.createElement("rect", {
          x: left,
          y: top,
          height,
          width
        })));
      }
    }, {
      key: "getXScales",
      value: function getXScales() {
        var xAxisMap = this.state.xAxisMap;
        return xAxisMap ? Object.entries(xAxisMap).reduce(function(res, _ref13) {
          var _ref14 = _slicedToArray(_ref13, 2), axisId = _ref14[0], axisProps = _ref14[1];
          return _objectSpread(_objectSpread({}, res), {}, _defineProperty({}, axisId, axisProps.scale));
        }, {}) : null;
      }
    }, {
      key: "getYScales",
      value: function getYScales() {
        var yAxisMap = this.state.yAxisMap;
        return yAxisMap ? Object.entries(yAxisMap).reduce(function(res, _ref15) {
          var _ref16 = _slicedToArray(_ref15, 2), axisId = _ref16[0], axisProps = _ref16[1];
          return _objectSpread(_objectSpread({}, res), {}, _defineProperty({}, axisId, axisProps.scale));
        }, {}) : null;
      }
    }, {
      key: "getXScaleByAxisId",
      value: function getXScaleByAxisId(axisId) {
        var _this$state$xAxisMap;
        return (_this$state$xAxisMap = this.state.xAxisMap) === null || _this$state$xAxisMap === void 0 || (_this$state$xAxisMap = _this$state$xAxisMap[axisId]) === null || _this$state$xAxisMap === void 0 ? void 0 : _this$state$xAxisMap.scale;
      }
    }, {
      key: "getYScaleByAxisId",
      value: function getYScaleByAxisId(axisId) {
        var _this$state$yAxisMap;
        return (_this$state$yAxisMap = this.state.yAxisMap) === null || _this$state$yAxisMap === void 0 || (_this$state$yAxisMap = _this$state$yAxisMap[axisId]) === null || _this$state$yAxisMap === void 0 ? void 0 : _this$state$yAxisMap.scale;
      }
    }, {
      key: "getItemByXY",
      value: function getItemByXY(chartXY) {
        var _this$state11 = this.state, formattedGraphicalItems = _this$state11.formattedGraphicalItems, activeItem = _this$state11.activeItem;
        if (formattedGraphicalItems && formattedGraphicalItems.length) {
          for (var i = 0, len = formattedGraphicalItems.length; i < len; i++) {
            var graphicalItem = formattedGraphicalItems[i];
            var props = graphicalItem.props, item = graphicalItem.item;
            var itemProps = item.type.defaultProps !== void 0 ? _objectSpread(_objectSpread({}, item.type.defaultProps), item.props) : item.props;
            var itemDisplayName = getDisplayName(item.type);
            if (itemDisplayName === "Bar") {
              var activeBarItem = (props.data || []).find(function(entry) {
                return isInRectangle(chartXY, entry);
              });
              if (activeBarItem) {
                return {
                  graphicalItem,
                  payload: activeBarItem
                };
              }
            } else if (itemDisplayName === "RadialBar") {
              var _activeBarItem = (props.data || []).find(function(entry) {
                return inRangeOfSector(chartXY, entry);
              });
              if (_activeBarItem) {
                return {
                  graphicalItem,
                  payload: _activeBarItem
                };
              }
            } else if (isFunnel(graphicalItem, activeItem) || isPie(graphicalItem, activeItem) || isScatter(graphicalItem, activeItem)) {
              var activeIndex = getActiveShapeIndexForTooltip({
                graphicalItem,
                activeTooltipItem: activeItem,
                itemData: itemProps.data
              });
              var childIndex = itemProps.activeIndex === void 0 ? activeIndex : itemProps.activeIndex;
              return {
                graphicalItem: _objectSpread(_objectSpread({}, graphicalItem), {}, {
                  childIndex
                }),
                payload: isScatter(graphicalItem, activeItem) ? itemProps.data[activeIndex] : graphicalItem.props.data[activeIndex]
              };
            }
          }
        }
        return null;
      }
    }, {
      key: "render",
      value: function render() {
        var _this3 = this;
        if (!validateWidthHeight(this)) {
          return null;
        }
        var _this$props6 = this.props, children = _this$props6.children, className = _this$props6.className, width = _this$props6.width, height = _this$props6.height, style = _this$props6.style, compact = _this$props6.compact, title2 = _this$props6.title, desc = _this$props6.desc, others = _objectWithoutProperties(_this$props6, _excluded2);
        var attrs = filterProps(others, false);
        if (compact) {
          return /* @__PURE__ */ React.createElement(ChartLayoutContextProvider, {
            state: this.state,
            width: this.props.width,
            height: this.props.height,
            clipPathId: this.clipPathId
          }, /* @__PURE__ */ React.createElement(Surface, _extends({}, attrs, {
            width,
            height,
            title: title2,
            desc
          }), this.renderClipPath(), renderByOrder(children, this.renderMap)));
        }
        if (this.props.accessibilityLayer) {
          var _this$props$tabIndex, _this$props$role;
          attrs.tabIndex = (_this$props$tabIndex = this.props.tabIndex) !== null && _this$props$tabIndex !== void 0 ? _this$props$tabIndex : 0;
          attrs.role = (_this$props$role = this.props.role) !== null && _this$props$role !== void 0 ? _this$props$role : "application";
          attrs.onKeyDown = function(e) {
            _this3.accessibilityManager.keyboardEvent(e);
          };
          attrs.onFocus = function() {
            _this3.accessibilityManager.focus();
          };
        }
        var events = this.parseEventsOfWrapper();
        return /* @__PURE__ */ React.createElement(ChartLayoutContextProvider, {
          state: this.state,
          width: this.props.width,
          height: this.props.height,
          clipPathId: this.clipPathId
        }, /* @__PURE__ */ React.createElement("div", _extends({
          className: clsx("recharts-wrapper", className),
          style: _objectSpread({
            position: "relative",
            cursor: "default",
            width,
            height
          }, style)
        }, events, {
          ref: function ref(node) {
            _this3.container = node;
          }
        }), /* @__PURE__ */ React.createElement(Surface, _extends({}, attrs, {
          width,
          height,
          title: title2,
          desc,
          style: FULL_WIDTH_AND_HEIGHT
        }), this.renderClipPath(), renderByOrder(children, this.renderMap)), this.renderLegend(), this.renderTooltip()));
      }
    }]);
  }(reactExports.Component);
  _defineProperty(CategoricalChartWrapper, "displayName", chartName);
  _defineProperty(CategoricalChartWrapper, "defaultProps", _objectSpread({
    layout: "horizontal",
    stackOffset: "none",
    barCategoryGap: "10%",
    barGap: 4,
    margin: {
      top: 5,
      right: 5,
      bottom: 5,
      left: 5
    },
    reverseStackOrder: false,
    syncMethod: "index"
  }, defaultProps2));
  _defineProperty(CategoricalChartWrapper, "getDerivedStateFromProps", function(nextProps, prevState) {
    var dataKey = nextProps.dataKey, data = nextProps.data, children = nextProps.children, width = nextProps.width, height = nextProps.height, layout = nextProps.layout, stackOffset = nextProps.stackOffset, margin = nextProps.margin;
    var dataStartIndex = prevState.dataStartIndex, dataEndIndex = prevState.dataEndIndex;
    if (prevState.updateId === void 0) {
      var defaultState = createDefaultState(nextProps);
      return _objectSpread(_objectSpread(_objectSpread({}, defaultState), {}, {
        updateId: 0
      }, updateStateOfAxisMapsOffsetAndStackGroups(_objectSpread(_objectSpread({
        props: nextProps
      }, defaultState), {}, {
        updateId: 0
      }), prevState)), {}, {
        prevDataKey: dataKey,
        prevData: data,
        prevWidth: width,
        prevHeight: height,
        prevLayout: layout,
        prevStackOffset: stackOffset,
        prevMargin: margin,
        prevChildren: children
      });
    }
    if (dataKey !== prevState.prevDataKey || data !== prevState.prevData || width !== prevState.prevWidth || height !== prevState.prevHeight || layout !== prevState.prevLayout || stackOffset !== prevState.prevStackOffset || !shallowEqual(margin, prevState.prevMargin)) {
      var _defaultState = createDefaultState(nextProps);
      var keepFromPrevState = {
        // (chartX, chartY) are (0,0) in default state, but we want to keep the last mouse position to avoid
        // any flickering
        chartX: prevState.chartX,
        chartY: prevState.chartY,
        // The tooltip should stay active when it was active in the previous render. If this is not
        // the case, the tooltip disappears and immediately re-appears, causing a flickering effect
        isTooltipActive: prevState.isTooltipActive
      };
      var updatesToState = _objectSpread(_objectSpread({}, getTooltipData(prevState, data, layout)), {}, {
        updateId: prevState.updateId + 1
      });
      var newState = _objectSpread(_objectSpread(_objectSpread({}, _defaultState), keepFromPrevState), updatesToState);
      return _objectSpread(_objectSpread(_objectSpread({}, newState), updateStateOfAxisMapsOffsetAndStackGroups(_objectSpread({
        props: nextProps
      }, newState), prevState)), {}, {
        prevDataKey: dataKey,
        prevData: data,
        prevWidth: width,
        prevHeight: height,
        prevLayout: layout,
        prevStackOffset: stackOffset,
        prevMargin: margin,
        prevChildren: children
      });
    }
    if (!isChildrenEqual(children, prevState.prevChildren)) {
      var _brush$props$startInd, _brush$props, _brush$props$endIndex, _brush$props2;
      var brush2 = findChildByType(children, Brush);
      var startIndex = brush2 ? (_brush$props$startInd = (_brush$props = brush2.props) === null || _brush$props === void 0 ? void 0 : _brush$props.startIndex) !== null && _brush$props$startInd !== void 0 ? _brush$props$startInd : dataStartIndex : dataStartIndex;
      var endIndex = brush2 ? (_brush$props$endIndex = (_brush$props2 = brush2.props) === null || _brush$props2 === void 0 ? void 0 : _brush$props2.endIndex) !== null && _brush$props$endIndex !== void 0 ? _brush$props$endIndex : dataEndIndex : dataEndIndex;
      var hasDifferentStartOrEndIndex = startIndex !== dataStartIndex || endIndex !== dataEndIndex;
      var hasGlobalData = !isNil$1(data);
      var newUpdateId = hasGlobalData && !hasDifferentStartOrEndIndex ? prevState.updateId : prevState.updateId + 1;
      return _objectSpread(_objectSpread({
        updateId: newUpdateId
      }, updateStateOfAxisMapsOffsetAndStackGroups(_objectSpread(_objectSpread({
        props: nextProps
      }, prevState), {}, {
        updateId: newUpdateId,
        dataStartIndex: startIndex,
        dataEndIndex: endIndex
      }), prevState)), {}, {
        prevChildren: children,
        dataStartIndex: startIndex,
        dataEndIndex: endIndex
      });
    }
    return null;
  });
  _defineProperty(CategoricalChartWrapper, "renderActiveDot", function(option, props, key2) {
    var dot;
    if (/* @__PURE__ */ reactExports.isValidElement(option)) {
      dot = /* @__PURE__ */ reactExports.cloneElement(option, props);
    } else if (isFunction(option)) {
      dot = option(props);
    } else {
      dot = /* @__PURE__ */ React.createElement(Dot, props);
    }
    return /* @__PURE__ */ React.createElement(Layer, {
      className: "recharts-active-dot",
      key: key2
    }, dot);
  });
  var CategoricalChart = /* @__PURE__ */ reactExports.forwardRef(function CategoricalChart2(props, ref) {
    return /* @__PURE__ */ React.createElement(CategoricalChartWrapper, _extends({}, props, {
      ref
    }));
  });
  CategoricalChart.displayName = CategoricalChartWrapper.displayName;
  return CategoricalChart;
};
var BarChart = generateCategoricalChart({
  chartName: "BarChart",
  GraphicalChild: Bar,
  defaultTooltipEventType: "axis",
  validateTooltipEventTypes: ["axis", "item"],
  axisComponents: [{
    axisType: "xAxis",
    AxisComp: XAxis
  }, {
    axisType: "yAxis",
    AxisComp: YAxis
  }],
  formatAxisMap
});
var PieChart = generateCategoricalChart({
  chartName: "PieChart",
  GraphicalChild: Pie,
  validateTooltipEventTypes: ["item"],
  defaultTooltipEventType: "item",
  legendContent: "children",
  axisComponents: [{
    axisType: "angleAxis",
    AxisComp: PolarAngleAxis
  }, {
    axisType: "radiusAxis",
    AxisComp: PolarRadiusAxis
  }],
  formatAxisMap: formatAxisMap$1,
  defaultProps: {
    layout: "centric",
    startAngle: 0,
    endAngle: 360,
    cx: "50%",
    cy: "50%",
    innerRadius: 0,
    outerRadius: "80%"
  }
});
const BookingsOverviewChart = ({
  data,
  currency,
  currencyPosition = "left",
  currencyDecimals = 2
}) => {
  const currencySymbolMap = {
    USD: "$",
    EUR: "€",
    GBP: "£",
    INR: "₹",
    GHS: "₵",
    AUD: "A$",
    CAD: "C$"
  };
  const symbol = currencySymbolMap[currency] || currency || "";
  const formatAmount = (value, { compact }) => {
    const v = Number(value) || 0;
    const decimals = Math.max(0, Math.min(4, currencyDecimals));
    const formatCore = (num, useK2) => {
      if (compact && useK2 && Math.abs(num) >= 1e3) {
        const base = (num / 1e3).toFixed(1);
        return `${base}k`;
      }
      return num.toFixed(decimals);
    };
    const useK = compact;
    const core = formatCore(v, useK);
    const mode = normalizeCurrencyPosition(currencyPosition);
    switch (mode) {
      case "right":
        return `${core}${symbol}`;
      case "left_space":
        return `${symbol} ${core}`;
      case "right_space":
        return `${core} ${symbol}`;
      case "left":
      default:
        return `${symbol}${core}`;
    }
  };
  const safeData = Array.isArray(data) ? data.map((d) => ({
    month: d.label,
    bookings: d.count ?? 0,
    amount: d.amount ?? 0
  })) : [];
  if (!safeData.length) {
    return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex items-center justify-center h-[140px] text-gray-500 dark:text-gray-400", children: "No data available" });
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-full", style: { height: 220 }, children: /* @__PURE__ */ jsxRuntimeExports.jsx(ResponsiveContainer, { width: "100%", height: "100%", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
    BarChart,
    {
      data: safeData,
      margin: { top: 16, right: 16, left: 24, bottom: 24 },
      children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(CartesianGrid, { strokeDasharray: "3 3", vertical: false }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          XAxis,
          {
            dataKey: "month",
            tickLine: false,
            axisLine: false,
            tick: { fontFamily: "inherit", fontSize: 11, fill: "#6b7280" }
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          YAxis,
          {
            yAxisId: "left",
            allowDecimals: false,
            tickLine: false,
            axisLine: { stroke: "#e5e7eb" },
            tick: { fontFamily: "inherit", fontSize: 11, fill: "#6b7280" }
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          YAxis,
          {
            yAxisId: "right",
            orientation: "right",
            tickLine: false,
            axisLine: false,
            tickFormatter: (value) => formatAmount(value, { compact: true }),
            tick: { fontFamily: "inherit", fontSize: 11, fill: "#6b7280" }
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          Tooltip,
          {
            cursor: { fill: "rgba(148, 163, 184, 0.12)" },
            formatter: (value, name) => {
              if (name === "Bookings") {
                return [value, "Bookings"];
              }
              if (name === "Amount") {
                const formatted = formatAmount(Number(value) || 0, {
                  compact: false
                });
                return [formatted, "Amount"];
              }
              return [value, name];
            }
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Legend, {}),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          Bar,
          {
            yAxisId: "left",
            dataKey: "bookings",
            name: "Bookings",
            radius: [4, 4, 0, 0],
            fill: "#3b82f6"
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          Bar,
          {
            yAxisId: "right",
            dataKey: "amount",
            name: "Amount",
            radius: [4, 4, 0, 0],
            fill: "#10b981"
          }
        )
      ]
    }
  ) }) });
};
const BookingStatusChart = ({ data }) => {
  const safeData = Array.isArray(data) ? data : [];
  const total = safeData.reduce((sum, item) => sum + (item.value || 0), 0);
  if (!safeData.length || total <= 0) {
    return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex items-center justify-center h-[140px] text-gray-500 dark:text-gray-400", children: "No data available" });
  }
  const chartData = safeData.map((item) => ({
    ...item,
    percent: total > 0 ? item.value / total * 100 : 0
  }));
  const renderLegend = ({ payload }) => {
    if (!payload || !payload.length) return null;
    return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex flex-col gap-1 text-xs sm:text-sm ml-4", children: payload.map((entry, index) => {
      var _a;
      const color2 = entry.color;
      const label = entry.value;
      const percent2 = ((_a = entry.payload) == null ? void 0 : _a.percent) ?? 0;
      const displayPercent = `${percent2.toFixed(1)}%`;
      return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "span",
          {
            className: "inline-block w-3 h-3 rounded",
            style: { backgroundColor: color2 }
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-700 dark:text-gray-300", children: label }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "ml-auto font-medium text-gray-900 dark:text-white", children: displayPercent })
      ] }, index);
    }) });
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-full", style: { height: 180 }, children: /* @__PURE__ */ jsxRuntimeExports.jsx(ResponsiveContainer, { width: "100%", height: "100%", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(PieChart, { children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      Pie,
      {
        data: chartData,
        dataKey: "value",
        nameKey: "label",
        cx: "40%",
        cy: "50%",
        innerRadius: 50,
        outerRadius: 70,
        paddingAngle: 2,
        children: chartData.map((entry, index) => /* @__PURE__ */ jsxRuntimeExports.jsx(Cell, { fill: entry.color }, `cell-${index}`))
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      Tooltip,
      {
        formatter: (_value, _name, props) => `${props.payload.percent.toFixed(1)}%`,
        contentStyle: { fontFamily: "inherit", fontSize: 11 }
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      Legend,
      {
        verticalAlign: "middle",
        align: "right",
        layout: "vertical",
        iconType: "circle",
        wrapperStyle: { fontFamily: "inherit", fontSize: 11 },
        content: renderLegend
      }
    )
  ] }) }) });
};
const UpcomingDepartures = ({
  departures,
  loading = false,
  onView
}) => {
  const formatDate2 = (dateString) => {
    const date2 = new Date(dateString);
    return date2.toLocaleDateString("en-US", {
      month: "short",
      day: "numeric",
      year: "numeric"
    });
  };
  const getDaysUntil = (dateString) => {
    const today = /* @__PURE__ */ new Date();
    const departure = new Date(dateString);
    const diffTime = departure.getTime() - today.getTime();
    const diffDays = Math.ceil(diffTime / (1e3 * 60 * 60 * 24));
    return diffDays;
  };
  if (loading) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { children: __("Upcoming Departures", "yatra") }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-500 dark:text-gray-400", children: __("Loading...", "yatra") }) })
    ] });
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { children: __("Upcoming Departures", "yatra") }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { children: departures && departures.length > 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-2", children: departures.slice(0, 5).map((departure) => {
      const daysUntil = getDaysUntil(departure.departure_date);
      const total = Number(departure.total_spots) || 0;
      let occupancy = 0;
      if (total > 0) {
        occupancy = (total - Number(departure.available_spots || 0)) / total * 100;
      }
      occupancy = Math.max(0, Math.min(100, occupancy));
      return /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "div",
        {
          className: "p-3 rounded-lg border border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors cursor-pointer",
          onClick: () => {
            if (onView) {
              onView(departure);
              return;
            }
            const admin = window == null ? void 0 : window.yatraAdmin;
            const baseUrl = (admin == null ? void 0 : admin.siteUrl) || "";
            const tripId = departure.trip_id || "";
            const query = `?page=yatra&subpage=departures&action=view&id=${departure.id}${tripId ? `&trip_id=${tripId}` : ""}`;
            window.location.href = `${baseUrl}/wp-admin/admin.php${query}`;
          },
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start justify-between mb-2", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("h4", { className: "font-medium text-gray-900 dark:text-white mb-1", children: departure.trip_title }),
                departure.destination && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1 text-sm text-gray-500 dark:text-gray-400 mb-2", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(MapPin, { className: "w-3 h-3" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: departure.destination })
                ] })
              ] }),
              daysUntil >= 0 && daysUntil <= 7 && /* @__PURE__ */ jsxRuntimeExports.jsx(Badge, { variant: daysUntil <= 3 ? "error" : "warning", children: daysUntil === 0 ? __("Today", "yatra") : daysUntil === 1 ? __("Tomorrow", "yatra") : `${daysUntil} ${__("days", "yatra")}` })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-4 text-sm text-gray-600 dark:text-gray-400", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Calendar$1, { className: "w-4 h-4" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: formatDate2(departure.departure_date) })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Users, { className: "w-4 h-4" }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { children: [
                  departure.available_spots,
                  " / ",
                  departure.total_spots,
                  " ",
                  __("available", "yatra")
                ] })
              ] })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-2", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                "div",
                {
                  className: "bg-blue-600 h-2 rounded-full transition-all",
                  style: { width: `${occupancy}%` }
                }
              ) }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-xs text-gray-500 dark:text-gray-400 mt-1 block", children: [
                occupancy.toFixed(0),
                "% ",
                __("occupied", "yatra")
              ] })
            ] })
          ]
        },
        departure.id
      );
    }) }) : /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-500 dark:text-gray-400", children: __("No upcoming departures", "yatra") }) })
  ] });
};
const PendingPayments = ({
  payments,
  loading = false,
  onView,
  onCollect
}) => {
  var _a;
  const globalCurrency = ((_a = window == null ? void 0 : window.yatraAdmin) == null ? void 0 : _a.currency) || "USD";
  const formatCurrency2 = (amount) => formatYatraMoney(Number(amount) || 0, globalCurrency, {
    zeroAsUnknown: false
  });
  const formatDate2 = (dateString) => {
    return new Date(dateString).toLocaleDateString();
  };
  const totalPending = (payments == null ? void 0 : payments.reduce((sum, p) => sum + p.amount, 0)) || 0;
  if (loading) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { children: __("Pending Payments", "yatra") }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-500 dark:text-gray-400", children: __("Loading...", "yatra") }) })
    ] });
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { children: __("Pending Payments", "yatra") }),
      totalPending > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx(Badge, { variant: "warning", className: "text-sm", children: formatCurrency2(totalPending) })
    ] }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { children: payments && payments.length > 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-2", children: payments.slice(0, 2).map((payment) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "div",
      {
        className: "p-3 rounded-lg border border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors",
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start justify-between mb-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2 mb-1", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("h4", { className: "text-sm font-medium text-gray-900 dark:text-white", children: payment.trip_title }),
                payment.days_overdue && payment.days_overdue > 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs(Badge, { variant: "error", className: "text-xs", children: [
                  payment.days_overdue,
                  " ",
                  __("days overdue", "yatra")
                ] })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1 text-sm text-gray-500 dark:text-gray-400 mb-1", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(User, { className: "w-3 h-3" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: payment.customer_name })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1 text-sm text-gray-500 dark:text-gray-400", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Clock, { className: "w-3 h-3" }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { children: [
                  __("Due", "yatra"),
                  ": ",
                  formatDate2(payment.due_date)
                ] })
              ] })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-right", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-base font-semibold text-gray-900 dark:text-white", children: formatCurrency2(payment.amount) }),
              payment.payment_method && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400", children: payment.payment_method })
            ] })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_edit_bookings", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-2 mt-2", children: [
            onView && /* @__PURE__ */ jsxRuntimeExports.jsx(
              Button,
              {
                variant: "outline",
                size: "sm",
                onClick: () => onView(payment),
                className: "flex-1",
                children: __("View", "yatra")
              }
            ),
            onCollect && /* @__PURE__ */ jsxRuntimeExports.jsxs(
              Button,
              {
                size: "sm",
                onClick: () => onCollect(payment),
                className: "flex-1",
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(DollarSign, { className: "w-4 h-4 mr-1" }),
                  __("Collect", "yatra")
                ]
              }
            )
          ] }) })
        ]
      },
      payment.id
    )) }) : /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-500 dark:text-gray-400", children: __("No pending payments", "yatra") }) })
  ] });
};
const RecentBookings = ({
  bookings,
  loading = false,
  onView
}) => {
  var _a;
  const formatDate2 = (dateString) => {
    return new Date(dateString).toLocaleDateString("en-US", {
      month: "short",
      day: "numeric",
      year: "numeric"
    });
  };
  const globalCurrency = ((_a = window == null ? void 0 : window.yatraAdmin) == null ? void 0 : _a.currency) || "USD";
  const formatCurrency2 = (amount) => formatYatraMoney(Number(amount) || 0, globalCurrency, {
    zeroAsUnknown: false
  });
  const getStatusColor = (status) => {
    switch (status) {
      case "confirmed":
        return "bg-green-100 text-green-700 dark:bg-green-900/20 dark:text-green-400";
      case "pending":
        return "bg-yellow-100 text-yellow-700 dark:bg-yellow-900/20 dark:text-yellow-400";
      case "cancelled":
        return "bg-red-100 text-red-700 dark:bg-red-900/20 dark:text-red-400";
      case "completed":
        return "bg-blue-100 text-blue-700 dark:bg-blue-900/20 dark:text-blue-400";
      default:
        return "bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-400";
    }
  };
  if (loading) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { children: __("Recent Bookings", "yatra") }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-500 dark:text-gray-400", children: __("Loading...", "yatra") }) })
    ] });
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { children: __("Recent Bookings", "yatra") }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { children: bookings && bookings.length > 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-2", children: bookings.slice(0, 5).map((booking) => /* @__PURE__ */ jsxRuntimeExports.jsx(
      "div",
      {
        className: "p-3 rounded-lg border border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors cursor-pointer group",
        onClick: () => onView && onView(booking),
        children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start justify-between mb-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1 min-w-0", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2 mb-1", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("h4", { className: "text-sm font-medium text-gray-900 dark:text-white truncate", children: booking.trip_title }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Badge,
                {
                  className: `text-xs ${getStatusColor(booking.status)}`,
                  children: booking.status
                }
              )
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3 text-sm text-gray-500 dark:text-gray-400", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(User, { className: "w-3 h-3" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "truncate", children: booking.customer_name })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Calendar$1, { className: "w-3 h-3" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: formatDate2(booking.booking_date) })
              ] })
            ] })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2 ml-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-right", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm font-semibold text-gray-900 dark:text-white", children: formatCurrency2(booking.total_amount) }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400", children: booking.booking_id })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowRight, { className: "w-4 h-4 text-gray-400 group-hover:text-gray-600 dark:group-hover:text-gray-300 transition-colors" })
          ] })
        ] })
      },
      booking.id
    )) }) : /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-500 dark:text-gray-400", children: __("No recent bookings", "yatra") }) })
  ] });
};
function getPrimaryRoleLabel() {
  var _a;
  const roles = (_a = window.yatraAdmin) == null ? void 0 : _a.roles;
  if (!Array.isArray(roles))
    return { slug: "", label: __("Team member", "yatra") };
  const systemRoles = [
    { slug: "yatra_owner", label: __("Owner", "yatra") },
    { slug: "yatra_manager", label: __("Manager", "yatra") },
    { slug: "yatra_sales_agent", label: __("Sales Agent", "yatra") },
    { slug: "yatra_front_desk", label: __("Front Desk", "yatra") },
    { slug: "yatra_guide", label: __("Guide", "yatra") },
    { slug: "yatra_accountant", label: __("Accountant", "yatra") },
    { slug: "yatra_marketing", label: __("Marketing", "yatra") },
    { slug: "yatra_auditor", label: __("Auditor", "yatra") }
  ];
  for (const candidate of systemRoles) {
    if (roles.includes(candidate.slug)) return candidate;
  }
  const custom = roles.find((r2) => r2.startsWith("yatra_"));
  if (custom) {
    const label = custom.replace(/^yatra_/, "").replace(/_/g, " ").replace(/\b\w/g, (c2) => c2.toUpperCase());
    return { slug: custom, label };
  }
  return { slug: "", label: __("Team member", "yatra") };
}
const RoleDashboard = () => {
  var _a, _b, _c, _d;
  const role = reactExports.useMemo(() => getPrimaryRoleLabel(), []);
  const displayName = ((_a = window.yatraAdmin) == null ? void 0 : _a.currentUserDisplayName) || __("there", "yatra");
  const defaultCurrency = ((_b = window == null ? void 0 : window.yatraAdmin) == null ? void 0 : _b.currency) || "USD";
  readYatraCurrencyPositionFromWindow();
  const currencyDecimalsRaw = window.yatraAdmin;
  Number.isFinite(
    Number(
      (currencyDecimalsRaw == null ? void 0 : currencyDecimalsRaw.decimalPlaces) ?? (currencyDecimalsRaw == null ? void 0 : currencyDecimalsRaw.currency_decimals)
    )
  ) ? Number(
    (currencyDecimalsRaw == null ? void 0 : currencyDecimalsRaw.decimalPlaces) ?? (currencyDecimalsRaw == null ? void 0 : currencyDecimalsRaw.currency_decimals)
  ) : 2;
  const formatCurrencyAmount = (amount) => formatYatraMoney(Number(amount) || 0, defaultCurrency, {
    zeroAsUnknown: false
  });
  const { data: bookingStats, isLoading: bookingStatsLoading } = useQuery({
    queryKey: ["role-dashboard-booking-stats"],
    queryFn: async () => {
      const response = await apiClient.get("/bookings/stats");
      return (response == null ? void 0 : response.data) ?? response ?? {};
    },
    enabled: canCap("yatra_view_bookings")
  });
  const { data: reportData } = useQuery({
    queryKey: ["role-dashboard-reports"],
    queryFn: async () => {
      const response = await apiClient.get("/reports");
      return (response == null ? void 0 : response.data) ?? response ?? {};
    },
    enabled: canCap("yatra_view_financial_reports") || canCap("yatra_view_operational_reports"),
    staleTime: 6e4
  });
  const recentBookings = reactExports.useMemo(
    () => (bookingStats == null ? void 0 : bookingStats.recent_bookings) || [],
    [bookingStats]
  );
  const { data: departures } = useQuery({
    queryKey: ["role-dashboard-departures"],
    queryFn: async () => {
      const response = await apiClient.get("/departures/upcoming");
      return (response == null ? void 0 : response.data) ?? response ?? [];
    },
    enabled: canCap("yatra_view_departures")
  });
  const { data: pendingPayments } = useQuery({
    queryKey: ["role-dashboard-pending-payments"],
    queryFn: async () => {
      const response = await apiClient.get("/payments/pending");
      return (response == null ? void 0 : response.data) ?? response ?? [];
    },
    enabled: canCap("yatra_view_financial_reports")
  });
  const quickActions = [
    {
      label: __("Bookings", "yatra"),
      icon: Calendar$1,
      cap: "yatra_view_bookings",
      onClick: () => navigateMenu("bookings")
    },
    {
      label: __("Enquiries", "yatra"),
      icon: MessageSquare,
      cap: "yatra_view_enquiries",
      onClick: () => navigateMenu("enquiries")
    },
    {
      label: __("Departures", "yatra"),
      icon: Plane,
      cap: "yatra_view_departures",
      onClick: () => navigateMenu("departures")
    },
    {
      label: __("Customers", "yatra"),
      icon: Users,
      cap: "yatra_view_customers",
      onClick: () => navigateMenu("customers")
    },
    {
      label: __("Payments", "yatra"),
      icon: CreditCard,
      cap: "yatra_view_financial_reports",
      onClick: () => navigateMenu("payments")
    },
    {
      label: __("Reports", "yatra"),
      icon: BarChart3,
      cap: "yatra_view_operational_reports",
      onClick: () => navigateMenu("reports")
    },
    {
      label: __("Email Campaigns", "yatra"),
      icon: Mail,
      cap: "yatra_manage_email_automation",
      onClick: () => navigateMenu("email-automation")
    },
    {
      label: __("Audit Log", "yatra"),
      icon: Shield,
      cap: "yatra_view_audit_log",
      onClick: () => navigateMenu("team", { tab: "audit" })
    }
  ];
  const visibleActions = quickActions.filter((a2) => canCap(a2.cap));
  const showBookingsCount = canCap("yatra_view_bookings");
  const showBookedRevenue = canCap("yatra_view_financial_reports");
  const showCollectedRevenue = canCap("yatra_view_financial_reports");
  const showConversion = canCap("yatra_view_operational_reports");
  const showOccupancy = canCap("yatra_view_operational_reports");
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-5", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { className: "border-blue-200 bg-gradient-to-br from-blue-50 via-white to-indigo-50 dark:border-blue-800 dark:from-blue-900/20 dark:via-gray-900 dark:to-indigo-900/20", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-5", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex items-start justify-between gap-3 flex-wrap", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start gap-3 min-w-0", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-12 h-12 rounded-full bg-blue-100 dark:bg-blue-900/40 flex items-center justify-center flex-shrink-0", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Shield, { className: "w-6 h-6 text-blue-600 dark:text-blue-400" }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "min-w-0", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("h1", { className: "text-xl font-semibold text-gray-900 dark:text-white", children: [
          __("Welcome back,", "yatra"),
          " ",
          displayName,
          "."
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "text-sm text-gray-600 dark:text-gray-300 mt-0.5", children: [
          __("You're signed in as", "yatra"),
          " ",
          /* @__PURE__ */ jsxRuntimeExports.jsx(Badge, { className: "bg-indigo-100 text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-300 ml-1", children: role.label }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "ml-2 text-xs text-gray-500 dark:text-gray-400", children: __(
            "Your dashboard is tailored to the surfaces your role can access.",
            "yatra"
          ) })
        ] })
      ] })
    ] }) }) }) }),
    visibleActions.length > 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs(CardHeader, { className: "pb-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Quick actions", "yatra") }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(CardDescription, { children: __(
          "Jump straight to the surfaces you use most. Filtered to what your role can open.",
          "yatra"
        ) })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-2", children: visibleActions.map((action) => {
        const Icon = action.icon;
        return /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "button",
          {
            type: "button",
            onClick: action.onClick,
            className: "flex items-center gap-3 p-3 rounded-lg border border-gray-200 dark:border-gray-700 hover:border-blue-300 hover:bg-blue-50/40 dark:hover:border-blue-700 dark:hover:bg-blue-900/10 transition-colors text-left group",
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-9 h-9 rounded-md bg-gray-100 dark:bg-gray-800 group-hover:bg-blue-100 dark:group-hover:bg-blue-900/30 flex items-center justify-center flex-shrink-0 transition-colors", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Icon, { className: "w-4 h-4 text-gray-600 dark:text-gray-300 group-hover:text-blue-600 dark:group-hover:text-blue-400" }) }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm font-medium text-gray-900 dark:text-white truncate", children: action.label }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowRight, { className: "w-3.5 h-3.5 text-gray-300 group-hover:text-blue-500 ml-auto flex-shrink-0" })
            ]
          },
          action.label
        );
      }) }) })
    ] }),
    (showBookingsCount || showBookedRevenue || showCollectedRevenue || showConversion || showOccupancy) && /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "div",
      {
        className: `grid gap-3 ${[
          showBookingsCount,
          showBookedRevenue,
          showCollectedRevenue,
          showConversion,
          showOccupancy
        ].filter(Boolean).length >= 4 ? "grid-cols-2 md:grid-cols-3 lg:grid-cols-5" : "grid-cols-1 sm:grid-cols-2 lg:grid-cols-3"}`,
        children: [
          showBookingsCount && /* @__PURE__ */ jsxRuntimeExports.jsx(
            StatCard,
            {
              title: __("Bookings", "yatra"),
              value: (bookingStats == null ? void 0 : bookingStats.total) ?? 0,
              icon: Calendar$1,
              color: "green",
              loading: bookingStatsLoading,
              onClick: () => navigateMenu("bookings")
            }
          ),
          showBookedRevenue && /* @__PURE__ */ jsxRuntimeExports.jsx(
            StatCard,
            {
              title: __("Booked Revenue", "yatra"),
              value: formatCurrencyAmount(
                (bookingStats == null ? void 0 : bookingStats.total_revenue) || 0
              ),
              icon: DollarSign,
              color: "purple",
              loading: bookingStatsLoading,
              tooltip: __(
                "Total value of confirmed bookings — gross, before refunds.",
                "yatra"
              ),
              onClick: () => navigateMenu("payments")
            }
          ),
          showCollectedRevenue && /* @__PURE__ */ jsxRuntimeExports.jsx(
            StatCard,
            {
              title: __("Collected Revenue", "yatra"),
              value: formatCurrencyAmount(
                (bookingStats == null ? void 0 : bookingStats.total_collected) || 0
              ),
              icon: DollarSign,
              color: "green",
              loading: bookingStatsLoading,
              tooltip: __(
                "Cash already received — actually in your accounts.",
                "yatra"
              ),
              onClick: () => navigateMenu("payments")
            }
          ),
          showConversion && /* @__PURE__ */ jsxRuntimeExports.jsx(
            StatCard,
            {
              title: __("Conversion", "yatra"),
              value: `${Number(
                ((_c = reportData == null ? void 0 : reportData.booking_stats) == null ? void 0 : _c.conversionRate) || 0
              ).toFixed(1)}%`,
              icon: TrendingUp,
              color: "blue",
              tooltip: __(
                "Share of bookings that landed in confirmed or completed.",
                "yatra"
              )
            }
          ),
          showOccupancy && /* @__PURE__ */ jsxRuntimeExports.jsx(
            StatCard,
            {
              title: __("Occupancy", "yatra"),
              value: `${Number(
                ((_d = reportData == null ? void 0 : reportData.operational_stats) == null ? void 0 : _d.occupancyRate) || 0
              ).toFixed(1)}%`,
              icon: CheckCircle,
              color: "orange",
              tooltip: __(
                "Booked seats vs total seats across upcoming departures.",
                "yatra"
              )
            }
          )
        ]
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-12 gap-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-3 lg:col-span-7", children: canCap("yatra_view_bookings") && (bookingStatsLoading ? /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-4", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-40 w-full" }) }) }) : /* @__PURE__ */ jsxRuntimeExports.jsx(
        RecentBookings,
        {
          bookings: recentBookings || [],
          loading: bookingStatsLoading,
          onView: (booking) => navigateMenu("bookings", {
            action: "view",
            id: String(booking.id)
          })
        }
      )) }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3 lg:col-span-5", children: [
        canCap("yatra_view_departures") && /* @__PURE__ */ jsxRuntimeExports.jsx(UpcomingDepartures, { departures: departures || [], loading: false }),
        canCap("yatra_view_financial_reports") && /* @__PURE__ */ jsxRuntimeExports.jsx(PendingPayments, { payments: pendingPayments || [], loading: false })
      ] })
    ] }),
    visibleActions.length === 0 && !showBookingsCount && !showBookedRevenue && !showConversion && /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { className: "border-dashed", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "p-8 text-center", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(RotateCcw, { className: "w-8 h-8 text-gray-300 mx-auto mb-3" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-base font-semibold text-gray-900 dark:text-white", children: __("Your role doesn't expose dashboard widgets yet.", "yatra") }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-500 dark:text-gray-400 mt-1 max-w-md mx-auto", children: sprintf(
        /* translators: %s: brand name */
        __(
          "Talk to your account owner — they can grant additional capabilities to your user from %s → Team & Access.",
          "yatra"
        ),
        brandName()
      ) })
    ] }) })
  ] });
};
const rangeLabels = () => ({
  all_time: __("All time", "yatra"),
  today: __("Today", "yatra"),
  last_7_days: __("Last 7 days", "yatra"),
  last_30_days: __("Last 30 days", "yatra"),
  last_90_days: __("Last 90 days", "yatra"),
  this_year: __("This year", "yatra")
});
function getDateBounds(range3) {
  if (range3 === "all_time") return {};
  const today = /* @__PURE__ */ new Date();
  const start = new Date(today);
  switch (range3) {
    case "today":
      start.setHours(0, 0, 0, 0);
      break;
    case "last_7_days":
      start.setDate(today.getDate() - 7);
      break;
    case "last_30_days":
      start.setDate(today.getDate() - 30);
      break;
    case "last_90_days":
      start.setDate(today.getDate() - 90);
      break;
    case "this_year":
      start.setMonth(0, 1);
      break;
  }
  const fmt = (d) => `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, "0")}-${d.getDate().toString().padStart(2, "0")}`;
  return { from: fmt(start), to: fmt(today) };
}
const SkeletonStatCard = () => /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "pt-6", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-4 w-24 mb-2" }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-8 w-32" })
  ] }),
  /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "w-12 h-12 rounded-full" })
] }) }) });
const WELCOME_DISMISSED_KEY = "yatra:dashboard:welcome-dismissed:v1";
const Dashboard = () => {
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
  const isWpAdmin = !!((_a = window.yatraAdmin) == null ? void 0 : _a.isWpAdmin);
  const { can } = usePermissions();
  const [range3, setRange] = reactExports.useState("all_time");
  const dateBounds = reactExports.useMemo(() => getDateBounds(range3), [range3]);
  const [welcomeDismissed, setWelcomeDismissed] = reactExports.useState(() => {
    try {
      return localStorage.getItem(WELCOME_DISMISSED_KEY) === "1";
    } catch {
      return false;
    }
  });
  const dismissWelcome = () => {
    setWelcomeDismissed(true);
    try {
      localStorage.setItem(WELCOME_DISMISSED_KEY, "1");
    } catch {
    }
  };
  const defaultCurrency = ((_b = window == null ? void 0 : window.yatraAdmin) == null ? void 0 : _b.currency) || ((_c = window == null ? void 0 : window.yatraBookingData) == null ? void 0 : _c.currency) || "USD";
  const currencyPosition = readYatraCurrencyPositionFromWindow();
  const currencyDecimalsRaw = ((_d = window == null ? void 0 : window.yatraAdmin) == null ? void 0 : _d.decimalPlaces) ?? ((_e = window == null ? void 0 : window.yatraAdmin) == null ? void 0 : _e.currency_decimals) ?? ((_f = window == null ? void 0 : window.yatraBookingData) == null ? void 0 : _f.decimalPlaces) ?? ((_g = window == null ? void 0 : window.yatraBookingData) == null ? void 0 : _g.currency_decimals);
  const currencyDecimals = Number.isFinite(Number(currencyDecimalsRaw)) ? Number(currencyDecimalsRaw) : 2;
  const formatCurrencyAmount = (amount) => formatYatraMoney(Number(amount) || 0, defaultCurrency, {
    zeroAsUnknown: false
  });
  const { data: bookingStats, isLoading: bookingStatsLoading } = useQuery({
    queryKey: ["dashboard-booking-stats"],
    queryFn: async () => {
      const response = await apiClient.get("/bookings/stats");
      return (response == null ? void 0 : response.data) ?? response ?? {};
    },
    enabled: isWpAdmin
  });
  const { data: tripsSummary } = useQuery({
    queryKey: ["dashboard-trips-total"],
    queryFn: async () => {
      const response = await apiClient.get("/trips", {
        params: { per_page: 1 }
      });
      return { total: (response == null ? void 0 : response.total) ?? 0 };
    },
    enabled: isWpAdmin && can("yatra_view_trips")
  });
  const { data: customersSummary } = useQuery({
    queryKey: ["dashboard-customers-total"],
    queryFn: async () => {
      const response = await apiClient.get("/customers", {
        params: { per_page: 1 }
      });
      return { total: (response == null ? void 0 : response.total) ?? 0 };
    },
    enabled: isWpAdmin && can("yatra_view_bookings")
  });
  const { data: reportData } = useQuery({
    queryKey: ["dashboard-reports", dateBounds.from, dateBounds.to],
    queryFn: async () => {
      const response = await apiClient.get("/reports", {
        params: {
          date_from: dateBounds.from,
          date_to: dateBounds.to
        }
      });
      return (response == null ? void 0 : response.data) ?? response ?? {};
    },
    enabled: isWpAdmin && !!dateBounds.from && !!dateBounds.to,
    staleTime: 6e4
  });
  const { data: bookingsChartData } = useQuery({
    queryKey: ["dashboard-bookings-chart", range3],
    queryFn: async () => {
      const now2 = /* @__PURE__ */ new Date();
      const pad2 = (n) => String(n).padStart(2, "0");
      const response = await apiClient.get("/bookings", {
        params: { per_page: 500 }
      });
      const items = (response == null ? void 0 : response.data) || [];
      const counts = {};
      const amounts = {};
      items.forEach((b) => {
        const dateStr = b.created_at || b.travel_date;
        const date2 = dateStr ? new Date(dateStr) : null;
        if (!date2 || Number.isNaN(date2.getTime())) return;
        const ym = `${date2.getFullYear()}-${pad2(date2.getMonth() + 1)}`;
        counts[ym] = (counts[ym] || 0) + 1;
        const amount = Number(b.total_amount ?? 0) || 0;
        amounts[ym] = (amounts[ym] || 0) + amount;
      });
      const months = [];
      for (let i = 5; i >= 0; i--) {
        const d = new Date(now2.getFullYear(), now2.getMonth() - i, 1);
        const ym = `${d.getFullYear()}-${pad2(d.getMonth() + 1)}`;
        const label = d.toLocaleDateString(void 0, {
          month: "short",
          year: "numeric"
        });
        months.push({
          label,
          count: counts[ym] || 0,
          amount: amounts[ym] || 0
        });
      }
      return months;
    },
    enabled: isWpAdmin && can("yatra_view_bookings") && range3 === "all_time"
  });
  const statusData = reactExports.useMemo(() => {
    const byStatus = (bookingStats == null ? void 0 : bookingStats.by_status) || {};
    const getCount = (key2) => {
      const entry = byStatus[key2];
      if (!entry) return 0;
      const raw = entry.count;
      const n = typeof raw === "string" ? parseInt(raw, 10) : Number(raw ?? 0);
      return Number.isNaN(n) ? 0 : n;
    };
    return [
      {
        label: __("Pending", "yatra"),
        value: getCount("pending"),
        color: "#f59e0b"
      },
      {
        label: __("Confirmed", "yatra"),
        value: getCount("confirmed"),
        color: "#10b981"
      },
      {
        label: __("Completed", "yatra"),
        value: getCount("completed"),
        color: "#3b82f6"
      },
      {
        label: __("Cancelled", "yatra"),
        value: getCount("cancelled"),
        color: "#ef4444"
      },
      {
        label: __("Refunded", "yatra"),
        value: getCount("refunded"),
        color: "#a855f7"
      }
    ];
  }, [bookingStats]);
  const { data: destinationsData } = useQuery({
    queryKey: ["dashboard-destinations"],
    queryFn: async () => {
      const response = await apiClient.get("/trips", {
        params: { per_page: 50 }
      });
      const trips = (response == null ? void 0 : response.data) || [];
      const counts = {};
      trips.forEach((trip) => {
        const destinations = trip.destinations || [];
        destinations.forEach((dest) => {
          const name = (dest == null ? void 0 : dest.name) || (dest == null ? void 0 : dest.destination_name) || "";
          if (!name) return;
          counts[name] = (counts[name] || 0) + 1;
        });
      });
      const palette2 = [
        "#3b82f6",
        "#10b981",
        "#f59e0b",
        "#ef4444",
        "#6366f1",
        "#14b8a6"
      ];
      return Object.entries(counts).sort((a2, b) => b[1] - a2[1]).slice(0, 6).map(([name, value], index) => ({
        label: name,
        value,
        color: palette2[index % palette2.length]
      }));
    },
    enabled: isWpAdmin && can("yatra_view_trips")
  });
  const { data: departures } = useQuery({
    queryKey: ["dashboard-upcoming-departures"],
    queryFn: async () => {
      const today = /* @__PURE__ */ new Date();
      const todayStr = today.toISOString().split("T")[0];
      const response = await apiClient.get("/departures", {
        params: {
          status: "upcoming",
          date_from: todayStr,
          include_past: false
        }
      });
      const items = (response == null ? void 0 : response.data) || [];
      return items.map((d) => {
        var _a2, _b2, _c2, _d2;
        const tripTitle = ((_a2 = d == null ? void 0 : d.trip) == null ? void 0 : _a2.title) || (d == null ? void 0 : d.trip_title) || (d == null ? void 0 : d.title) || "";
        const destination = ((_b2 = d == null ? void 0 : d.trip) == null ? void 0 : _b2.destinations) && ((_c2 = d.trip.destinations[0]) == null ? void 0 : _c2.name) || (d == null ? void 0 : d.destination) || void 0;
        const totalSpots = (d == null ? void 0 : d.total_spots) ?? (d == null ? void 0 : d.capacity) ?? (d == null ? void 0 : d.total_seats) ?? (d == null ? void 0 : d.max_travelers) ?? 0;
        const availableSpots = (d == null ? void 0 : d.available_spots) ?? (d == null ? void 0 : d.available_seats) ?? (d == null ? void 0 : d.remaining_slots) ?? totalSpots - ((d == null ? void 0 : d.bookings_count) || 0);
        return {
          id: d.id,
          trip_id: d.trip_id || ((_d2 = d == null ? void 0 : d.trip) == null ? void 0 : _d2.id),
          trip_title: tripTitle,
          departure_date: d.start_date || d.date || d.departure_date,
          available_spots: Number.isFinite(availableSpots) ? availableSpots : 0,
          total_spots: Number.isFinite(totalSpots) ? totalSpots : 0,
          status: d.status || "upcoming",
          destination
        };
      });
    },
    enabled: isWpAdmin && can("yatra_view_trips")
  });
  const { data: pendingPayments } = useQuery({
    queryKey: ["dashboard-pending-payments"],
    queryFn: async () => {
      const response = await apiClient.get("/payments", {
        params: { status: "pending", per_page: 5 }
      });
      return (response == null ? void 0 : response.data) || [];
    },
    enabled: isWpAdmin && can("yatra_view_bookings")
  });
  const { data: recentBookings } = useQuery({
    queryKey: ["dashboard-recent-bookings"],
    queryFn: async () => {
      const response = await apiClient.get("/bookings", {
        params: { per_page: 5 }
      });
      const items = (response == null ? void 0 : response.data) || [];
      return items.map((b) => ({
        id: b.id,
        booking_id: b.reference || `BK-${b.id}`,
        customer_name: b.customer_name || b.contact_first_name || "",
        trip_title: b.trip_title || "",
        booking_date: b.created_at || b.travel_date || "",
        total_amount: b.total_amount ?? 0,
        status: b.status || "pending"
      }));
    },
    enabled: isWpAdmin && can("yatra_view_bookings")
  });
  const trendLabel = `vs prev. ${range3 === "today" ? "day" : range3 === "this_year" ? "year" : range3.replace("last_", "").replace("_", " ")}`;
  const revenueChange = Number(((_h = reportData == null ? void 0 : reportData.revenue_stats) == null ? void 0 : _h.change) ?? 0);
  const totalChange = Number(
    ((_i = reportData == null ? void 0 : reportData.booking_stats) == null ? void 0 : _i.totalChange) ?? 0
  );
  const conversionChange = Number(
    ((_j = reportData == null ? void 0 : reportData.booking_stats) == null ? void 0 : _j.conversionRateChange) ?? 0
  );
  const hasPeriodData = range3 !== "all_time" && !!reportData;
  const goTo = (subpage, extras = {}) => {
    const admin = window == null ? void 0 : window.yatraAdmin;
    const baseUrl = (admin == null ? void 0 : admin.siteUrl) || "";
    const qs = Object.entries(extras).map(([k2, v]) => `&${k2}=${encodeURIComponent(v)}`).join("");
    window.location.href = `${baseUrl}/wp-admin/admin.php?page=yatra&subpage=${subpage}${qs}`;
  };
  if (!isWpAdmin) {
    return /* @__PURE__ */ jsxRuntimeExports.jsx(RoleDashboard, {});
  }
  if (bookingStatsLoading) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-4", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-3", children: Array.from({ length: 5 }).map((_, i) => /* @__PURE__ */ jsxRuntimeExports.jsx(SkeletonStatCard, {}, i)) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-6", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-64 w-full" }) }) })
    ] });
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-4", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("h1", { className: "text-xl font-semibold text-gray-900 dark:text-white", children: __("Dashboard", "yatra") }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400", children: __("Operations overview at a glance.", "yatra") })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "select",
          {
            value: range3,
            onChange: (e) => setRange(e.target.value),
            className: "rounded-md border border-gray-300 bg-white px-3 py-1.5 text-sm text-gray-700 shadow-sm focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-200",
            "aria-label": __("Date range", "yatra"),
            children: (() => {
              const labels = rangeLabels();
              return Object.keys(labels).map((k2) => /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: k2, children: labels[k2] }, k2));
            })()
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Button,
          {
            type: "button",
            onClick: () => goTo("trips", { action: "add" }),
            className: "inline-flex items-center gap-1",
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Plus, { className: "h-4 w-4" }),
              __("Add Trip", "yatra")
            ]
          }
        )
      ] })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(TodaysBriefCard, {}),
    !welcomeDismissed && /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { className: "border-blue-200 bg-gradient-to-r from-blue-50 to-indigo-50 dark:border-blue-800 dark:from-blue-900/20 dark:to-indigo-900/20", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-4", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start justify-between gap-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start gap-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Activity, { className: "mt-0.5 h-5 w-5 shrink-0 text-blue-600 dark:text-blue-400" }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "mb-1 font-semibold text-gray-900 dark:text-white", children: __("Welcome to Yatra", "yatra") }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-600 dark:text-gray-300", children: __(
            "Real-time insights for your travel business. Monitor performance, track bookings, and manage operations from one place.",
            "yatra"
          ) })
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        "button",
        {
          type: "button",
          onClick: dismissWelcome,
          className: "rounded-md p-1 text-gray-500 transition-colors hover:bg-blue-100 hover:text-gray-700 dark:hover:bg-blue-900/30 dark:hover:text-gray-200",
          "aria-label": __("Dismiss welcome message", "yatra"),
          children: /* @__PURE__ */ jsxRuntimeExports.jsx(X, { className: "h-4 w-4" })
        }
      )
    ] }) }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-2 gap-3 md:grid-cols-3 lg:grid-cols-5", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_view_trips", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        StatCard,
        {
          title: __("Total Trips", "yatra"),
          value: (tripsSummary == null ? void 0 : tripsSummary.total) || 0,
          icon: MapPin,
          color: "blue",
          loading: !tripsSummary,
          onClick: () => goTo("trips")
        }
      ) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_view_bookings", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        StatCard,
        {
          title: __("Total Bookings", "yatra"),
          value: (bookingStats == null ? void 0 : bookingStats.total) || 0,
          icon: Calendar$1,
          color: "green",
          loading: bookingStatsLoading,
          trend: hasPeriodData ? {
            value: totalChange,
            isPositive: totalChange >= 0,
            label: trendLabel
          } : void 0,
          onClick: () => goTo("bookings")
        }
      ) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_view_financial_reports", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        StatCard,
        {
          title: __("Booked Revenue", "yatra"),
          value: formatCurrencyAmount((bookingStats == null ? void 0 : bookingStats.total_revenue) || 0),
          icon: DollarSign,
          color: "purple",
          loading: bookingStatsLoading,
          tooltip: __(
            "Total value of confirmed bookings — the gross revenue you're entitled to. Not yet net of cancellations or refunds.",
            "yatra"
          ),
          trend: hasPeriodData ? {
            value: revenueChange,
            isPositive: revenueChange >= 0,
            label: trendLabel
          } : void 0,
          onClick: () => goTo("payments")
        }
      ) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_view_financial_reports", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        StatCard,
        {
          title: __("Collected Revenue", "yatra"),
          value: formatCurrencyAmount((bookingStats == null ? void 0 : bookingStats.total_collected) || 0),
          icon: DollarSign,
          color: "green",
          loading: bookingStatsLoading,
          tooltip: __(
            "Cash already received — what's actually in your accounts. The gap between Booked and Collected is your accounts-receivable (pending payments + scheduled instalments).",
            "yatra"
          ),
          onClick: () => goTo("payments")
        }
      ) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_view_customers", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        StatCard,
        {
          title: __("Total Customers", "yatra"),
          value: (customersSummary == null ? void 0 : customersSummary.total) || 0,
          icon: Users,
          color: "orange",
          loading: !customersSummary,
          onClick: () => goTo("customers")
        }
      ) })
    ] }),
    hasPeriodData && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-2 gap-3 md:grid-cols-4", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_view_operational_reports", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        StatCard,
        {
          title: __("Conversion Rate", "yatra"),
          value: `${Number(((_k = reportData == null ? void 0 : reportData.booking_stats) == null ? void 0 : _k.conversionRate) || 0).toFixed(1)}%`,
          icon: TrendingUp,
          color: "green",
          tooltip: __(
            "Share of bookings in this period that landed in a confirmed or completed state. Higher is better.",
            "yatra"
          ),
          trend: {
            value: conversionChange,
            isPositive: conversionChange >= 0,
            label: trendLabel
          }
        }
      ) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_view_financial_reports", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        StatCard,
        {
          title: __("Avg Booking Value", "yatra"),
          value: formatCurrencyAmount(
            Number(((_l = reportData == null ? void 0 : reportData.revenue_stats) == null ? void 0 : _l.average) || 0)
          ),
          icon: DollarSign,
          color: "purple",
          tooltip: __(
            "Mean revenue per booking in this period. A rising AOV with stable booking count is the cleanest growth signal.",
            "yatra"
          )
        }
      ) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_view_operational_reports", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        StatCard,
        {
          title: __("Occupancy Rate", "yatra"),
          value: `${Number(((_m = reportData == null ? void 0 : reportData.operational_stats) == null ? void 0 : _m.occupancyRate) || 0).toFixed(1)}%`,
          icon: Plane,
          color: "blue",
          tooltip: __(
            "Booked seats / total seats across upcoming departures. Capacity utilisation indicator.",
            "yatra"
          )
        }
      ) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_view_operational_reports", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        StatCard,
        {
          title: __("Cancellation Rate", "yatra"),
          value: `${Number(((_n = reportData == null ? void 0 : reportData.booking_stats) == null ? void 0 : _n.cancellationRate) || 0).toFixed(1)}%`,
          icon: CheckCircle,
          color: "red",
          tooltip: __(
            "Share of bookings that ended cancelled. Watch the trend — a spike usually points at a specific trip or timing issue.",
            "yatra"
          )
        }
      ) })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 gap-3 lg:grid-cols-12", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3 lg:col-span-7", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_view_bookings", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { children: __("Bookings Overview", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            BookingsOverviewChart,
            {
              data: bookingsChartData || [],
              currency: defaultCurrency,
              currencyPosition,
              currencyDecimals
            }
          ) })
        ] }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 gap-3 md:grid-cols-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_view_bookings", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { children: __("Booking Status", "yatra") }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(BookingStatusChart, { data: statusData || [] }) })
          ] }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_view_operational_reports", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { children: __("Popular Destinations", "yatra") }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "pb-2", children: destinationsData && destinationsData.length > 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx(
              SimpleBarChart,
              {
                data: destinationsData || [],
                title: "",
                height: 180,
                showValues: true
              }
            ) : /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "py-10 text-center text-sm text-gray-500 dark:text-gray-400", children: __("No destination data yet.", "yatra") }) })
          ] }) })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_view_bookings", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          RecentBookings,
          {
            bookings: recentBookings || [],
            loading: bookingStatsLoading,
            onView: (booking) => {
              goTo("bookings", { action: "view", id: String(booking.id) });
            }
          }
        ) })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3 lg:col-span-5", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_view_departures", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          UpcomingDepartures,
          {
            departures: departures || [],
            loading: bookingStatsLoading
          }
        ) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_view_financial_reports", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          PendingPayments,
          {
            payments: pendingPayments || [],
            loading: bookingStatsLoading
          }
        ) })
      ] })
    ] })
  ] });
};
const Input = reactExports.forwardRef(
  ({ className = "", type, ...props }, ref) => {
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "input",
      {
        type,
        className: `flex h-12 w-full rounded-md border-2 border-gray-300 bg-white px-4 py-3 text-base font-normal text-gray-900 ring-offset-white file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-gray-400 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100 dark:ring-offset-gray-900 dark:placeholder:text-gray-500 dark:focus-visible:ring-blue-400 transition-colors ${className}`,
        ref,
        ...props
      }
    );
  }
);
Input.displayName = "Input";
const sizeClasses = {
  sm: "max-w-md",
  md: "max-w-xl",
  lg: "max-w-2xl",
  xl: "max-w-4xl",
  full: "max-w-6xl"
};
const Modal = ({
  isOpen,
  onClose,
  title: title2,
  description,
  children,
  footer,
  size = "xl",
  maxWidthClassName,
  panelClassName = "",
  bodyClassName,
  showCloseButton = true,
  closeOnOverlayClick = true,
  loading = false,
  loadingSkeleton,
  error,
  errorComponent,
  hideHeader = false,
  hideFooter = false,
  customZIndex,
  bodyScrollClassName
}) => {
  reactExports.useEffect(() => {
    if (!isOpen) {
      return;
    }
    const originalOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      document.body.style.overflow = originalOverflow;
    };
  }, [isOpen]);
  if (!isOpen) {
    return null;
  }
  const panelWidthClass = maxWidthClassName || sizeClasses[size];
  const bodyClasses = bodyClassName ?? "px-6 py-5";
  const bodyScrollClasses = bodyScrollClassName ?? "max-h-[70vh] overflow-y-auto custom-scrollbar";
  const zIndex = customZIndex || 999999;
  const defaultLoadingSkeleton = /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-4 animate-pulse", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-3/4" }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-1/2" }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-5/6" }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2 pt-4", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-3 bg-gray-200 dark:bg-gray-700 rounded" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-3 bg-gray-200 dark:bg-gray-700 rounded w-4/5" })
    ] })
  ] });
  const defaultErrorComponent = error ? /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-center py-8", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "inline-flex items-center justify-center w-12 h-12 rounded-full bg-red-100 dark:bg-red-900/20 mb-4", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
      "svg",
      {
        className: "w-6 h-6 text-red-600 dark:text-red-400",
        fill: "none",
        viewBox: "0 0 24 24",
        stroke: "currentColor",
        children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          "path",
          {
            strokeLinecap: "round",
            strokeLinejoin: "round",
            strokeWidth: 2,
            d: "M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
          }
        )
      }
    ) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-red-600 dark:text-red-400 font-medium mb-2", children: __("Error", "yatra") }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-gray-600 dark:text-gray-400 text-sm", children: error })
  ] }) : null;
  return reactDomExports.createPortal(
    /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "div",
      {
        className: "fixed inset-0 flex items-center justify-center px-4",
        style: { zIndex },
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "div",
            {
              className: "absolute inset-0 bg-black/60 backdrop-blur-sm",
              onClick: () => {
                if (closeOnOverlayClick && !loading) {
                  onClose();
                }
              }
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "div",
            {
              className: `relative w-full ${panelWidthClass} bg-white dark:bg-gray-900 rounded-2xl shadow-2xl border border-gray-100 dark:border-gray-800 overflow-hidden animate-in fade-in zoom-in duration-150 yatra-model-ui ${panelClassName}`,
              style: { zIndex: zIndex + 1 },
              children: [
                !hideHeader && (title2 || showCloseButton) && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between px-6 py-4 border-b border-gray-100 dark:border-gray-800", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                    title2 && /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { className: "text-lg font-semibold text-gray-900 dark:text-white", children: title2 }),
                    description && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm text-gray-500 dark:text-gray-400", children: description })
                  ] }),
                  showCloseButton && /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "button",
                    {
                      type: "button",
                      onClick: onClose,
                      disabled: loading,
                      className: "p-2 rounded-full text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-purple-500 disabled:opacity-50 disabled:cursor-not-allowed",
                      "aria-label": __("Close modal", "yatra"),
                      children: /* @__PURE__ */ jsxRuntimeExports.jsx(X, { className: "w-5 h-5" })
                    }
                  )
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: `${bodyClasses} ${bodyScrollClasses}`, children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-full", children: loading ? loadingSkeleton || defaultLoadingSkeleton : error ? errorComponent || defaultErrorComponent : children }) }),
                !hideFooter && footer && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "px-6 py-4 border-t border-gray-100 dark:border-gray-800 bg-gray-50/70 dark:bg-gray-900/50", children: footer })
              ]
            }
          )
        ]
      }
    ),
    document.body
  );
};
const dropdownArrowLight = `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%236b7280' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E")`;
const dropdownArrowDark = `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%23d1d5db' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E")`;
const Select = reactExports.forwardRef(
  ({ className = "", children, style, ...props }, ref) => {
    const [isDark, setIsDark] = reactExports.useState(false);
    reactExports.useEffect(() => {
      const checkDarkMode = () => {
        setIsDark(document.documentElement.classList.contains("dark"));
      };
      checkDarkMode();
      const observer = new MutationObserver(checkDarkMode);
      observer.observe(document.documentElement, {
        attributes: true,
        attributeFilter: ["class"]
      });
      return () => observer.disconnect();
    }, []);
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "select",
      {
        className: `flex h-12 w-full rounded-md border-2 border-gray-300 bg-white px-4 text-base text-gray-900 ring-offset-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100 dark:ring-offset-gray-900 dark:focus-visible:ring-blue-400 transition-colors cursor-pointer ${className}`,
        ref,
        style: {
          paddingRight: "2.5rem",
          WebkitAppearance: "none",
          MozAppearance: "none",
          appearance: "none",
          backgroundImage: isDark ? dropdownArrowDark : dropdownArrowLight,
          backgroundRepeat: "no-repeat",
          backgroundPosition: "right 0.75rem center",
          backgroundSize: "16px 16px",
          ...style
        },
        ...props,
        children
      }
    );
  }
);
Select.displayName = "Select";
const DAY_HEAD = /^\s*(?:#+\s*)?(?:\*+\s*)?day\s+(\d+)\s*(?:[:\-–—]\s*)?(.*?)\s*\**?\s*$/i;
function parseItineraryText(text) {
  if (!text) return [];
  const lines = text.replace(/\r\n?/g, "\n").split("\n");
  const days = [];
  let current = null;
  let descriptionBuffer = [];
  const flush = () => {
    if (current) {
      current.description = cleanDescription(descriptionBuffer);
      days.push(current);
    }
    current = null;
    descriptionBuffer = [];
  };
  for (const rawLine of lines) {
    const line = rawLine.trimEnd();
    const headMatch = DAY_HEAD.exec(line);
    if (headMatch) {
      flush();
      const dayNum = parseInt(headMatch[1], 10);
      const title2 = (headMatch[2] || "").replace(/[\*_`]+/g, "").trim();
      current = {
        day: Number.isFinite(dayNum) && dayNum > 0 ? dayNum : days.length + 1,
        day_title: title2,
        description: ""
      };
      continue;
    }
    if (current) {
      descriptionBuffer.push(line);
    }
  }
  flush();
  return days.map((d, idx) => ({
    day: idx + 1,
    day_title: d.day_title,
    description: d.description
  }));
}
function cleanDescription(buffer) {
  const trimmed = buffer.join("\n").replace(/\s+$/g, "");
  return trimmed.replace(/^\s*\n+/g, "").replace(/\n{3,}/g, "\n\n").replace(/^[\*_]+|[\*_]+$/gm, "").trim();
}
const DEFAULT_SETUP = {
  name: "",
  slug: "",
  destinations: "",
  trip_type: "multi_day",
  duration_days: "5",
  duration_nights: "4",
  difficulty_level_id: "",
  difficulty_level_label: "",
  best_season: "",
  audience: "",
  activities: "",
  price: "",
  sale_price: "",
  extra_context: ""
};
const SECTIONS = [
  {
    id: "description",
    label: "Trip description",
    task: "trip-description",
    decode: (t) => plainTextToHtml(t),
    preview: (v) => typeof v === "string" ? v.replace(/<\/p>\s*<p>/gi, "\n\n").replace(/<[^>]+>/g, "").trim() : "",
    payloadKey: "description"
  },
  {
    id: "short_description",
    label: "Short description",
    task: "trip-short-description",
    decode: (t) => t.trim(),
    preview: (v) => String(v ?? ""),
    payloadKey: "short_description"
  },
  {
    id: "trip_details",
    label: "Trip details (logistics)",
    task: "trip-details",
    decode: (t) => plainTextToHtml(t),
    preview: (v) => typeof v === "string" ? v.replace(/<\/p>\s*<p>/gi, "\n\n").replace(/<[^>]+>/g, "").trim() : "",
    payloadKey: "trip_details"
  },
  {
    id: "what_makes_special",
    label: "What makes this trip special",
    task: "what-makes-special",
    decode: (t) => plainTextToHtml(t),
    preview: (v) => typeof v === "string" ? v.replace(/<\/p>\s*<p>/gi, "\n\n").replace(/<[^>]+>/g, "").trim() : "",
    payloadKey: "what_makes_special"
  },
  {
    id: "trip_story",
    label: "Trip story",
    task: "trip-story",
    decode: (t) => plainTextToHtml(t),
    preview: (v) => typeof v === "string" ? v.replace(/<\/p>\s*<p>/gi, "\n\n").replace(/<[^>]+>/g, "").trim() : "",
    payloadKey: "trip_story"
  },
  {
    id: "starting_location",
    label: "Starting location",
    task: "starting-location",
    decode: (t) => t.trim(),
    preview: (v) => String(v ?? ""),
    payloadKey: "starting_location"
  },
  {
    id: "ending_location",
    label: "Ending location",
    task: "ending-location",
    decode: (t) => t.trim(),
    preview: (v) => String(v ?? ""),
    payloadKey: "ending_location"
  },
  {
    id: "accommodation_type",
    label: "Accommodation tier",
    task: "accommodation-type",
    decode: (t) => t.trim(),
    preview: (v) => String(v ?? ""),
    payloadKey: "accommodation_type"
  },
  {
    id: "highlights",
    label: "Highlights",
    task: "trip-highlights",
    decode: (t) => t.split(/\r?\n/).map((l) => l.replace(/^[\s\-\*•·●]+/, "").trim()).filter((l) => l !== ""),
    preview: (v) => Array.isArray(v) ? v.map((s2) => `• ${s2}`).join("\n") : "",
    payloadKey: "highlights"
  },
  {
    id: "included_items",
    label: "What's included",
    task: "trip-included-items",
    decode: (t) => decodeAmenityList(t),
    preview: (v) => Array.isArray(v) ? v.map((i) => `• ${i.title}`).join("\n") : "",
    payloadKey: "included_items"
  },
  {
    id: "excluded_items",
    label: "What's excluded",
    task: "trip-excluded-items",
    decode: (t) => decodeAmenityList(t),
    preview: (v) => Array.isArray(v) ? v.map((i) => `• ${i.title}`).join("\n") : "",
    payloadKey: "excluded_items"
  },
  {
    id: "cancellation_policy",
    label: "Cancellation policy",
    task: "trip-cancellation-policy",
    decode: (t) => t.trim(),
    preview: (v) => String(v ?? ""),
    payloadKey: "cancellation_policy"
  },
  {
    id: "faqs",
    label: "FAQ",
    task: "trip-faq",
    decode: (t) => decodeFaq(t),
    preview: (v) => Array.isArray(v) ? v.map((f) => `Q: ${f.question}
A: ${f.answer}`).join("\n\n") : "",
    // Stored as a relationship row on the trip — same key as the
    // backend agent uses, so no mapping is needed.
    payloadKey: "faqs"
  },
  {
    id: "itinerary",
    label: "Day-by-day itinerary",
    task: "trip-itinerary",
    decode: (t) => parseItineraryText(t),
    preview: (v) => Array.isArray(v) ? v.map((d) => `Day ${d.day}: ${d.day_title || ""}
${d.description}`).join("\n\n") : "",
    payloadKey: null
  },
  {
    id: "meta_title",
    label: "SEO meta title",
    task: "seo-meta-title",
    decode: (t) => t.trim().slice(0, 60),
    preview: (v) => String(v ?? ""),
    payloadKey: "meta_title"
  },
  {
    id: "meta_description",
    label: "SEO meta description",
    task: "seo-meta-description",
    decode: (t) => t.trim().slice(0, 160),
    preview: (v) => String(v ?? ""),
    payloadKey: "meta_description"
  }
];
const SEASONS = [
  "spring",
  "summer",
  "monsoon",
  "autumn",
  "winter",
  "year-round"
];
const CreateTripWithAiWizard = ({
  open,
  onClose
}) => {
  const [phase, setPhase] = reactExports.useState("setup");
  const [setup, setSetup] = reactExports.useState(DEFAULT_SETUP);
  const [sections, setSections] = reactExports.useState(
    () => initialSectionState()
  );
  const [createError, setCreateError] = reactExports.useState(null);
  reactExports.useEffect(() => {
    if (open) {
      setPhase("setup");
      setSetup(DEFAULT_SETUP);
      setSections(initialSectionState());
      setCreateError(null);
    }
  }, [open]);
  reactExports.useEffect(() => {
    setSetup((prev) => ({ ...prev, slug: slugify(prev.name) }));
  }, [setup.name]);
  reactExports.useMemo(
    () => ({
      name: setup.name.trim(),
      destinations: [setup.destinations.trim()],
      categories: [],
      activities: setup.activities ? setup.activities.split(",").map((s2) => s2.trim()).filter(Boolean) : [],
      difficulty_level: setup.difficulty_level_label,
      duration_days: setup.trip_type === "single_day" ? "1" : setup.duration_days,
      duration_nights: setup.trip_type === "single_day" ? "0" : setup.duration_nights,
      best_season: setup.best_season,
      accommodation_type: "",
      transportation_included: "",
      starting_location: "",
      ending_location: "",
      price: setup.price,
      description: "",
      short_description: "",
      included_items: [],
      excluded_items: [],
      age_min: "",
      age_max: ""
    }),
    [setup]
  );
  if (!open) return null;
  if (!isAiReady()) {
    return /* @__PURE__ */ jsxRuntimeExports.jsx(Modal, { isOpen: open, onClose, size: "md", hideHeader: true, hideFooter: true, children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-6", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start gap-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(AlertCircle, { className: "mt-0.5 h-5 w-5 text-amber-500" }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "font-semibold text-gray-900 dark:text-white", children: __("AI Assistant not configured", "yatra") }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm text-gray-600 dark:text-gray-300", children: __(
          "Add an OpenAI or Anthropic key under Yatra → AI Assistant first.",
          "yatra"
        ) }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-3 flex gap-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { asChild: true, children: /* @__PURE__ */ jsxRuntimeExports.jsx("a", { href: "admin.php?page=yatra&subpage=ai-assistant", children: __("Open AI settings", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { variant: "outline", onClick: onClose, children: __("Cancel", "yatra") })
        ] })
      ] })
    ] }) }) });
  }
  const setupValid = setup.name.trim() !== "" && setup.destinations.trim() !== "";
  const coerceAgentSection = (id, content) => {
    if (id === "description" && typeof content === "string") {
      return plainTextToHtml(content);
    }
    return content;
  };
  const buildPreview = (id, decoded) => {
    const spec = SECTIONS.find((s2) => s2.id === id);
    return spec ? spec.preview(decoded) : "";
  };
  const startGeneration = async () => {
    setPhase("generating");
    setSections(() => {
      const next = initialSectionState();
      for (const s2 of SECTIONS) {
        next[s2.id] = { ...next[s2.id], status: "running" };
      }
      return next;
    });
    try {
      const res = await aiApi.wizardCreateTrip({
        name: setup.name,
        destinations: setup.destinations,
        trip_type: setup.trip_type,
        duration_days: setup.duration_days,
        duration_nights: setup.duration_nights,
        difficulty_level: setup.difficulty_level_label,
        best_season: setup.best_season,
        audience: setup.audience,
        activities: setup.activities,
        extra_context: setup.extra_context
      });
      const agentSections = res.sections || {};
      setSections((prev) => {
        const next = { ...prev };
        for (const s2 of SECTIONS) {
          const raw = agentSections[s2.id];
          if (raw === void 0 || raw === null) {
            next[s2.id] = {
              ...next[s2.id],
              status: "failed",
              error: "Agent didn't write this section",
              retryContext: ""
            };
            continue;
          }
          const decoded = coerceAgentSection(s2.id, raw);
          next[s2.id] = {
            status: "done",
            decoded,
            preview: buildPreview(s2.id, decoded),
            retryContext: ""
          };
        }
        return next;
      });
      setPhase("review");
    } catch (e) {
      const msg = extractError$1(e);
      setSections((prev) => {
        const next = { ...prev };
        for (const s2 of SECTIONS) {
          next[s2.id] = {
            ...next[s2.id],
            status: "failed",
            error: msg,
            retryContext: ""
          };
        }
        return next;
      });
      setPhase("review");
    }
  };
  const runSection = async (id, guidance = "") => {
    setSections((prev) => ({
      ...prev,
      [id]: {
        ...prev[id],
        status: "running",
        error: void 0,
        clarificationMessage: void 0,
        clarificationQuestions: void 0
      }
    }));
    const existing = {};
    for (const s2 of SECTIONS) {
      if (s2.id === id) continue;
      const st = sections[s2.id];
      if (st.status === "done" && st.decoded !== void 0) {
        let value = st.decoded;
        if (s2.id === "description" && typeof value === "string") {
          value = value.replace(/<\/p>\s*<p>/gi, "\n\n").replace(/<[^>]+>/g, "").trim();
        }
        existing[s2.id] = value;
      }
    }
    try {
      const res = await aiApi.wizardRegenSection(
        id,
        {
          name: setup.name,
          destinations: setup.destinations,
          trip_type: setup.trip_type,
          duration_days: setup.duration_days,
          duration_nights: setup.duration_nights,
          difficulty_level: setup.difficulty_level_label,
          best_season: setup.best_season,
          audience: setup.audience,
          activities: setup.activities,
          extra_context: setup.extra_context
        },
        existing,
        guidance
      );
      if (res.content === null || res.content === void 0) {
        setSections((prev) => ({
          ...prev,
          [id]: {
            ...prev[id],
            status: "failed",
            error: "Agent returned no content for this section."
          }
        }));
        return;
      }
      const decoded = coerceAgentSection(id, res.content);
      setSections((prev) => ({
        ...prev,
        [id]: {
          status: "done",
          decoded,
          preview: buildPreview(id, decoded),
          retryContext: ""
        }
      }));
    } catch (e) {
      setSections((prev) => ({
        ...prev,
        [id]: {
          ...prev[id],
          status: "failed",
          error: extractError$1(e)
        }
      }));
    }
  };
  const retrySection = (id) => {
    const ctx = sections[id].retryContext.trim();
    if (ctx === "") return;
    setSetup((prev) => ({
      ...prev,
      extra_context: [prev.extra_context.trim(), ctx].filter((s2) => s2 !== "").join("\n\n")
    }));
    void runSection(id, ctx);
  };
  const sectionsDone = Object.values(sections).filter(
    (s2) => s2.status === "done"
  ).length;
  const sectionsTotal = SECTIONS.length;
  const sectionsFailed = Object.values(sections).filter(
    (s2) => s2.status === "failed"
  ).length;
  const sectionsNeedContext = Object.values(sections).filter(
    (s2) => s2.status === "needs_context"
  ).length;
  const createTrip = async () => {
    var _a;
    setPhase("creating");
    setCreateError(null);
    const tripUpdate = {};
    for (const spec of SECTIONS) {
      if (!spec.payloadKey) continue;
      const st = sections[spec.id];
      if (st.status === "done" && st.decoded !== void 0) {
        tripUpdate[spec.payloadKey] = st.decoded;
      }
    }
    try {
      const createPayload = {
        title: setup.name.trim(),
        slug: setup.slug.trim() || slugify(setup.name),
        status: "draft",
        trip_type: setup.trip_type
      };
      const createResp = await apiClient.post("/trips", createPayload);
      const tripId = ((_a = createResp == null ? void 0 : createResp.data) == null ? void 0 : _a.id) ?? (createResp == null ? void 0 : createResp.id);
      if (!tripId) {
        throw new Error("Trip created but no ID returned.");
      }
      const patchPayload = {
        ...tripUpdate,
        duration_days: setup.trip_type === "single_day" ? 1 : Number(setup.duration_days),
        duration_nights: setup.trip_type === "single_day" ? 0 : Number(setup.duration_nights)
      };
      if (setup.best_season) {
        patchPayload.best_season = setup.best_season;
      }
      const difficultyId = parseInt(setup.difficulty_level_id, 10);
      if (Number.isFinite(difficultyId) && difficultyId > 0) {
        patchPayload.difficulty_level = difficultyId;
      }
      const priceNum = parseFloat(setup.price);
      if (Number.isFinite(priceNum) && priceNum >= 0) {
        patchPayload.original_price = priceNum;
      }
      const salePriceNum = parseFloat(setup.sale_price);
      if (Number.isFinite(salePriceNum) && salePriceNum > 0 && (!Number.isFinite(priceNum) || salePriceNum < priceNum)) {
        patchPayload.sale_price = salePriceNum;
      }
      await apiClient.put(`/trips/${tripId}`, patchPayload);
      const itinerarySt = sections.itinerary;
      let itineraryWarning = "";
      if (itinerarySt.status === "done" && Array.isArray(itinerarySt.decoded)) {
        const days = itinerarySt.decoded.map((d) => ({
          day: d.day,
          day_title: d.day_title,
          description: d.description,
          // Preserve activities the trip-creation agent generated so
          // each day's schedule entries persist to the day_entry
          // table alongside the day row. Without this the trip page
          // would render day overviews but no per-block schedule.
          activities: Array.isArray(d.activities) ? d.activities : []
        }));
        if (days.length > 0) {
          try {
            await aiApi.applyItinerary(tripId, days, true);
          } catch (e) {
            itineraryWarning = extractError$1(e);
            console.warn("Itinerary apply failed:", e);
          }
        }
      } else if (itinerarySt.status === "needs_context" || itinerarySt.status === "failed") {
        itineraryWarning = __(
          "Itinerary section didn't complete — you can build it from the Itinerary page after the wizard finishes.",
          "yatra"
        );
      }
      if (itineraryWarning) {
        console.warn("Wizard itinerary warning:", itineraryWarning);
      }
      setPhase("done");
      setTimeout(() => {
        var _a2;
        const base = ((_a2 = window.yatraAdmin) == null ? void 0 : _a2.siteUrl) || "";
        window.location.href = `${base}/wp-admin/admin.php?page=yatra&subpage=trips&action=edit&id=${tripId}`;
      }, 900);
    } catch (e) {
      setCreateError(extractError$1(e));
      setPhase("error");
    }
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    Modal,
    {
      isOpen: open,
      onClose: () => {
        if (phase !== "creating") onClose();
      },
      size: "xl",
      hideHeader: true,
      hideFooter: true,
      bodyClassName: "",
      bodyScrollClassName: "",
      children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex h-[85vh] max-h-[85vh] min-h-[480px] w-full flex-col", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between border-b border-gray-200 px-6 py-4 dark:border-gray-700", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "rounded-md bg-gradient-to-br from-blue-600 to-blue-700 p-1.5 text-white", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Sparkles, { className: "h-4 w-4" }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { className: "text-base font-semibold text-gray-900 dark:text-white", children: __("Create trip with AI", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-xs text-gray-500 dark:text-gray-400", children: phaseLabel(phase) })
            ] })
          ] }),
          phase !== "creating" && /* @__PURE__ */ jsxRuntimeExports.jsx(
            "button",
            {
              type: "button",
              onClick: onClose,
              className: "rounded text-gray-400 hover:text-gray-600",
              "aria-label": __("Close", "yatra"),
              children: /* @__PURE__ */ jsxRuntimeExports.jsx(X, { className: "h-5 w-5" })
            }
          )
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "border-b border-gray-100 px-6 py-2 dark:border-gray-700", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Steps, { phase }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1 overflow-y-auto px-6 py-4", children: [
          phase === "setup" && /* @__PURE__ */ jsxRuntimeExports.jsx(
            SetupStep,
            {
              setup,
              onChange: (patch) => setSetup((prev) => ({ ...prev, ...patch }))
            }
          ),
          phase === "generating" && /* @__PURE__ */ jsxRuntimeExports.jsx(
            GeneratingStep,
            {
              sections,
              done: sectionsDone,
              total: sectionsTotal
            }
          ),
          phase === "review" && /* @__PURE__ */ jsxRuntimeExports.jsx(
            ReviewStep,
            {
              sections,
              onRetryContextChange: (id, v) => setSections((prev) => ({
                ...prev,
                [id]: { ...prev[id], retryContext: v }
              })),
              onRetry: (id) => retrySection(id),
              onRerun: (id) => void runSection(id)
            }
          ),
          phase === "creating" && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex h-full flex-col items-center justify-center gap-3 text-center", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Loader2, { className: "h-8 w-8 animate-spin text-blue-500" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm font-medium text-gray-900 dark:text-white", children: __("Saving your AI-generated trip…", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-xs text-gray-500 dark:text-gray-400", children: __(
              "Creating the draft, applying content, building itinerary days.",
              "yatra"
            ) })
          ] }),
          phase === "done" && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex h-full flex-col items-center justify-center gap-3 text-center", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "rounded-full bg-green-100 p-3 dark:bg-green-900/30", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Check, { className: "h-6 w-6 text-green-600" }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-base font-semibold text-gray-900 dark:text-white", children: __("Trip created.", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-xs text-gray-500 dark:text-gray-400", children: __("Redirecting to the trip editor…", "yatra") })
          ] }),
          phase === "error" && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "rounded-md border border-red-200 bg-red-50 p-3 text-sm text-red-700 dark:border-red-500/40 dark:bg-red-900/20 dark:text-red-300", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(AlertCircle, { className: "mr-1 inline h-4 w-4" }),
              createError || __("Something went wrong.", "yatra")
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400", children: __(
              "Your generated content is still here — you can retry, or go back to review and edit it.",
              "yatra"
            ) })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between border-t border-gray-200 px-6 py-3 dark:border-gray-700", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-xs text-gray-500 dark:text-gray-400", children: [
            phase === "generating" && /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
              sectionsDone,
              "/",
              sectionsTotal,
              " ",
              __("ready", "yatra"),
              sectionsNeedContext > 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "ml-2 text-amber-600 dark:text-amber-300", children: [
                sectionsNeedContext,
                " ",
                __("need more info", "yatra")
              ] }),
              sectionsFailed > 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "ml-2 text-red-500", children: [
                sectionsFailed,
                " ",
                __("failed", "yatra")
              ] })
            ] }),
            phase === "review" && /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
              sectionsDone,
              "/",
              sectionsTotal,
              " ",
              __("sections accepted", "yatra"),
              sectionsNeedContext > 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "ml-2 text-amber-600 dark:text-amber-300", children: [
                sectionsNeedContext,
                " ",
                __("waiting for input", "yatra")
              ] })
            ] })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-2", children: [
            phase === "setup" && /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { variant: "outline", onClick: onClose, children: __("Cancel", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs(Button, { onClick: startGeneration, disabled: !setupValid, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Wand2, { className: "mr-2 h-4 w-4" }),
                __("Generate with AI", "yatra")
              ] })
            ] }),
            phase === "generating" && /* @__PURE__ */ jsxRuntimeExports.jsxs(Button, { variant: "outline", disabled: true, children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Loader2, { className: "mr-2 h-4 w-4 animate-spin" }),
              __("Working…", "yatra")
            ] }),
            phase === "review" && /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs(Button, { variant: "outline", onClick: () => setPhase("setup"), children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(ChevronLeft, { className: "mr-2 h-4 w-4" }),
                __("Back", "yatra")
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs(
                Button,
                {
                  onClick: createTrip,
                  disabled: sectionsDone === 0,
                  title: sectionsDone === 0 ? __(
                    "At least one section needs to succeed before you can create the trip.",
                    "yatra"
                  ) : "",
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(Check, { className: "mr-2 h-4 w-4" }),
                    __("Create trip", "yatra")
                  ]
                }
              )
            ] }),
            phase === "error" && /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs(Button, { variant: "outline", onClick: () => setPhase("review"), children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(ChevronLeft, { className: "mr-2 h-4 w-4" }),
                __("Back to review", "yatra")
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs(Button, { onClick: createTrip, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(RefreshCw, { className: "mr-2 h-4 w-4" }),
                __("Retry create", "yatra")
              ] })
            ] })
          ] })
        ] })
      ] })
    }
  );
};
const Steps = ({ phase }) => {
  const order = ["setup", "generating", "review", "creating"];
  const activeIdx = phase === "done" ? order.length : phase === "error" ? order.indexOf("creating") : order.indexOf(phase);
  return /* @__PURE__ */ jsxRuntimeExports.jsx("ol", { className: "flex items-center gap-1 text-[11px]", children: order.map((p, i) => {
    const active = i === activeIdx;
    const past = i < activeIdx || phase === "done";
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { className: "flex items-center gap-1", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        "div",
        {
          className: `flex h-5 w-5 items-center justify-center rounded-full text-[10px] font-semibold ${past ? "bg-green-500 text-white" : active ? "bg-blue-600 text-white" : "bg-gray-200 text-gray-500 dark:bg-gray-700 dark:text-gray-400"}`,
          children: past ? /* @__PURE__ */ jsxRuntimeExports.jsx(Check, { className: "h-3 w-3" }) : i + 1
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        "span",
        {
          className: `${active ? "font-medium text-blue-700 dark:text-blue-300" : "text-gray-500 dark:text-gray-400"}`,
          children: p === "setup" ? __("Setup", "yatra") : p === "generating" ? __("Generate", "yatra") : p === "review" ? __("Review", "yatra") : __("Save", "yatra")
        }
      ),
      i < order.length - 1 && /* @__PURE__ */ jsxRuntimeExports.jsx(ChevronRight, { className: "h-3 w-3 text-gray-300 dark:text-gray-600" })
    ] }, p);
  }) });
};
const SetupStep = ({ setup, onChange }) => {
  var _a;
  const { data: difficultyData } = useQuery({
    queryKey: ["wizard-difficulty-levels"],
    queryFn: async () => {
      try {
        const resp = await apiClient.get("/difficulty-levels", {
          params: { per_page: 100 }
        });
        const list = Array.isArray(resp == null ? void 0 : resp.data) ? resp.data : [];
        return list.filter((d) => d && d.id && d.name).map((d) => ({ id: Number(d.id), name: String(d.name) }));
      } catch {
        return [];
      }
    },
    staleTime: 5 * 60 * 1e3
  });
  const difficulties = difficultyData || [];
  const currency = ((_a = window == null ? void 0 : window.yatraAdmin) == null ? void 0 : _a.currency) || "USD";
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-600 dark:text-gray-300", children: __(
      "Tell AI about the trip — the more specific, the better the draft. You'll edit everything afterwards.",
      "yatra"
    ) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Field$1, { label: __("Trip name", "yatra"), required: true, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
      Input,
      {
        value: setup.name,
        placeholder: __("e.g. 7-Day Dhaka Cultural Tour", "yatra"),
        onChange: (e) => onChange({ name: e.target.value })
      }
    ) }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid gap-3 md:grid-cols-4", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "md:col-span-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Field$1, { label: __("Destination(s)", "yatra"), required: true, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        Input,
        {
          value: setup.destinations,
          placeholder: __("e.g. Dhaka, Bangladesh", "yatra"),
          onChange: (e) => onChange({ destinations: e.target.value })
        }
      ) }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Field$1, { label: __("Type", "yatra"), children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Select,
        {
          value: setup.trip_type,
          onChange: (e) => onChange({
            trip_type: e.target.value
          }),
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "multi_day", children: __("Multi-day", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "single_day", children: __("Single day", "yatra") })
          ]
        }
      ) }),
      setup.trip_type === "multi_day" ? /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-2 gap-2", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Field$1, { label: __("Days", "yatra"), children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          Input,
          {
            type: "number",
            min: 1,
            max: 60,
            value: setup.duration_days,
            onChange: (e) => onChange({ duration_days: e.target.value })
          }
        ) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Field$1, { label: __("Nights", "yatra"), children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          Input,
          {
            type: "number",
            min: 0,
            max: 60,
            value: setup.duration_nights,
            onChange: (e) => onChange({ duration_nights: e.target.value })
          }
        ) })
      ] }) : /* @__PURE__ */ jsxRuntimeExports.jsx("div", {})
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid gap-3 md:grid-cols-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(Field$1, { label: __("Difficulty", "yatra"), children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Select,
        {
          value: setup.difficulty_level_id,
          onChange: (e) => {
            const id = e.target.value;
            const match2 = difficulties.find((d) => String(d.id) === id);
            onChange({
              difficulty_level_id: id,
              difficulty_level_label: match2 ? match2.name : ""
            });
          },
          disabled: difficulties.length === 0,
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "", children: difficulties.length === 0 ? __("(no difficulty levels configured)", "yatra") : __("(skip — operator picks later)", "yatra") }),
            difficulties.map((d) => /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: String(d.id), children: d.name }, d.id))
          ]
        }
      ) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Field$1, { label: __("Best season", "yatra"), children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Select,
        {
          value: setup.best_season,
          onChange: (e) => onChange({ best_season: e.target.value }),
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "", children: __("(any)", "yatra") }),
            SEASONS.map((s2) => /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: s2, children: s2.charAt(0).toUpperCase() + s2.slice(1) }, s2))
          ]
        }
      ) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Field$1, { label: __("Audience", "yatra"), children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        Input,
        {
          value: setup.audience,
          placeholder: __("couples, families, solo…", "yatra"),
          onChange: (e) => onChange({ audience: e.target.value })
        }
      ) })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid gap-3 md:grid-cols-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(Field$1, { label: __("Price per person", "yatra"), hint: `(${currency})`, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        Input,
        {
          type: "number",
          min: 0,
          step: "0.01",
          value: setup.price,
          placeholder: __("e.g. 1499", "yatra"),
          onChange: (e) => onChange({ price: e.target.value })
        }
      ) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        Field$1,
        {
          label: __("Sale price (optional)", "yatra"),
          hint: `(${currency})`,
          children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            Input,
            {
              type: "number",
              min: 0,
              step: "0.01",
              value: setup.sale_price,
              placeholder: __("e.g. 1299", "yatra"),
              onChange: (e) => onChange({ sale_price: e.target.value })
            }
          )
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", {})
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      Field$1,
      {
        label: __("Key activities", "yatra"),
        hint: __("(comma-separated)", "yatra"),
        children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          Input,
          {
            value: setup.activities,
            placeholder: __(
              "food tours, rickshaw rides, mosque visits, river cruise",
              "yatra"
            ),
            onChange: (e) => onChange({ activities: e.target.value })
          }
        )
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      Field$1,
      {
        label: __("Anything else AI should know", "yatra"),
        hint: __("(optional but recommended)", "yatra"),
        children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          "textarea",
          {
            rows: 2,
            className: "w-full rounded-md border border-gray-300 bg-white p-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-400 dark:border-gray-600 dark:bg-gray-800",
            value: setup.extra_context,
            placeholder: __(
              "Mid-range hotels, halal-friendly meals, max group size 10…",
              "yatra"
            ),
            onChange: (e) => onChange({ extra_context: e.target.value })
          }
        )
      }
    )
  ] });
};
const GeneratingStep = ({ sections, done, total }) => {
  const pct = total === 0 ? 0 : Math.round(done / total * 100);
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "rounded-md bg-blue-50 p-3 dark:bg-blue-900/20", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mb-2 flex items-center justify-between text-sm", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-medium text-blue-900 dark:text-blue-200", children: __("AI is drafting your trip…", "yatra") }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-blue-700 dark:text-blue-300", children: [
          pct,
          "%"
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-1.5 w-full overflow-hidden rounded-full bg-blue-200 dark:bg-blue-900/40", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        "div",
        {
          className: "h-full bg-blue-600 transition-all dark:bg-blue-400",
          style: { width: `${pct}%` }
        }
      ) })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-1", children: SECTIONS.map((s2) => /* @__PURE__ */ jsxRuntimeExports.jsx(SectionStatusRow, { spec: s2, state: sections[s2.id] }, s2.id)) })
  ] });
};
const ReviewStep = ({ sections, onRetryContextChange, onRetry, onRerun }) => {
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-600 dark:text-gray-300", children: __(
      "Review each section below. You can re-run any individual section, or fill in details for sections AI needs more info on.",
      "yatra"
    ) }),
    SECTIONS.map((spec) => /* @__PURE__ */ jsxRuntimeExports.jsx(
      ReviewRow,
      {
        spec,
        state: sections[spec.id],
        onRetryContextChange: (v) => onRetryContextChange(spec.id, v),
        onRetry: () => onRetry(spec.id),
        onRerun: () => onRerun(spec.id)
      },
      spec.id
    ))
  ] });
};
const SectionStatusRow = ({ spec, state }) => {
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2 rounded-md border border-gray-100 px-3 py-1.5 text-xs dark:border-gray-800", children: [
    state.status === "idle" && /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-400", children: "○" }),
    state.status === "running" && /* @__PURE__ */ jsxRuntimeExports.jsx(Loader2, { className: "h-3.5 w-3.5 animate-spin text-blue-500" }),
    state.status === "done" && /* @__PURE__ */ jsxRuntimeExports.jsx(CheckCircle2, { className: "h-3.5 w-3.5 text-green-500" }),
    state.status === "failed" && /* @__PURE__ */ jsxRuntimeExports.jsx(AlertCircle, { className: "h-3.5 w-3.5 text-red-500" }),
    state.status === "needs_context" && /* @__PURE__ */ jsxRuntimeExports.jsx(HelpCircle, { className: "h-3.5 w-3.5 text-amber-500" }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-700 dark:text-gray-200", children: spec.label })
  ] });
};
const ReviewRow = ({ spec, state, onRetryContextChange, onRetry, onRerun }) => {
  const [open, setOpen] = reactExports.useState(true);
  const sectionSummary = summarize(spec.id, state);
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "rounded-md border border-gray-200 dark:border-gray-700", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "button",
      {
        type: "button",
        onClick: () => setOpen((v) => !v),
        className: "flex w-full items-center justify-between gap-2 px-3 py-2 text-left text-sm hover:bg-gray-50 dark:hover:bg-gray-800/60",
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
            state.status === "done" && /* @__PURE__ */ jsxRuntimeExports.jsx(CheckCircle2, { className: "h-4 w-4 text-green-500" }),
            state.status === "failed" && /* @__PURE__ */ jsxRuntimeExports.jsx(AlertCircle, { className: "h-4 w-4 text-red-500" }),
            state.status === "needs_context" && /* @__PURE__ */ jsxRuntimeExports.jsx(HelpCircle, { className: "h-4 w-4 text-amber-500" }),
            state.status === "running" && /* @__PURE__ */ jsxRuntimeExports.jsx(Loader2, { className: "h-4 w-4 animate-spin text-blue-500" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-medium text-gray-900 dark:text-white", children: spec.label }),
            sectionSummary && /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-xs text-gray-500 dark:text-gray-400", children: [
              "· ",
              sectionSummary
            ] })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "button",
              {
                type: "button",
                onClick: (e) => {
                  e.stopPropagation();
                  onRerun();
                },
                className: "rounded border border-gray-200 px-2 py-0.5 text-[11px] text-gray-600 hover:bg-gray-50 dark:border-gray-600 dark:text-gray-300 dark:hover:bg-gray-700",
                title: __("Re-run this section", "yatra"),
                children: /* @__PURE__ */ jsxRuntimeExports.jsx(RefreshCw, { className: "inline h-3 w-3" })
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              ChevronRight,
              {
                className: `h-4 w-4 text-gray-400 transition-transform ${open ? "rotate-90" : ""}`
              }
            )
          ] })
        ]
      }
    ),
    open && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2 border-t border-gray-200 p-3 dark:border-gray-700", children: [
      state.status === "done" && state.preview && /* @__PURE__ */ jsxRuntimeExports.jsx("pre", { className: "max-h-64 overflow-auto whitespace-pre-wrap rounded bg-gray-50 p-2 text-xs text-gray-800 dark:bg-gray-900 dark:text-gray-200", children: state.preview }),
      state.status === "failed" && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "rounded bg-red-50 p-2 text-xs text-red-700 dark:bg-red-900/30 dark:text-red-300", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(AlertCircle, { className: "mr-1 inline h-3 w-3" }),
        state.error
      ] }),
      state.status === "needs_context" && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "rounded-md border border-amber-200 bg-amber-50/60 p-2 text-xs text-amber-900 dark:border-amber-500/40 dark:bg-amber-900/20 dark:text-amber-200", children: [
          state.clarificationMessage && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mb-1", children: state.clarificationMessage }),
          state.clarificationQuestions && state.clarificationQuestions.length > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx("ul", { className: "list-disc space-y-0.5 pl-4", children: state.clarificationQuestions.map((q, i) => /* @__PURE__ */ jsxRuntimeExports.jsx("li", { children: q }, i)) })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "textarea",
          {
            rows: 3,
            className: "w-full rounded-md border border-amber-200 bg-white p-2 text-xs focus:outline-none focus:ring-2 focus:ring-amber-400 dark:border-amber-500/40 dark:bg-gray-800",
            placeholder: __(
              "Type the answers — these get added to the prompt and only this section regenerates.",
              "yatra"
            ),
            value: state.retryContext,
            onChange: (e) => onRetryContextChange(e.target.value)
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex justify-end", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Button,
          {
            size: "sm",
            onClick: onRetry,
            disabled: state.retryContext.trim() === "",
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Wand2, { className: "mr-2 h-3 w-3" }),
              __("Try again with this", "yatra")
            ]
          }
        ) })
      ] })
    ] })
  ] });
};
const Field$1 = ({ label, hint, required, children }) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
  /* @__PURE__ */ jsxRuntimeExports.jsxs("label", { className: "mb-1 flex items-center gap-1 text-xs font-medium text-gray-700 dark:text-gray-200", children: [
    label,
    required && /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" }),
    hint && /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "ml-1 text-[10px] font-normal text-gray-400", children: hint })
  ] }),
  children
] });
function summarize(id, state) {
  if (state.status !== "done") return "";
  const d = state.decoded;
  if (id === "itinerary" && Array.isArray(d)) {
    return `${d.length} ${d.length === 1 ? "day" : "days"} drafted`;
  }
  if (id === "highlights" && Array.isArray(d)) {
    return `${d.length} ${d.length === 1 ? "highlight" : "highlights"}`;
  }
  if ((id === "included_items" || id === "excluded_items") && Array.isArray(d)) {
    return `${d.length} ${d.length === 1 ? "item" : "items"}`;
  }
  if (id === "faqs" && Array.isArray(d)) {
    return `${d.length} Q&A`;
  }
  if (typeof d === "string") {
    const len = d.replace(/<[^>]+>/g, "").length;
    return `${len} ${len === 1 ? "char" : "chars"}`;
  }
  return "";
}
function initialSectionState() {
  const out = {};
  for (const s2 of SECTIONS) {
    out[s2.id] = { status: "idle", retryContext: "" };
  }
  return out;
}
function phaseLabel(phase) {
  switch (phase) {
    case "setup":
      return __("Step 1 of 4 — tell AI about the trip", "yatra");
    case "generating":
      return __("Step 2 of 4 — drafting", "yatra");
    case "review":
      return __("Step 3 of 4 — review", "yatra");
    case "creating":
      return __("Step 4 of 4 — saving", "yatra");
    case "done":
      return __("Done", "yatra");
    case "error":
      return __("Error", "yatra");
  }
}
function slugify(s2) {
  return s2.toLowerCase().trim().replace(/[^\p{L}\p{N}-]+/gu, "-").replace(/^-+|-+$/g, "").slice(0, 80);
}
function plainTextToHtml(text) {
  if (!text) return "";
  const escape = (s2) => s2.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
  const paragraphs = text.replace(/\r\n?/g, "\n").split(/\n{2,}/).map((p) => p.trim()).filter((p) => p !== "");
  return paragraphs.map((p) => `<p>${escape(p).replace(/\n/g, "<br>")}</p>`).join("");
}
function decodeAmenityList(text) {
  return text.split(/\r?\n/).map((line) => line.replace(/^[\s\-\*••]+/, "").trim()).filter((line) => line !== "" && !/^Day\s+\d+/i.test(line)).map((title2) => ({ title: title2, description: "" }));
}
function decodeFaq(text) {
  const out = [];
  const blocks = text.replace(/\r\n?/g, "\n").split(/\n{2,}/);
  for (const block of blocks) {
    const qMatch = block.match(/^\s*Q[:\.\-]\s*(.+)/im);
    const aMatch = block.match(/A[:\.\-]\s*([\s\S]+)/im);
    if (qMatch) {
      out.push({
        question: qMatch[1].trim(),
        answer: aMatch ? aMatch[1].trim() : ""
      });
    }
  }
  return out;
}
function extractError$1(e) {
  var _a;
  if (!e) return "Request failed.";
  const data = ((_a = e == null ? void 0 : e.response) == null ? void 0 : _a.data) ?? (e == null ? void 0 : e.data) ?? null;
  if (data && typeof data === "object" && typeof data.message === "string") {
    return data.message;
  }
  return (e == null ? void 0 : e.message) || "Request failed.";
}
const PageHeader = ({
  description,
  actions,
  actionCapability,
  actionRequirePro = false
}) => {
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between mb-8", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: description && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-500 dark:text-gray-400", children: description }) }),
    actions && /* @__PURE__ */ jsxRuntimeExports.jsx(
      ConditionalRender,
      {
        capability: actionCapability,
        requirePro: actionRequirePro,
        children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex items-center gap-3", children: actions })
      }
    )
  ] });
};
const HelpText = ({
  text,
  variant = "info",
  className = ""
}) => {
  const Icon = variant === "help" ? HelpCircle : Info;
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(
    "div",
    {
      className: `flex items-start gap-1.5 text-[11px] text-gray-400 dark:text-gray-500 ${className}`,
      children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Icon, { className: "w-3 h-3 mt-0.5 flex-shrink-0 opacity-60" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "opacity-80", children: text })
      ]
    }
  );
};
const getErrorContext = (error) => {
  if (!error) {
    return { details: "" };
  }
  const requestInfo = error == null ? void 0 : error.requestInfo;
  const maybeResponse = error == null ? void 0 : error.response;
  const serialize = (value) => {
    if (value == null) {
      return "";
    }
    if (typeof value === "string") {
      return value;
    }
    try {
      return JSON.stringify(value, null, 2);
    } catch {
      return String(value);
    }
  };
  if ((maybeResponse == null ? void 0 : maybeResponse.data) !== void 0 && (maybeResponse == null ? void 0 : maybeResponse.data) !== null) {
    return {
      details: serialize(maybeResponse.data),
      requestInfo
    };
  }
  if (typeof error === "string") {
    return {
      details: error,
      requestInfo
    };
  }
  if (error instanceof Error) {
    return {
      details: error.stack || error.message || "",
      requestInfo
    };
  }
  return {
    details: serialize(error),
    requestInfo
  };
};
function isWordPressPlainPermalink() {
  var _a;
  if (typeof window === "undefined") {
    return false;
  }
  const ps = (_a = window == null ? void 0 : window.yatraAdmin) == null ? void 0 : _a.permalinkStructure;
  return ps === "plain";
}
function getYatraSiteUrlFromWindow() {
  var _a;
  if (typeof window === "undefined") {
    return "";
  }
  return ((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || "";
}
function resolveYatraPermalinkBases(fromSettings) {
  const ya = typeof window !== "undefined" ? window.yatraAdmin : void 0;
  const s2 = fromSettings;
  return {
    trip_base: (s2 == null ? void 0 : s2.trip_base) ?? (ya == null ? void 0 : ya.tripBase) ?? "trip",
    destination_base: (s2 == null ? void 0 : s2.destination_base) ?? "destination",
    activity_base: (s2 == null ? void 0 : s2.activity_base) ?? "activity",
    trip_category_base: (s2 == null ? void 0 : s2.trip_category_base) ?? "trip-category"
  };
}
function buildTripPlainUrl(baseSite, tripBase, slug) {
  const base = baseSite.replace(/\/$/, "");
  const q = new URLSearchParams();
  q.set(tripBase, slug);
  return `${base}/?${q.toString()}`;
}
function buildTaxonomyPlainUrl(baseSite, archiveBase, slug) {
  const base = baseSite.replace(/\/$/, "");
  const key2 = (archiveBase || "").trim() || "destination";
  const q = new URLSearchParams();
  q.set(key2, slug);
  return `${base}/?${q.toString()}`;
}
function buildYatraSinglePublicUrls(params) {
  const baseSite = (params.siteUrl ?? getYatraSiteUrlFromWindow()).replace(
    /\/$/,
    ""
  );
  const bases = resolveYatraPermalinkBases(params.bases);
  const slug = (params.slug || "").trim();
  switch (params.entity) {
    case "trip":
      return {
        plainUrl: buildTripPlainUrl(baseSite, bases.trip_base, slug),
        prettyUrl: `${baseSite}/${bases.trip_base}/${slug}`
      };
    case "destination":
      return {
        plainUrl: buildTaxonomyPlainUrl(baseSite, bases.destination_base, slug),
        prettyUrl: `${baseSite}/${bases.destination_base}/${slug}`
      };
    case "activity":
      return {
        plainUrl: buildTaxonomyPlainUrl(baseSite, bases.activity_base, slug),
        prettyUrl: `${baseSite}/${bases.activity_base}/${slug}`
      };
    case "category":
      return {
        plainUrl: buildTaxonomyPlainUrl(
          baseSite,
          bases.trip_category_base,
          slug
        ),
        prettyUrl: `${baseSite}/${bases.trip_category_base}/${slug}`
      };
  }
}
function buildYatraSinglePreviewUrl(params) {
  const { plainUrl, prettyUrl } = buildYatraSinglePublicUrls(params);
  return isWordPressPlainPermalink() ? plainUrl : prettyUrl;
}
function buildYatraListingPublicUrl(baseSegment, siteUrl) {
  const seg = (baseSegment || "trip").trim();
  const raw = siteUrl !== void 0 ? siteUrl : getYatraSiteUrlFromWindow();
  const siteBase = raw.replace(/\/$/, "");
  if (isWordPressPlainPermalink()) {
    if (!siteBase) {
      return `/?yatra_page=${encodeURIComponent(seg)}`;
    }
    return `${siteBase}/?yatra_page=${encodeURIComponent(seg)}`;
  }
  if (!siteBase) {
    return `/${seg}/`;
  }
  return `${siteBase}/${seg}/`;
}
function buildYatraAccountViewUrl(siteUrl, customerAccountPath) {
  const raw = (customerAccountPath || "").trim().replace(/^\/+/, "");
  const parts = raw.split("/").filter((p) => p.length > 0);
  const segment = parts.length > 0 ? parts[parts.length - 1] : "my-account";
  const slug = (segment || "my-account").trim();
  return buildYatraListingPublicUrl(slug, siteUrl || void 0);
}
const generateSlug = (text) => {
  if (!text) return "";
  return text.toLowerCase().trim().replace(/[\s_]+/g, "-").replace(/[^\p{L}\p{N}-]+/gu, "").replace(/-+/g, "-").replace(/^-+|-+$/g, "");
};
const Pagination = ({
  currentPage,
  totalPages,
  totalItems,
  itemsPerPage,
  onPageChange,
  itemName = "items"
}) => {
  const generatePageNumbers = () => {
    const pages = [];
    const maxVisiblePages = 5;
    let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
    let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);
    if (endPage - startPage + 1 < maxVisiblePages) {
      startPage = Math.max(1, endPage - maxVisiblePages + 1);
    }
    if (startPage > 1) {
      pages.push(
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          Button,
          {
            variant: 1 === currentPage ? "default" : "outline",
            size: "sm",
            onClick: () => onPageChange(1),
            className: "h-8 w-8 p-0",
            children: "1"
          },
          1
        )
      );
      if (startPage > 2) {
        pages.push(
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "px-2 text-gray-500", children: "..." }, "ellipsis1")
        );
      }
    }
    for (let i = startPage; i <= endPage; i++) {
      pages.push(
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          Button,
          {
            variant: i === currentPage ? "default" : "outline",
            size: "sm",
            onClick: () => onPageChange(i),
            className: "h-8 w-8 p-0",
            children: i
          },
          i
        )
      );
    }
    if (endPage < totalPages) {
      if (endPage < totalPages - 1) {
        pages.push(
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "px-2 text-gray-500", children: "..." }, "ellipsis2")
        );
      }
      pages.push(
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          Button,
          {
            variant: totalPages === currentPage ? "default" : "outline",
            size: "sm",
            onClick: () => onPageChange(totalPages),
            className: "h-8 w-8 p-0",
            children: totalPages
          },
          totalPages
        )
      );
    }
    return pages;
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-sm text-gray-600 dark:text-gray-400", children: [
      __("Showing", "yatra"),
      " ",
      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-medium text-gray-900 dark:text-white", children: (currentPage - 1) * itemsPerPage + 1 }),
      " ",
      "-",
      " ",
      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-medium text-gray-900 dark:text-white", children: Math.min(currentPage * itemsPerPage, totalItems) }),
      " ",
      __("of", "yatra"),
      " ",
      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-medium text-gray-900 dark:text-white", children: totalItems }),
      " ",
      itemName
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        Button,
        {
          variant: "outline",
          size: "sm",
          onClick: () => onPageChange(Math.max(1, currentPage - 1)),
          disabled: currentPage === 1,
          className: "h-8 px-3",
          children: __("Previous", "yatra")
        }
      ),
      generatePageNumbers(),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        Button,
        {
          variant: "outline",
          size: "sm",
          onClick: () => onPageChange(Math.min(totalPages, currentPage + 1)),
          disabled: currentPage >= totalPages,
          className: "h-8 px-3",
          children: __("Next", "yatra")
        }
      )
    ] })
  ] });
};
const Table$1 = reactExports.forwardRef(({ className = "", ...props }, ref) => /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "relative w-full overflow-auto", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
  "table",
  {
    ref,
    className: `w-full caption-bottom text-sm ${className}`,
    ...props
  }
) }));
Table$1.displayName = "Table";
const TableHeader = reactExports.forwardRef(({ className = "", ...props }, ref) => /* @__PURE__ */ jsxRuntimeExports.jsx("thead", { ref, className: `[&_tr]:border-b ${className}`, ...props }));
TableHeader.displayName = "TableHeader";
const TableBody = reactExports.forwardRef(({ className = "", ...props }, ref) => /* @__PURE__ */ jsxRuntimeExports.jsx(
  "tbody",
  {
    ref,
    className: `[&_tr:last-child]:border-0 ${className}`,
    ...props
  }
));
TableBody.displayName = "TableBody";
const TableRow = reactExports.forwardRef(({ className = "", ...props }, ref) => /* @__PURE__ */ jsxRuntimeExports.jsx(
  "tr",
  {
    ref,
    className: `border-b transition-colors hover:bg-gray-50 dark:hover:bg-gray-800/50 data-[state=selected]:bg-gray-100 dark:data-[state=selected]:bg-gray-800 ${className}`,
    ...props
  }
));
TableRow.displayName = "TableRow";
const TableHead = reactExports.forwardRef(({ className = "", ...props }, ref) => /* @__PURE__ */ jsxRuntimeExports.jsx(
  "th",
  {
    ref,
    className: `h-12 px-4 text-left align-middle text-sm font-medium text-gray-500 dark:text-gray-400 [&:has([role=checkbox])]:pr-0 ${className}`,
    ...props
  }
));
TableHead.displayName = "TableHead";
const TableCell = reactExports.forwardRef(({ className = "", ...props }, ref) => /* @__PURE__ */ jsxRuntimeExports.jsx(
  "td",
  {
    ref,
    className: `p-4 align-middle text-sm [&:has([role=checkbox])]:pr-0 ${className}`,
    ...props
  }
));
TableCell.displayName = "TableCell";
const Table = ({
  data,
  columns,
  actions = [],
  isLoading = false,
  isError = false,
  errorText = __("Error loading data", "yatra"),
  emptyText = __("No items found", "yatra"),
  emptyDescription = __("Get started by creating your first item.", "yatra"),
  onCreateClick,
  onSort,
  getSortIcon,
  selectedItemIds = [],
  onSelectItem,
  onSelectAll,
  isAllSelected = false,
  getItemId = (item) => item.id,
  getItemStatus = (item) => item.status,
  statusFilter = "",
  capability = "yatra_view_trips",
  skeletonRows = 5,
  errorDescription = __(
    "Something went wrong while loading this data. Please try again in a moment.",
    "yatra"
  ),
  onRetry,
  errorDetails,
  errorRequestInfo,
  // Hierarchical props
  isHierarchical = false,
  expandedIds = /* @__PURE__ */ new Set(),
  onToggleExpand,
  getChildren,
  renderRowContent
}) => {
  const [openDropdownId, setOpenDropdownId] = reactExports.useState(
    null
  );
  const [dropdownPosition, setDropdownPosition] = reactExports.useState(null);
  const [copied, setCopied] = reactExports.useState(false);
  const handleRetry = () => {
    if (onRetry) {
      onRetry();
      return;
    }
    if (typeof window !== "undefined") {
      window.location.reload();
    }
  };
  React.useEffect(() => {
    const handleClickOutside = (event) => {
      const target2 = event.target;
      if (target2.closest("[data-dropdown-trigger]") || target2.closest("[data-dropdown-content]")) {
        return;
      }
      setOpenDropdownId(null);
    };
    if (openDropdownId !== null) {
      document.addEventListener("click", handleClickOutside);
      return () => document.removeEventListener("click", handleClickOutside);
    }
  }, [openDropdownId]);
  const getVisibleActions = (item) => actions.filter((a2) => !a2.condition || a2.condition(item));
  const openActionsMenu = (e, item) => {
    e.preventDefault();
    e.stopPropagation();
    const itemId = getItemId(item);
    const rect = e.currentTarget.getBoundingClientRect();
    const visibleActions = getVisibleActions(item);
    const dropdownHeight = visibleActions.length * 40 + 16;
    const spaceBelow = window.innerHeight - rect.bottom;
    const spaceAbove = rect.top;
    const shouldPositionAbove = spaceBelow < dropdownHeight && spaceAbove > dropdownHeight;
    setDropdownPosition({
      top: shouldPositionAbove ? Math.max(8, rect.top - dropdownHeight) : rect.bottom,
      right: window.innerWidth - rect.right
    });
    setOpenDropdownId(openDropdownId === itemId ? null : itemId);
  };
  const renderActionsDropdown = (item) => {
    const itemId = getItemId(item);
    if (openDropdownId !== itemId || !dropdownPosition) return null;
    return reactDomExports.createPortal(
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        "div",
        {
          className: "fixed min-w-[180px] w-max bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-md shadow-md py-1",
          style: {
            top: `${dropdownPosition.top}px`,
            right: `${dropdownPosition.right}px`,
            zIndex: 999999
          },
          "data-dropdown-content": true,
          onClick: (e) => e.stopPropagation(),
          children: getVisibleActions(item).map((action) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "button",
            {
              type: "button",
              onClick: (e) => {
                e.preventDefault();
                e.stopPropagation();
                action.onClick(item);
                setOpenDropdownId(null);
              },
              className: `w-full px-4 py-2 text-left text-sm hover:bg-gray-100 dark:hover:bg-gray-700 flex items-center gap-3 transition-colors cursor-pointer whitespace-nowrap ${action.variant === "destructive" ? "text-red-600 dark:text-red-400" : action.variant === "outline" ? "text-blue-600 dark:text-blue-400" : "text-gray-700 dark:text-gray-300"}`,
              children: [
                action.icon,
                action.label
              ]
            },
            action.key
          ))
        }
      ),
      document.body
    );
  };
  const renderSkeleton = () => /* @__PURE__ */ jsxRuntimeExports.jsxs(Table$1, { children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(TableHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(TableRow, { children: [
      isHierarchical && /* @__PURE__ */ jsxRuntimeExports.jsx(TableHead, { className: "w-12" }),
      onSelectItem && onSelectAll && /* @__PURE__ */ jsxRuntimeExports.jsx(TableHead, { className: "w-12" }),
      columns.filter((col) => col.visible !== false).map((column) => /* @__PURE__ */ jsxRuntimeExports.jsx(TableHead, { className: column.width, children: column.label }, column.key)),
      actions.length > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx(TableHead, { className: "text-right w-[100px]", children: __("Actions", "yatra") })
    ] }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(TableBody, { children: [...Array(skeletonRows)].map((_, index) => /* @__PURE__ */ jsxRuntimeExports.jsxs(TableRow, { children: [
      isHierarchical && /* @__PURE__ */ jsxRuntimeExports.jsx(TableCell, { children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-4 h-4 bg-gray-100 dark:bg-gray-800 rounded animate-pulse" }) }),
      onSelectItem && onSelectAll && /* @__PURE__ */ jsxRuntimeExports.jsx(TableCell, { children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-4 h-4 bg-gray-100 dark:bg-gray-800 rounded animate-pulse" }) }),
      columns.filter((col) => col.visible !== false).map((column) => /* @__PURE__ */ jsxRuntimeExports.jsx(TableCell, { children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-100 dark:bg-gray-800 rounded animate-pulse" }) }, `${column.key}-${index}`)),
      actions.length > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx(TableCell, { className: "text-right", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex items-center justify-end gap-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 w-4 bg-gray-100 dark:bg-gray-800 rounded animate-pulse" }) }) })
    ] }, `skeleton-${index}`)) })
  ] });
  const composedErrorText = reactExports.useMemo(() => {
    const parts = [];
    if (errorRequestInfo) {
      if (errorRequestInfo.method) {
        parts.push(`Request Method: ${errorRequestInfo.method}`);
      }
      if (errorRequestInfo.url) {
        parts.push(`Request URL: ${errorRequestInfo.url}`);
      }
      if (errorRequestInfo.payload) {
        parts.push(`Request Payload:
${errorRequestInfo.payload}`);
      }
    }
    if (errorDetails) {
      parts.push(`Response:
${errorDetails}`);
    }
    return parts.join("\n\n").trim();
  }, [errorRequestInfo, errorDetails]);
  const renderError = () => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative flex flex-col items-center justify-center text-center py-14 px-6 my-4 min-h-[360px]", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "absolute inset-4 rounded-2xl border-2 border-dashed border-red-200/60 dark:border-red-900/50 bg-gradient-to-br from-red-50 via-orange-50/60 to-white dark:from-red-900/40 dark:via-orange-900/10 dark:to-gray-900 shadow-sm" }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative z-10 max-w-lg mx-auto space-y-6", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "inline-flex items-center justify-center w-24 h-24 rounded-2xl bg-gradient-to-br from-red-100 via-rose-50 to-orange-100 dark:from-red-900/50 dark:via-rose-800/30 dark:to-orange-900/40 ring-8 ring-red-100/70 dark:ring-red-900/30 shadow-lg", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        "svg",
        {
          className: "w-12 h-12 text-red-500 dark:text-red-300",
          viewBox: "0 0 24 24",
          fill: "none",
          stroke: "currentColor",
          strokeWidth: "1.5",
          children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            "path",
            {
              strokeLinecap: "round",
              strokeLinejoin: "round",
              d: "M12 9v4m0 4h.01M10.29 3.86L2.82 17a2 2 0 001.71 3h14.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"
            }
          )
        }
      ) }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-2xl font-bold text-gray-900 dark:text-white", children: errorText }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-base text-gray-600 dark:text-gray-400 leading-relaxed", children: errorDescription })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col sm:flex-row items-center justify-center gap-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { onClick: handleRetry, className: "w-full sm:w-auto px-6", children: __("Try again", "yatra") }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          Button,
          {
            variant: "outline",
            onClick: () => {
              if (typeof window !== "undefined") {
                window.open(
                  "https://wordpress.org/support/plugin/yatra",
                  "_blank"
                );
              }
            },
            className: "w-full sm:w-auto px-6 text-gray-700 dark:text-gray-200 border-gray-200 dark:border-gray-700",
            children: __("Visit support center", "yatra")
          }
        )
      ] }),
      (errorDetails || errorRequestInfo) && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative w-full text-left rounded-2xl border border-red-100/80 dark:border-red-900/40 bg-white/90 dark:bg-gray-900/70 shadow-inner space-y-0", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between px-4 py-3 border-b border-red-50 dark:border-red-900/30", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm font-medium text-gray-700 dark:text-gray-300", children: __("Technical details", "yatra") }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Button,
            {
              type: "button",
              size: "sm",
              variant: "ghost",
              className: "flex items-center gap-2 text-gray-600 dark:text-gray-300 hover:text-gray-900",
              onClick: () => {
                if (!(navigator == null ? void 0 : navigator.clipboard) || !composedErrorText) {
                  return;
                }
                navigator.clipboard.writeText(composedErrorText).then(() => {
                  setCopied(true);
                  setTimeout(() => setCopied(false), 2e3);
                }).catch(() => {
                });
              },
              children: copied ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Check, { className: "w-4 h-4" }),
                __("Copied", "yatra")
              ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Copy, { className: "w-4 h-4" }),
                __("Copy details", "yatra")
              ] })
            }
          )
        ] }),
        errorRequestInfo && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "px-4 py-3 border-b border-red-50 dark:border-red-900/20 space-y-2 text-sm text-left text-gray-700 dark:text-gray-200", children: [
          errorRequestInfo.method && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-medium", children: __("Method:", "yatra") }),
            " ",
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-mono", children: errorRequestInfo.method })
          ] }),
          errorRequestInfo.url && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "break-all", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-medium", children: __("URL:", "yatra") }),
            " ",
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-mono", children: errorRequestInfo.url })
          ] }),
          errorRequestInfo.payload && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-medium block mb-1", children: __("Payload:", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("pre", { className: "max-h-40 overflow-auto px-3 py-2 rounded bg-red-50/60 dark:bg-red-900/30 text-xs font-mono text-gray-800 dark:text-gray-100 whitespace-pre-wrap", children: errorRequestInfo.payload })
          ] })
        ] }),
        errorDetails && /* @__PURE__ */ jsxRuntimeExports.jsx("pre", { className: "max-h-56 overflow-auto px-4 py-3 text-xs leading-relaxed font-mono text-gray-700 dark:text-gray-200 whitespace-pre-wrap", children: errorDetails })
      ] })
    ] })
  ] });
  const renderEmpty = () => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative flex flex-col items-center justify-center text-center py-12 px-6 my-4 min-h-[350px]", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "absolute inset-4 bg-gradient-to-br from-gray-50/80 via-blue-50/30 to-white dark:from-gray-900/80 dark:via-blue-900/20 dark:to-gray-800/80 rounded-2xl border-2 border-dashed border-gray-300/50 dark:border-gray-600/50 shadow-sm" }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative z-10 max-w-lg mx-auto space-y-8", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "inline-flex items-center justify-center w-24 h-24 rounded-2xl bg-gradient-to-br from-blue-100 via-blue-50 to-indigo-100 dark:from-blue-900/40 dark:via-blue-800/20 dark:to-indigo-900/40 ring-8 ring-blue-100/60 dark:ring-blue-900/30 shadow-lg", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "svg",
        {
          className: "w-12 h-12 text-blue-600 dark:text-blue-400",
          fill: "none",
          stroke: "currentColor",
          viewBox: "0 0 24 24",
          strokeWidth: "1.5",
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "path",
              {
                strokeLinecap: "round",
                strokeLinejoin: "round",
                d: "M7 7h10v10H7zM5 3h14a2 2 0 012 2v14a2 2 0 01-2 2H5a2 2 0 01-2-2V5a2 2 0 012-2z"
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "path",
              {
                strokeLinecap: "round",
                strokeLinejoin: "round",
                d: "M9 9h6M9 12h6M9 15h4"
              }
            )
          ]
        }
      ) }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-4", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-2xl font-bold text-gray-900 dark:text-white", children: emptyText }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-base text-gray-600 dark:text-gray-400 leading-relaxed max-w-md mx-auto", children: emptyDescription })
      ] }),
      onCreateClick && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "pt-4", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Button,
        {
          onClick: onCreateClick,
          className: "inline-flex items-center gap-3 px-8 py-3 bg-blue-600 hover:bg-blue-700 text-white text-base font-semibold rounded-xl shadow-lg hover:shadow-xl transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 dark:focus:ring-offset-gray-900 transform hover:scale-[1.02]",
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "svg",
              {
                className: "w-4 h-4",
                fill: "none",
                stroke: "currentColor",
                viewBox: "0 0 24 24",
                strokeWidth: "2",
                children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "path",
                  {
                    strokeLinecap: "round",
                    strokeLinejoin: "round",
                    d: "M12 4v16m8-8H4"
                  }
                )
              }
            ),
            __("Create New", "yatra")
          ]
        }
      ) })
    ] })
  ] });
  const renderHierarchicalRow = (item, index, isChild = false) => {
    const itemId = getItemId(item);
    const itemStatus = getItemStatus(item);
    const isTrash = itemStatus === "trash" || statusFilter === "trash";
    const children = getChildren ? getChildren(item) : [];
    const hasChildren = children.length > 0;
    const isExpanded = expandedIds.has(itemId);
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(React.Fragment, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs(
        TableRow,
        {
          className: `${isTrash ? "bg-red-50/30 dark:bg-red-900/10 opacity-75 hover:bg-red-50/50 dark:hover:bg-red-900/20" : ""} ${isChild ? "bg-gray-50 dark:bg-gray-900/50" : ""}`,
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(TableCell, { className: "w-12", children: hasChildren && onToggleExpand && /* @__PURE__ */ jsxRuntimeExports.jsx(
              "button",
              {
                onClick: () => onToggleExpand(itemId),
                className: "p-1 hover:bg-gray-200 dark:hover:bg-gray-700 rounded",
                children: isExpanded ? /* @__PURE__ */ jsxRuntimeExports.jsx(ChevronDown, { className: "w-4 h-4" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(ChevronRight, { className: "w-4 h-4" })
              }
            ) }),
            onSelectItem && /* @__PURE__ */ jsxRuntimeExports.jsx(TableCell, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
              "input",
              {
                type: "checkbox",
                className: "rounded border-gray-300 dark:border-gray-600",
                checked: selectedItemIds.includes(itemId),
                onChange: (e) => onSelectItem(itemId, e.target.checked),
                "aria-label": __("Select item", "yatra")
              }
            ) }),
            renderRowContent ? renderRowContent(item, index, isChild).map(
              (cellContent, cellIndex) => /* @__PURE__ */ jsxRuntimeExports.jsx(
                TableCell,
                {
                  className: isTrash ? "text-gray-400 dark:text-gray-600" : "",
                  children: cellContent
                },
                `cell-${itemId}-${cellIndex}`
              )
            ) : columns.filter((col) => col.visible !== false).map((column) => /* @__PURE__ */ jsxRuntimeExports.jsx(
              TableCell,
              {
                className: isTrash ? "text-gray-400 dark:text-gray-600" : "",
                children: column.render ? column.render(item, index) : item[column.key]
              },
              `${column.key}-${itemId}`
            )),
            actions.length > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx(TableCell, { className: "text-right", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative inline-block", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Button,
                {
                  variant: "ghost",
                  size: "icon",
                  onClick: (e) => openActionsMenu(e, item),
                  className: "h-8 w-8 hover:bg-gray-100 dark:hover:bg-gray-700",
                  "aria-label": __("More actions", "yatra"),
                  "data-dropdown-trigger": true,
                  children: /* @__PURE__ */ jsxRuntimeExports.jsx(MoreVertical, { className: "w-4 h-4" })
                }
              ),
              renderActionsDropdown(item)
            ] }) })
          ]
        }
      ),
      hasChildren && isExpanded && children.map(
        (child, childIndex) => renderHierarchicalRow(child, childIndex, true)
      )
    ] }, itemId);
  };
  const renderFlatRow = (item, index) => {
    const itemId = getItemId(item);
    const itemStatus = getItemStatus(item);
    const isTrash = itemStatus === "trash" || statusFilter === "trash";
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(
      TableRow,
      {
        className: isTrash ? "bg-red-50/30 dark:bg-red-900/10 opacity-75 hover:bg-red-50/50 dark:hover:bg-red-900/20" : "",
        children: [
          onSelectItem && /* @__PURE__ */ jsxRuntimeExports.jsx(TableCell, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            "input",
            {
              type: "checkbox",
              className: "rounded border-gray-300 dark:border-gray-600",
              checked: selectedItemIds.includes(itemId),
              onChange: (e) => onSelectItem(itemId, e.target.checked),
              "aria-label": __("Select item", "yatra")
            }
          ) }),
          columns.filter((col) => col.visible !== false).map((column) => /* @__PURE__ */ jsxRuntimeExports.jsx(
            TableCell,
            {
              className: isTrash ? "text-gray-400 dark:text-gray-600" : "",
              children: column.render ? column.render(item, index) : item[column.key]
            },
            `${column.key}-${itemId}`
          )),
          actions.length > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx(TableCell, { className: "text-right", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative inline-block", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              Button,
              {
                variant: "ghost",
                size: "icon",
                onClick: (e) => openActionsMenu(e, item),
                className: "h-8 w-8 hover:bg-gray-100 dark:hover:bg-gray-700",
                "aria-label": __("More actions", "yatra"),
                "data-dropdown-trigger": true,
                children: /* @__PURE__ */ jsxRuntimeExports.jsx(MoreVertical, { className: "w-4 h-4" })
              }
            ),
            renderActionsDropdown(item)
          ] }) })
        ]
      },
      itemId
    );
  };
  const renderTable = () => {
    if (isLoading) return renderSkeleton();
    if (isError) return renderError();
    if (data.length === 0) return renderEmpty();
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(Table$1, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(TableHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(TableRow, { children: [
        isHierarchical && /* @__PURE__ */ jsxRuntimeExports.jsx(TableHead, { className: "w-12" }),
        onSelectItem && onSelectAll && /* @__PURE__ */ jsxRuntimeExports.jsx(TableHead, { className: "w-12", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          "input",
          {
            type: "checkbox",
            className: "rounded border-gray-300 dark:border-gray-600",
            checked: isAllSelected,
            onChange: (e) => onSelectAll(e.target.checked),
            "aria-label": __("Select all items", "yatra")
          }
        ) }),
        columns.filter((col) => col.visible !== false).map((column) => /* @__PURE__ */ jsxRuntimeExports.jsx(TableHead, { className: column.width, children: column.sortable && onSort ? /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "button",
          {
            onClick: () => onSort(column.key),
            className: "flex items-center hover:text-gray-900 dark:hover:text-white transition-colors",
            children: [
              column.label,
              getSortIcon && getSortIcon(column.key)
            ]
          }
        ) : column.label }, column.key)),
        actions.length > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx(TableHead, { className: "text-right w-[100px]", children: __("Actions", "yatra") })
      ] }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(TableBody, { children: data.map(
        (item, index) => isHierarchical ? renderHierarchicalRow(item, index) : renderFlatRow(item, index)
      ) })
    ] });
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability, children: renderTable() });
};
const ConfirmationDialog = ({
  isOpen,
  onClose,
  onConfirm,
  title: title2,
  message: message2,
  description,
  confirmText,
  cancelText,
  variant = "danger",
  isLoading = false,
  icon,
  secondaryAction
}) => {
  const displayMessage = description || message2 || "";
  const getVariantStyles = () => {
    switch (variant) {
      case "danger":
        return "text-red-600 dark:text-red-400";
      case "warning":
        return "text-yellow-600 dark:text-yellow-400";
      case "info":
        return "text-blue-600 dark:text-blue-400";
      default:
        return "text-gray-600 dark:text-gray-400";
    }
  };
  const getButtonVariant = () => {
    switch (variant) {
      case "danger":
        return "destructive";
      case "warning":
        return "default";
      case "info":
        return "default";
      default:
        return "default";
    }
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    Modal,
    {
      isOpen,
      onClose,
      title: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start gap-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: `flex-shrink-0 mt-0.5 ${getVariantStyles()}`, children: icon || /* @__PURE__ */ jsxRuntimeExports.jsx(AlertTriangle, { className: "w-6 h-6" }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: title2 || __("Confirm Action", "yatra") })
      ] }),
      hideHeader: false,
      hideFooter: false,
      size: "sm",
      panelClassName: "yatra-confirmation-ui yatra-model-ui",
      bodyClassName: "px-6 py-5",
      footer: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-2 justify-end pt-2 flex-wrap", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { variant: "outline", onClick: onClose, disabled: isLoading, children: cancelText || __("Cancel", "yatra") }),
        secondaryAction && /* @__PURE__ */ jsxRuntimeExports.jsx(
          Button,
          {
            variant: secondaryAction.variant || "outline",
            onClick: secondaryAction.onClick,
            disabled: isLoading,
            children: secondaryAction.label
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          Button,
          {
            variant: getButtonVariant(),
            onClick: onConfirm,
            disabled: isLoading,
            className: "min-w-[100px]",
            children: isLoading ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Loader2, { className: "w-4 h-4 mr-2 animate-spin" }),
              __("Deleting...", "yatra")
            ] }) : confirmText || __("Confirm", "yatra")
          }
        )
      ] }),
      children: /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-600 dark:text-gray-400 leading-relaxed", children: displayMessage })
    }
  );
};
const BulkActionToolbar = ({
  selectedIds,
  bulkAction,
  setBulkAction,
  onApply,
  onClearSelection,
  statusFilter,
  setStatusFilter,
  statusOptions,
  showColumnsDropdown,
  setShowColumnsDropdown,
  columnOptions,
  onToggleColumn,
  bulkMutationPending,
  totalItems,
  bulkActionOptions
}) => {
  const [confirmDialog, setConfirmDialog] = reactExports.useState({
    isOpen: false,
    action: "",
    count: 0
  });
  const handleApplyClick = () => {
    if (!bulkAction || selectedIds.length === 0) {
      onApply();
      return;
    }
    setConfirmDialog({
      isOpen: true,
      action: bulkAction,
      count: selectedIds.length
    });
  };
  const handleConfirm = () => {
    setConfirmDialog({ isOpen: false, action: "", count: 0 });
    onApply();
    setBulkAction("");
  };
  const handleCancel = () => {
    setConfirmDialog({ isOpen: false, action: "", count: 0 });
  };
  React.useEffect(() => {
    const handleClickOutside = (event) => {
      const target2 = event.target;
      if (target2.closest("[data-columns-trigger]") || target2.closest("[data-columns-content]")) {
        return;
      }
      setShowColumnsDropdown(false);
    };
    if (showColumnsDropdown) {
      document.addEventListener("click", handleClickOutside);
      return () => document.removeEventListener("click", handleClickOutside);
    }
  }, [showColumnsDropdown, setShowColumnsDropdown]);
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "py-3 space-y-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between gap-4", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3 flex-nowrap", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Select,
          {
            value: bulkAction,
            onChange: (e) => setBulkAction(e.target.value),
            className: "min-w-[140px]",
            disabled: totalItems === 0,
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "", children: __("Bulk actions", "yatra") }),
              bulkActionOptions.map((option) => /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: option.value, children: option.label }, option.value))
            ]
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          Button,
          {
            variant: "outline",
            onClick: handleApplyClick,
            disabled: bulkMutationPending || selectedIds.length === 0,
            className: "h-11 px-4 flex-shrink-0",
            children: __("Apply", "yatra")
          }
        ),
        selectedIds.length > 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2 text-sm text-gray-600 dark:text-gray-400 bg-blue-50 dark:bg-blue-900/20 px-2 py-1 rounded border border-blue-200 dark:border-blue-800 whitespace-nowrap", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-medium text-xs", children: `${__("Selected:", "yatra")} ${selectedIds.length}` }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "button",
            {
              type: "button",
              className: "text-xs text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300 font-medium",
              onClick: onClearSelection,
              children: __("Clear", "yatra")
            }
          )
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1 flex-shrink-0", children: [
        statusOptions.map((filter2) => {
          const isActive = statusFilter === filter2.key;
          return /* @__PURE__ */ jsxRuntimeExports.jsx(
            "button",
            {
              type: "button",
              className: `px-3 py-2.5 text-sm font-medium rounded border transition-all duration-200 ${isActive ? "bg-gray-900 text-white border-gray-900 shadow-sm" : "bg-white dark:bg-gray-800 text-gray-600 dark:text-gray-300 border-gray-300 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-700 hover:border-gray-400 dark:border-gray-500"}`,
              onClick: () => {
                setStatusFilter(filter2.key);
                onClearSelection();
                setBulkAction("");
              },
              children: /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "flex items-center gap-2", children: [
                filter2.label,
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "span",
                  {
                    className: `px-1.5 py-0.5 text-xs rounded-full font-medium ${isActive ? "bg-white text-gray-900" : "bg-gray-100 dark:bg-gray-700 text-gray-500 dark:text-gray-400"}`,
                    children: filter2.count ?? 0
                  }
                )
              ] })
            },
            filter2.key
          );
        }),
        columnOptions.length > 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative ml-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Button,
            {
              variant: "outline",
              size: "sm",
              onClick: (e) => {
                e.preventDefault();
                e.stopPropagation();
                setShowColumnsDropdown(!showColumnsDropdown);
              },
              className: "h-10 px-3 flex items-center gap-2",
              "data-columns-trigger": true,
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Columns, { className: "w-4 h-4" }),
                __("Columns", "yatra")
              ]
            }
          ),
          showColumnsDropdown && /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "div",
            {
              className: "absolute right-0 top-11 z-[9999] bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-md shadow-lg py-2",
              style: { width: "240px", minWidth: "240px" },
              "data-columns-content": true,
              onClick: (e) => e.stopPropagation(),
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "px-4 py-2.5 text-sm font-medium text-gray-900 dark:text-white border-b border-gray-200 dark:border-gray-700", children: __("Show Columns", "yatra") }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "py-1", children: columnOptions.map((option) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
                  "label",
                  {
                    className: "flex items-center px-4 py-3 hover:bg-gray-50 dark:hover:bg-gray-700 cursor-pointer whitespace-nowrap",
                    children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx(
                        "input",
                        {
                          type: "checkbox",
                          checked: option.visible,
                          onChange: () => onToggleColumn(option.key),
                          className: "rounded border-gray-300 dark:border-gray-600 h-4 w-4 mr-3 text-blue-600 focus:ring-blue-500"
                        }
                      ),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm text-gray-700 dark:text-gray-300 ml-2", children: option.label })
                    ]
                  },
                  option.key
                )) })
              ]
            }
          )
        ] })
      ] })
    ] }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      ConfirmationDialog,
      {
        isOpen: confirmDialog.isOpen,
        onClose: handleCancel,
        onConfirm: handleConfirm,
        title: (() => {
          switch (confirmDialog.action) {
            case "delete":
              return __("Delete Permanently", "yatra");
            case "mark_trash":
            case "trash":
              return __("Move to Trash", "yatra");
            case "mark_publish":
            case "publish":
              return __("Publish Items", "yatra");
            case "mark_draft":
            case "draft":
              return __("Make Draft", "yatra");
            case "mark_archived":
              return __("Archive Items", "yatra");
            case "restore":
              return __("Restore Items", "yatra");
            default:
              return __("Confirm Bulk Action", "yatra");
          }
        })(),
        message: (() => {
          const count = confirmDialog.count;
          switch (confirmDialog.action) {
            case "delete":
              return __(
                "Are you sure you want to permanently delete {count} item(s)? This action cannot be undone.",
                "yatra"
              ).replace("{count}", count.toString());
            case "mark_trash":
            case "trash":
              return __(
                "Are you sure you want to move {count} item(s) to trash?",
                "yatra"
              ).replace("{count}", count.toString());
            case "mark_publish":
            case "publish":
              return __(
                "Are you sure you want to publish {count} item(s)?",
                "yatra"
              ).replace("{count}", count.toString());
            case "mark_draft":
            case "draft":
              return __(
                "Are you sure you want to make {count} item(s) draft?",
                "yatra"
              ).replace("{count}", count.toString());
            case "mark_archived":
              return __(
                "Are you sure you want to archive {count} item(s)?",
                "yatra"
              ).replace("{count}", count.toString());
            case "restore":
              return __(
                "Are you sure you want to restore {count} item(s)?",
                "yatra"
              ).replace("{count}", count.toString());
            default:
              return __(
                "Are you sure you want to perform this action on {count} item(s)?",
                "yatra"
              ).replace("{count}", count.toString());
          }
        })(),
        confirmText: (() => {
          switch (confirmDialog.action) {
            case "delete":
              return __("Delete Permanently", "yatra");
            case "mark_trash":
            case "trash":
              return __("Move to Trash", "yatra");
            case "mark_publish":
            case "publish":
              return __("Publish", "yatra");
            case "mark_draft":
            case "draft":
              return __("Make Draft", "yatra");
            case "mark_archived":
              return __("Archive", "yatra");
            case "restore":
              return __("Restore", "yatra");
            default:
              return __("Confirm", "yatra");
          }
        })(),
        cancelText: __("Cancel", "yatra"),
        variant: confirmDialog.action === "delete" ? "danger" : "warning",
        isLoading: bulkMutationPending
      }
    )
  ] });
};
const Trips = () => {
  var _a, _b, _c, _d, _e;
  const [searchTerm, setSearchTerm] = reactExports.useState("");
  const [statusFilter, setStatusFilter] = reactExports.useState("all");
  const [sortBy2, setSortBy] = reactExports.useState("id");
  const [sortOrder, setSortOrder] = reactExports.useState("desc");
  const [page, setPage] = reactExports.useState(1);
  const [isCreateModalOpen, setIsCreateModalOpen] = reactExports.useState(false);
  const [isAiWizardOpen, setIsAiWizardOpen] = reactExports.useState(false);
  const [newTripTitle, setNewTripTitle] = reactExports.useState("");
  const [createTripError, setCreateTripError] = reactExports.useState(null);
  const [newTripSlug, setNewTripSlug] = reactExports.useState("");
  const [isSlugManuallyEdited, setIsSlugManuallyEdited] = reactExports.useState(false);
  const [selectedIds, setSelectedIds] = reactExports.useState([]);
  const [bulkAction, setBulkAction] = reactExports.useState("");
  const [showColumnsDropdown, setShowColumnsDropdown] = reactExports.useState(false);
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = reactExports.useState(false);
  const [tripToDelete, setTripToDelete] = reactExports.useState(null);
  const queryClient2 = useQueryClient();
  const { can, isPro } = usePermissions();
  const { showToast } = useToast();
  const { navigate } = useNavigate();
  const { data: statsData } = useQuery({
    queryKey: ["trips-stats"],
    queryFn: async () => {
      try {
        const response = await apiClient.get("/trips/stats");
        return response;
      } catch (error2) {
        return {
          all: 0,
          published: 0,
          draft: 0,
          review: 0,
          approved: 0,
          archived: 0,
          trash: 0
        };
      }
    },
    enabled: can("yatra_view_trips")
  });
  const queryParams = reactExports.useMemo(() => {
    const params = {
      page,
      per_page: 10,
      orderby: sortBy2,
      order: sortOrder
    };
    if (searchTerm) {
      params.search = searchTerm;
    }
    if (statusFilter !== "all") {
      params.status = statusFilter;
    }
    return params;
  }, [searchTerm, statusFilter, sortBy2, sortOrder, page]);
  const { data, isLoading, error, refetch } = useQuery({
    queryKey: ["trips", queryParams],
    queryFn: async () => {
      const response = await apiClient.get("/trips", { params: queryParams });
      return response;
    },
    enabled: can("yatra_view_trips"),
    staleTime: 0,
    // Force fresh data
    gcTime: 0
    // Don't cache (new name for cacheTime)
  });
  const deleteMutation = useMutation({
    mutationFn: async (id) => {
      return await apiClient.delete(`/trips/${id}/permanent-delete`);
    },
    onSuccess: () => {
      queryClient2.invalidateQueries({ queryKey: ["trips"] });
      queryClient2.invalidateQueries({ queryKey: ["trips-stats"] });
      setIsDeleteDialogOpen(false);
      setTripToDelete(null);
      showToast(__("Trip deleted permanently.", "yatra"), "success");
    },
    onError: () => {
      showToast(
        __("Failed to delete trip. Please try again.", "yatra"),
        "error"
      );
    }
  });
  const createTripMutation = useMutation({
    mutationFn: async ({ title: title2, slug }) => {
      const trimmedTitle = title2.trim();
      const trimmedSlug = slug.trim();
      const payload = {
        title: trimmedTitle,
        slug: trimmedSlug,
        status: "draft",
        trip_type: "multi_day"
      };
      const response = await apiClient.post("/trips", payload);
      return (response == null ? void 0 : response.data) || response;
    },
    onSuccess: (data2) => {
      showToast(
        __("Trip created as draft. Redirecting to builder...", "yatra"),
        "success"
      );
      queryClient2.invalidateQueries({ queryKey: ["trips"] });
      queryClient2.invalidateQueries({ queryKey: ["trips-stats"] });
      setIsCreateModalOpen(false);
      setNewTripTitle("");
      setNewTripSlug("");
      setIsSlugManuallyEdited(false);
      setCreateTripError(null);
      if (data2 == null ? void 0 : data2.id) {
        setTimeout(() => {
          var _a2;
          window.location.href = `${((_a2 = window.yatraAdmin) == null ? void 0 : _a2.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=trips&action=edit&id=${data2.id}`;
        }, 600);
      }
    },
    onError: (error2) => {
      var _a2, _b2;
      const message2 = ((_b2 = (_a2 = error2 == null ? void 0 : error2.response) == null ? void 0 : _a2.data) == null ? void 0 : _b2.message) || (error2 == null ? void 0 : error2.message) || __("Failed to create trip. Please try again.", "yatra");
      setCreateTripError(message2);
      showToast(message2, "error");
    }
  });
  const r2 = data;
  const trips = Array.isArray(r2 == null ? void 0 : r2.data) ? r2.data : Array.isArray((_a = r2 == null ? void 0 : r2.data) == null ? void 0 : _a.data) ? r2.data.data : [];
  const total = Number(((_b = r2 == null ? void 0 : r2.meta) == null ? void 0 : _b.total) ?? (r2 == null ? void 0 : r2.total) ?? 0);
  const itemsPerPage = Number(((_c = r2 == null ? void 0 : r2.meta) == null ? void 0 : _c.per_page) ?? (r2 == null ? void 0 : r2.per_page) ?? 10) || 10;
  const totalPages = Math.ceil(total / itemsPerPage);
  const errorContext = getErrorContext(error);
  const { data: difficultyLevelsData } = useQuery({
    queryKey: ["difficulty-levels-lookup"],
    queryFn: async () => {
      try {
        const response = await apiClient.get("/difficulty-levels", {
          params: { per_page: 100 }
        });
        return response.data || [];
      } catch (error2) {
        console.error("Failed to load difficulty levels", error2);
        return [];
      }
    },
    staleTime: 5 * 60 * 1e3
    // 5 minutes
  });
  const difficultyLevels = reactExports.useMemo(() => {
    return (difficultyLevelsData || []).reduce(
      (acc, level) => {
        if (level && level.id && level.name) {
          acc[level.id.toString()] = level.name;
        }
        return acc;
      },
      {}
    );
  }, [difficultyLevelsData]);
  const formatLabel = (value) => {
    if (!value) return "";
    if (value && /^\d+$/.test(value) && difficultyLevels[value]) {
      return difficultyLevels[value];
    }
    return "";
  };
  const summarizeDestinations = (trip) => {
    const names = (trip.destinations || []).map((dest) => dest.name).filter(Boolean);
    if (!names.length) return null;
    const summary = names.slice(0, 2).join(", ");
    const remaining = names.length - 2;
    return remaining > 0 ? `${summary} +${remaining}` : summary;
  };
  const summarizeActivities = (trip) => {
    const names = (trip.activity_types || []).map((act) => act.name).filter(Boolean);
    if (!names.length) return null;
    const summary = names.slice(0, 2).join(", ");
    const remaining = names.length - 2;
    return remaining > 0 ? `${summary} +${remaining}` : summary;
  };
  const summarizeCategories = (trip) => {
    const names = (trip.trip_category || []).map((cat) => cat.name).filter(Boolean);
    if (!names.length) return null;
    const summary = names.slice(0, 2).join(", ");
    const remaining = names.length - 2;
    return remaining > 0 ? `${summary} +${remaining}` : summary;
  };
  const summarizeTravelers = (trip) => {
    const { min_travelers, max_travelers } = trip;
    if (min_travelers && max_travelers) {
      return `${min_travelers}-${max_travelers} ${__("pax", "yatra")}`;
    }
    if (min_travelers) {
      return `${__("Min", "yatra")} ${min_travelers} ${__("pax", "yatra")}`;
    }
    if (max_travelers) {
      return `${__("Up to", "yatra")} ${max_travelers} ${__("pax", "yatra")}`;
    }
    return null;
  };
  const handleNewTripTitleChange = (value) => {
    setNewTripTitle(value);
    if (!isSlugManuallyEdited) {
      setNewTripSlug(generateSlug(value));
    }
  };
  const handleNewTripSlugChange = (value) => {
    if (!isSlugManuallyEdited) {
      setIsSlugManuallyEdited(true);
    }
    const sanitized = value.toLowerCase().replace(/[^\p{L}\p{N}-]/gu, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");
    setNewTripSlug(sanitized);
  };
  const enableSlugEditing = () => {
    if (!isSlugManuallyEdited) {
      if (!newTripSlug.trim()) {
        setNewTripSlug(generateSlug(newTripTitle || "new-trip"));
      }
      setIsSlugManuallyEdited(true);
    }
  };
  const formatDate2 = (dateString) => {
    return new Date(dateString).toLocaleDateString("en-US", {
      month: "short",
      day: "numeric",
      year: "numeric"
    });
  };
  const formatPrice = (trip) => {
    const currencyCode = defaultCurrency;
    if (trip.pricing_type === "traveler_based") {
      let minPrice = null;
      let maxPrice = null;
      if (Array.isArray(trip.price_types) && trip.price_types.length > 0) {
        const pricesFromTypes = trip.price_types.map(
          (pt) => pt.sale_price || pt.discounted_price || pt.original_price || 0
        ).filter((val) => typeof val === "number" && val > 0);
        if (pricesFromTypes.length > 0) {
          minPrice = Math.min(...pricesFromTypes);
          maxPrice = Math.max(...pricesFromTypes);
        }
      } else {
        if (typeof trip.traveler_min_price === "number" && trip.traveler_min_price > 0) {
          minPrice = trip.traveler_min_price;
        }
        if (typeof trip.traveler_max_price === "number" && trip.traveler_max_price > 0) {
          maxPrice = trip.traveler_max_price;
        }
      }
      if (minPrice !== null && maxPrice !== null) {
        if (minPrice === maxPrice) {
          return `${formatYatraMoney(minPrice, currencyCode, { zeroAsUnknown: false })} 
`;
        }
        return `${formatYatraMoney(minPrice, currencyCode, { zeroAsUnknown: false })} - ${formatYatraMoney(maxPrice, currencyCode, { zeroAsUnknown: false })}`;
      }
    }
    const price = trip.sale_price || trip.discounted_price || trip.original_price || 0;
    if (!price) {
      return "-";
    }
    return formatYatraMoney(Number(price), currencyCode, {
      zeroAsUnknown: false
    });
  };
  const getStatusBadge = (status) => {
    const statusMap = {
      publish: {
        className: "bg-green-100 text-green-700 dark:bg-green-900/20 dark:text-green-400",
        label: __("Published", "yatra")
      },
      draft: {
        className: "bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-400",
        label: __("Draft", "yatra")
      },
      archived: {
        className: "bg-red-100 text-red-700 dark:bg-red-900/20 dark:text-red-400",
        label: __("Archived", "yatra")
      },
      review: {
        className: "bg-yellow-100 text-yellow-700 dark:bg-yellow-900/20 dark:text-yellow-400",
        label: __("Review", "yatra")
      },
      approved: {
        className: "bg-blue-100 text-blue-700 dark:bg-blue-900/20 dark:text-blue-400",
        label: __("Approved", "yatra")
      },
      trash: {
        className: "bg-gray-200 text-gray-700 dark:bg-gray-800 dark:text-gray-300",
        label: __("Trash", "yatra")
      }
    };
    const statusInfo = statusMap[status] || {
      className: "bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-400",
      label: status
    };
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "span",
      {
        className: `inline-flex items-center px-2 py-1 rounded-md text-xs font-medium ${statusInfo.className}`,
        children: statusInfo.label
      }
    );
  };
  const getTripTypeBadge = (tripType) => {
    if (!tripType) return null;
    const typeMap = {
      single_day: {
        className: "bg-blue-100 text-blue-700 dark:bg-blue-900/20 dark:text-blue-400",
        label: __("Single Day", "yatra")
      },
      multi_day: {
        className: "bg-indigo-100 text-indigo-800 dark:bg-indigo-900/20 dark:text-indigo-400",
        label: __("Multi-Day", "yatra")
      },
      flexible: {
        className: "bg-teal-100 text-teal-700 dark:bg-teal-900/20 dark:text-teal-400",
        label: __("Flexible", "yatra")
      }
    };
    const typeInfo = typeMap[tripType] || {
      className: "bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-400",
      label: tripType
    };
    return /* @__PURE__ */ jsxRuntimeExports.jsx(Badge, { className: `text-xs ${typeInfo.className}`, children: typeInfo.label });
  };
  const handleEdit = (trip) => {
    var _a2;
    window.location.href = `${((_a2 = window.yatraAdmin) == null ? void 0 : _a2.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=trips&action=edit&id=${trip.id}`;
  };
  const handleDelete = (trip) => {
    setTripToDelete(trip);
    setIsDeleteDialogOpen(true);
  };
  const { data: settings2 } = useQuery({
    queryKey: ["settings"],
    queryFn: async () => {
      try {
        const response = await fetchSettings();
        return response;
      } catch (error2) {
        return null;
      }
    },
    enabled: can("yatra_access_admin"),
    staleTime: 5 * 60 * 1e3
    // Cache for 5 minutes
  });
  const defaultCurrency = ((_d = window == null ? void 0 : window.yatraAdmin) == null ? void 0 : _d.currency) || (settings2 == null ? void 0 : settings2.default_currency) || "USD";
  const handleView = async (trip) => {
    const tripSlug = trip.slug || "";
    const { plainUrl, prettyUrl } = buildYatraSinglePublicUrls({
      entity: "trip",
      slug: tripSlug,
      bases: settings2
    });
    if (isWordPressPlainPermalink()) {
      if (!tripSlug) {
        showToast(__("Trip slug is missing", "yatra"), "error");
        return;
      }
      window.open(plainUrl, "_blank", "noopener,noreferrer");
      return;
    }
    let apiPermalink = (trip == null ? void 0 : trip.permalink) || (trip == null ? void 0 : trip.url);
    if (!apiPermalink && trip.id) {
      try {
        const detail = await apiClient.get(`/trips/${trip.id}`);
        apiPermalink = (detail == null ? void 0 : detail.permalink) || (detail == null ? void 0 : detail.url) || apiPermalink;
      } catch (e) {
      }
    }
    if (apiPermalink) {
      window.open(apiPermalink, "_blank", "noopener,noreferrer");
      return;
    }
    if (!tripSlug) {
      showToast(__("Trip slug is missing", "yatra"), "error");
      return;
    }
    window.open(prettyUrl, "_blank", "noopener,noreferrer");
  };
  const handleCreateTrip = () => {
    setIsCreateModalOpen(true);
    setCreateTripError(null);
    setNewTripTitle("");
    setNewTripSlug("");
    setIsSlugManuallyEdited(false);
  };
  const handleCreateTripConfirm = () => {
    const title2 = newTripTitle.trim();
    if (!title2) {
      setCreateTripError(__("Trip title is required", "yatra"));
      return;
    }
    const slugBase = isSlugManuallyEdited ? newTripSlug : generateSlug(title2);
    const slug = slugBase.trim();
    if (!slug) {
      setCreateTripError(__("Trip slug is required", "yatra"));
      return;
    }
    if (!/^[\p{L}\p{N}-]+$/u.test(slug)) {
      setCreateTripError(
        __("Slug can only contain letters, numbers, and hyphens", "yatra")
      );
      return;
    }
    setNewTripSlug(slug);
    createTripMutation.mutate({ title: title2, slug });
  };
  const handleResetFilters = () => {
    setSearchTerm("");
    setStatusFilter("all");
    setSortBy("id");
    setSortOrder("desc");
    setPage(1);
  };
  const handleSort = (field) => {
    if (sortBy2 === field) {
      setSortOrder(sortOrder === "asc" ? "desc" : "asc");
    } else {
      setSortBy(field);
      setSortOrder("asc");
    }
  };
  const getSortIcon = (field) => {
    if (sortBy2 !== field) {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowUpDown, { className: "w-3.5 h-3.5 ml-1 text-gray-400" });
    }
    return sortOrder === "asc" ? /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowUp, { className: "w-3.5 h-3.5 ml-1 text-gray-600 dark:text-gray-300" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowDown, { className: "w-3.5 h-3.5 ml-1 text-gray-600 dark:text-gray-300" });
  };
  const hasFilters = searchTerm || statusFilter !== "all" || sortBy2 !== "id" || sortOrder !== "desc";
  const updateTripStatus = async (trip, status) => {
    await apiClient.put(`/trips/${trip.id}`, {
      status,
      title: trip.title,
      slug: trip.slug
    });
    queryClient2.invalidateQueries({ queryKey: ["trips"] });
    queryClient2.invalidateQueries({ queryKey: ["trips-stats"] });
  };
  const [visibleColumns, setVisibleColumns] = reactExports.useState(
    () => {
      const defaults2 = {
        trip: true,
        price: true,
        status: true,
        trip_type: true,
        duration: false,
        availability: true,
        // Availability status (has dates, seats)
        capacity: false,
        // Min/Max travelers
        countries: false,
        difficulty: false,
        attributes: false,
        // Custom attributes count
        // Control chips inside Trip column
        destinations: true,
        activities: true,
        categories: true,
        bookings: true,
        created: true,
        modified: false
        // Last modified date
      };
      if (typeof window === "undefined") {
        return defaults2;
      }
      const stored = window.localStorage.getItem("yatra-trips-visible-columns");
      if (stored) {
        try {
          const parsed = JSON.parse(stored);
          return { ...defaults2, ...parsed };
        } catch {
          return defaults2;
        }
      }
      return defaults2;
    }
  );
  const toggleColumn = (columnKey) => {
    const updated = {
      ...visibleColumns,
      [columnKey]: !visibleColumns[columnKey]
    };
    setVisibleColumns(updated);
    if (typeof window !== "undefined") {
      window.localStorage.setItem(
        "yatra-trips-visible-columns",
        JSON.stringify(updated)
      );
    }
  };
  const columnOptions = [
    { key: "trip", label: __("Trip", "yatra"), visible: visibleColumns.trip },
    {
      key: "price",
      label: __("Price", "yatra"),
      visible: visibleColumns.price
    },
    {
      key: "status",
      label: __("Status", "yatra"),
      visible: visibleColumns.status
    },
    {
      key: "trip_type",
      label: __("Trip Type", "yatra"),
      visible: visibleColumns.trip_type
    },
    {
      key: "duration",
      label: __("Duration", "yatra"),
      visible: visibleColumns.duration
    },
    {
      key: "countries",
      label: __("Countries", "yatra"),
      visible: visibleColumns.countries
    },
    {
      key: "difficulty",
      label: __("Difficulty", "yatra"),
      visible: visibleColumns.difficulty
    },
    {
      key: "availability",
      label: __("Availability", "yatra"),
      visible: visibleColumns.availability
    },
    {
      key: "capacity",
      label: __("Capacity", "yatra"),
      visible: visibleColumns.capacity
    },
    {
      key: "attributes",
      label: __("Attributes", "yatra"),
      visible: visibleColumns.attributes
    },
    // These control which chips are shown inside the Trip column
    {
      key: "destinations",
      label: __("Destinations (chips)", "yatra"),
      visible: visibleColumns.destinations
    },
    {
      key: "activities",
      label: __("Activities (chips)", "yatra"),
      visible: visibleColumns.activities
    },
    {
      key: "categories",
      label: __("Categories (chips)", "yatra"),
      visible: visibleColumns.categories
    },
    ...isPro ? [
      {
        key: "bookings",
        label: __("Bookings", "yatra"),
        visible: visibleColumns.bookings
      }
    ] : [],
    {
      key: "created",
      label: __("Created", "yatra"),
      visible: visibleColumns.created
    },
    {
      key: "modified",
      label: __("Modified", "yatra"),
      visible: visibleColumns.modified
    }
  ];
  const isAllSelected = trips.length > 0 && selectedIds.length === trips.length;
  const handleSelectItem = (id, checked) => {
    setSelectedIds(
      (prev) => checked ? [...prev, id] : prev.filter((existingId) => existingId !== id)
    );
  };
  const handleSelectAll = (checked) => {
    if (checked) {
      setSelectedIds(trips.map((trip) => trip.id));
    } else {
      setSelectedIds([]);
    }
  };
  const statusCounts = reactExports.useMemo(() => {
    if (statsData) {
      return {
        all: statsData.all ?? 0,
        publish: statsData.published ?? 0,
        draft: statsData.draft ?? 0,
        review: statsData.review ?? 0,
        approved: statsData.approved ?? 0,
        archived: statsData.archived ?? 0,
        trash: statsData.trash ?? 0
      };
    }
    return {
      all: 0,
      publish: 0,
      draft: 0,
      review: 0,
      approved: 0,
      archived: 0,
      trash: 0
    };
  }, [statsData]);
  const statusOptions = [
    { key: "all", label: __("All", "yatra"), count: statusCounts.all },
    {
      key: "publish",
      label: __("Published", "yatra"),
      count: statusCounts.publish
    },
    { key: "draft", label: __("Draft", "yatra"), count: statusCounts.draft },
    { key: "review", label: __("Review", "yatra"), count: statusCounts.review },
    {
      key: "approved",
      label: __("Approved", "yatra"),
      count: statusCounts.approved
    },
    {
      key: "archived",
      label: __("Archived", "yatra"),
      count: statusCounts.archived
    },
    { key: "trash", label: __("Trash", "yatra"), count: statusCounts.trash }
  ];
  const bulkActionOptions = reactExports.useMemo(() => {
    if (statusFilter === "trash") {
      return [
        { value: "mark_draft", label: __("Restore to Draft", "yatra") },
        { value: "delete", label: __("Delete Permanently", "yatra") }
      ];
    }
    return [
      { value: "mark_publish", label: __("Mark as Published", "yatra") },
      { value: "mark_draft", label: __("Mark as Draft", "yatra") },
      { value: "mark_archived", label: __("Archive", "yatra") },
      { value: "mark_trash", label: __("Move to Trash", "yatra") },
      { value: "delete", label: __("Delete Permanently", "yatra") }
    ];
  }, [statusFilter]);
  const handleBulkApply = async () => {
    if (!bulkAction || selectedIds.length === 0) return;
    try {
      if (bulkAction === "delete") {
        await Promise.all(
          selectedIds.map(
            (id) => apiClient.delete(`/trips/${id}/permanent-delete`)
          )
        );
        showToast(__("Trips deleted permanently", "yatra"), "success");
      } else if (bulkAction.startsWith("mark_")) {
        const status = bulkAction.replace("mark_", "");
        const selectedTrips = trips.filter(
          (trip) => selectedIds.includes(trip.id)
        );
        await Promise.all(
          selectedTrips.map((trip) => updateTripStatus(trip, status))
        );
        showToast(__("Trip status updated successfully", "yatra"), "success");
      }
      queryClient2.invalidateQueries({ queryKey: ["trips"] });
      queryClient2.invalidateQueries({ queryKey: ["trips-stats"] });
      setSelectedIds([]);
      setBulkAction("");
    } catch (error2) {
      showToast(__("Bulk action failed", "yatra"), "error");
    }
  };
  const columns = reactExports.useMemo(() => {
    const cols = [];
    cols.push({
      key: "title",
      label: __("Trip", "yatra"),
      sortable: true,
      visible: visibleColumns.trip,
      width: "w-[300px]",
      render: (trip) => {
        var _a2, _b2;
        const editUrl = `${((_a2 = window.yatraAdmin) == null ? void 0 : _a2.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=trips&action=edit&id=${trip.id}`;
        return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start gap-3", children: [
          trip.featured_image_url ? /* @__PURE__ */ jsxRuntimeExports.jsx(
            "img",
            {
              src: trip.featured_image_url,
              alt: trip.title,
              className: "w-12 h-12 object-cover rounded flex-shrink-0"
            }
          ) : /* @__PURE__ */ jsxRuntimeExports.jsx(
            "img",
            {
              src: `${((_b2 = window.yatraAdmin) == null ? void 0 : _b2.siteUrl) || ""}/wp-content/plugins/yatra/assets/images/trip-placeholder.svg`,
              alt: trip.title,
              className: "w-12 h-12 object-cover rounded flex-shrink-0"
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1 min-w-0", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "a",
                {
                  href: editUrl,
                  onClick: (e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    handleEdit(trip);
                  },
                  className: "font-medium text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300 underline-offset-2 hover:underline truncate",
                  children: trip.title
                }
              ),
              can("yatra_view_trips") && trip.status !== "trash" && /* @__PURE__ */ jsxRuntimeExports.jsx(
                "button",
                {
                  type: "button",
                  onClick: (e) => {
                    e.stopPropagation();
                    handleView(trip);
                  },
                  className: "ml-1 inline-flex items-center justify-center rounded-full p-1 text-gray-400 hover:text-gray-700 hover:bg-gray-100 dark:text-gray-400 dark:hover:text-white dark:hover:bg-gray-800",
                  title: __("View trip in new tab", "yatra"),
                  children: /* @__PURE__ */ jsxRuntimeExports.jsx(ExternalLink, { className: "w-3.5 h-3.5" })
                }
              )
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-xs text-gray-500 dark:text-gray-400 mt-0.5 truncate", children: [
              trip.slug,
              /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "ml-1 text-[11px] text-gray-400 dark:text-gray-500", children: [
                "(ID: ",
                trip.id,
                ")"
              ] })
            ] }),
            (() => {
              const destinationLabel = summarizeDestinations(trip);
              const durationLabel = trip.duration_days ? `${trip.duration_days}${__("d", "yatra")}${trip.duration_nights ? ` / ${trip.duration_nights}${__("n", "yatra")}` : ""}` : null;
              const travelerLabel = summarizeTravelers(trip);
              const categoryLabel = summarizeCategories(trip);
              const activityLabel = summarizeActivities(trip);
              const difficultyLabel = formatLabel(trip.difficulty_level);
              const chips = [
                destinationLabel && visibleColumns.destinations && {
                  key: "dest",
                  label: destinationLabel,
                  icon: Route
                },
                durationLabel && {
                  key: "duration",
                  label: durationLabel,
                  icon: Calendar$1
                },
                travelerLabel && {
                  key: "traveler",
                  label: travelerLabel,
                  icon: Users
                },
                activityLabel && visibleColumns.activities && {
                  key: "activity",
                  label: activityLabel,
                  icon: Activity
                },
                categoryLabel && visibleColumns.categories && {
                  key: "category",
                  label: categoryLabel,
                  icon: FolderTree
                },
                difficultyLabel && {
                  key: "difficulty",
                  label: difficultyLabel,
                  icon: TrendingUp
                }
              ].filter(Boolean);
              if (!chips.length) return null;
              return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex flex-wrap gap-2 mt-1", children: chips.map(({ key: key2, label, icon: Icon }) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
                "span",
                {
                  className: "inline-flex items-center gap-1 rounded-full bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-300 px-2 py-0.5 text-[11px]",
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(Icon, { className: "w-3 h-3" }),
                    label
                  ]
                },
                `${trip.id}-${key2}`
              )) });
            })()
          ] }),
          trip.featured_priority && trip.featured_priority !== "none" && isPro && /* @__PURE__ */ jsxRuntimeExports.jsx(Badge, { className: "text-xs bg-blue-100 text-blue-700 dark:bg-blue-900/20 dark:text-blue-400", children: trip.featured_priority === "featured" ? __("Featured", "yatra") : trip.featured_priority === "new" ? __("New", "yatra") : trip.featured_priority === "limited" ? __("Limited", "yatra") : trip.featured_priority === "bestseller" ? __("Bestseller", "yatra") : trip.featured_priority })
        ] });
      }
    });
    cols.push({
      key: "price",
      label: __("Price", "yatra"),
      sortable: true,
      visible: visibleColumns.price,
      render: (trip) => /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-medium", children: formatPrice(trip) })
    });
    cols.push({
      key: "status",
      label: __("Status", "yatra"),
      sortable: true,
      visible: visibleColumns.status,
      render: (trip) => getStatusBadge(trip.status)
    });
    cols.push({
      key: "trip_type",
      label: __("Trip Type", "yatra"),
      sortable: true,
      visible: visibleColumns.trip_type,
      render: (trip) => getTripTypeBadge(trip.trip_type)
    });
    cols.push({
      key: "duration",
      label: __("Duration", "yatra"),
      sortable: false,
      visible: visibleColumns.duration,
      render: (trip) => {
        if (!trip.duration_days && !trip.duration_nights) return null;
        const days = trip.duration_days ? `${trip.duration_days} ${__("days", "yatra")}` : "";
        const nights = trip.duration_nights ? `${trip.duration_nights} ${__("nights", "yatra")}` : "";
        const label = [days, nights].filter(Boolean).join(" / ");
        return /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm text-gray-700 dark:text-gray-300", children: label });
      }
    });
    cols.push({
      key: "countries",
      label: __("Countries", "yatra"),
      sortable: false,
      visible: visibleColumns.countries,
      render: (trip) => {
        const list = (trip.countries || []).filter(Boolean);
        if (!list.length) return null;
        return /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm text-gray-700 dark:text-gray-300", children: list.join(", ") });
      }
    });
    cols.push({
      key: "difficulty",
      label: __("Difficulty", "yatra"),
      sortable: false,
      visible: visibleColumns.difficulty,
      render: (trip) => {
        const difficultyValue = trip.difficulty_level;
        if (!difficultyValue || difficultyValue === "0" || Number(difficultyValue) === 0)
          return null;
        const difficultyText = formatLabel(String(difficultyValue));
        if (!difficultyText) return null;
        return /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm text-gray-700 dark:text-gray-300", children: difficultyText });
      }
    });
    cols.push({
      key: "availability",
      label: __("Availability", "yatra"),
      sortable: false,
      visible: visibleColumns.availability,
      render: (trip) => {
        const dates = trip.availability_dates || [];
        if (!dates.length) {
          return /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs text-gray-400 dark:text-gray-500", children: __("No dates", "yatra") });
        }
        const availableCount = dates.filter(
          (d) => d.status === "available"
        ).length;
        return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-sm", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-gray-700 dark:text-gray-300", children: [
            dates.length,
            " ",
            __("dates", "yatra")
          ] }),
          availableCount > 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-xs text-green-600 dark:text-green-400", children: [
            availableCount,
            " ",
            __("available", "yatra")
          ] })
        ] });
      }
    });
    cols.push({
      key: "capacity",
      label: __("Capacity", "yatra"),
      sortable: false,
      visible: visibleColumns.capacity,
      render: (trip) => {
        if (!trip.min_travelers && !trip.max_travelers) return null;
        const min2 = trip.min_travelers || 0;
        const max2 = trip.max_travelers || 0;
        return /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-sm text-gray-700 dark:text-gray-300", children: [
          min2,
          "-",
          max2,
          " ",
          __("travelers", "yatra")
        ] });
      }
    });
    cols.push({
      key: "attributes",
      label: __("Attributes", "yatra"),
      sortable: false,
      visible: visibleColumns.attributes,
      render: (trip) => {
        const attrCount = trip.attributes ? Object.keys(trip.attributes).length : 0;
        if (!attrCount) {
          return /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs text-gray-400 dark:text-gray-500", children: __("None", "yatra") });
        }
        return /* @__PURE__ */ jsxRuntimeExports.jsxs(Badge, { className: "text-xs bg-blue-100 text-blue-700 dark:bg-blue-900/20 dark:text-blue-400", children: [
          attrCount,
          " ",
          __("attributes", "yatra")
        ] });
      }
    });
    if (isPro) {
      cols.push({
        key: "bookings",
        label: __("Bookings", "yatra"),
        sortable: false,
        visible: visibleColumns.bookings,
        render: (trip) => /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-600 dark:text-gray-400", children: trip.bookings_count || 0 })
      });
    }
    cols.push({
      key: "date",
      label: __("Created", "yatra"),
      sortable: true,
      visible: visibleColumns.created,
      render: (trip) => /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-500 dark:text-gray-400 text-sm", children: formatDate2(trip.created_at) })
    });
    cols.push({
      key: "modified",
      label: __("Modified", "yatra"),
      sortable: true,
      visible: visibleColumns.modified,
      render: (trip) => {
        if (!trip.updated_at) return null;
        return /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-500 dark:text-gray-400 text-sm", children: formatDate2(trip.updated_at) });
      }
    });
    return cols;
  }, [
    isPro,
    visibleColumns,
    summarizeDestinations,
    summarizeTravelers,
    summarizeCategories,
    formatLabel,
    formatPrice,
    getStatusBadge,
    getTripTypeBadge
  ]);
  const navigateToAvailability = (trip) => {
    navigate({
      subpage: "trips",
      tab: "availability",
      trip_id: trip.id.toString()
    });
  };
  const navigateToRecurringRules = (trip) => {
    navigate({
      subpage: "trips",
      tab: "availability",
      trip_id: trip.id.toString(),
      tab_mode: "recurring"
    });
  };
  const tableActions = reactExports.useMemo(() => {
    const actions = [];
    if (can("yatra_view_trips")) {
      actions.push({
        key: "view",
        label: __("View (frontend)", "yatra"),
        icon: /* @__PURE__ */ jsxRuntimeExports.jsx(ExternalLink, { className: "w-4 h-4" }),
        onClick: (trip) => handleView(trip),
        condition: (trip) => trip.status !== "trash"
        // Hide for trash trips
      });
    }
    actions.push({
      key: "view-availability",
      label: __("View Availability", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Calendar$1, { className: "w-4 h-4" }),
      onClick: (trip) => navigateToAvailability(trip)
    });
    actions.push({
      key: "view-recurring",
      label: __("View Recurring Rules", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(RefreshCw, { className: "w-4 h-4" }),
      onClick: (trip) => navigateToRecurringRules(trip)
    });
    if (can("yatra_edit_trips")) {
      actions.push({
        key: "edit",
        label: __("Edit", "yatra"),
        icon: /* @__PURE__ */ jsxRuntimeExports.jsx(PenSquare, { className: "w-4 h-4" }),
        onClick: (trip) => handleEdit(trip)
      });
      actions.push({
        key: "duplicate",
        label: __("Duplicate", "yatra"),
        icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Copy, { className: "w-4 h-4" }),
        onClick: async (trip) => {
          try {
            await apiClient.post(`/trips/${trip.id}/duplicate`);
            showToast(__("Trip duplicated as draft.", "yatra"), "success");
            queryClient2.invalidateQueries({ queryKey: ["trips"] });
          } catch (error2) {
            console.error("Failed to duplicate trip", error2);
            showToast(__("Failed to duplicate trip.", "yatra"), "error");
          }
        }
      });
      actions.push({
        key: "publish",
        label: __("Mark as Published", "yatra"),
        icon: /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowUp, { className: "w-4 h-4" }),
        onClick: async (trip) => {
          await updateTripStatus(trip, "publish");
          showToast(__("Trip marked as published.", "yatra"), "success");
          queryClient2.invalidateQueries({ queryKey: ["trips"] });
        },
        condition: (trip) => trip.status !== "publish" && trip.status !== "trash"
      });
      actions.push({
        key: "draft",
        label: __("Mark as Draft", "yatra"),
        icon: /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowDown, { className: "w-4 h-4" }),
        onClick: async (trip) => {
          await updateTripStatus(trip, "draft");
          showToast(__("Trip marked as draft.", "yatra"), "success");
          queryClient2.invalidateQueries({ queryKey: ["trips"] });
        },
        condition: (trip) => trip.status !== "draft" && trip.status !== "trash"
      });
      actions.push({
        key: "archive",
        label: __("Archive", "yatra"),
        icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Archive, { className: "w-4 h-4" }),
        onClick: async (trip) => {
          await updateTripStatus(trip, "archived");
          showToast(__("Trip archived.", "yatra"), "success");
          queryClient2.invalidateQueries({ queryKey: ["trips"] });
        },
        condition: (trip) => trip.status !== "archived" && trip.status !== "trash"
      });
      actions.push({
        key: "trash",
        label: __("Move to Trash", "yatra"),
        icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "w-4 h-4" }),
        onClick: async (trip) => {
          await updateTripStatus(trip, "trash");
          showToast(__("Trip moved to trash.", "yatra"), "success");
          queryClient2.invalidateQueries({ queryKey: ["trips"] });
        },
        condition: (trip) => trip.status !== "trash"
      });
      actions.push({
        key: "restore",
        label: __("Restore to Draft", "yatra"),
        icon: /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowUp, { className: "w-4 h-4" }),
        onClick: async (trip) => {
          await updateTripStatus(trip, "draft");
          showToast(__("Trip restored to draft.", "yatra"), "success");
          queryClient2.invalidateQueries({ queryKey: ["trips"] });
        },
        condition: (trip) => trip.status === "trash"
      });
    }
    if (can("yatra_delete_trips")) {
      actions.push({
        key: "delete",
        label: __("Delete Permanently", "yatra"),
        icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "w-4 h-4" }),
        onClick: (trip) => handleDelete(trip),
        variant: "destructive",
        condition: () => true
        // Show for all trips
      });
    }
    return actions;
  }, [can, queryClient2, showToast]);
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        PageHeader,
        {
          title: __("All Trips", "yatra"),
          description: __(
            "Manage your travel packages and tours. Create, edit, and organize all your trips in one place.",
            "yatra"
          ),
          actionCapability: "yatra_edit_trips",
          actions: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
            window.WP_DEBUG && /* @__PURE__ */ jsxRuntimeExports.jsx(
              Button,
              {
                onClick: () => {
                  refetch();
                },
                variant: "outline",
                className: "text-xs",
                children: __("Refresh Data", "yatra")
              }
            ),
            isAiEligible() && isAiModuleEnabled() && /* @__PURE__ */ jsxRuntimeExports.jsxs(
              Button,
              {
                type: "button",
                onClick: () => setIsAiWizardOpen(true),
                className: "inline-flex items-center gap-2 whitespace-nowrap bg-gradient-to-r from-blue-600 to-blue-700 text-white border-0 hover:from-blue-700 hover:to-blue-800",
                title: __(
                  "Have AI draft an entire trip — details, itinerary, SEO — from a few setup questions.",
                  "yatra"
                ),
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(Sparkles, { className: "h-4 w-4 shrink-0" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: __("Add Trip with AI", "yatra") })
                ]
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              Button,
              {
                onClick: handleCreateTrip,
                className: "inline-flex items-center gap-2 whitespace-nowrap",
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(Plus, { className: "h-4 w-4 shrink-0" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: __("Add New Trip", "yatra") })
                ]
              }
            )
          ] })
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "p-4", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mb-3", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          HelpText,
          {
            text: __(
              "Use the search box to find trips by name. Use filters to show only published, draft, or other status trips. Click column headers to sort.",
              "yatra"
            )
          }
        ) }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col lg:flex-row gap-3 items-stretch lg:items-center w-full", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1 min-w-0 relative", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Search, { className: "absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              Input,
              {
                type: "text",
                placeholder: __("Search by trip name...", "yatra"),
                value: searchTerm,
                onChange: (e) => setSearchTerm(e.target.value),
                className: "pl-10 w-full",
                title: __("Type to search for trips by name", "yatra")
              }
            )
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-full lg:w-auto lg:min-w-[160px]", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Select,
            {
              value: statusFilter,
              onChange: (e) => setStatusFilter(e.target.value),
              className: "w-full",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "all", children: __("All Status", "yatra") }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "publish", children: __("Published", "yatra") }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "draft", children: __("Draft", "yatra") }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "review", children: __("Review", "yatra") }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "approved", children: __("Approved", "yatra") }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "archived", children: __("Archived", "yatra") }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "trash", children: __("Trash", "yatra") })
              ]
            }
          ) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-full lg:w-auto lg:min-w-[140px]", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Select,
            {
              value: sortBy2,
              onChange: (e) => setSortBy(e.target.value),
              className: "w-full",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "title", children: __("Title", "yatra") }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "price", children: __("Price", "yatra") }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "date", children: __("Date", "yatra") }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "status", children: __("Status", "yatra") })
              ]
            }
          ) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-full lg:w-auto lg:flex-shrink-0", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Button,
            {
              variant: "outline",
              onClick: () => setSortOrder(sortOrder === "asc" ? "desc" : "asc"),
              className: "px-4 flex items-center gap-2 w-full lg:w-auto",
              title: sortOrder === "asc" ? __("Ascending", "yatra") : __("Descending", "yatra"),
              children: [
                sortOrder === "asc" ? /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowUp, { className: "w-4 h-4" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowDown, { className: "w-4 h-4" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm whitespace-nowrap", children: sortOrder === "asc" ? __("Asc", "yatra") : __("Desc", "yatra") })
              ]
            }
          ) }),
          hasFilters && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-full lg:w-auto lg:flex-shrink-0", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Button,
            {
              variant: "outline",
              onClick: handleResetFilters,
              className: "flex items-center gap-2 w-full lg:w-auto",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(X, { className: "w-4 h-4" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm", children: __("Reset", "yatra") })
              ]
            }
          ) })
        ] })
      ] }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(ConditionalRender, { capability: "yatra_view_trips", children: [
        !error && /* @__PURE__ */ jsxRuntimeExports.jsx(
          BulkActionToolbar,
          {
            selectedIds,
            bulkAction,
            setBulkAction,
            onApply: handleBulkApply,
            onClearSelection: () => setSelectedIds([]),
            statusFilter,
            setStatusFilter,
            statusOptions,
            showColumnsDropdown,
            setShowColumnsDropdown,
            columnOptions,
            onToggleColumn: toggleColumn,
            bulkMutationPending: false,
            totalItems: total,
            bulkActionOptions
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-0", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          Table,
          {
            data: trips,
            columns,
            actions: tableActions,
            isLoading,
            isError: !!error,
            errorText: __("Error Loading Trips", "yatra"),
            errorDescription: __(
              "We couldn’t connect to the trips service. Please refresh or try again shortly.",
              "We couldn’t connect to the trips service. Please refresh or try again shortly."
            ),
            onRetry: () => queryClient2.invalidateQueries({ queryKey: ["trips"] }),
            errorDetails: errorContext.details,
            errorRequestInfo: errorContext.requestInfo,
            emptyText: searchTerm || statusFilter !== "all" ? __("No trips match your search", "yatra") : __("No trips yet", "yatra"),
            emptyDescription: searchTerm || statusFilter !== "all" ? __(
              "Try adjusting your search or filters to see more results.",
              "yatra"
            ) : __(
              "Get started by creating your first travel package. Click the button above to add a new trip.",
              "yatra"
            ),
            onCreateClick: !searchTerm && statusFilter === "all" ? handleCreateTrip : void 0,
            onSort: handleSort,
            getSortIcon,
            selectedItemIds: selectedIds,
            onSelectItem: handleSelectItem,
            onSelectAll: handleSelectAll,
            isAllSelected,
            getItemId: (trip) => trip.id
          }
        ) }) }),
        total > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-4", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          Pagination,
          {
            currentPage: page,
            totalPages,
            totalItems: total,
            itemsPerPage,
            onPageChange: setPage,
            itemName: __("trips", "yatra")
          }
        ) })
      ] })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      Modal,
      {
        isOpen: isCreateModalOpen,
        onClose: () => {
          if (!createTripMutation.isPending) {
            setIsCreateModalOpen(false);
            setCreateTripError(null);
          }
        },
        title: __("Create New Trip", "yatra"),
        description: __(
          "Give your trip a name and URL. We'll create a draft and take you to the trip builder.",
          "yatra"
        ),
        size: "lg",
        footer: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-end gap-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Button,
            {
              variant: "outline",
              onClick: () => {
                if (!createTripMutation.isPending) {
                  setIsCreateModalOpen(false);
                  setCreateTripError(null);
                }
              },
              disabled: createTripMutation.isPending,
              children: __("Cancel", "yatra")
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Button,
            {
              onClick: handleCreateTripConfirm,
              className: "flex items-center gap-2",
              disabled: createTripMutation.isPending,
              children: [
                createTripMutation.isPending && /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "w-4 h-4 border-2 border-white/40 border-t-white rounded-full animate-spin" }),
                createTripMutation.isPending ? __("Creating…", "yatra") : __("Create & Continue", "yatra")
              ]
            }
          )
        ] }),
        children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-6", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("label", { className: "text-sm font-medium text-gray-700 dark:text-gray-300 flex items-center gap-1", children: [
              __("Trip Title", "yatra"),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              Input,
              {
                value: newTripTitle,
                onChange: (e) => handleNewTripTitleChange(e.target.value),
                placeholder: __("e.g., Bali Beach Retreat", "yatra"),
                disabled: createTripMutation.isPending,
                className: "text-base"
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400", children: __(
              "A catchy title that describes your trip. Recommended: 50-60 characters for best SEO results.",
              "yatra"
            ) })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("label", { className: "text-sm font-medium text-gray-700 dark:text-gray-300 flex items-center gap-1", children: [
                __("Trip URL", "yatra"),
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-[10px] font-normal text-gray-400", children: __("(URL friendly)", "yatra") })
              ] }),
              !isSlugManuallyEdited && /* @__PURE__ */ jsxRuntimeExports.jsx(
                "button",
                {
                  type: "button",
                  onClick: enableSlugEditing,
                  className: "text-xs text-blue-600 dark:text-blue-400 hover:underline",
                  children: __("Customize URL", "yatra")
                }
              )
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              Input,
              {
                value: newTripSlug,
                onChange: (e) => handleNewTripSlugChange(e.target.value),
                placeholder: __("bali-beach-retreat", "yatra"),
                disabled: createTripMutation.isPending,
                readOnly: !isSlugManuallyEdited,
                className: `font-mono text-sm ${!isSlugManuallyEdited ? "bg-gray-100 dark:bg-gray-800 cursor-not-allowed" : ""}`
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400", children: isSlugManuallyEdited ? __(
              "Editing slug manually. Keep it short, lowercase, and hyphen-separated.",
              "yatra"
            ) : __(
              'Auto-generated from the title. Click "Customize URL" if you need a custom slug.',
              "yatra"
            ) }),
            (newTripSlug || newTripTitle) && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "p-3 bg-gray-50 dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-600 dark:text-gray-400 mb-1", children: __("Preview:", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "text-xs text-gray-900 dark:text-white font-mono break-all", children: [
                ((_e = window.yatraAdmin) == null ? void 0 : _e.siteUrl) || "https://example.com",
                "/trips/",
                newTripSlug || generateSlug(newTripTitle)
              ] })
            ] })
          ] }),
          createTripError && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg", children: /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-red-600 dark:text-red-400", children: createTripError }) })
        ] })
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      CreateTripWithAiWizard,
      {
        open: isAiWizardOpen,
        onClose: () => setIsAiWizardOpen(false)
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      ConfirmationDialog,
      {
        isOpen: isDeleteDialogOpen && !!tripToDelete,
        onClose: () => {
          if (!deleteMutation.isPending) {
            setIsDeleteDialogOpen(false);
            setTripToDelete(null);
          }
        },
        onConfirm: () => {
          if (tripToDelete && !deleteMutation.isPending) {
            deleteMutation.mutate(tripToDelete.id);
          }
        },
        title: __("Delete Trip Permanently", "yatra"),
        message: tripToDelete ? __(
          'Are you sure you want to permanently delete "{title}"? This cannot be undone and will remove all associated bookings.',
          "yatra"
        ).replace("{title}", tripToDelete.title) : "",
        confirmText: __("Delete Permanently", "yatra"),
        cancelText: __("Cancel", "yatra"),
        variant: "danger",
        isLoading: deleteMutation.isPending
      }
    )
  ] });
};
const SearchFilterToolbar = ({
  searchTerm,
  onSearchChange,
  statusFilter,
  onStatusChange,
  statusOptions,
  sortBy: sortBy2,
  onSortByChange,
  sortOrder,
  onSortOrderChange,
  sortOptions,
  onResetFilters,
  hasFilters,
  placeholder = "Search..."
}) => {
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col lg:flex-row gap-2 items-stretch lg:items-center", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative min-w-0 w-full lg:flex-[3]", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(Search, { className: "absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        Input,
        {
          type: "text",
          placeholder,
          value: searchTerm,
          onChange: (e) => onSearchChange(e.target.value),
          className: "pl-10 w-full"
        }
      )
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      Select,
      {
        value: statusFilter,
        onChange: (e) => onStatusChange(e.target.value),
        className: "w-full lg:w-48 lg:flex-none",
        children: statusOptions.map((option) => /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: option.value, children: option.label }, option.value))
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      Select,
      {
        value: sortBy2,
        onChange: (e) => onSortByChange(e.target.value),
        className: "w-full lg:w-48 lg:flex-none",
        children: sortOptions.map((option) => /* @__PURE__ */ jsxRuntimeExports.jsxs("option", { value: option.value, children: [
          option.label,
          sortBy2 === option.value && (sortOrder === "asc" ? /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowUp, { className: "w-3.5 h-3.5 ml-1 text-gray-600 dark:text-gray-300" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowDown, { className: "w-3.5 h-3.5 ml-1 text-gray-600 dark:text-gray-300" }))
        ] }, option.value))
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsxs(
      Button,
      {
        variant: "outline",
        onClick: () => onSortOrderChange(sortOrder === "asc" ? "desc" : "asc"),
        className: "h-11 px-4 flex items-center gap-1.5 flex-shrink-0",
        title: sortOrder === "asc" ? __("Ascending", "yatra") : __("Descending", "yatra"),
        children: [
          sortOrder === "asc" ? /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowUp, { className: "w-4 h-4" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowDown, { className: "w-4 h-4" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs", children: sortOrder === "asc" ? __("Asc", "yatra") : __("Desc", "yatra") })
        ]
      }
    ),
    hasFilters && /* @__PURE__ */ jsxRuntimeExports.jsxs(
      Button,
      {
        variant: "outline",
        onClick: onResetFilters,
        className: "h-11 flex items-center gap-2 flex-shrink-0",
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(X, { className: "w-4 h-4" }),
          __("Reset", "yatra")
        ]
      }
    )
  ] });
};
const getDefaultBulkStatusOptions = (statusFilter) => {
  const options2 = [];
  switch (statusFilter) {
    case "publish":
      options2.push({ value: "trash", label: __("Move to Trash", "yatra") });
      options2.push({ value: "draft", label: __("Make Draft", "yatra") });
      break;
    case "draft":
      options2.push({ value: "publish", label: __("Make Published", "yatra") });
      options2.push({ value: "trash", label: __("Move to Trash", "yatra") });
      break;
    case "trash":
      options2.push({ value: "publish", label: __("Make Published", "yatra") });
      options2.push({ value: "draft", label: __("Make Draft", "yatra") });
      options2.push({
        value: "delete",
        label: __("Delete Permanently", "yatra")
      });
      break;
    case "all":
    default:
      options2.push({ value: "publish", label: __("Make Published", "yatra") });
      options2.push({ value: "draft", label: __("Make Draft", "yatra") });
      options2.push({ value: "trash", label: __("Move to Trash", "yatra") });
      break;
  }
  return options2;
};
const Activities = () => {
  const [searchTerm, setSearchTerm] = reactExports.useState("");
  const [statusFilter, setStatusFilter] = reactExports.useState("all");
  const [sortBy2, setSortBy] = reactExports.useState("id");
  const [sortOrder, setSortOrder] = reactExports.useState("desc");
  const [page, setPage] = reactExports.useState(1);
  const [permanentDeleteConfirm, setPermanentDeleteConfirm] = reactExports.useState({
    isOpen: false,
    activity: null
  });
  const [individualActionConfirm, setIndividualActionConfirm] = reactExports.useState({
    isOpen: false,
    action: "",
    activity: null
  });
  const [selectedIds, setSelectedIds] = reactExports.useState([]);
  const [bulkAction, setBulkAction] = reactExports.useState("");
  const [openDropdown, setOpenDropdown] = reactExports.useState(
    null
  );
  const [showColumnsDropdown, setShowColumnsDropdown] = reactExports.useState(false);
  const [visibleColumns, setVisibleColumns] = reactExports.useState(() => {
    const defaultColumns = {
      name: true,
      description: true,
      trips: true,
      status: true,
      seo_title: false,
      seo_description: false,
      seo_keywords: false,
      created_at: false,
      updated_at: false,
      created_by_name: false,
      updated_by_name: false
    };
    const saved = localStorage.getItem("yatra-activities-columns-v2");
    return saved ? { ...defaultColumns, ...JSON.parse(saved) } : defaultColumns;
  });
  const queryClient2 = useQueryClient();
  const { can } = usePermissions();
  const { showToast } = useToast();
  reactExports.useMemo(
    () => [
      {
        Header: __("Name", "yatra"),
        accessor: "name",
        Cell: ({ row }) => /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex items-center", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm font-medium text-gray-900", children: row.original.name }) })
      },
      {
        Header: __("Description", "yatra"),
        accessor: "description",
        Cell: ({ row }) => /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-500", children: row.original.description })
      },
      {
        Header: __("Trips", "yatra"),
        accessor: "trip_count",
        Cell: ({ row }) => /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-500", children: row.original.trip_count || 0 })
      },
      {
        Header: __("Status", "yatra"),
        accessor: "status",
        Cell: ({ row }) => /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-500", children: row.original.status })
      },
      {
        Header: __("SEO Title", "yatra"),
        accessor: "metadata.seo_title",
        Cell: ({ row }) => {
          var _a;
          return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-500", children: ((_a = row.original.metadata) == null ? void 0 : _a.seo_title) || "" });
        }
      },
      {
        Header: __("SEO Description", "yatra"),
        accessor: "metadata.seo_description",
        Cell: ({ row }) => {
          var _a;
          return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-500", children: ((_a = row.original.metadata) == null ? void 0 : _a.seo_description) || "" });
        }
      },
      {
        Header: __("SEO Keywords", "yatra"),
        accessor: "metadata.seo_keywords",
        Cell: ({ row }) => {
          var _a;
          return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-500", children: ((_a = row.original.metadata) == null ? void 0 : _a.seo_keywords) || "" });
        }
      },
      {
        Header: __("Created At", "yatra"),
        accessor: "created_at",
        Cell: ({ row }) => /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-500", children: row.original.created_at })
      },
      {
        Header: __("Updated At", "yatra"),
        accessor: "updated_at",
        Cell: ({ row }) => /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-500", children: row.original.updated_at })
      },
      {
        Header: __("Created By", "yatra"),
        accessor: "created_by_name",
        Cell: ({ row }) => /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-500", children: row.original.created_by_name || "" })
      },
      {
        Header: __("Updated By", "yatra"),
        accessor: "updated_by_name",
        Cell: ({ row }) => /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-500", children: row.original.updated_by_name || "" })
      }
    ],
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [visibleColumns]
  );
  const toggleColumn = (columnKey) => {
    const newVisibleColumns = {
      ...visibleColumns,
      [columnKey]: !visibleColumns[columnKey]
    };
    setVisibleColumns(newVisibleColumns);
    localStorage.setItem(
      "yatra-activities-columns-v2",
      JSON.stringify(newVisibleColumns)
    );
  };
  reactExports.useEffect(() => {
    const handleClickOutside = (event) => {
      const target2 = event.target;
      if (target2.closest("[data-dropdown-trigger]") || target2.closest("[data-dropdown-content]") || target2.closest("[data-columns-trigger]") || target2.closest("[data-columns-content]")) {
        return;
      }
      setOpenDropdown(null);
      setShowColumnsDropdown(false);
    };
    if (openDropdown !== null || showColumnsDropdown) {
      document.addEventListener("click", handleClickOutside);
      return () => document.removeEventListener("click", handleClickOutside);
    }
  }, [openDropdown, showColumnsDropdown]);
  const queryParams = reactExports.useMemo(() => {
    const params = {
      page,
      per_page: 10,
      orderby: sortBy2,
      order: sortOrder
    };
    if (searchTerm) {
      params.search = searchTerm;
    }
    if (statusFilter !== "all") {
      params.status = statusFilter;
    }
    return params;
  }, [searchTerm, statusFilter, sortBy2, sortOrder, page]);
  const { data: statsData } = useQuery({
    queryKey: ["activities-stats"],
    queryFn: async () => {
      try {
        const response = await apiClient.get("/activities/stats");
        return response;
      } catch (error2) {
        return { all: 0, publish: 0, draft: 0, trash: 0 };
      }
    },
    enabled: can("yatra_view_trips")
  });
  const { data, isLoading, error } = useQuery({
    queryKey: ["activities", queryParams],
    queryFn: async () => {
      try {
        const response = await apiClient.get("/activities", {
          params: queryParams
        });
        return response;
      } catch (error2) {
        showToast(
          (error2 == null ? void 0 : error2.message) || __("Failed to load activities", "yatra"),
          "error"
        );
        throw error2;
      }
    },
    enabled: can("yatra_view_trips")
  });
  const { data: settings2 } = useQuery({
    queryKey: ["settings"],
    queryFn: async () => {
      try {
        const response = await fetchSettings();
        return response;
      } catch (error2) {
        return null;
      }
    },
    enabled: can("yatra_access_admin"),
    staleTime: 5 * 60 * 1e3
    // Cache for 5 minutes
  });
  const activities = (data == null ? void 0 : data.data) || [];
  const total = (data == null ? void 0 : data.total) || 0;
  const totalPages = Math.ceil(total / 10);
  const errorContext = getErrorContext(error);
  const statusCounts = reactExports.useMemo(() => {
    if (statsData) {
      return {
        all: statsData.all ?? 0,
        publish: statsData.publish ?? 0,
        draft: statsData.draft ?? 0,
        trash: statsData.trash ?? 0
      };
    }
    return {
      all: 0,
      publish: 0,
      draft: 0,
      trash: 0
    };
  }, [statsData]);
  const bulkMutation = useMutation({
    mutationFn: async ({
      action,
      ids
    }) => {
      return await apiClient.post("/activities/bulk", { action, ids });
    },
    onSuccess: () => {
      queryClient2.invalidateQueries({ queryKey: ["activities"] });
      queryClient2.invalidateQueries({ queryKey: ["activities-stats"] });
      showToast(__("Bulk action completed successfully", "yatra"), "success");
      setSelectedIds([]);
      setBulkAction("");
    },
    onError: (error2) => {
      showToast(
        (error2 == null ? void 0 : error2.message) || __("Failed to perform bulk action", "yatra"),
        "error"
      );
    }
  });
  const handleEdit = (activity2) => {
    var _a;
    window.location.href = `${((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=trips&tab=activities&action=edit&id=${activity2.id}`;
  };
  const handleView = async (activity2) => {
    const activitySlug = activity2.slug || "";
    const { plainUrl, prettyUrl } = buildYatraSinglePublicUrls({
      entity: "activity",
      slug: activitySlug,
      bases: settings2
    });
    if (isWordPressPlainPermalink()) {
      if (!activitySlug) {
        showToast(__("Activity slug is missing", "yatra"), "error");
        return;
      }
      window.open(plainUrl, "_blank", "noopener,noreferrer");
      return;
    }
    let apiPermalink = (activity2 == null ? void 0 : activity2.permalink) || (activity2 == null ? void 0 : activity2.url);
    if (!apiPermalink && activity2.id) {
      try {
        const detail = await apiClient.get(`/activities/${activity2.id}`);
        apiPermalink = (detail == null ? void 0 : detail.permalink) || (detail == null ? void 0 : detail.url) || apiPermalink;
      } catch (e) {
      }
    }
    if (apiPermalink) {
      window.open(apiPermalink, "_blank", "noopener,noreferrer");
      return;
    }
    if (!activitySlug) {
      showToast(__("Activity slug is missing", "yatra"), "error");
      return;
    }
    window.open(prettyUrl, "_blank", "noopener,noreferrer");
  };
  const handlePermanentDelete = (activity2) => {
    setPermanentDeleteConfirm({ isOpen: true, activity: activity2 });
  };
  const confirmPermanentDelete = () => {
    if (permanentDeleteConfirm.activity) {
      bulkMutation.mutate({
        action: "delete",
        ids: [permanentDeleteConfirm.activity.id]
      });
      setPermanentDeleteConfirm({ isOpen: false, activity: null });
    }
  };
  const confirmIndividualAction = () => {
    if (individualActionConfirm.activity) {
      const action = individualActionConfirm.action === "restore" ? "restore" : "trash";
      bulkMutation.mutate({
        action,
        ids: [individualActionConfirm.activity.id]
      });
      setIndividualActionConfirm({ isOpen: false, action: "", activity: null });
    }
  };
  const handleCreateActivity = () => {
    var _a;
    window.location.href = `${((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=trips&tab=activities&action=create`;
  };
  reactExports.useEffect(() => {
    setSelectedIds(
      (prev) => prev.filter(
        (id) => activities.some((activity2) => activity2.id === id)
      )
    );
  }, [activities]);
  const handleBulkApply = () => {
    if (!bulkAction) {
      showToast(__("Select a bulk action first.", "yatra"), "warning");
      return;
    }
    if (selectedIds.length === 0) {
      showToast(__("Select at least one activity.", "yatra"), "warning");
      return;
    }
    bulkMutation.mutate({ action: bulkAction, ids: selectedIds });
  };
  const viewFilters = [
    { key: "all", label: __("All", "yatra"), count: statusCounts.all ?? 0 },
    {
      key: "publish",
      label: __("Published", "yatra"),
      count: statusCounts.publish ?? 0
    },
    {
      key: "draft",
      label: __("Draft", "yatra"),
      count: statusCounts.draft ?? 0
    },
    {
      key: "trash",
      label: __("Trash", "yatra"),
      count: statusCounts.trash ?? 0
    }
  ];
  const handleResetFilters = () => {
    setSearchTerm("");
    setStatusFilter("all");
    setSortBy("name");
    setSortOrder("asc");
    setPage(1);
    setSelectedIds([]);
    setBulkAction("");
  };
  const handleSort = (field) => {
    if (sortBy2 === field) {
      setSortOrder(sortOrder === "asc" ? "desc" : "asc");
    } else {
      setSortBy(field);
      setSortOrder(field === "id" ? "desc" : "asc");
    }
  };
  const getSortIcon = (field) => {
    if (sortBy2 !== field) {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowUpDown, { className: "w-3.5 h-3.5 ml-1 text-gray-400" });
    }
    return sortOrder === "asc" ? /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowUp, { className: "w-3.5 h-3.5 ml-1 text-gray-600 dark:text-gray-300" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowDown, { className: "w-3.5 h-3.5 ml-1 text-gray-600 dark:text-gray-300" });
  };
  const hasFilters = searchTerm || statusFilter !== "all" || sortBy2 !== "id" || sortOrder !== "desc";
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      ConfirmationDialog,
      {
        isOpen: permanentDeleteConfirm.isOpen,
        onClose: () => setPermanentDeleteConfirm({ isOpen: false, activity: null }),
        onConfirm: confirmPermanentDelete,
        title: __("Delete Activity Permanently", "yatra"),
        message: permanentDeleteConfirm.activity ? __(
          'Are you sure you want to permanently delete "{name}"? This action cannot be undone.',
          "yatra"
        ).replace("{name}", permanentDeleteConfirm.activity.name) : __(
          "Are you sure you want to permanently delete this activity? This action cannot be undone.",
          "yatra"
        ),
        confirmText: __("Delete Permanently", "yatra"),
        cancelText: __("Cancel", "yatra"),
        variant: "danger",
        isLoading: bulkMutation.isPending
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      ConfirmationDialog,
      {
        isOpen: individualActionConfirm.isOpen,
        onClose: () => setIndividualActionConfirm({
          isOpen: false,
          action: "",
          activity: null
        }),
        onConfirm: confirmIndividualAction,
        title: individualActionConfirm.action === "trash" ? __("Move to Trash", "yatra") : __("Restore Activity", "yatra"),
        message: individualActionConfirm.activity ? individualActionConfirm.action === "trash" ? __(
          'Are you sure you want to move "{name}" to trash?',
          "yatra"
        ).replace("{name}", individualActionConfirm.activity.name) : __(
          'Are you sure you want to restore "{name}"?',
          "yatra"
        ).replace("{name}", individualActionConfirm.activity.name) : individualActionConfirm.action === "trash" ? __(
          "Are you sure you want to move this activity to trash?",
          "yatra"
        ) : __("Are you sure you want to restore this activity?", "yatra"),
        confirmText: individualActionConfirm.action === "trash" ? __("Move to Trash", "yatra") : __("Restore", "yatra"),
        cancelText: __("Cancel", "yatra"),
        variant: "warning",
        isLoading: bulkMutation.isPending
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      PageHeader,
      {
        title: __("Activities", "yatra"),
        description: __(
          "Manage your travel activities and experiences",
          "yatra"
        ),
        actionCapability: "yatra_edit_trips",
        actions: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Button,
          {
            onClick: handleCreateActivity,
            className: "flex items-center gap-2",
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Plus, { className: "w-4 h-4" }),
              __("Add New Activity", "yatra")
            ]
          }
        )
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-3", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
      SearchFilterToolbar,
      {
        searchTerm,
        onSearchChange: setSearchTerm,
        statusFilter,
        onStatusChange: (value) => {
          setStatusFilter(value);
          setPage(1);
          setSelectedIds([]);
          setBulkAction("");
        },
        statusOptions: [
          { value: "all", label: __("All Status", "yatra") },
          { value: "publish", label: __("Published", "yatra") },
          { value: "draft", label: __("Draft", "yatra") },
          { value: "trash", label: __("Trash", "yatra") }
        ],
        sortBy: sortBy2,
        onSortByChange: setSortBy,
        sortOrder,
        onSortOrderChange: setSortOrder,
        sortOptions: [
          { value: "name", label: __("Name", "yatra") },
          { value: "status", label: __("Status", "yatra") },
          { value: "created_at", label: __("Created At", "yatra") },
          { value: "updated_at", label: __("Updated At", "yatra") }
        ],
        onResetFilters: handleResetFilters,
        hasFilters: !!hasFilters,
        placeholder: __("Search activities...", "yatra")
      }
    ) }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_view_trips", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
      !error && /* @__PURE__ */ jsxRuntimeExports.jsx(
        BulkActionToolbar,
        {
          selectedIds,
          bulkAction,
          setBulkAction,
          onApply: handleBulkApply,
          onClearSelection: () => setSelectedIds([]),
          statusFilter,
          setStatusFilter: (value) => {
            setStatusFilter(value);
            setPage(1);
            setSelectedIds([]);
            setBulkAction("");
          },
          statusOptions: viewFilters,
          showColumnsDropdown,
          setShowColumnsDropdown,
          columnOptions: [
            {
              key: "name",
              label: __("Activity", "yatra"),
              visible: visibleColumns.name
            },
            {
              key: "description",
              label: __("Description", "yatra"),
              visible: visibleColumns.description
            },
            {
              key: "trips",
              label: __("Trips", "yatra"),
              visible: visibleColumns.trips
            },
            {
              key: "seo_title",
              label: __("SEO Title", "yatra"),
              visible: visibleColumns.seo_title
            },
            {
              key: "seo_description",
              label: __("SEO Description", "yatra"),
              visible: visibleColumns.seo_description
            },
            {
              key: "seo_keywords",
              label: __("SEO Keywords", "yatra"),
              visible: visibleColumns.seo_keywords
            },
            {
              key: "status",
              label: __("Status", "yatra"),
              visible: visibleColumns.status
            },
            {
              key: "created_at",
              label: __("Created Date", "yatra"),
              visible: visibleColumns.created_at
            },
            {
              key: "updated_at",
              label: __("Updated Date", "yatra"),
              visible: visibleColumns.updated_at
            },
            {
              key: "created_by_name",
              label: __("Created By", "yatra"),
              visible: visibleColumns.created_by_name
            },
            {
              key: "updated_by_name",
              label: __("Updated By", "yatra"),
              visible: visibleColumns.updated_by_name
            }
          ],
          onToggleColumn: toggleColumn,
          bulkMutationPending: bulkMutation.isPending,
          totalItems: activities.length,
          bulkActionOptions: getDefaultBulkStatusOptions(statusFilter)
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { className: "overflow-visible", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-0 overflow-visible", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        Table,
        {
          data: activities,
          columns: [
            {
              key: "name",
              label: __("Activity", "yatra"),
              sortable: true,
              visible: visibleColumns.name,
              render: (activity2) => {
                var _a;
                return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-10 h-10 rounded-lg bg-blue-100 dark:bg-blue-900/30 flex items-center justify-center flex-shrink-0", children: activity2.icon ? activity2.icon.type === "image" ? /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "img",
                    {
                      src: activity2.icon.value,
                      alt: activity2.name,
                      className: "w-full h-full object-cover rounded-lg"
                    }
                  ) : /* @__PURE__ */ jsxRuntimeExports.jsx(
                    IconSelector,
                    {
                      iconName: activity2.icon.value,
                      provider: activity2.icon.provider ?? "yatra",
                      className: "w-5 h-5 text-blue-600 dark:text-blue-400"
                    }
                  ) : /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-5 h-5 text-blue-600 dark:text-blue-400 flex items-center justify-center text-xs font-semibold", children: activity2.name.charAt(0).toUpperCase() }) }),
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1", children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx(
                        "a",
                        {
                          href: `${((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=trips&tab=activities&action=edit&id=${activity2.id}`,
                          className: "font-medium text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 hover:underline transition-colors cursor-pointer",
                          children: activity2.name
                        }
                      ),
                      can("yatra_view_trips") && activity2.status !== "trash" && /* @__PURE__ */ jsxRuntimeExports.jsx(
                        "button",
                        {
                          type: "button",
                          onClick: (e) => {
                            e.stopPropagation();
                            handleView(activity2);
                          },
                          className: "ml-1 inline-flex items-center justify-center rounded-full p-1 text-gray-400 hover:text-gray-700 hover:bg-gray-100 dark:text-gray-400 dark:hover:text-white dark:hover:bg-gray-800",
                          title: __(
                            "View activity in new tab",
                            "yatra"
                          ),
                          children: /* @__PURE__ */ jsxRuntimeExports.jsx(ExternalLink, { className: "w-3.5 h-3.5" })
                        }
                      )
                    ] }),
                    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-sm text-gray-500 dark:text-gray-400 flex items-center gap-2", children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: activity2.slug }),
                      /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-[11px] text-gray-400 dark:text-gray-500", children: [
                        "(",
                        __("ID:", "yatra"),
                        " ",
                        activity2.id,
                        ")"
                      ] })
                    ] })
                  ] })
                ] });
              }
            },
            {
              key: "trips",
              label: __("Trips", "yatra"),
              sortable: false,
              visible: visibleColumns.trips,
              render: (activity2) => /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300", children: typeof activity2.trip_count === "number" ? activity2.trip_count : 0 })
            },
            {
              key: "description",
              label: __("Description", "yatra"),
              visible: visibleColumns.description,
              render: (activity2) => /* @__PURE__ */ jsxRuntimeExports.jsx(
                "span",
                {
                  className: `block max-w-[300px] truncate ${activity2.status === "trash" || statusFilter === "trash" ? "text-gray-400 dark:text-gray-600" : "text-gray-600 dark:text-gray-400"}`,
                  title: activity2.description || "",
                  children: activity2.description || __("No description", "yatra")
                }
              )
            },
            {
              key: "seo_title",
              label: __("SEO Title", "yatra"),
              visible: visibleColumns.seo_title,
              render: (activity2) => {
                var _a;
                return /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "span",
                  {
                    className: activity2.status === "trash" || statusFilter === "trash" ? "text-gray-400 dark:text-gray-600" : "text-gray-600 dark:text-gray-400",
                    children: ((_a = activity2.metadata) == null ? void 0 : _a.seo_title) || __("Not set", "yatra")
                  }
                );
              }
            },
            {
              key: "seo_description",
              label: __("SEO Description", "yatra"),
              visible: visibleColumns.seo_description,
              render: (activity2) => {
                var _a, _b;
                return /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "span",
                  {
                    className: activity2.status === "trash" || statusFilter === "trash" ? "text-gray-400 dark:text-gray-600" : "text-gray-600 dark:text-gray-400",
                    title: ((_a = activity2.metadata) == null ? void 0 : _a.seo_description) || "",
                    children: ((_b = activity2.metadata) == null ? void 0 : _b.seo_description) ? activity2.metadata.seo_description.length > 50 ? activity2.metadata.seo_description.substring(
                      0,
                      50
                    ) + "..." : activity2.metadata.seo_description : __("Not set", "yatra")
                  }
                );
              }
            },
            {
              key: "seo_keywords",
              label: __("SEO Keywords", "yatra"),
              visible: visibleColumns.seo_keywords,
              render: (activity2) => {
                var _a, _b;
                return /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "span",
                  {
                    className: activity2.status === "trash" || statusFilter === "trash" ? "text-gray-400 dark:text-gray-600" : "text-gray-600 dark:text-gray-400",
                    title: ((_a = activity2.metadata) == null ? void 0 : _a.seo_keywords) || "",
                    children: ((_b = activity2.metadata) == null ? void 0 : _b.seo_keywords) ? activity2.metadata.seo_keywords.length > 30 ? activity2.metadata.seo_keywords.substring(0, 30) + "..." : activity2.metadata.seo_keywords : __("Not set", "yatra")
                  }
                );
              }
            },
            {
              key: "status",
              label: __("Status", "yatra"),
              sortable: true,
              visible: visibleColumns.status,
              render: (activity2) => /* @__PURE__ */ jsxRuntimeExports.jsx(
                "span",
                {
                  className: `inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${activity2.status === "trash" || statusFilter === "trash" ? "bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400" : activity2.status === "publish" ? "bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400" : "bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400"}`,
                  children: activity2.status === "trash" || statusFilter === "trash" ? __("Trash", "yatra") : activity2.status === "publish" ? __("Published", "yatra") : __("Draft", "yatra")
                }
              )
            },
            {
              key: "created_at",
              label: __("Created Date", "yatra"),
              sortable: true,
              visible: visibleColumns.created_at,
              render: (activity2) => /* @__PURE__ */ jsxRuntimeExports.jsx(
                "span",
                {
                  className: activity2.status === "trash" || statusFilter === "trash" ? "text-gray-400 dark:text-gray-600" : "text-gray-600 dark:text-gray-400",
                  children: new Date(activity2.created_at).toLocaleDateString(
                    "en-US",
                    {
                      year: "numeric",
                      month: "short",
                      day: "numeric",
                      hour: "2-digit",
                      minute: "2-digit"
                    }
                  )
                }
              )
            },
            {
              key: "updated_at",
              label: __("Updated Date", "yatra"),
              sortable: true,
              visible: visibleColumns.updated_at,
              render: (activity2) => /* @__PURE__ */ jsxRuntimeExports.jsx(
                "span",
                {
                  className: activity2.status === "trash" || statusFilter === "trash" ? "text-gray-400 dark:text-gray-600" : "text-gray-600 dark:text-gray-400",
                  children: new Date(activity2.updated_at).toLocaleDateString(
                    "en-US",
                    {
                      year: "numeric",
                      month: "short",
                      day: "numeric",
                      hour: "2-digit",
                      minute: "2-digit"
                    }
                  )
                }
              )
            },
            {
              key: "created_by_name",
              label: __("Created By", "yatra"),
              visible: visibleColumns.created_by_name,
              render: (activity2) => /* @__PURE__ */ jsxRuntimeExports.jsx(
                "span",
                {
                  className: activity2.status === "trash" || statusFilter === "trash" ? "text-gray-400 dark:text-gray-600" : "text-gray-600 dark:text-gray-400",
                  children: activity2.created_by_name || __("Unknown", "yatra")
                }
              )
            },
            {
              key: "updated_by_name",
              label: __("Updated By", "yatra"),
              visible: visibleColumns.updated_by_name,
              render: (activity2) => /* @__PURE__ */ jsxRuntimeExports.jsx(
                "span",
                {
                  className: activity2.status === "trash" || statusFilter === "trash" ? "text-gray-400 dark:text-gray-600" : "text-gray-600 dark:text-gray-400",
                  children: activity2.updated_by_name || __("Unknown", "yatra")
                }
              )
            }
          ],
          actions: [
            {
              key: "view",
              label: __("View", "yatra"),
              icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Eye, { className: "w-4 h-4" }),
              onClick: (activity2) => {
                var _a;
                const activityUrl = `${((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || ""}/activity/${activity2.slug}`;
                window.open(activityUrl, "_blank");
              },
              condition: () => true
              // Always show view action
            },
            {
              key: "edit",
              label: __("Edit", "yatra"),
              icon: /* @__PURE__ */ jsxRuntimeExports.jsx(PenSquare, { className: "w-4 h-4" }),
              onClick: handleEdit,
              condition: () => can("yatra_edit_trips")
            },
            {
              key: "restore",
              label: __("Restore", "yatra"),
              icon: /* @__PURE__ */ jsxRuntimeExports.jsx(RotateCcw, { className: "w-4 h-4" }),
              onClick: (activity2) => {
                bulkMutation.mutate({
                  action: "restore",
                  ids: [activity2.id]
                });
              },
              condition: (activity2) => (activity2.status === "trash" || statusFilter === "trash") && can("yatra_edit_trips")
            },
            {
              key: "trash",
              label: __("Move to Trash", "yatra"),
              icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "w-4 h-4" }),
              onClick: (activity2) => {
                bulkMutation.mutate({
                  action: "trash",
                  ids: [activity2.id]
                });
              },
              condition: (activity2) => activity2.status !== "trash" && statusFilter !== "trash" && can("yatra_edit_trips")
            },
            {
              key: "delete",
              label: __("Delete Permanently", "yatra"),
              icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "w-4 h-4" }),
              onClick: handlePermanentDelete,
              condition: (activity2) => (activity2.status === "trash" || statusFilter === "trash") && can("yatra_delete_trips"),
              variant: "destructive"
            }
          ],
          isLoading,
          isError: !!error,
          errorText: __("Error loading activities", "yatra"),
          errorDescription: __(
            "We couldn’t connect to the activities service. Please refresh or try again shortly.",
            "We couldn’t connect to the activities service. Please refresh or try again shortly."
          ),
          onRetry: () => queryClient2.invalidateQueries({ queryKey: ["activities"] }),
          errorDetails: errorContext.details,
          errorRequestInfo: errorContext.requestInfo,
          emptyText: __("No activities found", "yatra"),
          emptyDescription: hasFilters ? __(
            "Try adjusting your filters to see more results.",
            "yatra"
          ) : __(
            "Get started by creating your first activity.",
            "yatra"
          ),
          onCreateClick: can("yatra_edit_trips") ? handleCreateActivity : void 0,
          onSort: handleSort,
          getSortIcon,
          selectedItemIds: selectedIds,
          onSelectItem: (id, checked) => {
            if (checked) {
              setSelectedIds([...selectedIds, id]);
            } else {
              setSelectedIds(
                selectedIds.filter((selectedId) => selectedId !== id)
              );
            }
          },
          onSelectAll: (checked) => {
            if (checked) {
              setSelectedIds(activities.map((a2) => a2.id));
            } else {
              setSelectedIds([]);
            }
          },
          isAllSelected: activities.length > 0 && selectedIds.length === activities.length,
          getItemId: (activity2) => activity2.id,
          getItemStatus: (activity2) => activity2.status,
          statusFilter,
          skeletonRows: 5
        },
        `activities-table-${JSON.stringify(visibleColumns)}`
      ) }) })
    ] }) }),
    total > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-4", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
      Pagination,
      {
        currentPage: page,
        totalPages,
        totalItems: total,
        itemsPerPage: 10,
        onPageChange: (newPage) => setPage(newPage),
        itemName: __("activities", "yatra")
      }
    ) })
  ] });
};
function prepareWordPressMediaFrameOpen() {
  var _a;
  const active = document.activeElement;
  if (active instanceof HTMLElement) {
    active.blur();
  }
  (_a = document.getElementById("wpwrap")) == null ? void 0 : _a.removeAttribute("aria-hidden");
}
const useWordPressMedia = (options = {}) => {
  const {
    title = "Select or Upload Image",
    buttonText = "Use this image",
    multiple = false,
    library = { type: "image" }
  } = options;
  const openMediaLibrary = reactExports.useCallback(
    (callback) => {
      const getWpMedia = () => {
        if (typeof window.yatraWpMedia === "function") {
          return window.yatraWpMedia;
        }
        try {
          const wpMedia2 = new Function(
            'return (typeof wp !== "undefined" && typeof wp.media === "function") ? wp.media : null'
          )();
          if (wpMedia2) {
            return wpMedia2;
          }
        } catch (e) {
        }
        try {
          if (typeof window.wp === "object" && window.wp !== null && typeof window.wp.media === "function") {
            return window.wp.media;
          }
        } catch (e) {
        }
        try {
          const wpMedia = eval(
            '(typeof wp !== "undefined" && typeof wp.media === "function") ? wp.media : null'
          );
          if (wpMedia) {
            return wpMedia;
          }
        } catch (e) {
        }
        return null;
      };
      const ensureMediaLibrary = (retries = 50, delay = 100) => {
        return new Promise((resolve, reject) => {
          const checkMedia = () => {
            const wpMedia2 = getWpMedia();
            if (wpMedia2 && typeof wpMedia2 === "function") {
              resolve(wpMedia2);
              return;
            }
            if (retries > 0) {
              retries--;
              setTimeout(checkMedia, delay);
            } else {
              reject(
                new Error(
                  __(
                    "WordPress media library is not available. Please refresh the page.",
                    "yatra"
                  )
                )
              );
            }
          };
          if (typeof window.jQuery !== "undefined") {
            window.jQuery(document).ready(() => {
              setTimeout(checkMedia, 500);
            });
          } else if (document.readyState === "complete" || document.readyState === "interactive") {
            setTimeout(checkMedia, 500);
          } else {
            document.addEventListener("DOMContentLoaded", () => {
              setTimeout(checkMedia, 500);
            });
            setTimeout(checkMedia, 1e3);
          }
        });
      };
      ensureMediaLibrary().then((wpMedia2) => {
        const frame = wpMedia2({
          title,
          button: {
            text: buttonText
          },
          multiple,
          library
        });
        if (!frame) {
          throw new Error(__("Failed to create media frame.", "yatra"));
        }
        frame.on("select", () => {
          const selection = frame.state().get("selection");
          const attachments = selection.toJSON();
          if (multiple) {
            const formattedAttachments = attachments.map(
              (attachment) => ({
                id: attachment.id,
                url: attachment.url,
                alt: attachment.alt || "",
                title: attachment.title || "",
                caption: attachment.caption || "",
                description: attachment.description || "",
                sizes: attachment.sizes || {}
              })
            );
            callback(formattedAttachments);
          } else {
            const attachment = attachments[0];
            if (attachment) {
              const formattedAttachment = {
                id: attachment.id,
                url: attachment.url,
                alt: attachment.alt || "",
                title: attachment.title || "",
                caption: attachment.caption || "",
                description: attachment.description || "",
                sizes: attachment.sizes || {}
              };
              callback(formattedAttachment);
            }
          }
        });
        prepareWordPressMediaFrameOpen();
        frame.open();
      }).catch((error) => {
        console.error("Error opening WordPress media library:", error);
        alert(
          error.message || __(
            "WordPress media library is not available. Please refresh the page.",
            "yatra"
          )
        );
      });
    },
    [title, buttonText, multiple, library]
  );
  return { openMediaLibrary };
};
const categoryLabels = {
  activity: "Activities",
  travel: "Travel",
  food: "Food & Dining",
  accommodation: "Accommodation",
  transport: "Transportation",
  general: "General",
  media: "Media"
};
const IconPicker = ({
  value,
  onChange,
  label,
  helpText,
  error,
  required = false,
  allowImageUpload = true,
  allowIconSelection = true,
  size = "md",
  className = ""
}) => {
  const [isOpen, setIsOpen] = reactExports.useState(false);
  const [activeTab, setActiveTab] = reactExports.useState("icons");
  const [iconLibrary, setIconLibrary] = reactExports.useState("yatra");
  const [searchTerm, setSearchTerm] = reactExports.useState("");
  const [selectedCategory, setSelectedCategory] = reactExports.useState("all");
  const yatraIconOptions = reactExports.useMemo(() => getIconOptions(), []);
  const [imagePreview, setImagePreview] = reactExports.useState(
    (value == null ? void 0 : value.type) === "image" ? value.value.startsWith("http") ? value.value : null : null
  );
  reactExports.useEffect(() => {
    var _a;
    if ((value == null ? void 0 : value.type) === "image") {
      if (value.value.startsWith("http://") || value.value.startsWith("https://")) {
        setImagePreview(value.value);
      } else if (/^\d+$/.test(value.value) && ((_a = window.yatraAdmin) == null ? void 0 : _a.apiUrl)) {
        const apiUrl = window.yatraAdmin.apiUrl.replace("/yatra/v1", "");
        fetch(`${apiUrl}/wp/v2/media/${value.value}`).then((res) => res.json()).then((data) => {
          if (data && data.source_url) {
            setImagePreview(data.source_url);
          }
        }).catch(() => {
        });
      }
    } else {
      setImagePreview(null);
    }
  }, [value]);
  const { openMediaLibrary: openMediaLibrary2 } = useWordPressMedia({
    title: __("Select or Upload Image", "yatra"),
    buttonText: __("Use this image", "yatra"),
    multiple: false,
    library: { type: "image" }
  });
  const sizeClasses2 = {
    sm: "w-8 h-8",
    md: "w-12 h-12",
    lg: "w-16 h-16"
  };
  const iconSizeClasses = {
    sm: "w-4 h-4",
    md: "w-6 h-6",
    lg: "w-8 h-8"
  };
  const filteredYatraIcons = reactExports.useMemo(() => {
    const q = searchTerm.toLowerCase();
    return yatraIconOptions.filter((icon) => {
      const matchesSearch = icon.label.toLowerCase().includes(q) || icon.name.toLowerCase().includes(q);
      const matchesCategory = selectedCategory === "all" || icon.category === selectedCategory;
      return matchesSearch && matchesCategory;
    });
  }, [yatraIconOptions, searchTerm, selectedCategory]);
  const faSourceList = iconLibrary === "fa-regular" ? FA_FREE_REGULAR_PICKER : FA_FREE_SOLID_PICKER;
  const filteredFaIcons = reactExports.useMemo(() => {
    const q = searchTerm.toLowerCase();
    return faSourceList.filter(
      (row) => row.label.toLowerCase().includes(q) || row.name.toLowerCase().includes(q)
    );
  }, [faSourceList, searchTerm]);
  const categories = reactExports.useMemo(
    () => [
      "all",
      ...Array.from(new Set(yatraIconOptions.map((icon) => icon.category)))
    ],
    [yatraIconOptions]
  );
  const selectYatraIcon = (name) => {
    onChange({ type: "icon", value: name, provider: "yatra" });
    setIsOpen(false);
    setSearchTerm("");
  };
  const selectFaIcon = (name, style) => {
    onChange({ type: "icon", value: name, provider: style });
    setIsOpen(false);
    setSearchTerm("");
  };
  const handleWordPressMediaSelect = reactExports.useCallback(() => {
    openMediaLibrary2((attachment) => {
      if (attachment && !Array.isArray(attachment)) {
        const attachmentId = String(attachment.id);
        setImagePreview(attachment.url);
        onChange({ type: "image", value: attachmentId });
        setIsOpen(false);
      }
    });
  }, [openMediaLibrary2, onChange]);
  const handleRemoveImage = () => {
    setImagePreview(null);
    onChange(null);
  };
  const handleImageUrlChange = (url) => {
    if (url.trim()) {
      setImagePreview(url);
      onChange({ type: "image", value: url.trim() });
    } else {
      handleRemoveImage();
    }
  };
  const selectionSummary = () => {
    if (!value) {
      return __("Select Icon or Upload Image", "yatra");
    }
    if (value.type === "image") {
      return __("Custom Image", "yatra");
    }
    const p = value.provider ?? "yatra";
    if (p === "fa-solid") {
      return `${__("Font Awesome Solid", "yatra")}: ${value.value}`;
    }
    if (p === "fa-regular") {
      return `${__("Font Awesome Regular", "yatra")}: ${value.value}`;
    }
    const meta = yatraIconOptions.find((o) => o.name === value.value);
    return `${__("Yatra", "yatra")}: ${(meta == null ? void 0 : meta.label) || value.value}`;
  };
  const renderIconPreview = () => {
    if (!value || value.type !== "icon") {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(Image, { className: `${iconSizeClasses[size]} text-gray-400` });
    }
    const p = value.provider ?? "yatra";
    if (p === "fa-solid" || p === "fa-regular") {
      const prefix2 = p === "fa-regular" ? "fa-regular" : "fa-solid";
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        "i",
        {
          className: `${prefix2} fa-${value.value} ${iconSizeClasses[size]} text-gray-700 dark:text-gray-300 inline-flex items-center justify-center`,
          "aria-hidden": "true"
        }
      );
    }
    const opt = yatraIconOptions.find((o) => o.name === value.value);
    if (opt == null ? void 0 : opt.svg) {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        "span",
        {
          className: `inline-flex items-center justify-center ${iconSizeClasses[size]} text-gray-700 dark:text-gray-300 [&>svg]:w-full [&>svg]:h-full`,
          dangerouslySetInnerHTML: { __html: opt.svg }
        }
      );
    }
    return /* @__PURE__ */ jsxRuntimeExports.jsx(Image, { className: `${iconSizeClasses[size]} text-gray-400` });
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: `space-y-2 ${className}`, children: [
    label && /* @__PURE__ */ jsxRuntimeExports.jsxs("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300", children: [
      label,
      " ",
      required && /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
    ] }),
    helpText && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400", children: helpText }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        "div",
        {
          className: `${sizeClasses2[size]} rounded-lg border-2 border-gray-300 dark:border-gray-600 flex items-center justify-center bg-gray-50 dark:bg-gray-800 overflow-hidden`,
          children: (value == null ? void 0 : value.type) === "image" && imagePreview ? /* @__PURE__ */ jsxRuntimeExports.jsx(
            "img",
            {
              src: imagePreview,
              alt: __("Selected", "yatra"),
              className: "w-full h-full object-cover"
            }
          ) : renderIconPreview()
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex-1", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        Button,
        {
          type: "button",
          variant: "outline",
          onClick: () => setIsOpen(!isOpen),
          className: "w-full justify-start",
          children: selectionSummary()
        }
      ) }),
      value && /* @__PURE__ */ jsxRuntimeExports.jsx(
        Button,
        {
          type: "button",
          variant: "ghost",
          size: "icon",
          onClick: () => {
            onChange(null);
            setImagePreview(null);
          },
          className: "text-red-600 hover:text-red-700 hover:bg-red-50 dark:hover:bg-red-900/20",
          children: /* @__PURE__ */ jsxRuntimeExports.jsx(X, { className: "w-4 h-4" })
        }
      )
    ] }),
    error && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-red-600 dark:text-red-400", children: error }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs(
      Modal,
      {
        isOpen,
        onClose: () => setIsOpen(false),
        title: __("Select Icon or Upload Image", "yatra"),
        size: "xl",
        showCloseButton: true,
        customZIndex: 99999,
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex border-b border-gray-200 dark:border-gray-700", children: [
            allowIconSelection && /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "button",
              {
                type: "button",
                onClick: () => setActiveTab("icons"),
                className: `flex-1 px-4 py-3 text-sm font-medium transition-colors ${activeTab === "icons" ? "border-b-2 border-blue-600 text-blue-600 dark:text-blue-400 bg-blue-50 dark:bg-blue-900/20" : "text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white"}`,
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(Sparkles, { className: "w-4 h-4 inline mr-2" }),
                  __("Icons", "yatra")
                ]
              }
            ),
            allowImageUpload && /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "button",
              {
                type: "button",
                onClick: () => setActiveTab("upload"),
                className: `flex-1 px-4 py-3 text-sm font-medium transition-colors ${activeTab === "upload" ? "border-b-2 border-blue-600 text-blue-600 dark:text-blue-400 bg-blue-50 dark:bg-blue-900/20" : "text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white"}`,
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(Upload, { className: "w-4 h-4 inline mr-2" }),
                  __("Upload Image", "yatra")
                ]
              }
            )
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "p-4 max-h-[60vh] overflow-y-auto", children: [
            activeTab === "icons" && allowIconSelection && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-4", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-wrap gap-2 border-b border-gray-100 dark:border-gray-800 pb-3", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Badge,
                  {
                    variant: iconLibrary === "yatra" ? "info" : "outline",
                    className: "cursor-pointer",
                    onClick: () => setIconLibrary("yatra"),
                    children: __("Yatra library", "yatra")
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Badge,
                  {
                    variant: iconLibrary === "fa-solid" ? "info" : "outline",
                    className: "cursor-pointer",
                    onClick: () => setIconLibrary("fa-solid"),
                    children: __("Font Awesome Solid", "yatra")
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Badge,
                  {
                    variant: iconLibrary === "fa-regular" ? "info" : "outline",
                    className: "cursor-pointer",
                    onClick: () => setIconLibrary("fa-regular"),
                    children: __("Font Awesome Regular", "yatra")
                  }
                )
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Search, { className: "absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Input,
                  {
                    type: "text",
                    placeholder: __("Search icons...", "yatra"),
                    value: searchTerm,
                    onChange: (e) => setSearchTerm(e.target.value),
                    className: "pl-9"
                  }
                )
              ] }),
              (iconLibrary === "fa-solid" || iconLibrary === "fa-regular") && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400", children: __(
                "Tip: use search to filter the full Font Awesome Free library (1000+ solid, 150+ regular).",
                "yatra"
              ) }),
              iconLibrary === "yatra" && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex flex-wrap gap-2", children: categories.map((category) => /* @__PURE__ */ jsxRuntimeExports.jsx(
                Badge,
                {
                  variant: selectedCategory === category ? "info" : "outline",
                  className: "cursor-pointer",
                  onClick: () => setSelectedCategory(category),
                  children: category === "all" ? __("All", "yatra") : categoryLabels[category] || category
                },
                category
              )) }),
              iconLibrary === "yatra" && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid grid-cols-6 sm:grid-cols-8 md:grid-cols-10 gap-3", children: filteredYatraIcons.map((icon) => {
                const isSelected = (value == null ? void 0 : value.type) === "icon" && (value.provider ?? "yatra") === "yatra" && value.value === icon.name;
                return /* @__PURE__ */ jsxRuntimeExports.jsxs(
                  "button",
                  {
                    type: "button",
                    onClick: () => selectYatraIcon(icon.name),
                    className: `relative p-3 rounded-lg border-2 transition-all hover:border-blue-500 hover:bg-blue-50 dark:hover:bg-blue-900/20 ${isSelected ? "border-blue-600 bg-blue-50 dark:bg-blue-900/20" : "border-gray-200 dark:border-gray-700"}`,
                    title: icon.label,
                    children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx(
                        "span",
                        {
                          className: "w-6 h-6 mx-auto text-gray-700 dark:text-gray-300 flex items-center justify-center [&>svg]:w-6 [&>svg]:h-6",
                          dangerouslySetInnerHTML: { __html: icon.svg }
                        }
                      ),
                      isSelected && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "absolute top-1 right-1 bg-blue-600 rounded-full p-0.5", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Check, { className: "w-3 h-3 text-white" }) })
                    ]
                  },
                  icon.name
                );
              }) }),
              (iconLibrary === "fa-solid" || iconLibrary === "fa-regular") && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid grid-cols-6 sm:grid-cols-8 md:grid-cols-10 gap-3", children: filteredFaIcons.map((row) => {
                const isSelected = (value == null ? void 0 : value.type) === "icon" && value.provider === row.style && value.value === row.name;
                return /* @__PURE__ */ jsxRuntimeExports.jsxs(
                  "button",
                  {
                    type: "button",
                    onClick: () => selectFaIcon(row.name, row.style),
                    className: `relative p-3 rounded-lg border-2 transition-all hover:border-blue-500 hover:bg-blue-50 dark:hover:bg-blue-900/20 ${isSelected ? "border-blue-600 bg-blue-50 dark:bg-blue-900/20" : "border-gray-200 dark:border-gray-700"}`,
                    title: row.label,
                    children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx(
                        "i",
                        {
                          className: `${row.style} fa-${row.name} w-6 h-6 mx-auto text-gray-700 dark:text-gray-300 inline-flex items-center justify-center`,
                          "aria-hidden": "true"
                        }
                      ),
                      isSelected && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "absolute top-1 right-1 bg-blue-600 rounded-full p-0.5", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Check, { className: "w-3 h-3 text-white" }) })
                    ]
                  },
                  `${row.style}-${row.name}`
                );
              }) }),
              iconLibrary === "yatra" && filteredYatraIcons.length === 0 && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-center py-8 text-gray-500 dark:text-gray-400", children: __("No icons found", "yatra") }),
              (iconLibrary === "fa-solid" || iconLibrary === "fa-regular") && filteredFaIcons.length === 0 && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-center py-8 text-gray-500 dark:text-gray-400", children: __("No icons found", "yatra") })
            ] }),
            activeTab === "upload" && allowImageUpload && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-6 p-2", children: imagePreview ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-4", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "relative group", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative overflow-hidden rounded-xl border-2 border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "img",
                {
                  src: imagePreview,
                  alt: __("Preview", "yatra"),
                  className: "w-full h-64 object-contain"
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-3", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs(
                  Button,
                  {
                    type: "button",
                    variant: "outline",
                    size: "sm",
                    onClick: handleWordPressMediaSelect,
                    className: "bg-white/90 hover:bg-white text-gray-900 border-white",
                    children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx(Upload, { className: "w-4 h-4 mr-2" }),
                      __("Change Image", "yatra")
                    ]
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsxs(
                  Button,
                  {
                    type: "button",
                    variant: "destructive",
                    size: "sm",
                    onClick: handleRemoveImage,
                    className: "bg-red-500/90 hover:bg-red-600",
                    children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx(X, { className: "w-4 h-4 mr-2" }),
                      __("Remove", "yatra")
                    ]
                  }
                )
              ] })
            ] }) }) }) : /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-4", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "div",
                {
                  onClick: handleWordPressMediaSelect,
                  className: "group cursor-pointer border-2 border-dashed border-gray-300 dark:border-gray-600 hover:border-blue-400 dark:hover:border-blue-500 rounded-xl p-12 text-center transition-all duration-200 hover:bg-blue-50/50 dark:hover:bg-blue-900/10",
                  children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col items-center gap-4", children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-16 h-16 rounded-full bg-blue-100 dark:bg-blue-900/30 flex items-center justify-center group-hover:scale-110 transition-transform", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Upload, { className: "w-8 h-8 text-blue-600 dark:text-blue-400" }) }),
                    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-base font-semibold text-gray-900 dark:text-white", children: __("Upload Image", "yatra") }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-600 dark:text-gray-400", children: __("Click to open WordPress Media Library", "yatra") })
                    ] })
                  ] })
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "absolute inset-0 flex items-center", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-full border-t border-gray-200 dark:border-gray-700" }) }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "relative flex justify-center text-xs uppercase", children: /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "bg-white dark:bg-gray-900 px-3 text-gray-500 dark:text-gray-400", children: __("Or", "yatra") }) })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300", children: __("Enter Image URL", "yatra") }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Input,
                  {
                    type: "url",
                    placeholder: __("https://example.com/image.png", "yatra"),
                    value: (value == null ? void 0 : value.type) === "image" ? value.value : "",
                    onChange: (e) => handleImageUrlChange(e.target.value),
                    className: "h-11"
                  }
                )
              ] })
            ] }) })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "border-t border-gray-200 dark:border-gray-700 p-4 flex justify-end gap-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            Button,
            {
              type: "button",
              variant: "outline",
              onClick: () => setIsOpen(false),
              children: __("Close", "yatra")
            }
          ) })
        ]
      }
    )
  ] });
};
const RichTextEditor = ({
  value,
  onChange,
  label,
  placeholder,
  helperText,
  disabled = false,
  minHeight = 280,
  maxHeight = 600
}) => {
  const modules = reactExports.useMemo(
    () => ({
      toolbar: [
        [{ header: [1, 2, 3, false] }],
        ["bold", "italic", "underline", "strike"],
        [{ list: "ordered" }, { list: "bullet" }],
        [{ align: [] }],
        ["link"],
        ["clean"]
      ]
    }),
    []
  );
  const formats = [
    "header",
    "bold",
    "italic",
    "underline",
    "strike",
    "list",
    "bullet",
    "align",
    "link"
  ];
  const handleChange = (content) => {
    const normalized = content === "<p><br></p>" ? "" : content;
    onChange(normalized);
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "w-full", children: [
    label && /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5", children: label }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      "div",
      {
        className: `yatra-quill-editor ${disabled ? "opacity-60 cursor-not-allowed" : ""}`,
        children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          ReactQuill,
          {
            theme: "snow",
            value: value || "",
            onChange: handleChange,
            modules,
            formats,
            placeholder,
            readOnly: disabled,
            style: {
              minHeight: `${minHeight}px`,
              maxHeight: `${maxHeight}px`
            }
          }
        )
      }
    ),
    helperText && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-xs text-gray-500 dark:text-gray-400", children: helperText })
  ] });
};
function restRoot() {
  var _a;
  const raw = ((_a = window.yatraAdmin) == null ? void 0 : _a.restUrl) || "/wp-json/";
  return raw.endsWith("/") ? raw : `${raw}/`;
}
function parsePageTitle(payload) {
  var _a;
  if (!payload || typeof payload !== "object") {
    return "";
  }
  const p = payload;
  if (typeof ((_a = p.title) == null ? void 0 : _a.rendered) === "string") {
    return p.title.rendered.replace(/<[^>]+>/g, "").trim();
  }
  return "";
}
function parseLandingPageIdFromMetadata(metadata) {
  const raw = metadata == null ? void 0 : metadata.landing_page_id;
  if (raw == null || raw === "") {
    return null;
  }
  const n = typeof raw === "number" ? raw : parseInt(String(raw).trim(), 10);
  return Number.isFinite(n) && n > 0 ? n : null;
}
async function fetchPublishedPagePermalink(pageId) {
  var _a;
  if (!pageId) {
    return null;
  }
  const nonce = ((_a = window.yatraAdmin) == null ? void 0 : _a.nonce) || "";
  const url = `${restRoot()}wp/v2/pages/${pageId}?context=embed`;
  const res = await fetch(url, {
    credentials: "same-origin",
    headers: {
      "X-WP-Nonce": nonce,
      Accept: "application/json"
    }
  });
  if (!res.ok) {
    return null;
  }
  const data = await res.json();
  if (typeof (data == null ? void 0 : data.link) !== "string" || data.link === "") {
    return null;
  }
  return data.link;
}
async function fetchPublishedPagesFirstPage() {
  var _a;
  const nonce = ((_a = window.yatraAdmin) == null ? void 0 : _a.nonce) || "";
  const params = new URLSearchParams({
    per_page: "100",
    orderby: "title",
    order: "asc",
    status: "publish",
    context: "embed"
  });
  const res = await fetch(`${restRoot()}wp/v2/pages?${params}`, {
    credentials: "same-origin",
    headers: {
      "X-WP-Nonce": nonce,
      Accept: "application/json"
    }
  });
  if (!res.ok) {
    return { items: [], total: null };
  }
  const data = await res.json();
  const items = Array.isArray(data) ? data : [];
  const totalRaw = res.headers.get("X-WP-Total");
  const total = totalRaw !== null && totalRaw !== "" ? parseInt(totalRaw, 10) : null;
  return { items, total: Number.isFinite(total) ? total : null };
}
async function fetchSinglePublishedPage(pageId) {
  var _a;
  const nonce = ((_a = window.yatraAdmin) == null ? void 0 : _a.nonce) || "";
  const res = await fetch(`${restRoot()}wp/v2/pages/${pageId}?context=embed`, {
    credentials: "same-origin",
    headers: {
      "X-WP-Nonce": nonce,
      Accept: "application/json"
    }
  });
  if (!res.ok) {
    return null;
  }
  const data = await res.json();
  if (!data || typeof data.id !== "number") {
    return null;
  }
  return data;
}
function sortPagesByTitle(list) {
  return [...list].sort((a2, b) => {
    const ta = parsePageTitle(a2).toLowerCase();
    const tb = parsePageTitle(b).toLowerCase();
    return ta.localeCompare(tb);
  });
}
function mergePageUnique(list, extra) {
  const id = Number(extra.id);
  if (!Number.isFinite(id) || id <= 0) {
    return list;
  }
  if (list.some((p) => Number(p.id) === id)) {
    return list;
  }
  return sortPagesByTitle([...list, extra]);
}
function ClassificationLandingPageField({
  value,
  onChange,
  selectId = "yatra-classification-landing-page"
}) {
  var _a;
  const moduleOn = Boolean(
    typeof window !== "undefined" && ((_a = window.yatraAdmin) == null ? void 0 : _a.customLandingPagesModuleEnabled)
  );
  const [pages, setPages] = reactExports.useState([]);
  const [loading, setLoading] = reactExports.useState(true);
  const [loadError, setLoadError] = reactExports.useState(false);
  const [totalPublished, setTotalPublished] = reactExports.useState(null);
  reactExports.useEffect(() => {
    if (!moduleOn) {
      return;
    }
    let cancelled = false;
    void (async () => {
      setLoading(true);
      setLoadError(false);
      try {
        const { items, total } = await fetchPublishedPagesFirstPage();
        if (cancelled) {
          return;
        }
        setPages(sortPagesByTitle(items));
        setTotalPublished(total);
      } catch {
        if (!cancelled) {
          setLoadError(true);
          setPages([]);
        }
      } finally {
        if (!cancelled) {
          setLoading(false);
        }
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [moduleOn]);
  reactExports.useEffect(() => {
    if (!moduleOn || !value) {
      return;
    }
    if (pages.some((p) => Number(p.id) === value)) {
      return;
    }
    let cancelled = false;
    void (async () => {
      const one2 = await fetchSinglePublishedPage(value);
      if (cancelled || !one2) {
        return;
      }
      setPages((prev) => mergePageUnique(prev, one2));
    })();
    return () => {
      cancelled = true;
    };
  }, [moduleOn, value, pages]);
  const selectValue = reactExports.useMemo(
    () => value && value > 0 ? String(value) : "",
    [value]
  );
  if (!moduleOn) {
    return null;
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Custom landing page", "yatra") }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3 text-sm", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-600 dark:text-gray-400", children: __(
        "Public catalog links and redirects use this WordPress page URL instead of the default Yatra taxonomy path.",
        "yatra"
      ) }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-1", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "label",
          {
            htmlFor: selectId,
            className: "block text-sm font-medium text-gray-700 dark:text-gray-300",
            children: __("WordPress page", "yatra")
          }
        ),
        loading ? /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2 text-sm text-gray-500 dark:text-gray-400 py-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Loader2, { className: "w-4 h-4 animate-spin" }),
          __("Loading pages…", "yatra")
        ] }) : loadError ? /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-red-600 dark:text-red-400", children: __(
          "Could not load pages. Check that you are logged in and try again.",
          "yatra"
        ) }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Select,
          {
            id: selectId,
            className: "w-full h-10",
            value: selectValue,
            onChange: (e) => {
              const v = e.target.value;
              if (v === "") {
                onChange(null);
                return;
              }
              const n = parseInt(v, 10);
              onChange(Number.isFinite(n) && n > 0 ? n : null);
            },
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "", children: __("— Default Yatra URL (no custom page) —", "yatra") }),
              pages.map((p) => {
                const id = Number(p.id);
                const label = parsePageTitle(p) || __("(no title)", "yatra");
                return /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: String(id), children: label }, id);
              })
            ]
          }
        ),
        totalPublished !== null && totalPublished > 100 && !loading && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400", children: sprintf(
          // translators: %d: total number of published pages on the site.
          __(
            "Showing the first 100 published pages (of %d). Change the selection in WordPress → Pages if yours is not listed.",
            "yatra"
          ),
          totalPublished
        ) })
      ] })
    ] })
  ] });
}
const ActivityForm = () => {
  const queryClient2 = useQueryClient();
  const { can } = usePermissions();
  const { showToast } = useToast();
  const [formData, setFormData] = reactExports.useState({
    name: "",
    slug: "",
    description: "",
    icon: null,
    status: "publish",
    seo_title: "",
    seo_description: "",
    seo_keywords: "",
    landing_page_id: null
  });
  const [errors, setErrors] = reactExports.useState({});
  const [isSubmitting, setIsSubmitting] = reactExports.useState(false);
  const [isSlugEditable, setIsSlugEditable] = reactExports.useState(false);
  const action = reactExports.useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get("action") || "create";
  }, []);
  const activityId = reactExports.useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get("id") ? parseInt(params.get("id") || "0") : null;
  }, []);
  const isEditMode = action === "edit" && activityId !== null;
  const { data: activityData, isLoading: isLoadingActivity } = useQuery({
    queryKey: ["activity", activityId],
    queryFn: async () => {
      if (!activityId) return null;
      try {
        const response = await apiClient.get(`/activities/${activityId}`);
        return response;
      } catch (error) {
        showToast(
          (error == null ? void 0 : error.message) || __("Failed to load activity", "yatra"),
          "error"
        );
        throw error;
      }
    },
    enabled: isEditMode && can("yatra_view_trips")
  });
  const { data: settings2 } = useQuery({
    queryKey: ["settings"],
    queryFn: async () => {
      try {
        const response = await fetchSettings();
        return (response == null ? void 0 : response.data) || response;
      } catch (error) {
        return {};
      }
    }
  });
  reactExports.useEffect(() => {
    var _a, _b, _c;
    if (activityData && isEditMode) {
      setFormData({
        name: activityData.name || "",
        slug: activityData.slug || "",
        description: activityData.description || "",
        icon: activityData.icon || null,
        status: activityData.status || "draft",
        seo_title: ((_a = activityData.metadata) == null ? void 0 : _a.seo_title) || "",
        seo_description: ((_b = activityData.metadata) == null ? void 0 : _b.seo_description) || "",
        seo_keywords: ((_c = activityData.metadata) == null ? void 0 : _c.seo_keywords) || "",
        landing_page_id: parseLandingPageIdFromMetadata(
          activityData.metadata
        )
      });
    }
  }, [activityData, isEditMode]);
  const handleNameChange = (value) => {
    if (!isEditMode && !isSlugEditable) {
      const newSlug = generateSlug(value);
      setFormData((prev) => ({
        ...prev,
        name: value,
        slug: newSlug
      }));
    } else {
      setFormData((prev) => ({
        ...prev,
        name: value
      }));
    }
    if (errors.name) {
      setErrors((prev) => ({ ...prev, name: "" }));
    }
  };
  const handleSlugChange = (value) => {
    if (isSlugEditable) {
      setFormData((prev) => ({ ...prev, slug: value }));
      if (errors.slug) {
        setErrors((prev) => ({ ...prev, slug: "" }));
      }
    }
  };
  const handleToggleSlugEdit = () => {
    if (isSlugEditable) {
      const newSlug = generateSlug(formData.name);
      setFormData((prev) => ({ ...prev, slug: newSlug }));
    }
    setIsSlugEditable(!isSlugEditable);
  };
  const handleFieldChange = (field, value) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
    if (errors[field]) {
      setErrors((prev) => ({ ...prev, [field]: "" }));
    }
  };
  const validateForm = () => {
    const newErrors = {};
    if (!formData.name.trim()) {
      newErrors.name = __("Name is required", "yatra");
    }
    if (!formData.slug.trim()) {
      newErrors.slug = __("Slug is required", "yatra");
    } else if (!/^[\p{L}\p{N}-]+$/u.test(formData.slug)) {
      newErrors.slug = __(
        "Slug can only contain letters, numbers, and hyphens",
        "yatra"
      );
    }
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };
  const saveMutation = useMutation({
    mutationFn: async (data) => {
      const payload = {
        name: data.name.trim(),
        slug: data.slug.trim(),
        description: data.description.trim(),
        icon: data.icon,
        status: data.status,
        seo_title: data.seo_title.trim(),
        seo_description: data.seo_description.trim(),
        seo_keywords: data.seo_keywords.trim(),
        landing_page_id: data.landing_page_id ?? null
      };
      if (isEditMode && isSlugEditable) {
        payload.preserve_slug = true;
      }
      if (isEditMode && activityId) {
        return await apiClient.put(`/activities/${activityId}`, payload);
      } else {
        return await apiClient.post("/activities", payload);
      }
    },
    onSuccess: (response) => {
      var _a;
      queryClient2.invalidateQueries({ queryKey: ["activities"] });
      queryClient2.invalidateQueries({ queryKey: ["activity", activityId] });
      showToast(
        isEditMode ? __("Activity updated successfully", "yatra") : __("Activity created successfully", "yatra"),
        "success"
      );
      if (!isEditMode && (response == null ? void 0 : response.id)) {
        const editUrl = `${((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=trips&tab=activities&action=edit&id=${response.id}`;
        setTimeout(() => {
          window.location.href = editUrl;
        }, 800);
      } else {
        setIsSubmitting(false);
      }
    },
    onError: (error) => {
      const errorMessage = (error == null ? void 0 : error.message) || __("An error occurred while saving the activity", "yatra");
      showToast(errorMessage, "error");
      setIsSubmitting(false);
    }
  });
  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!validateForm()) {
      showToast(__("Please fix the form errors", "yatra"), "warning");
      return;
    }
    setIsSubmitting(true);
    setErrors({});
    saveMutation.mutate(formData);
  };
  const handleCancel = () => {
    var _a;
    window.location.href = `${((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=trips&tab=activities`;
  };
  if (isEditMode && isLoadingActivity) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg p-6", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-8 bg-gray-200 dark:bg-gray-700 rounded w-1/4 mb-2 animate-pulse" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-1/2 animate-pulse" })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-3 gap-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "lg:col-span-2 space-y-3", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "p-6 space-y-4", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-20 mb-2 animate-pulse" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-16 mb-2 animate-pulse" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-24 mb-2 animate-pulse" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-32 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" })
          ] })
        ] }) }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "p-6 space-y-4", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-16 mb-2 animate-pulse" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" })
          ] }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "p-6 space-y-4", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-20 mb-2 animate-pulse" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-40 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" })
          ] }) })
        ] })
      ] })
    ] });
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      PageHeader,
      {
        title: isEditMode ? __("Edit Activity", "yatra") : __("Add New Activity", "yatra"),
        description: isEditMode ? __("Update activity information", "yatra") : __("Create a new travel activity", "yatra"),
        actions: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Button,
            {
              variant: "outline",
              onClick: handleCancel,
              className: "flex items-center gap-2",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowLeft, { className: "w-4 h-4" }),
                __("Back", "yatra")
              ]
            }
          ),
          formData.slug && /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Button,
            {
              variant: "outline",
              onClick: async () => {
                var _a;
                if (formData.landing_page_id && ((_a = window.yatraAdmin) == null ? void 0 : _a.customLandingPagesModuleEnabled)) {
                  const link2 = await fetchPublishedPagePermalink(
                    formData.landing_page_id
                  );
                  if (link2) {
                    window.open(link2, "_blank", "noopener,noreferrer");
                    return;
                  }
                }
                const targetUrl = buildYatraSinglePreviewUrl({
                  entity: "activity",
                  slug: formData.slug || "",
                  bases: settings2
                });
                window.open(targetUrl, "_blank", "noopener,noreferrer");
              },
              className: "flex items-center gap-2",
              title: __("Preview activity in new tab", "yatra"),
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Eye, { className: "w-4 h-4" }),
                __("Preview", "yatra")
              ]
            }
          )
        ] })
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_edit_trips", children: /* @__PURE__ */ jsxRuntimeExports.jsx("form", { onSubmit: handleSubmit, children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-3 gap-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "lg:col-span-2 space-y-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Basic Information", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs(
                "label",
                {
                  htmlFor: "name",
                  className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                  children: [
                    __("Name", "yatra"),
                    " ",
                    /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
                  ]
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Input,
                {
                  id: "name",
                  type: "text",
                  value: formData.name,
                  onChange: (e) => handleNameChange(e.target.value),
                  placeholder: __("Enter activity name", "yatra"),
                  className: errors.name ? "border-red-500" : "",
                  required: true
                }
              ),
              errors.name && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm text-red-500", children: errors.name })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs(
                "label",
                {
                  htmlFor: "slug",
                  className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                  children: [
                    __("Slug", "yatra"),
                    " ",
                    /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
                  ]
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Input,
                  {
                    id: "slug",
                    type: "text",
                    value: formData.slug,
                    onChange: (e) => handleSlugChange(e.target.value),
                    placeholder: __("activity-slug", "yatra"),
                    className: `pr-10 ${errors.slug ? "border-red-500" : ""} ${!isSlugEditable ? "bg-gray-50 dark:bg-gray-800 cursor-not-allowed" : ""}`,
                    disabled: !isSlugEditable,
                    required: true
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "button",
                  {
                    type: "button",
                    onClick: handleToggleSlugEdit,
                    className: "absolute right-2 top-1/2 -translate-y-1/2 p-1.5 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors rounded",
                    "aria-label": isSlugEditable ? __("Cancel editing slug", "yatra") : __("Edit slug", "yatra"),
                    children: isSlugEditable ? /* @__PURE__ */ jsxRuntimeExports.jsx(X, { className: "w-4 h-4" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(Pen, { className: "w-4 h-4" })
                  }
                )
              ] }),
              errors.slug && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm text-red-500", children: errors.slug }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-xs text-gray-500 dark:text-gray-400", children: isSlugEditable ? __(
                "Manually editing slug. Click X to cancel and regenerate from name.",
                "yatra"
              ) : __(
                "Auto-generated from name. Click edit icon to customize.",
                "yatra"
              ) })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              RichTextEditor,
              {
                label: __("Description", "yatra"),
                value: formData.description || "",
                onChange: (value) => handleFieldChange("description", value),
                placeholder: __(
                  "Write a rich description (supports formatting, lists, links...)",
                  "yatra"
                ),
                helperText: __(
                  "Use formatting, bullet lists, and links to create a compelling description. HTML is supported.",
                  "yatra"
                ),
                minHeight: 360,
                maxHeight: 720
              }
            )
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          ClassificationLandingPageField,
          {
            selectId: "yatra-activity-landing-page",
            value: formData.landing_page_id,
            onChange: (id) => setFormData((prev) => ({ ...prev, landing_page_id: id }))
          }
        )
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Status", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "space-y-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "label",
              {
                htmlFor: "status",
                className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                children: __("Status", "yatra")
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              Select,
              {
                id: "status",
                value: formData.status,
                onChange: (e) => handleFieldChange("status", e.target.value),
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "draft", children: __("Draft", "yatra") }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "publish", children: __("Publish", "yatra") }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "trash", children: __("Trash", "yatra") })
                ]
              }
            )
          ] }) })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("SEO Settings", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "label",
                {
                  htmlFor: "seo_title",
                  className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",
                  children: __("Meta Title", "yatra")
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Input,
                {
                  id: "seo_title",
                  type: "text",
                  value: formData.seo_title,
                  onChange: (e) => handleFieldChange("seo_title", e.target.value),
                  placeholder: __(
                    "e.g., {name} Activities | Your Travel Agency",
                    "yatra"
                  ),
                  className: "w-full"
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400 mt-1", children: __(
                "Custom title for search engines. Use {name} as placeholder.",
                "yatra"
              ) })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "label",
                {
                  htmlFor: "seo_description",
                  className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",
                  children: __("Meta Description", "yatra")
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "textarea",
                {
                  id: "seo_description",
                  value: formData.seo_description,
                  onChange: (e) => handleFieldChange("seo_description", e.target.value),
                  placeholder: __(
                    "e.g., Discover amazing {name} activities and experiences. Book your adventure today!",
                    "yatra"
                  ),
                  rows: 3,
                  className: "w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-white"
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400 mt-1", children: __(
                "Description for search engines (150-160 characters). Use {name} as placeholder.",
                "yatra"
              ) })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "label",
                {
                  htmlFor: "seo_keywords",
                  className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",
                  children: __("Meta Keywords", "yatra")
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Input,
                {
                  id: "seo_keywords",
                  type: "text",
                  value: formData.seo_keywords,
                  onChange: (e) => handleFieldChange("seo_keywords", e.target.value),
                  placeholder: __(
                    "e.g., activities, adventure, {name}, travel, experiences",
                    "yatra"
                  ),
                  className: "w-full"
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400 mt-1", children: __(
                "Comma-separated keywords. Use {name} as placeholder.",
                "yatra"
              ) })
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Activity Icon or Image", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            IconPicker,
            {
              value: formData.icon,
              onChange: (value) => handleFieldChange("icon", value),
              label: __("Select Icon or Upload Image", "yatra"),
              helpText: __(
                "Choose a library icon or upload a custom image to visually represent this activity.",
                "yatra"
              ),
              allowImageUpload: true,
              allowIconSelection: true,
              size: "md"
            }
          ) })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-3", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-2", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Button,
            {
              type: "submit",
              disabled: isSubmitting,
              className: "flex-1 flex items-center justify-center gap-2",
              children: isSubmitting ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Loader2, { className: "w-4 h-4 animate-spin" }),
                __("Saving...", "yatra")
              ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Save, { className: "w-4 h-4" }),
                isEditMode ? __("Update Activity", "yatra") : __("Create Itinerary Activity", "yatra")
              ] })
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Button,
            {
              type: "button",
              variant: "outline",
              onClick: handleCancel,
              disabled: isSubmitting,
              children: __("Cancel", "yatra")
            }
          )
        ] }) }) }) })
      ] })
    ] }) }) })
  ] });
};
const Destinations = () => {
  const [searchTerm, setSearchTerm] = reactExports.useState("");
  const [showColumnsDropdown, setShowColumnsDropdown] = reactExports.useState(false);
  const [sortBy2, setSortBy] = reactExports.useState("id");
  const [sortOrder, setSortOrder] = reactExports.useState("desc");
  const [page, setPage] = reactExports.useState(1);
  const [statusFilter, setStatusFilter] = reactExports.useState("all");
  const [selectedIds, setSelectedIds] = reactExports.useState([]);
  const [bulkAction, setBulkAction] = reactExports.useState("");
  const [visibleColumns, setVisibleColumns] = reactExports.useState(() => {
    const defaultColumns = {
      name: true,
      description: true,
      trips: true,
      status: true,
      seo_title: false,
      seo_description: false,
      seo_keywords: false,
      created_at: false,
      updated_at: false,
      created_by_name: false,
      updated_by_name: false
    };
    const saved = localStorage.getItem("yatra_destinations_visible_columns_v2");
    return saved ? { ...defaultColumns, ...JSON.parse(saved) } : defaultColumns;
  });
  const [deleteConfirm, setDeleteConfirm] = reactExports.useState({
    isOpen: false,
    destination: null
  });
  const queryClient2 = useQueryClient();
  const { can } = usePermissions();
  const { showToast } = useToast();
  reactExports.useEffect(() => {
    const handleClickOutside = (event) => {
      const target2 = event.target;
      if (!target2.closest("[data-columns-trigger]") && !target2.closest("[data-columns-content]")) {
        setShowColumnsDropdown(false);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);
  const queryParams = reactExports.useMemo(() => {
    const params = {
      page,
      per_page: 10,
      orderby: sortBy2,
      order: sortOrder
    };
    if (searchTerm) {
      params.search = searchTerm;
    }
    if (statusFilter !== "all") {
      params.status = statusFilter;
    }
    return params;
  }, [searchTerm, statusFilter, sortBy2, sortOrder, page]);
  const { data: statsData } = useQuery({
    queryKey: ["destinations-stats"],
    queryFn: async () => {
      try {
        const response = await apiClient.get("/destinations/stats");
        return response;
      } catch (error2) {
        return { all: 0, publish: 0, draft: 0, trash: 0 };
      }
    },
    enabled: can("yatra_view_trips")
  });
  const { data, isLoading, error } = useQuery({
    queryKey: ["destinations", queryParams],
    queryFn: async () => {
      try {
        const response = await apiClient.get("/destinations", {
          params: queryParams
        });
        return response;
      } catch (error2) {
        showToast(
          (error2 == null ? void 0 : error2.message) || __("Failed to load destinations", "yatra"),
          "error"
        );
        throw error2;
      }
    },
    enabled: can("yatra_view_trips")
  });
  const { data: settings2 } = useQuery({
    queryKey: ["settings"],
    queryFn: async () => {
      try {
        const response = await fetchSettings();
        return response;
      } catch (error2) {
        return null;
      }
    },
    enabled: can("yatra_access_admin"),
    staleTime: 5 * 60 * 1e3
    // Cache for 5 minutes
  });
  const deleteMutation = useMutation({
    mutationFn: async (id) => {
      return await apiClient.delete(`/destinations/${id}`);
    },
    onSuccess: () => {
      queryClient2.invalidateQueries({ queryKey: ["destinations"] });
      queryClient2.invalidateQueries({ queryKey: ["destinations-stats"] });
      showToast(__("Destination deleted successfully", "yatra"), "success");
      setDeleteConfirm({ isOpen: false, destination: null });
    },
    onError: (error2) => {
      showToast(
        (error2 == null ? void 0 : error2.message) || __("Failed to delete destination", "yatra"),
        "error"
      );
    }
  });
  const destinations = (data == null ? void 0 : data.data) || [];
  const total = (data == null ? void 0 : data.total) || 0;
  const totalPages = Math.ceil(total / 10);
  const errorContext = getErrorContext(error);
  const handleEdit = (destination) => {
    var _a;
    window.location.href = `${((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=trips&tab=destinations&action=edit&id=${destination.id}`;
  };
  const handleView = async (destination) => {
    const destinationSlug = destination.slug || "";
    const { plainUrl, prettyUrl } = buildYatraSinglePublicUrls({
      entity: "destination",
      slug: destinationSlug,
      bases: settings2
    });
    if (isWordPressPlainPermalink()) {
      if (!destinationSlug) {
        showToast(__("Destination slug is missing", "yatra"), "error");
        return;
      }
      window.open(plainUrl, "_blank", "noopener,noreferrer");
      return;
    }
    let apiPermalink = (destination == null ? void 0 : destination.permalink) || (destination == null ? void 0 : destination.url);
    if (!apiPermalink && destination.id) {
      try {
        const detail = await apiClient.get(`/destinations/${destination.id}`);
        apiPermalink = (detail == null ? void 0 : detail.permalink) || (detail == null ? void 0 : detail.url) || apiPermalink;
      } catch (e) {
      }
    }
    if (apiPermalink) {
      window.open(apiPermalink, "_blank", "noopener,noreferrer");
      return;
    }
    if (!destinationSlug) {
      showToast(__("Destination slug is missing", "yatra"), "error");
      return;
    }
    window.open(prettyUrl, "_blank", "noopener,noreferrer");
  };
  const handleDelete = (destination) => {
    setDeleteConfirm({ isOpen: true, destination });
  };
  const confirmDelete = () => {
    if (deleteConfirm.destination) {
      deleteMutation.mutate(deleteConfirm.destination.id);
    }
  };
  const handleCreateDestination = () => {
    var _a;
    window.location.href = `${((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=trips&tab=destinations&action=create`;
  };
  const handleResetFilters = () => {
    setSearchTerm("");
    setStatusFilter("all");
    setSortBy("id");
    setSortOrder("desc");
    setPage(1);
  };
  const handleSort = (field) => {
    if (sortBy2 === field) {
      setSortOrder(sortOrder === "asc" ? "desc" : "asc");
    } else {
      setSortBy(field);
      setSortOrder(field === "id" ? "desc" : "asc");
    }
  };
  const getSortIcon = (field) => {
    if (sortBy2 !== field) {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowUpDown, { className: "w-3.5 h-3.5 ml-1 text-gray-400" });
    }
    return sortOrder === "asc" ? /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowUp, { className: "w-3.5 h-3.5 ml-1 text-gray-600 dark:text-gray-300" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowDown, { className: "w-3.5 h-3.5 ml-1 text-gray-600 dark:text-gray-300" });
  };
  const toggleColumn = (columnKey) => {
    const newVisibleColumns = {
      ...visibleColumns,
      [columnKey]: !visibleColumns[columnKey]
    };
    setVisibleColumns(newVisibleColumns);
    localStorage.setItem(
      "yatra_destinations_visible_columns_v2",
      JSON.stringify(newVisibleColumns)
    );
  };
  const statusCounts = reactExports.useMemo(() => {
    if (statsData) {
      return {
        all: statsData.all ?? 0,
        publish: statsData.publish ?? 0,
        draft: statsData.draft ?? 0,
        trash: statsData.trash ?? 0
      };
    }
    return {
      all: 0,
      publish: 0,
      draft: 0,
      trash: 0
    };
  }, [statsData]);
  const bulkMutation = useMutation({
    mutationFn: async ({
      action,
      ids
    }) => {
      return await apiClient.post("/destinations/bulk", { action, ids });
    },
    onSuccess: () => {
      queryClient2.invalidateQueries({ queryKey: ["destinations"] });
      queryClient2.invalidateQueries({ queryKey: ["destinations-stats"] });
      showToast(__("Bulk action completed successfully", "yatra"), "success");
      setSelectedIds([]);
      setBulkAction("");
    },
    onError: (error2) => {
      showToast(
        (error2 == null ? void 0 : error2.message) || __("Failed to perform bulk action", "yatra"),
        "error"
      );
    }
  });
  const handleBulkApply = () => {
    if (!bulkAction) {
      showToast(__("Select a bulk action first.", "yatra"), "warning");
      return;
    }
    if (selectedIds.length === 0) {
      showToast(__("Select at least one destination.", "yatra"), "warning");
      return;
    }
    bulkMutation.mutate({ action: bulkAction, ids: selectedIds });
  };
  const viewFilters = [
    { key: "all", label: __("All", "yatra"), count: statusCounts.all ?? 0 },
    {
      key: "publish",
      label: __("Published", "yatra"),
      count: statusCounts.publish ?? 0
    },
    {
      key: "draft",
      label: __("Draft", "yatra"),
      count: statusCounts.draft ?? 0
    },
    {
      key: "trash",
      label: __("Trash", "yatra"),
      count: statusCounts.trash ?? 0
    }
  ];
  const hasFilters = searchTerm || statusFilter !== "all" || sortBy2 !== "id" || sortOrder !== "desc";
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      ConfirmationDialog,
      {
        isOpen: deleteConfirm.isOpen,
        onClose: () => setDeleteConfirm({ isOpen: false, destination: null }),
        onConfirm: confirmDelete,
        title: __("Delete Destination", "yatra"),
        message: deleteConfirm.destination ? __(
          'Are you sure you want to delete "{name}"? This action cannot be undone.',
          "yatra"
        ).replace("{name}", deleteConfirm.destination.name) : __(
          "Are you sure you want to delete this destination? This action cannot be undone.",
          "yatra"
        ),
        confirmText: __("Delete", "yatra"),
        cancelText: __("Cancel", "yatra"),
        variant: "danger",
        isLoading: deleteMutation.isPending
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      PageHeader,
      {
        title: __("Destinations", "yatra"),
        description: __("Manage your travel destinations", "yatra"),
        actionCapability: "yatra_edit_trips",
        actions: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Button,
          {
            onClick: handleCreateDestination,
            className: "flex items-center gap-2",
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Plus, { className: "w-4 h-4" }),
              __("Add New Destination", "yatra")
            ]
          }
        )
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-3", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
      SearchFilterToolbar,
      {
        searchTerm,
        onSearchChange: setSearchTerm,
        statusFilter,
        onStatusChange: (value) => {
          setStatusFilter(value);
          setPage(1);
          setSelectedIds([]);
          setBulkAction("");
        },
        statusOptions: [
          { value: "all", label: __("All Status", "yatra") },
          { value: "publish", label: __("Published", "yatra") },
          { value: "draft", label: __("Draft", "yatra") },
          { value: "trash", label: __("Trash", "yatra") }
        ],
        sortBy: sortBy2,
        onSortByChange: setSortBy,
        sortOrder,
        onSortOrderChange: setSortOrder,
        sortOptions: [
          { value: "name", label: __("Name", "yatra") },
          { value: "status", label: __("Status", "yatra") },
          { value: "created_at", label: __("Created At", "yatra") },
          { value: "updated_at", label: __("Updated At", "yatra") }
        ],
        onResetFilters: handleResetFilters,
        hasFilters: !!hasFilters,
        placeholder: __("Search destinations...", "yatra")
      }
    ) }) }),
    !error && /* @__PURE__ */ jsxRuntimeExports.jsx(
      BulkActionToolbar,
      {
        selectedIds,
        bulkAction,
        setBulkAction,
        onApply: handleBulkApply,
        onClearSelection: () => setSelectedIds([]),
        statusFilter,
        setStatusFilter: (value) => {
          setStatusFilter(value);
          setPage(1);
          setSelectedIds([]);
          setBulkAction("");
        },
        statusOptions: viewFilters,
        showColumnsDropdown,
        setShowColumnsDropdown,
        columnOptions: [
          {
            key: "name",
            label: __("Destination", "yatra"),
            visible: visibleColumns.name
          },
          {
            key: "description",
            label: __("Description", "yatra"),
            visible: visibleColumns.description
          },
          {
            key: "trips",
            label: __("Trips", "yatra"),
            visible: visibleColumns.trips
          },
          {
            key: "seo_title",
            label: __("SEO Title", "yatra"),
            visible: visibleColumns.seo_title
          },
          {
            key: "seo_description",
            label: __("SEO Description", "yatra"),
            visible: visibleColumns.seo_description
          },
          {
            key: "seo_keywords",
            label: __("SEO Keywords", "yatra"),
            visible: visibleColumns.seo_keywords
          },
          {
            key: "status",
            label: __("Status", "yatra"),
            visible: visibleColumns.status
          },
          {
            key: "created_at",
            label: __("Created Date", "yatra"),
            visible: visibleColumns.created_at
          },
          {
            key: "updated_at",
            label: __("Updated Date", "yatra"),
            visible: visibleColumns.updated_at
          },
          {
            key: "created_by_name",
            label: __("Created By", "yatra"),
            visible: visibleColumns.created_by_name
          },
          {
            key: "updated_by_name",
            label: __("Updated By", "yatra"),
            visible: visibleColumns.updated_by_name
          }
        ],
        onToggleColumn: toggleColumn,
        bulkMutationPending: bulkMutation.isPending,
        totalItems: destinations.length,
        bulkActionOptions: getDefaultBulkStatusOptions(statusFilter)
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_view_trips", children: /* @__PURE__ */ jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { className: "overflow-visible", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-0 overflow-visible", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
      Table,
      {
        data: destinations,
        columns: reactExports.useMemo(
          () => [
            {
              key: "name",
              label: __("Destination", "yatra"),
              sortable: true,
              visible: visibleColumns.name,
              render: (destination) => {
                var _a;
                return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-10 h-10 rounded-lg bg-blue-100 dark:bg-blue-900/30 flex items-center justify-center flex-shrink-0", children: destination.icon ? destination.icon.type === "image" ? /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "img",
                    {
                      src: destination.icon.value,
                      alt: destination.name,
                      className: "w-full h-full object-cover rounded-lg"
                    }
                  ) : /* @__PURE__ */ jsxRuntimeExports.jsx(
                    IconSelector,
                    {
                      iconName: destination.icon.value,
                      provider: destination.icon.provider ?? "yatra",
                      className: "w-5 h-5 text-blue-600 dark:text-blue-400"
                    }
                  ) : /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-5 h-5 text-blue-600 dark:text-blue-400 flex items-center justify-center text-xs font-semibold", children: destination.name.charAt(0).toUpperCase() }) }),
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1", children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx(
                        "a",
                        {
                          href: `${((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=trips&tab=destinations&action=edit&id=${destination.id}`,
                          className: "font-medium text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 hover:underline transition-colors cursor-pointer",
                          children: destination.name
                        }
                      ),
                      can("yatra_view_trips") && destination.status !== "trash" && /* @__PURE__ */ jsxRuntimeExports.jsx(
                        "button",
                        {
                          type: "button",
                          onClick: (e) => {
                            e.stopPropagation();
                            handleView(destination);
                          },
                          className: "ml-1 inline-flex items-center justify-center rounded-full p-1 text-gray-400 hover:text-gray-700 hover:bg-gray-100 dark:text-gray-400 dark:hover:text-white dark:hover:bg-gray-800",
                          title: __(
                            "View destination in new tab",
                            "yatra"
                          ),
                          children: /* @__PURE__ */ jsxRuntimeExports.jsx(ExternalLink, { className: "w-3.5 h-3.5" })
                        }
                      )
                    ] }),
                    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-sm text-gray-500 dark:text-gray-400 flex items-center gap-2", children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: destination.slug }),
                      /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-[11px] text-gray-400 dark:text-gray-500", children: [
                        "(",
                        __("ID:", "yatra"),
                        " ",
                        destination.id,
                        ")"
                      ] })
                    ] })
                  ] })
                ] });
              }
            },
            {
              key: "trips",
              label: __("Trips", "yatra"),
              sortable: false,
              visible: visibleColumns.trips,
              render: (destination) => /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300", children: typeof destination.trip_count === "number" ? destination.trip_count : 0 })
            },
            {
              key: "description",
              label: __("Description", "yatra"),
              visible: visibleColumns.description,
              render: (destination) => /* @__PURE__ */ jsxRuntimeExports.jsx(
                "span",
                {
                  className: `block max-w-[300px] truncate ${destination.status === "trash" || statusFilter === "trash" ? "text-gray-400 dark:text-gray-600" : "text-gray-600 dark:text-gray-400"}`,
                  title: destination.description || "",
                  children: destination.description || __("No description", "yatra")
                }
              )
            },
            {
              key: "seo_title",
              label: __("SEO Title", "yatra"),
              visible: visibleColumns.seo_title,
              render: (destination) => {
                var _a;
                return /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "span",
                  {
                    className: destination.status === "trash" || statusFilter === "trash" ? "text-gray-400 dark:text-gray-600" : "text-gray-600 dark:text-gray-400",
                    children: ((_a = destination.metadata) == null ? void 0 : _a.seo_title) || __("Not set", "yatra")
                  }
                );
              }
            },
            {
              key: "seo_description",
              label: __("SEO Description", "yatra"),
              visible: visibleColumns.seo_description,
              render: (destination) => {
                var _a, _b;
                return /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "span",
                  {
                    className: destination.status === "trash" || statusFilter === "trash" ? "text-gray-400 dark:text-gray-600" : "text-gray-600 dark:text-gray-400",
                    title: ((_a = destination.metadata) == null ? void 0 : _a.seo_description) || "",
                    children: ((_b = destination.metadata) == null ? void 0 : _b.seo_description) ? destination.metadata.seo_description.length > 50 ? destination.metadata.seo_description.substring(
                      0,
                      50
                    ) + "..." : destination.metadata.seo_description : __("Not set", "yatra")
                  }
                );
              }
            },
            {
              key: "seo_keywords",
              label: __("SEO Keywords", "yatra"),
              visible: visibleColumns.seo_keywords,
              render: (destination) => {
                var _a, _b;
                return /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "span",
                  {
                    className: destination.status === "trash" || statusFilter === "trash" ? "text-gray-400 dark:text-gray-600" : "text-gray-600 dark:text-gray-400",
                    title: ((_a = destination.metadata) == null ? void 0 : _a.seo_keywords) || "",
                    children: ((_b = destination.metadata) == null ? void 0 : _b.seo_keywords) ? destination.metadata.seo_keywords.length > 30 ? destination.metadata.seo_keywords.substring(
                      0,
                      30
                    ) + "..." : destination.metadata.seo_keywords : __("Not set", "yatra")
                  }
                );
              }
            },
            {
              key: "status",
              label: __("Status", "yatra"),
              sortable: true,
              visible: visibleColumns.status,
              render: (destination) => /* @__PURE__ */ jsxRuntimeExports.jsx(
                "span",
                {
                  className: `inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${destination.status === "trash" || statusFilter === "trash" ? "bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400" : destination.status === "publish" ? "bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400" : "bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400"}`,
                  children: destination.status === "trash" || statusFilter === "trash" ? __("Trash", "yatra") : destination.status === "publish" ? __("Published", "yatra") : __("Draft", "yatra")
                }
              )
            },
            {
              key: "created_at",
              label: __("Created Date", "yatra"),
              sortable: true,
              visible: visibleColumns.created_at,
              render: (destination) => /* @__PURE__ */ jsxRuntimeExports.jsx(
                "span",
                {
                  className: destination.status === "trash" || statusFilter === "trash" ? "text-gray-400 dark:text-gray-600" : "text-gray-600 dark:text-gray-400",
                  children: new Date(destination.created_at).toLocaleDateString(
                    "en-US",
                    {
                      year: "numeric",
                      month: "short",
                      day: "numeric",
                      hour: "2-digit",
                      minute: "2-digit"
                    }
                  )
                }
              )
            },
            {
              key: "updated_at",
              label: __("Updated Date", "yatra"),
              sortable: true,
              visible: visibleColumns.updated_at,
              render: (destination) => /* @__PURE__ */ jsxRuntimeExports.jsx(
                "span",
                {
                  className: destination.status === "trash" || statusFilter === "trash" ? "text-gray-400 dark:text-gray-600" : "text-gray-600 dark:text-gray-400",
                  children: new Date(destination.updated_at).toLocaleDateString(
                    "en-US",
                    {
                      year: "numeric",
                      month: "short",
                      day: "numeric",
                      hour: "2-digit",
                      minute: "2-digit"
                    }
                  )
                }
              )
            },
            {
              key: "created_by_name",
              label: __("Created By", "yatra"),
              visible: visibleColumns.created_by_name,
              render: (destination) => /* @__PURE__ */ jsxRuntimeExports.jsx(
                "span",
                {
                  className: destination.status === "trash" || statusFilter === "trash" ? "text-gray-400 dark:text-gray-600" : "text-gray-600 dark:text-gray-400",
                  children: destination.created_by_name || __("Unknown", "yatra")
                }
              )
            },
            {
              key: "updated_by_name",
              label: __("Updated By", "yatra"),
              visible: visibleColumns.updated_by_name,
              render: (destination) => /* @__PURE__ */ jsxRuntimeExports.jsx(
                "span",
                {
                  className: destination.status === "trash" || statusFilter === "trash" ? "text-gray-400 dark:text-gray-600" : "text-gray-600 dark:text-gray-400",
                  children: destination.updated_by_name || __("Unknown", "yatra")
                }
              )
            }
          ],
          // eslint-disable-next-line react-hooks/exhaustive-deps
          [visibleColumns]
        ),
        actions: [
          {
            key: "view",
            label: __("View", "yatra"),
            icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Eye, { className: "w-4 h-4" }),
            onClick: (destination) => {
              var _a;
              const destinationUrl = `${((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || ""}/destination/${destination.slug}`;
              window.open(destinationUrl, "_blank");
            },
            condition: () => true
            // Always show view action
          },
          {
            key: "edit",
            label: __("Edit", "yatra"),
            icon: /* @__PURE__ */ jsxRuntimeExports.jsx(PenSquare, { className: "w-4 h-4" }),
            onClick: handleEdit,
            condition: () => can("yatra_edit_trips")
          },
          {
            key: "restore",
            label: __("Restore", "yatra"),
            icon: /* @__PURE__ */ jsxRuntimeExports.jsx(RotateCcw, { className: "w-4 h-4" }),
            onClick: (destination) => {
              bulkMutation.mutate({
                action: "restore",
                ids: [destination.id]
              });
            },
            condition: (destination) => (destination.status === "trash" || statusFilter === "trash") && can("yatra_edit_trips")
          },
          {
            key: "trash",
            label: __("Move to Trash", "yatra"),
            icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "w-4 h-4" }),
            onClick: (destination) => {
              bulkMutation.mutate({
                action: "trash",
                ids: [destination.id]
              });
            },
            condition: (destination) => destination.status !== "trash" && statusFilter !== "trash" && can("yatra_edit_trips")
          },
          {
            key: "delete",
            label: __("Delete Permanently", "yatra"),
            icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "w-4 h-4" }),
            onClick: handleDelete,
            condition: (destination) => (destination.status === "trash" || statusFilter === "trash") && can("yatra_delete_trips"),
            variant: "destructive"
          }
        ],
        isLoading,
        isError: !!error,
        errorText: __("Error loading destinations", "yatra"),
        errorDescription: __(
          "We couldn’t connect to the destinations service. Please refresh or try again shortly.",
          "yatra"
        ),
        onRetry: () => queryClient2.invalidateQueries({ queryKey: ["destinations"] }),
        errorDetails: errorContext.details,
        errorRequestInfo: errorContext.requestInfo,
        emptyText: __("No destinations found", "yatra"),
        emptyDescription: hasFilters ? __(
          "Try adjusting your filters to see more results.",
          "yatra"
        ) : __(
          "Get started by creating your first destination.",
          "yatra"
        ),
        onCreateClick: can("yatra_edit_trips") ? handleCreateDestination : void 0,
        onSort: handleSort,
        getSortIcon,
        selectedItemIds: selectedIds,
        onSelectItem: (id, checked) => {
          if (checked) {
            setSelectedIds([...selectedIds, id]);
          } else {
            setSelectedIds(
              selectedIds.filter((selectedId) => selectedId !== id)
            );
          }
        },
        onSelectAll: (checked) => {
          if (checked) {
            setSelectedIds(destinations.map((d) => d.id));
          } else {
            setSelectedIds([]);
          }
        },
        isAllSelected: destinations.length > 0 && selectedIds.length === destinations.length,
        getItemId: (destination) => destination.id,
        getItemStatus: (destination) => destination.status,
        statusFilter,
        skeletonRows: 5
      },
      `destinations-table-${JSON.stringify(visibleColumns)}`
    ) }) }) }) }),
    total > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-4", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
      Pagination,
      {
        currentPage: page,
        totalPages,
        totalItems: total,
        itemsPerPage: 10,
        onPageChange: (newPage) => setPage(newPage),
        itemName: __("destinations", "yatra")
      }
    ) })
  ] });
};
const DestinationForm = () => {
  const queryClient2 = useQueryClient();
  const { can } = usePermissions();
  const { showToast } = useToast();
  const [formData, setFormData] = reactExports.useState({
    name: "",
    slug: "",
    description: "",
    icon: null,
    status: "publish",
    seo_title: "",
    seo_description: "",
    seo_keywords: "",
    landing_page_id: null
  });
  const [errors, setErrors] = reactExports.useState({});
  const [isSubmitting, setIsSubmitting] = reactExports.useState(false);
  const [isSlugEditable, setIsSlugEditable] = reactExports.useState(false);
  const action = reactExports.useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get("action") || "create";
  }, []);
  const destinationId = reactExports.useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get("id") ? parseInt(params.get("id") || "0") : null;
  }, []);
  const isEditMode = action === "edit" && destinationId !== null;
  const { data: destinationData, isLoading: isLoadingDestination } = useQuery({
    queryKey: ["destination", destinationId],
    queryFn: async () => {
      if (!destinationId) return null;
      try {
        const response = await apiClient.get(`/destinations/${destinationId}`);
        return response;
      } catch (error) {
        showToast(
          (error == null ? void 0 : error.message) || __("Failed to load destination", "yatra"),
          "error"
        );
        throw error;
      }
    },
    enabled: isEditMode && can("yatra_view_trips")
  });
  const { data: settings2 } = useQuery({
    queryKey: ["settings"],
    queryFn: async () => {
      try {
        const response = await fetchSettings();
        return (response == null ? void 0 : response.data) || response;
      } catch (error) {
        return {};
      }
    }
  });
  reactExports.useEffect(() => {
    var _a, _b, _c;
    if (destinationData && isEditMode) {
      setFormData({
        name: destinationData.name || "",
        slug: destinationData.slug || "",
        description: destinationData.description || "",
        icon: destinationData.icon || null,
        status: destinationData.status || "draft",
        seo_title: ((_a = destinationData.metadata) == null ? void 0 : _a.seo_title) || "",
        seo_description: ((_b = destinationData.metadata) == null ? void 0 : _b.seo_description) || "",
        seo_keywords: ((_c = destinationData.metadata) == null ? void 0 : _c.seo_keywords) || "",
        landing_page_id: parseLandingPageIdFromMetadata(
          destinationData.metadata
        )
      });
    }
  }, [destinationData, isEditMode]);
  const handleNameChange = (value) => {
    if (!isEditMode && !isSlugEditable) {
      const newSlug = generateSlug(value);
      setFormData((prev) => ({
        ...prev,
        name: value,
        slug: newSlug
      }));
    } else {
      setFormData((prev) => ({
        ...prev,
        name: value
      }));
    }
    if (errors.name) {
      setErrors((prev) => ({ ...prev, name: "" }));
    }
  };
  const handleSlugChange = (value) => {
    if (isSlugEditable) {
      setFormData((prev) => ({ ...prev, slug: value }));
      if (errors.slug) {
        setErrors((prev) => ({ ...prev, slug: "" }));
      }
    }
  };
  const handleToggleSlugEdit = () => {
    if (isSlugEditable) {
      const newSlug = generateSlug(formData.name);
      setFormData((prev) => ({ ...prev, slug: newSlug }));
    }
    setIsSlugEditable(!isSlugEditable);
  };
  const handleFieldChange = (field, value) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
    if (errors[field]) {
      setErrors((prev) => ({ ...prev, [field]: "" }));
    }
  };
  const validateForm = () => {
    const newErrors = {};
    if (!formData.name.trim()) {
      newErrors.name = __("Name is required", "yatra");
    }
    if (!formData.slug.trim()) {
      newErrors.slug = __("Slug is required", "yatra");
    } else if (!/^[\p{L}\p{N}-]+$/u.test(formData.slug)) {
      newErrors.slug = __(
        "Slug can only contain letters, numbers, and hyphens",
        "yatra"
      );
    }
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };
  const saveMutation = useMutation({
    mutationFn: async (data) => {
      const payload = {
        name: data.name.trim(),
        slug: data.slug.trim(),
        description: data.description.trim(),
        icon: data.icon,
        status: data.status,
        seo_title: data.seo_title.trim(),
        seo_description: data.seo_description.trim(),
        seo_keywords: data.seo_keywords.trim(),
        landing_page_id: data.landing_page_id ?? null
      };
      if (isEditMode && isSlugEditable) {
        payload.preserve_slug = true;
      }
      if (isEditMode && destinationId) {
        return await apiClient.put(`/destinations/${destinationId}`, payload);
      } else {
        return await apiClient.post("/destinations", payload);
      }
    },
    onSuccess: (response) => {
      var _a, _b;
      queryClient2.invalidateQueries({ queryKey: ["destinations"] });
      queryClient2.invalidateQueries({
        queryKey: ["destination", destinationId]
      });
      showToast(
        isEditMode ? __("Destination updated successfully", "yatra") : __("Destination created successfully", "yatra"),
        "success"
      );
      setIsSubmitting(false);
      if (!isEditMode) {
        const newId = response == null ? void 0 : response.id;
        if (newId) {
          window.location.href = `${((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=trips&tab=destinations&action=edit&id=${newId}`;
        } else {
          window.location.href = `${((_b = window.yatraAdmin) == null ? void 0 : _b.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=trips&tab=destinations`;
        }
      }
    },
    onError: (error) => {
      const errorMessage = (error == null ? void 0 : error.message) || __("An error occurred while saving the destination", "yatra");
      showToast(errorMessage, "error");
      setIsSubmitting(false);
    }
  });
  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!validateForm()) {
      showToast(__("Please fix the form errors", "yatra"), "warning");
      return;
    }
    setIsSubmitting(true);
    setErrors({});
    saveMutation.mutate(formData);
  };
  const handleCancel = () => {
    var _a;
    window.location.href = `${((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=trips&tab=destinations`;
  };
  if (isEditMode && isLoadingDestination) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg p-6", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-8 bg-gray-200 dark:bg-gray-700 rounded w-1/4 mb-2 animate-pulse" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-1/2 animate-pulse" })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-3 gap-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "lg:col-span-2 space-y-3", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "p-6 space-y-4", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-20 mb-2 animate-pulse" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-16 mb-2 animate-pulse" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-24 mb-2 animate-pulse" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-32 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" })
          ] })
        ] }) }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "p-6 space-y-4", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-16 mb-2 animate-pulse" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" })
          ] }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "p-6 space-y-4", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-20 mb-2 animate-pulse" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-40 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" })
          ] }) })
        ] })
      ] })
    ] });
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      PageHeader,
      {
        title: isEditMode ? __("Edit Destination", "yatra") : __("Add New Destination", "yatra"),
        description: isEditMode ? __("Update destination information", "yatra") : __("Create a new travel destination", "yatra"),
        actions: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Button,
            {
              variant: "outline",
              onClick: handleCancel,
              className: "flex items-center gap-2",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowLeft, { className: "w-4 h-4" }),
                __("Back", "yatra")
              ]
            }
          ),
          formData.slug && /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Button,
            {
              variant: "outline",
              onClick: async () => {
                var _a;
                if (formData.landing_page_id && ((_a = window.yatraAdmin) == null ? void 0 : _a.customLandingPagesModuleEnabled)) {
                  const link2 = await fetchPublishedPagePermalink(
                    formData.landing_page_id
                  );
                  if (link2) {
                    window.open(link2, "_blank", "noopener,noreferrer");
                    return;
                  }
                }
                const targetUrl = buildYatraSinglePreviewUrl({
                  entity: "destination",
                  slug: formData.slug || "",
                  bases: settings2
                });
                window.open(targetUrl, "_blank", "noopener,noreferrer");
              },
              className: "flex items-center gap-2",
              title: __("Preview destination in new tab", "yatra"),
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Eye, { className: "w-4 h-4" }),
                __("Preview", "yatra")
              ]
            }
          )
        ] })
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_edit_trips", children: /* @__PURE__ */ jsxRuntimeExports.jsx("form", { onSubmit: handleSubmit, children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-3 gap-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "lg:col-span-2 space-y-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Basic Information", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs(
                "label",
                {
                  htmlFor: "name",
                  className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                  children: [
                    __("Name", "yatra"),
                    " ",
                    /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
                  ]
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Input,
                {
                  id: "name",
                  type: "text",
                  value: formData.name,
                  onChange: (e) => handleNameChange(e.target.value),
                  placeholder: __("Enter destination name", "yatra"),
                  className: errors.name ? "border-red-500" : "",
                  required: true
                }
              ),
              errors.name && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm text-red-500", children: errors.name })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs(
                "label",
                {
                  htmlFor: "slug",
                  className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                  children: [
                    __("Slug", "yatra"),
                    " ",
                    /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
                  ]
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Input,
                  {
                    id: "slug",
                    type: "text",
                    value: formData.slug,
                    onChange: (e) => handleSlugChange(e.target.value),
                    placeholder: __("destination-slug", "yatra"),
                    className: `pr-10 ${errors.slug ? "border-red-500" : ""} ${!isSlugEditable ? "bg-gray-50 dark:bg-gray-800 cursor-not-allowed" : ""}`,
                    disabled: !isSlugEditable,
                    required: true
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "button",
                  {
                    type: "button",
                    onClick: handleToggleSlugEdit,
                    className: "absolute right-2 top-1/2 -translate-y-1/2 p-1.5 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors rounded",
                    "aria-label": isSlugEditable ? __("Cancel editing slug", "yatra") : __("Edit slug", "yatra"),
                    children: isSlugEditable ? /* @__PURE__ */ jsxRuntimeExports.jsx(X, { className: "w-4 h-4" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(Pen, { className: "w-4 h-4" })
                  }
                )
              ] }),
              errors.slug && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm text-red-500", children: errors.slug }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-xs text-gray-500 dark:text-gray-400", children: isSlugEditable ? __(
                "Manually editing slug. Click X to cancel and regenerate from name.",
                "yatra"
              ) : __(
                "Auto-generated from name. Click edit icon to customize.",
                "yatra"
              ) })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              RichTextEditor,
              {
                label: __("Description", "yatra"),
                value: formData.description || "",
                onChange: (value) => handleFieldChange("description", value),
                placeholder: __(
                  "Write a rich description (supports formatting, lists, links...)",
                  "yatra"
                ),
                helperText: __(
                  "Use formatting, bullet lists, and links to create a compelling description. HTML is supported.",
                  "yatra"
                ),
                minHeight: 360,
                maxHeight: 720
              }
            )
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          ClassificationLandingPageField,
          {
            selectId: "yatra-destination-landing-page",
            value: formData.landing_page_id,
            onChange: (id) => setFormData((prev) => ({ ...prev, landing_page_id: id }))
          }
        )
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Status", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "space-y-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "label",
              {
                htmlFor: "status",
                className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                children: __("Status", "yatra")
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              Select,
              {
                id: "status",
                value: formData.status,
                onChange: (e) => handleFieldChange("status", e.target.value),
                className: "w-full h-10",
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "draft", children: __("Draft", "yatra") }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "publish", children: __("Publish", "yatra") }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "trash", children: __("Trash", "yatra") })
                ]
              }
            )
          ] }) })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("SEO Settings", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "label",
                {
                  htmlFor: "seo_title",
                  className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",
                  children: __("Meta Title", "yatra")
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Input,
                {
                  id: "seo_title",
                  type: "text",
                  value: formData.seo_title,
                  onChange: (e) => handleFieldChange("seo_title", e.target.value),
                  placeholder: __(
                    "e.g., {name} Destinations | Your Travel Agency",
                    "yatra"
                  ),
                  className: "w-full"
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400 mt-1", children: __(
                "Custom title for search engines. Use {name} as placeholder.",
                "yatra"
              ) })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "label",
                {
                  htmlFor: "seo_description",
                  className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",
                  children: __("Meta Description", "yatra")
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "textarea",
                {
                  id: "seo_description",
                  value: formData.seo_description,
                  onChange: (e) => handleFieldChange("seo_description", e.target.value),
                  placeholder: __(
                    "e.g., Discover amazing destinations in {name}. Plan your perfect trip today!",
                    "yatra"
                  ),
                  rows: 3,
                  className: "w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-white"
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400 mt-1", children: __(
                "Description for search engines (150-160 characters). Use {name} as placeholder.",
                "yatra"
              ) })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "label",
                {
                  htmlFor: "seo_keywords",
                  className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",
                  children: __("Meta Keywords", "yatra")
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Input,
                {
                  id: "seo_keywords",
                  type: "text",
                  value: formData.seo_keywords,
                  onChange: (e) => handleFieldChange("seo_keywords", e.target.value),
                  placeholder: __(
                    "e.g., destinations, travel, {name}, tourism, trips",
                    "yatra"
                  ),
                  className: "w-full"
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400 mt-1", children: __(
                "Comma-separated keywords. Use {name} as placeholder.",
                "yatra"
              ) })
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Destination Icon or Image", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            IconPicker,
            {
              value: formData.icon,
              onChange: (value) => handleFieldChange("icon", value),
              label: __("Select Icon or Upload Image", "yatra"),
              helpText: __(
                "Choose a library icon or upload a custom image to visually represent this destination.",
                "yatra"
              ),
              allowImageUpload: true,
              allowIconSelection: true,
              size: "md"
            }
          ) })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-3", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-2", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Button,
            {
              type: "submit",
              disabled: isSubmitting,
              className: "flex-1 flex items-center justify-center gap-2",
              children: isSubmitting ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Loader2, { className: "w-4 h-4 animate-spin" }),
                __("Saving...", "yatra")
              ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Save, { className: "w-4 h-4" }),
                isEditMode ? __("Update Destination", "yatra") : __("Create Destination", "yatra")
              ] })
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Button,
            {
              type: "button",
              variant: "outline",
              onClick: handleCancel,
              disabled: isSubmitting,
              children: __("Cancel", "yatra")
            }
          )
        ] }) }) }) })
      ] })
    ] }) }) })
  ] });
};
const Categories = () => {
  const { can } = usePermissions();
  const [searchTerm, setSearchTerm] = reactExports.useState("");
  const [statusFilter, setStatusFilter] = reactExports.useState("all");
  const [parentFilter, setParentFilter] = reactExports.useState("all");
  const [sortBy2, setSortBy] = reactExports.useState("name");
  const [sortOrder, setSortOrder] = reactExports.useState("asc");
  const [page, setPage] = reactExports.useState(1);
  const [expandedCategories, setExpandedCategories] = reactExports.useState(
    /* @__PURE__ */ new Set()
  );
  const [deleteConfirm, setDeleteConfirm] = reactExports.useState({
    isOpen: false,
    category: null
  });
  const [selectedIds, setSelectedIds] = reactExports.useState([]);
  const [bulkAction, setBulkAction] = reactExports.useState("");
  const [showColumnsDropdown, setShowColumnsDropdown] = reactExports.useState(false);
  const [visibleColumns, setVisibleColumns] = reactExports.useState(() => {
    const defaultColumns = {
      name: true,
      description: true,
      trips: true,
      status: true,
      seo_title: false,
      seo_description: false,
      seo_keywords: false,
      created_at: true
    };
    const saved = localStorage.getItem("yatra_categories_columns_v2");
    return saved ? { ...defaultColumns, ...JSON.parse(saved) } : defaultColumns;
  });
  const queryClient2 = useQueryClient();
  const { showToast } = useToast();
  const queryParams = reactExports.useMemo(() => {
    const params = {
      page,
      per_page: 50,
      // Get more items to handle hierarchical display
      orderby: sortBy2,
      order: sortOrder,
      hierarchical: true
      // Request hierarchical data
    };
    if (searchTerm) {
      params.search = searchTerm;
    }
    if (statusFilter !== "all") {
      params.status = statusFilter;
    }
    if (parentFilter === "top-level") {
      params.parent_id = null;
    }
    return params;
  }, [searchTerm, statusFilter, parentFilter, sortBy2, sortOrder, page]);
  const { data, isLoading, error } = useQuery({
    queryKey: ["trip-categories", queryParams],
    queryFn: async () => {
      try {
        const response = await apiClient.get("/trip-categories", {
          params: queryParams
        });
        return response;
      } catch (error2) {
        showToast(
          (error2 == null ? void 0 : error2.message) || __("Failed to load categories", "yatra"),
          "error"
        );
        throw error2;
      }
    },
    enabled: can("yatra_view_trips")
  });
  const deleteMutation = useMutation({
    mutationFn: async (id) => {
      return await apiClient.delete(`/trip-categories/${id}`);
    },
    onSuccess: () => {
      queryClient2.invalidateQueries({ queryKey: ["trip-categories"] });
      showToast(__("Category deleted successfully", "yatra"), "success");
      setDeleteConfirm({ isOpen: false, category: null });
    },
    onError: (error2) => {
      showToast(
        (error2 == null ? void 0 : error2.message) || __("Failed to delete category", "yatra"),
        "error"
      );
    }
  });
  const categories = (data == null ? void 0 : data.data) || [];
  const total = (data == null ? void 0 : data.total) || 0;
  const totalPages = Math.ceil(total / 50);
  const errorContext = getErrorContext(error);
  const toggleColumn = (columnKey) => {
    const newVisibleColumns = {
      ...visibleColumns,
      [columnKey]: !visibleColumns[columnKey]
    };
    setVisibleColumns(newVisibleColumns);
    localStorage.setItem(
      "yatra_categories_columns_v2",
      JSON.stringify(newVisibleColumns)
    );
  };
  const statusCounts = reactExports.useMemo(() => {
    const counts = {
      all: 0,
      publish: 0,
      draft: 0,
      trash: 0
    };
    const countCategory = (cat) => {
      counts.all++;
      if (cat.status === "publish") counts.publish++;
      else if (cat.status === "draft") counts.draft++;
      else if (cat.status === "trash") counts.trash++;
    };
    categories.forEach((cat) => {
      countCategory(cat);
      if (cat.subcategories && Array.isArray(cat.subcategories)) {
        cat.subcategories.forEach((sub) => {
          countCategory(sub);
        });
      }
    });
    return counts;
  }, [categories]);
  const bulkMutation = useMutation({
    mutationFn: async ({
      action,
      ids
    }) => {
      if (action === "delete") {
        await Promise.all(
          ids.map((id) => apiClient.delete(`/trip-categories/${id}`))
        );
      } else {
        await Promise.all(
          ids.map(async (id) => {
            try {
              const categoryResponse = await apiClient.get(
                `/trip-categories/${id}`
              );
              const category = categoryResponse;
              if (!category || !category.name) {
                return;
              }
              await apiClient.put(`/trip-categories/${id}`, {
                name: category.name,
                slug: category.slug,
                description: category.description,
                icon: category.icon,
                parent_id: category.parent_id,
                status: action
              });
            } catch {
              throw new Error("bulk_item_failed");
            }
          })
        );
      }
    },
    onSuccess: (_data, variables) => {
      queryClient2.invalidateQueries({ queryKey: ["trip-categories"] });
      const msgMap = {
        delete: __("Selected categories deleted successfully", "yatra"),
        trash: __("Selected categories moved to trash", "yatra"),
        draft: __("Selected categories marked as draft", "yatra"),
        publish: __("Selected categories published", "yatra")
      };
      showToast(
        msgMap[variables.action] || __("Bulk action completed", "yatra"),
        "success"
      );
      setSelectedIds([]);
      setBulkAction("");
    },
    onError: (error2, variables) => {
      const msgMapError = {
        delete: __("Failed to delete selected categories", "yatra"),
        trash: __("Failed to move categories to trash", "yatra"),
        draft: __("Failed to mark categories as draft", "yatra"),
        publish: __("Failed to publish categories", "yatra")
      };
      showToast(
        (error2 == null ? void 0 : error2.message) || msgMapError[variables.action] || __("Bulk action failed", "yatra"),
        "error"
      );
    }
  });
  const handleBulkApply = () => {
    if (!bulkAction) {
      showToast(__("Select a bulk action first.", "yatra"), "warning");
      return;
    }
    if (selectedIds.length === 0) {
      showToast(__("Select at least one category.", "yatra"), "warning");
      return;
    }
    bulkMutation.mutate({ action: bulkAction, ids: selectedIds });
  };
  const processedCategories = reactExports.useMemo(() => {
    if (!Array.isArray(categories) || categories.length === 0) {
      return [];
    }
    const normalized = categories.map((cat) => ({
      ...cat,
      subcategories: Array.isArray(cat.subcategories) ? cat.subcategories : []
    }));
    const term = searchTerm.trim().toLowerCase();
    const matchesSearch = (cat) => {
      var _a, _b, _c;
      if (!term) return true;
      const name = ((_a = cat.name) == null ? void 0 : _a.toLowerCase()) || "";
      const slug = ((_b = cat.slug) == null ? void 0 : _b.toLowerCase()) || "";
      const desc = ((_c = cat.description) == null ? void 0 : _c.toLowerCase()) || "";
      return name.includes(term) || slug.includes(term) || desc.includes(term);
    };
    const filterByStatusAndSearch = (items) => {
      return items.map((cat) => {
        const filteredSubcategories = cat.subcategories ? cat.subcategories.filter((sub) => {
          const statusOk = statusFilter === "all" || sub.status === statusFilter;
          const searchOk = matchesSearch(sub);
          return statusOk && searchOk;
        }) : [];
        return {
          ...cat,
          subcategories: filteredSubcategories
        };
      }).filter((cat) => {
        if (statusFilter === "all" && !term) return true;
        const statusOk = statusFilter === "all" || cat.status === statusFilter;
        const searchOk = matchesSearch(cat);
        const hasMatchingChildren = cat.subcategories && cat.subcategories.length > 0;
        return statusOk && searchOk || hasMatchingChildren;
      });
    };
    const filtered = filterByStatusAndSearch(normalized);
    if (parentFilter === "subcategories") {
      const onlySubs = filtered.flatMap(
        (cat) => (cat.subcategories || []).map((sub) => ({
          ...sub,
          parent_name: cat.name,
          __subOnly: true,
          subcategories: []
        }))
      );
      return onlySubs;
    }
    if (parentFilter === "top-level") {
      return filtered.map((cat) => ({
        ...cat,
        subcategories: []
        // Don't show subcategories when filtering for top-level only
      }));
    }
    return filtered;
  }, [categories, parentFilter, statusFilter, searchTerm]);
  const { data: settings2 } = useQuery({
    queryKey: ["settings"],
    queryFn: async () => {
      try {
        const response = await fetchSettings();
        return response;
      } catch (error2) {
        return null;
      }
    },
    enabled: can("yatra_access_admin"),
    staleTime: 5 * 60 * 1e3
    // Cache for 5 minutes
  });
  reactExports.useEffect(() => {
    if (expandedCategories.size > 0) return;
    const initialExpanded = /* @__PURE__ */ new Set();
    processedCategories.forEach((cat) => {
      if (!cat.__subOnly && cat.subcategories && cat.subcategories.length > 0) {
        initialExpanded.add(cat.id);
      }
    });
    if (initialExpanded.size > 0) {
      setExpandedCategories(initialExpanded);
    }
  }, [processedCategories, expandedCategories.size]);
  const formatDate2 = (dateString) => {
    if (!dateString) return __("N/A", "yatra");
    try {
      const date2 = new Date(dateString);
      return date2.toLocaleDateString("en-US", {
        month: "short",
        day: "numeric",
        year: "numeric",
        hour: "2-digit",
        minute: "2-digit"
      });
    } catch (e) {
      return dateString;
    }
  };
  const getStatusBadge = (status) => {
    const statusMap = {
      publish: {
        className: "bg-green-100 text-green-700 dark:bg-green-900/20 dark:text-green-400",
        label: __("Publish", "yatra")
      },
      draft: {
        className: "bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-400",
        label: __("Draft", "yatra")
      },
      trash: {
        className: "bg-red-100 text-red-700 dark:bg-red-900/20 dark:text-red-400",
        label: __("Trash", "yatra")
      }
    };
    const statusInfo = statusMap[status] || {
      className: "bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-400",
      label: status
    };
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "span",
      {
        className: `inline-flex items-center px-2 py-1 rounded-md text-xs font-medium ${statusInfo.className}`,
        children: statusInfo.label
      }
    );
  };
  const renderIcon = (icon) => {
    if (!icon) {
      return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-8 h-8 rounded bg-gray-100 dark:bg-gray-800 flex items-center justify-center", children: /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs text-gray-400 dark:text-gray-500", children: "—" }) });
    }
    if (icon.type === "image") {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        "img",
        {
          src: icon.value,
          alt: "",
          className: "w-8 h-8 rounded object-cover",
          onError: (e) => {
            const target2 = e.target;
            target2.style.display = "none";
            if (target2.parentElement) {
              target2.parentElement.innerHTML = '<div class="w-8 h-8 rounded bg-gray-100 dark:bg-gray-800 flex items-center justify-center"><span class="text-xs text-gray-400 dark:text-gray-500">—</span></div>';
            }
          }
        }
      );
    }
    return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-8 h-8 rounded bg-gray-100 dark:bg-gray-800 flex items-center justify-center", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
      IconSelector,
      {
        iconName: icon.value,
        provider: icon.provider ?? "yatra",
        className: "w-5 h-5 text-gray-600 dark:text-gray-400"
      }
    ) });
  };
  const toggleExpand = (categoryId) => {
    const id = typeof categoryId === "string" ? parseInt(categoryId, 10) : categoryId;
    setExpandedCategories((prev) => {
      const newSet = new Set(prev);
      if (newSet.has(id)) {
        newSet.delete(id);
      } else {
        newSet.add(id);
      }
      return newSet;
    });
  };
  const handleEdit = (category) => {
    var _a;
    window.location.href = `${((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=trips&tab=categories&action=edit&id=${category.id}`;
  };
  const handleView = async (category) => {
    const categorySlug = category.slug || "";
    const { plainUrl, prettyUrl } = buildYatraSinglePublicUrls({
      entity: "category",
      slug: categorySlug,
      bases: settings2
    });
    if (isWordPressPlainPermalink()) {
      if (!categorySlug) {
        showToast(__("Category slug is missing", "yatra"), "error");
        return;
      }
      window.open(plainUrl, "_blank", "noopener,noreferrer");
      return;
    }
    let apiPermalink = (category == null ? void 0 : category.permalink) || (category == null ? void 0 : category.url);
    if (!apiPermalink && category.id) {
      try {
        const detail = await apiClient.get(`/trip-categories/${category.id}`);
        apiPermalink = (detail == null ? void 0 : detail.permalink) || (detail == null ? void 0 : detail.url) || apiPermalink;
      } catch (e) {
      }
    }
    if (apiPermalink) {
      window.open(apiPermalink, "_blank", "noopener,noreferrer");
      return;
    }
    if (!categorySlug) {
      showToast(__("Category slug is missing", "yatra"), "error");
      return;
    }
    window.open(prettyUrl, "_blank", "noopener,noreferrer");
  };
  const confirmDelete = () => {
    if (deleteConfirm.category) {
      deleteMutation.mutate(deleteConfirm.category.id);
    }
  };
  const handleCreateCategory = () => {
    var _a;
    window.location.href = `${((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=trips&tab=categories&action=create`;
  };
  const handleResetFilters = () => {
    setSearchTerm("");
    setStatusFilter("all");
    setParentFilter("all");
    setSortBy("name");
    setSortOrder("asc");
    setPage(1);
  };
  const hasFilters = searchTerm || statusFilter !== "all" || parentFilter !== "all" || sortBy2 !== "name" || sortOrder !== "asc";
  const columns = reactExports.useMemo(
    () => [
      {
        key: "name",
        label: __("Name", "yatra"),
        sortable: true,
        visible: visibleColumns.name,
        render: (category) => {
          var _a;
          const editUrl = `${((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=trips&tab=categories&action=edit&id=${category.id}`;
          return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex items-start gap-2", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1 min-w-0", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "a",
                {
                  href: editUrl,
                  onClick: (e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    handleEdit(category);
                  },
                  className: "font-medium text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300 underline-offset-2 hover:underline truncate",
                  children: category.name
                }
              ),
              can("yatra_view_trips") && category.status !== "trash" && /* @__PURE__ */ jsxRuntimeExports.jsx(
                "button",
                {
                  type: "button",
                  onClick: (e) => {
                    e.stopPropagation();
                    handleView(category);
                  },
                  className: "ml-1 inline-flex items-center justify-center rounded-full p-1 text-gray-400 hover:text-gray-700 hover:bg-gray-100 dark:text-gray-400 dark:hover:text-white dark:hover:bg-gray-800",
                  title: __("View category in new tab", "yatra"),
                  children: /* @__PURE__ */ jsxRuntimeExports.jsx(ExternalLink, { className: "w-3.5 h-3.5" })
                }
              )
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-xs text-gray-500 dark:text-gray-400 mt-0.5 truncate", children: [
              category.slug,
              /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "ml-1 text-[11px] text-gray-400 dark:text-gray-500", children: [
                "(ID: ",
                category.id,
                ")"
              ] })
            ] })
          ] }) });
        }
      },
      {
        key: "trips",
        label: __("Trips", "yatra"),
        visible: visibleColumns.trips,
        render: (category) => /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300", children: typeof category.trip_count === "number" ? category.trip_count : 0 })
      },
      {
        key: "description",
        label: __("Description", "yatra"),
        visible: visibleColumns.description,
        render: (category) => /* @__PURE__ */ jsxRuntimeExports.jsx(
          "span",
          {
            className: `block max-w-[300px] truncate ${category.status === "trash" || statusFilter === "trash" ? "text-gray-400 dark:text-gray-600" : "text-gray-600 dark:text-gray-400"}`,
            title: category.description || "",
            children: category.description || __("No description", "yatra")
          }
        )
      },
      {
        key: "seo_title",
        label: __("SEO Title", "yatra"),
        visible: visibleColumns.seo_title,
        render: (category) => {
          var _a;
          return /* @__PURE__ */ jsxRuntimeExports.jsx(
            "span",
            {
              className: category.status === "trash" ? "text-gray-400 dark:text-gray-600" : "text-gray-600 dark:text-gray-400",
              children: ((_a = category.metadata) == null ? void 0 : _a.seo_title) || __("Not set", "yatra")
            }
          );
        }
      },
      {
        key: "seo_description",
        label: __("SEO Description", "yatra"),
        visible: visibleColumns.seo_description,
        render: (category) => {
          var _a, _b;
          return /* @__PURE__ */ jsxRuntimeExports.jsx(
            "span",
            {
              className: category.status === "trash" ? "text-gray-400 dark:text-gray-600" : "text-gray-600 dark:text-gray-400",
              title: ((_a = category.metadata) == null ? void 0 : _a.seo_description) || "",
              children: ((_b = category.metadata) == null ? void 0 : _b.seo_description) ? category.metadata.seo_description.length > 50 ? category.metadata.seo_description.substring(0, 50) + "..." : category.metadata.seo_description : __("Not set", "yatra")
            }
          );
        }
      },
      {
        key: "seo_keywords",
        label: __("SEO Keywords", "yatra"),
        visible: visibleColumns.seo_keywords,
        render: (category) => {
          var _a, _b;
          return /* @__PURE__ */ jsxRuntimeExports.jsx(
            "span",
            {
              className: category.status === "trash" ? "text-gray-400 dark:text-gray-600" : "text-gray-600 dark:text-gray-400",
              title: ((_a = category.metadata) == null ? void 0 : _a.seo_keywords) || "",
              children: ((_b = category.metadata) == null ? void 0 : _b.seo_keywords) ? category.metadata.seo_keywords.length > 30 ? category.metadata.seo_keywords.substring(0, 30) + "..." : category.metadata.seo_keywords : __("Not set", "yatra")
            }
          );
        }
      },
      {
        key: "status",
        label: __("Status", "yatra"),
        sortable: true,
        visible: visibleColumns.status,
        render: (category) => {
          return /* @__PURE__ */ jsxRuntimeExports.jsx(
            "span",
            {
              className: `inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${category.status === "publish" ? "bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300" : category.status === "draft" ? "bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-300" : "bg-gray-100 text-gray-800 dark:bg-gray-900/30 dark:text-gray-300"}`,
              children: category.status === "publish" ? __("Published", "yatra") : category.status === "draft" ? __("Draft", "yatra") : category.status === "trash" ? __("Trash", "yatra") : category.status
            }
          );
        }
      },
      {
        key: "created_at",
        label: __("Created", "yatra"),
        sortable: true,
        visible: visibleColumns.created_at
      }
    ],
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [visibleColumns]
  );
  const statusMutation = useMutation({
    mutationFn: async ({ id, status }) => {
      const categoryResponse = await apiClient.get(`/trip-categories/${id}`);
      const category = categoryResponse;
      return apiClient.put(`/trip-categories/${id}`, {
        name: category.name,
        slug: category.slug,
        description: category.description,
        icon: category.icon,
        parent_id: category.parent_id,
        status
      });
    },
    onSuccess: (_data, variables) => {
      queryClient2.invalidateQueries({ queryKey: ["trip-categories"] });
      const msgMap = {
        trash: __("Category moved to trash", "yatra"),
        draft: __("Category marked as draft", "yatra"),
        publish: __("Category published", "yatra")
      };
      const msg = msgMap[variables.status] || __("Category updated successfully", "yatra");
      showToast(msg, "success");
    },
    onError: (error2, variables) => {
      const msgMapError = {
        trash: __("Failed to move category to trash", "yatra"),
        draft: __("Failed to mark category as draft", "yatra"),
        publish: __("Failed to publish category", "yatra")
      };
      const fallback = msgMapError[variables.status] || __("Failed to update category", "yatra");
      showToast((error2 == null ? void 0 : error2.message) || fallback, "error");
    }
  });
  const actions = [
    {
      key: "view",
      label: __("View (frontend)", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(ExternalLink, { className: "w-4 h-4" }),
      onClick: (category) => {
        var _a;
        const categoryUrl = `${((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || ""}/trip-category/${category.slug}`;
        window.open(categoryUrl, "_blank");
      },
      condition: (category) => category.status !== "trash"
      // Hide for trash categories
    },
    {
      key: "edit",
      label: __("Edit", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(PenSquare, { className: "w-4 h-4" }),
      onClick: (category) => handleEdit(category),
      condition: () => can("yatra_edit_trips")
    },
    {
      key: "publish",
      label: __("Make Published", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(PenSquare, { className: "w-4 h-4" }),
      onClick: (category) => statusMutation.mutate({ id: category.id, status: "publish" }),
      condition: (category) => can("yatra_edit_trips") && category.status !== "publish"
    },
    {
      key: "draft",
      label: __("Make Draft", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(PenSquare, { className: "w-4 h-4" }),
      onClick: (category) => statusMutation.mutate({ id: category.id, status: "draft" }),
      condition: (category) => can("yatra_edit_trips") && category.status !== "draft"
    },
    {
      key: "trash",
      label: __("Move to Trash", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "w-4 h-4" }),
      onClick: (category) => statusMutation.mutate({ id: category.id, status: "trash" }),
      variant: "destructive",
      condition: (category) => can("yatra_edit_trips") && category.status !== "trash"
    },
    {
      key: "delete",
      label: __("Delete Permanently", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "w-4 h-4" }),
      onClick: (category) => setDeleteConfirm({ isOpen: true, category }),
      variant: "destructive",
      condition: (category) => can("yatra_edit_trips") && category.status === "trash"
    }
  ];
  const renderRowContent = (category, _index, isChild = false) => {
    const visibleColumns2 = columns.filter((col) => col.visible !== false);
    return visibleColumns2.map((column) => {
      var _a;
      switch (column.key) {
        case "name":
          return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
            renderIcon(category.icon),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "font-medium text-gray-900 dark:text-white flex items-center gap-1", children: [
                isChild && /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-400 mr-1", children: "└─" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "a",
                  {
                    href: `${((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=trips&tab=categories&action=edit&id=${category.id}`,
                    className: "font-medium text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 hover:underline transition-colors cursor-pointer",
                    children: category.name
                  }
                ),
                can("yatra_view_trips") && category.status !== "trash" && /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "button",
                  {
                    type: "button",
                    onClick: (e) => {
                      e.stopPropagation();
                      handleView(category);
                    },
                    className: "ml-1 inline-flex items-center justify-center rounded-full p-1 text-gray-400 hover:text-gray-700 hover:bg-gray-100 dark:text-gray-400 dark:hover:text-white dark:hover:bg-gray-800",
                    title: __("View category in new tab", "yatra"),
                    children: /* @__PURE__ */ jsxRuntimeExports.jsx(ExternalLink, { className: "w-3.5 h-3.5" })
                  }
                )
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-sm text-gray-500 dark:text-gray-400 flex items-center gap-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: category.slug }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-[11px] text-gray-400 dark:text-gray-500", children: [
                  "(",
                  __("ID:", "yatra"),
                  " ",
                  category.id,
                  ")"
                ] })
              ] }),
              category.parent_name && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-xs text-gray-500 dark:text-gray-400", children: [
                __("Parent:", "yatra"),
                " ",
                category.parent_name
              ] })
            ] })
          ] });
        case "trips":
          return /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300", children: typeof category.trip_count === "number" ? category.trip_count : 0 });
        case "description":
          return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "max-w-xs truncate text-sm text-gray-600 dark:text-gray-400", children: category.description || "—" });
        case "status":
          return getStatusBadge(category.status);
        case "created_at":
          return /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm text-gray-600 dark:text-gray-400", children: formatDate2(category.created_at) });
        case "seo_title":
        case "seo_description":
        case "seo_keywords":
          return column.render ? column.render(category) : null;
        default:
          return column.render ? column.render(category) : category[column.key];
      }
    });
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      ConfirmationDialog,
      {
        isOpen: deleteConfirm.isOpen,
        onClose: () => setDeleteConfirm({ isOpen: false, category: null }),
        onConfirm: confirmDelete,
        title: __("Delete Category", "yatra"),
        message: deleteConfirm.category ? __(
          'Are you sure you want to delete "{name}"? This action cannot be undone.',
          "yatra"
        ).replace("{name}", deleteConfirm.category.name) : __(
          "Are you sure you want to delete this category? This action cannot be undone.",
          "yatra"
        ),
        confirmText: __("Delete Permanently", "yatra"),
        cancelText: __("Cancel", "yatra"),
        variant: "danger",
        isLoading: deleteMutation.isPending
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      PageHeader,
      {
        title: __("Categories", "yatra"),
        description: __("Manage trip categories and subcategories", "yatra"),
        actionCapability: "yatra_edit_trips",
        actions: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Button,
          {
            onClick: handleCreateCategory,
            className: "flex items-center gap-2",
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Plus, { className: "w-4 h-4" }),
              __("Add New Category", "yatra")
            ]
          }
        )
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col gap-3 lg:flex-row lg:items-center", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "min-w-0 w-full lg:flex-[4]", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        SearchFilterToolbar,
        {
          searchTerm,
          onSearchChange: setSearchTerm,
          statusFilter,
          onStatusChange: (value) => {
            setStatusFilter(value);
            setPage(1);
          },
          statusOptions: [
            { value: "all", label: __("All Status", "yatra") },
            { value: "publish", label: __("Publish", "yatra") },
            { value: "draft", label: __("Draft", "yatra") },
            { value: "trash", label: __("Trash", "yatra") }
          ],
          sortBy: sortBy2,
          onSortByChange: (value) => {
            setSortBy(value);
            setSortOrder("asc");
            setPage(1);
          },
          sortOrder,
          onSortOrderChange: (order) => {
            setSortOrder(order);
            setPage(1);
          },
          sortOptions: [
            { value: "name", label: __("Name", "yatra") },
            { value: "status", label: __("Status", "yatra") },
            { value: "created_at", label: __("Created", "yatra") }
          ],
          onResetFilters: handleResetFilters,
          hasFilters: !!hasFilters,
          placeholder: __("Search categories", "yatra")
        }
      ) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-full lg:w-48 xl:w-56 lg:flex-none", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Select,
        {
          value: parentFilter,
          onChange: (e) => setParentFilter(
            e.target.value
          ),
          className: "w-full text-sm truncate",
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "all", children: __("All Categories", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "top-level", children: __("Top Level Only", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "subcategories", children: __("Subcategories Only", "yatra") })
          ]
        }
      ) })
    ] }) }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      BulkActionToolbar,
      {
        selectedIds,
        bulkAction,
        setBulkAction,
        onApply: handleBulkApply,
        onClearSelection: () => setSelectedIds([]),
        statusFilter,
        setStatusFilter: (value) => {
          setStatusFilter(value);
          setPage(1);
          setSelectedIds([]);
          setBulkAction("");
        },
        statusOptions: [
          { key: "all", label: __("All", "yatra"), count: statusCounts.all },
          {
            key: "publish",
            label: __("Published", "yatra"),
            count: statusCounts.publish
          },
          {
            key: "draft",
            label: __("Draft", "yatra"),
            count: statusCounts.draft
          },
          {
            key: "trash",
            label: __("Trash", "yatra"),
            count: statusCounts.trash
          }
        ],
        showColumnsDropdown,
        setShowColumnsDropdown,
        columnOptions: [
          {
            key: "name",
            label: __("Category", "yatra"),
            visible: visibleColumns.name
          },
          {
            key: "description",
            label: __("Description", "yatra"),
            visible: visibleColumns.description
          },
          {
            key: "trips",
            label: __("Trips", "yatra"),
            visible: visibleColumns.trips
          },
          {
            key: "seo_title",
            label: __("SEO Title", "yatra"),
            visible: visibleColumns.seo_title
          },
          {
            key: "seo_description",
            label: __("SEO Description", "yatra"),
            visible: visibleColumns.seo_description
          },
          {
            key: "seo_keywords",
            label: __("SEO Keywords", "yatra"),
            visible: visibleColumns.seo_keywords
          },
          {
            key: "status",
            label: __("Status", "yatra"),
            visible: visibleColumns.status
          },
          {
            key: "created_at",
            label: __("Created Date", "yatra"),
            visible: visibleColumns.created_at
          }
        ],
        onToggleColumn: toggleColumn,
        bulkMutationPending: bulkMutation.isPending,
        totalItems: processedCategories.length,
        bulkActionOptions: getDefaultBulkStatusOptions(statusFilter)
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "p-0", children: [
      null,
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        Table,
        {
          data: processedCategories,
          columns,
          actions,
          isLoading,
          isError: !!error,
          errorText: __("Error loading categories", "yatra"),
          errorDescription: __(
            "We couldn’t connect to the categories service. Please refresh or try again shortly.",
            "We couldn’t connect to the categories service. Please refresh or try again shortly."
          ),
          onRetry: () => queryClient2.invalidateQueries({ queryKey: ["trip-categories"] }),
          errorDetails: errorContext.details,
          errorRequestInfo: errorContext.requestInfo,
          emptyText: __("No categories found", "yatra"),
          emptyDescription: __(
            "Organize trips into categories to help travelers find the perfect fit.",
            "Organize trips into categories to help travelers find the perfect fit."
          ),
          onCreateClick: handleCreateCategory,
          selectedItemIds: selectedIds,
          onSelectItem: (id, checked) => {
            if (checked) {
              setSelectedIds([...selectedIds, id]);
            } else {
              setSelectedIds(
                selectedIds.filter((selectedId) => selectedId !== id)
              );
            }
          },
          onSelectAll: (checked) => {
            if (checked) {
              setSelectedIds(
                processedCategories.map((cat) => cat.id)
              );
            } else {
              setSelectedIds([]);
            }
          },
          isAllSelected: processedCategories.length > 0 && selectedIds.length === processedCategories.length,
          getItemId: (category) => category.id,
          getItemStatus: (category) => category.status,
          statusFilter,
          skeletonRows: 5,
          capability: "yatra_view_trips",
          isHierarchical: true,
          expandedIds: expandedCategories,
          onToggleExpand: toggleExpand,
          getChildren: (category) => category.subcategories || [],
          renderRowContent
        },
        `categories-table-${JSON.stringify(visibleColumns)}`
      )
    ] }) }),
    total > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-4", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
      Pagination,
      {
        currentPage: page,
        totalPages,
        totalItems: total,
        itemsPerPage: 10,
        onPageChange: (newPage) => setPage(newPage),
        itemName: __("categories", "yatra")
      }
    ) })
  ] });
};
function parseTripCategoryIsFeatured(raw) {
  if (raw === true || raw === 1) {
    return true;
  }
  if (raw === false || raw === 0 || raw === null || raw === void 0) {
    return false;
  }
  if (typeof raw === "string") {
    const t = raw.trim();
    return t === "1" || t.toLowerCase() === "true";
  }
  return Number(raw) === 1;
}
const CategoryForm = () => {
  const queryClient2 = useQueryClient();
  const { can } = usePermissions();
  const { showToast } = useToast();
  const [formData, setFormData] = reactExports.useState({
    name: "",
    slug: "",
    description: "",
    icon: null,
    parent_id: "",
    status: "publish",
    is_featured: false,
    seo_title: "",
    seo_description: "",
    seo_keywords: "",
    landing_page_id: null
  });
  const [errors, setErrors] = reactExports.useState({});
  const [isSubmitting, setIsSubmitting] = reactExports.useState(false);
  const [isSlugEditable, setIsSlugEditable] = reactExports.useState(false);
  const action = reactExports.useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get("action") || "create";
  }, []);
  const categoryId = reactExports.useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get("id") ? parseInt(params.get("id") || "0", 10) : null;
  }, []);
  const isEditMode = action === "edit" && categoryId !== null;
  const { data: categoryData, isLoading: isLoadingCategory } = useQuery({
    queryKey: ["trip-category", categoryId],
    queryFn: async () => {
      if (!categoryId) return null;
      try {
        const response = await apiClient.get(`/trip-categories/${categoryId}`);
        return response;
      } catch (error) {
        showToast(
          (error == null ? void 0 : error.message) || __("Failed to load category", "yatra"),
          "error"
        );
        throw error;
      }
    },
    enabled: isEditMode && can("yatra_view_trips")
  });
  const { data: parentCategoriesData } = useQuery({
    queryKey: ["trip-categories", "parent-options"],
    queryFn: async () => {
      try {
        const response = await apiClient.get("/trip-categories", {
          params: {
            per_page: 100,
            parent_id: null,
            hierarchical: false,
            orderby: "name",
            order: "ASC"
          }
        });
        const payload = (response == null ? void 0 : response.data) || response;
        if (!payload) {
          return [];
        }
        if (Array.isArray(payload)) {
          return payload;
        }
        return payload.data || [];
      } catch (error) {
        return [];
      }
    },
    enabled: can("yatra_view_trips")
  });
  const { data: settings2 } = useQuery({
    queryKey: ["settings"],
    queryFn: async () => {
      try {
        const response = await fetchSettings();
        return (response == null ? void 0 : response.data) || response;
      } catch (error) {
        return {};
      }
    }
  });
  const parentOptions = reactExports.useMemo(() => {
    if (!parentCategoriesData || !Array.isArray(parentCategoriesData)) {
      return [];
    }
    return parentCategoriesData.filter((cat) => {
      if (!cat || typeof cat !== "object") return false;
      if (cat.parent_id) return false;
      if (isEditMode && categoryId && cat.id === categoryId) return false;
      return true;
    });
  }, [parentCategoriesData, isEditMode, categoryId]);
  reactExports.useEffect(() => {
    var _a, _b, _c;
    if (categoryData && isEditMode) {
      setFormData({
        name: categoryData.name || "",
        slug: categoryData.slug || "",
        description: categoryData.description || "",
        icon: categoryData.icon || null,
        parent_id: categoryData.parent_id ?? "",
        status: categoryData.status || "publish",
        is_featured: parseTripCategoryIsFeatured(
          categoryData.is_featured
        ),
        seo_title: ((_a = categoryData.metadata) == null ? void 0 : _a.seo_title) || "",
        seo_description: ((_b = categoryData.metadata) == null ? void 0 : _b.seo_description) || "",
        seo_keywords: ((_c = categoryData.metadata) == null ? void 0 : _c.seo_keywords) || "",
        landing_page_id: parseLandingPageIdFromMetadata(
          categoryData.metadata
        )
      });
    }
  }, [categoryData, isEditMode]);
  const handleNameChange = (value) => {
    if (!isEditMode && !isSlugEditable) {
      const newSlug = generateSlug(value);
      setFormData((prev) => ({
        ...prev,
        name: value,
        slug: newSlug
      }));
    } else {
      setFormData((prev) => ({ ...prev, name: value }));
    }
    if (errors.name) {
      setErrors((prev) => ({ ...prev, name: "" }));
    }
  };
  const handleSlugChange = (value) => {
    if (isSlugEditable) {
      setFormData((prev) => ({ ...prev, slug: value }));
      if (errors.slug) {
        setErrors((prev) => ({ ...prev, slug: "" }));
      }
    }
  };
  const handleToggleSlugEdit = () => {
    if (isSlugEditable) {
      const newSlug = generateSlug(formData.name);
      setFormData((prev) => ({ ...prev, slug: newSlug }));
    }
    setIsSlugEditable(!isSlugEditable);
  };
  const handleFieldChange = (field, value) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
    if (errors[field]) {
      setErrors((prev) => ({ ...prev, [field]: "" }));
    }
  };
  const validateForm = () => {
    const newErrors = {};
    if (!formData.name.trim()) {
      newErrors.name = __("Name is required", "yatra");
    }
    if (!formData.slug.trim()) {
      newErrors.slug = __("Slug is required", "yatra");
    } else if (!/^[\p{L}\p{N}-]+$/u.test(formData.slug)) {
      newErrors.slug = __(
        "Slug can only contain letters, numbers, and hyphens",
        "yatra"
      );
    }
    if (formData.parent_id && categoryId && Number(formData.parent_id) === categoryId) {
      newErrors.parent_id = __("Category cannot be its own parent", "yatra");
    }
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };
  const saveMutation = useMutation({
    mutationFn: async (data) => {
      const payload = {
        name: data.name.trim(),
        slug: data.slug.trim(),
        description: data.description.trim(),
        icon: data.icon,
        parent_id: data.parent_id === "" ? null : Number(data.parent_id),
        status: data.status,
        is_featured: data.is_featured ? 1 : 0,
        seo_title: data.seo_title.trim(),
        seo_description: data.seo_description.trim(),
        seo_keywords: data.seo_keywords.trim(),
        landing_page_id: data.landing_page_id ?? null
      };
      if (isEditMode && isSlugEditable) {
        payload.preserve_slug = true;
      }
      if (isEditMode && categoryId) {
        return await apiClient.put(`/trip-categories/${categoryId}`, payload);
      }
      return await apiClient.post("/trip-categories", payload);
    },
    onSuccess: (response) => {
      var _a, _b;
      queryClient2.invalidateQueries({ queryKey: ["trip-categories"] });
      queryClient2.invalidateQueries({
        queryKey: ["trip-category", categoryId]
      });
      showToast(
        isEditMode ? __("Category updated successfully", "yatra") : __("Category created successfully", "yatra"),
        "success"
      );
      setIsSubmitting(false);
      if (!isEditMode) {
        const newId = response == null ? void 0 : response.id;
        if (newId) {
          window.location.href = `${((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=trips&tab=categories&action=edit&id=${newId}`;
        } else {
          window.location.href = `${((_b = window.yatraAdmin) == null ? void 0 : _b.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=trips&tab=categories`;
        }
      }
    },
    onError: (error) => {
      const errorMessage = (error == null ? void 0 : error.message) || __("An error occurred while saving the category", "yatra");
      showToast(errorMessage, "error");
      setIsSubmitting(false);
    }
  });
  const handleSubmit = (e) => {
    e.preventDefault();
    if (!validateForm()) {
      showToast(__("Please fix the form errors", "yatra"), "warning");
      return;
    }
    setIsSubmitting(true);
    setErrors({});
    saveMutation.mutate(formData);
  };
  const handleCancel = () => {
    var _a;
    window.location.href = `${((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=trips&tab=categories`;
  };
  if (isEditMode && isLoadingCategory) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg p-6", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-8 bg-gray-200 dark:bg-gray-700 rounded w-1/4 mb-2 animate-pulse" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-1/2 animate-pulse" })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-3 gap-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "lg:col-span-2 space-y-3", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "p-6 space-y-4", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-20 mb-2 animate-pulse" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-16 mb-2 animate-pulse" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-24 mb-2 animate-pulse" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-32 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-20 mb-2 animate-pulse" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-32 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" })
          ] })
        ] }) }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "p-6 space-y-4", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-24 mb-2 animate-pulse" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" })
          ] }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "p-6 space-y-4", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-16 mb-2 animate-pulse" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" })
          ] }) })
        ] })
      ] })
    ] });
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      PageHeader,
      {
        title: isEditMode ? __("Edit Category", "yatra") : __("Add New Category", "yatra"),
        description: isEditMode ? __("Update category information", "yatra") : __("Create a new trip category", "yatra"),
        actions: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Button,
            {
              variant: "outline",
              onClick: handleCancel,
              className: "flex items-center gap-2",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowLeft, { className: "w-4 h-4" }),
                __("Back", "yatra")
              ]
            }
          ),
          formData.slug && /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Button,
            {
              variant: "outline",
              onClick: async () => {
                var _a;
                if (formData.landing_page_id && ((_a = window.yatraAdmin) == null ? void 0 : _a.customLandingPagesModuleEnabled)) {
                  const link2 = await fetchPublishedPagePermalink(
                    formData.landing_page_id
                  );
                  if (link2) {
                    window.open(link2, "_blank", "noopener,noreferrer");
                    return;
                  }
                }
                const targetUrl = buildYatraSinglePreviewUrl({
                  entity: "category",
                  slug: formData.slug || "",
                  bases: settings2
                });
                window.open(targetUrl, "_blank", "noopener,noreferrer");
              },
              className: "flex items-center gap-2",
              title: __("Preview category in new tab", "yatra"),
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Eye, { className: "w-4 h-4" }),
                __("Preview", "yatra")
              ]
            }
          )
        ] })
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_edit_trips", children: /* @__PURE__ */ jsxRuntimeExports.jsx("form", { onSubmit: handleSubmit, children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-3 gap-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "lg:col-span-2 space-y-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Basic Information", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs(
                "label",
                {
                  htmlFor: "name",
                  className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                  children: [
                    __("Name", "yatra"),
                    " ",
                    /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
                  ]
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Input,
                {
                  id: "name",
                  type: "text",
                  value: formData.name,
                  onChange: (e) => handleNameChange(e.target.value),
                  placeholder: __("Enter category name", "yatra"),
                  className: errors.name ? "border-red-500" : "",
                  required: true
                }
              ),
              errors.name && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm text-red-500", children: errors.name })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs(
                "label",
                {
                  htmlFor: "slug",
                  className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                  children: [
                    __("Slug", "yatra"),
                    " ",
                    /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
                  ]
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Input,
                  {
                    id: "slug",
                    type: "text",
                    value: formData.slug,
                    onChange: (e) => handleSlugChange(e.target.value),
                    placeholder: __("category-slug", "yatra"),
                    className: `pr-10 ${errors.slug ? "border-red-500" : ""} ${!isSlugEditable ? "bg-gray-50 dark:bg-gray-800 cursor-not-allowed" : ""}`,
                    disabled: !isSlugEditable,
                    required: true
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "button",
                  {
                    type: "button",
                    onClick: handleToggleSlugEdit,
                    className: "absolute right-2 top-1/2 -translate-y-1/2 p-1.5 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors rounded",
                    "aria-label": isSlugEditable ? __("Cancel editing slug", "yatra") : __("Edit slug", "yatra"),
                    children: isSlugEditable ? /* @__PURE__ */ jsxRuntimeExports.jsx(X, { className: "w-4 h-4" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(Pen, { className: "w-4 h-4" })
                  }
                )
              ] }),
              errors.slug && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm text-red-500", children: errors.slug }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-xs text-gray-500 dark:text-gray-400", children: isSlugEditable ? __(
                "Manually editing slug. Click X to cancel and regenerate from name.",
                "yatra"
              ) : __(
                "Auto-generated from name. Click edit icon to customize.",
                "yatra"
              ) })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-4", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
              RichTextEditor,
              {
                label: __("Description", "yatra"),
                value: formData.description || "",
                onChange: (value) => handleFieldChange("description", value),
                placeholder: __("Enter category description...", "yatra"),
                helperText: __(
                  "Describe what this category is for and what types of trips it contains.",
                  "yatra"
                ),
                minHeight: 120,
                maxHeight: 360
              }
            ) })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          ClassificationLandingPageField,
          {
            selectId: "yatra-category-landing-page",
            value: formData.landing_page_id,
            onChange: (id) => setFormData((prev) => ({ ...prev, landing_page_id: id }))
          }
        )
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Hierarchy", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "space-y-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "label",
              {
                htmlFor: "parent_id",
                className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                children: __("Parent Category", "yatra")
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              Select,
              {
                id: "parent_id",
                value: formData.parent_id === "" ? "" : String(formData.parent_id),
                onChange: (e) => handleFieldChange(
                  "parent_id",
                  e.target.value === "" ? "" : Number(e.target.value)
                ),
                className: "w-full h-10",
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "", children: __("None (Top Level)", "yatra") }),
                  parentOptions.map((cat) => /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: cat.id, children: cat.name }, cat.id))
                ]
              }
            ),
            errors.parent_id && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm text-red-500", children: errors.parent_id }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-xs text-gray-500 dark:text-gray-400", children: __(
              "Assign a parent category to create subcategories.",
              "yatra"
            ) })
          ] }) })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Status", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Select,
            {
              id: "status",
              value: formData.status,
              onChange: (e) => handleFieldChange("status", e.target.value),
              className: "w-full h-10",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "draft", children: __("Draft", "yatra") }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "publish", children: __("Publish", "yatra") }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "trash", children: __("Trash", "yatra") })
              ]
            }
          ) })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Visibility", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs("label", { className: "flex items-start gap-3 cursor-pointer", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "input",
              {
                type: "checkbox",
                className: "mt-1 h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500",
                checked: formData.is_featured,
                onChange: (e) => handleFieldChange("is_featured", e.target.checked)
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "block text-sm font-medium text-gray-900 dark:text-gray-100", children: __("Featured category", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "block text-xs text-gray-500 dark:text-gray-400 mt-0.5", children: __(
                "Shows a “Featured” badge on Trip Category blocks and the [yatra_trip_category] shortcode cards.",
                "yatra"
              ) })
            ] })
          ] }) })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("SEO Settings", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "label",
                {
                  htmlFor: "seo_title",
                  className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",
                  children: __("Meta Title", "yatra")
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Input,
                {
                  id: "seo_title",
                  type: "text",
                  value: formData.seo_title,
                  onChange: (e) => handleFieldChange("seo_title", e.target.value),
                  placeholder: __(
                    "e.g., {name} Trip Categories | Your Travel Agency",
                    "yatra"
                  ),
                  className: "w-full"
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400 mt-1", children: __(
                "Custom title for search engines. Use {name} as placeholder.",
                "yatra"
              ) })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "label",
                {
                  htmlFor: "seo_description",
                  className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",
                  children: __("Meta Description", "yatra")
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "textarea",
                {
                  id: "seo_description",
                  value: formData.seo_description,
                  onChange: (e) => handleFieldChange("seo_description", e.target.value),
                  placeholder: __(
                    "e.g., Browse {name} trip categories and find your perfect adventure. Book now!",
                    "yatra"
                  ),
                  rows: 3,
                  className: "w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-white"
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400 mt-1", children: __(
                "Description for search engines (150-160 characters). Use {name} as placeholder.",
                "yatra"
              ) })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "label",
                {
                  htmlFor: "seo_keywords",
                  className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",
                  children: __("Meta Keywords", "yatra")
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Input,
                {
                  id: "seo_keywords",
                  type: "text",
                  value: formData.seo_keywords,
                  onChange: (e) => handleFieldChange("seo_keywords", e.target.value),
                  placeholder: __(
                    "e.g., categories, trips, {name}, travel, adventure",
                    "yatra"
                  ),
                  className: "w-full"
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400 mt-1", children: __(
                "Comma-separated keywords. Use {name} as placeholder.",
                "yatra"
              ) })
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Category Icon or Image", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            IconPicker,
            {
              value: formData.icon,
              onChange: (value) => handleFieldChange("icon", value),
              label: __("Select Icon or Upload Image", "yatra"),
              helpText: __(
                "Choose a library icon or upload a custom image for this category.",
                "yatra"
              ),
              allowImageUpload: true,
              allowIconSelection: true,
              size: "md"
            }
          ) })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-3", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-2", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Button,
            {
              type: "submit",
              disabled: isSubmitting,
              className: "flex-1 flex items-center justify-center gap-2",
              children: isSubmitting ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Loader2, { className: "w-4 h-4 animate-spin" }),
                __("Saving...", "yatra")
              ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Save, { className: "w-4 h-4" }),
                isEditMode ? __("Update Category", "yatra") : __("Create Category", "yatra")
              ] })
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Button,
            {
              type: "button",
              variant: "outline",
              onClick: handleCancel,
              disabled: isSubmitting,
              children: __("Cancel", "yatra")
            }
          )
        ] }) }) }) })
      ] })
    ] }) }) })
  ] });
};
const DifficultyLevels = () => {
  const [searchTerm, setSearchTerm] = reactExports.useState("");
  const [statusFilter, setStatusFilter] = reactExports.useState("all");
  const [sortBy2, setSortBy] = reactExports.useState("sorting");
  const [sortOrder, setSortOrder] = reactExports.useState("asc");
  const [page, setPage] = reactExports.useState(1);
  const [selectedIds, setSelectedIds] = reactExports.useState([]);
  const [bulkAction, setBulkAction] = reactExports.useState("");
  const [showColumnsDropdown, setShowColumnsDropdown] = reactExports.useState(false);
  const [visibleColumns, setVisibleColumns] = reactExports.useState(() => {
    const defaultColumns = {
      sorting: true,
      name: true,
      description: true,
      trips: true,
      status: true,
      created_at: false
    };
    const saved = localStorage.getItem("yatra_difficulty_levels_columns");
    return saved ? { ...defaultColumns, ...JSON.parse(saved) } : defaultColumns;
  });
  const { can } = usePermissions();
  const { showToast } = useToast();
  const queryClient2 = useQueryClient();
  const [deleteConfirm, setDeleteConfirm] = reactExports.useState({
    isOpen: false,
    level: null
  });
  const columns = [
    {
      key: "sorting",
      label: __("Order", "yatra"),
      sortable: true,
      width: "100px",
      visible: visibleColumns.sorting,
      render: (level) => /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-900 dark:text-white", children: level.sorting })
    },
    {
      key: "name",
      label: __("Name", "yatra"),
      sortable: true,
      visible: visibleColumns.name,
      render: (level) => {
        var _a;
        return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3", children: [
          renderIcon(level.icon),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "a",
              {
                href: `${((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=trips&tab=difficulty-levels&action=edit&id=${level.id}`,
                className: "font-medium text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 hover:underline transition-colors cursor-pointer",
                children: level.name
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-xs text-gray-500 dark:text-gray-400 flex items-center gap-2", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: level.slug || "—" }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-[11px] text-gray-400 dark:text-gray-500", children: [
                "(",
                __("ID:", "yatra"),
                " ",
                level.id,
                ")"
              ] })
            ] })
          ] })
        ] });
      }
    },
    {
      key: "description",
      label: __("Description", "yatra"),
      visible: visibleColumns.description,
      render: (level) => /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "max-w-xs truncate text-sm text-gray-600 dark:text-gray-400", children: level.description || "—" })
    },
    {
      key: "trips",
      label: __("Trips", "yatra"),
      visible: visibleColumns.trips,
      render: (level) => /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300", children: typeof level.trip_count === "number" ? level.trip_count : 0 })
    },
    {
      key: "status",
      label: __("Status", "yatra"),
      sortable: true,
      visible: visibleColumns.status,
      render: (level) => getStatusBadge(level.status)
    },
    {
      key: "created_at",
      label: __("Created", "yatra"),
      sortable: true,
      visible: visibleColumns.created_at,
      render: (level) => /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-600 dark:text-gray-400", children: formatDate2(level.created_at) })
    }
  ];
  const actions = [
    {
      key: "edit",
      label: __("Edit", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(PenSquare, { className: "w-4 h-4" }),
      onClick: (level) => handleEdit(level),
      condition: () => can("yatra_edit_trips")
    },
    {
      key: "publish",
      label: __("Make Published", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(PenSquare, { className: "w-4 h-4" }),
      onClick: (level) => statusMutation.mutate({ id: level.id, status: "publish" }),
      condition: (level) => can("yatra_edit_trips") && level.status !== "publish"
    },
    {
      key: "draft",
      label: __("Make Draft", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(PenSquare, { className: "w-4 h-4" }),
      onClick: (level) => statusMutation.mutate({ id: level.id, status: "draft" }),
      condition: (level) => can("yatra_edit_trips") && level.status !== "draft"
    },
    {
      key: "delete",
      label: __("Delete", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "w-4 h-4" }),
      onClick: (level) => setDeleteConfirm({ isOpen: true, level }),
      variant: "destructive",
      condition: (level) => can("yatra_edit_trips") && level.status === "trash"
    },
    {
      key: "trash",
      label: __("Move to Trash", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "w-4 h-4" }),
      onClick: (level) => statusMutation.mutate({ id: level.id, status: "trash" }),
      variant: "destructive",
      condition: (level) => can("yatra_edit_trips") && level.status !== "trash"
    }
  ];
  const queryParams = reactExports.useMemo(() => {
    const params = {
      page,
      per_page: 20,
      orderby: sortBy2,
      order: sortOrder
    };
    if (searchTerm) {
      params.search = searchTerm;
    }
    if (statusFilter !== "all") {
      params.status = statusFilter;
    }
    return params;
  }, [searchTerm, statusFilter, sortBy2, sortOrder, page]);
  const { data: statsData } = useQuery({
    queryKey: ["difficulty-levels-stats"],
    queryFn: async () => {
      try {
        const response = await apiClient.get("/difficulty-levels/stats");
        return response;
      } catch (error2) {
        return { all: 0, publish: 0, draft: 0, trash: 0 };
      }
    },
    enabled: can("yatra_view_trips")
  });
  const { data, isLoading, error } = useQuery({
    queryKey: ["difficulty-levels", queryParams],
    queryFn: async () => {
      try {
        const response = await apiClient.get("/difficulty-levels", {
          params: queryParams
        });
        return response;
      } catch (error2) {
        showToast(
          (error2 == null ? void 0 : error2.message) || __("Failed to load difficulty levels", "yatra"),
          "error"
        );
        throw error2;
      }
    },
    enabled: can("yatra_view_trips")
  });
  const deleteMutation = useMutation({
    mutationFn: async (id) => apiClient.delete(`/difficulty-levels/${id}`),
    onSuccess: () => {
      queryClient2.invalidateQueries({ queryKey: ["difficulty-levels"] });
      queryClient2.invalidateQueries({ queryKey: ["difficulty-levels-stats"] });
      showToast(
        __("Difficulty level deleted successfully", "yatra"),
        "success"
      );
    },
    onError: (error2) => {
      showToast(
        (error2 == null ? void 0 : error2.message) || __("Failed to delete difficulty level", "yatra"),
        "error"
      );
    }
  });
  const statusMutation = useMutation({
    mutationFn: async ({ id, status }) => {
      const levelResponse = await apiClient.get(`/difficulty-levels/${id}`);
      const level = levelResponse;
      return apiClient.put(`/difficulty-levels/${id}`, {
        name: level.name,
        slug: level.slug,
        description: level.description,
        icon: level.icon,
        sorting: level.sorting,
        status
      });
    },
    onSuccess: (_data, variables) => {
      queryClient2.invalidateQueries({ queryKey: ["difficulty-levels"] });
      queryClient2.invalidateQueries({ queryKey: ["difficulty-levels-stats"] });
      const msgMap = {
        trash: __("Difficulty level moved to trash", "yatra"),
        draft: __("Difficulty level marked as draft", "yatra"),
        publish: __("Difficulty level published", "yatra")
      };
      const msg = msgMap[variables.status] || __("Difficulty level updated successfully", "yatra");
      showToast(msg, "success");
    },
    onError: (error2, variables) => {
      const msgMapError = {
        trash: __("Failed to move difficulty level to trash", "yatra"),
        draft: __("Failed to mark difficulty level as draft", "yatra"),
        publish: __("Failed to publish difficulty level", "yatra")
      };
      const fallback = msgMapError[variables.status] || __("Failed to update difficulty level", "yatra");
      showToast((error2 == null ? void 0 : error2.message) || fallback, "error");
    }
  });
  const levels = (data == null ? void 0 : data.data) || [];
  const total = (data == null ? void 0 : data.total) || 0;
  const totalPages = Math.ceil(total / 20);
  const errorContext = getErrorContext(error);
  const statusCounts = reactExports.useMemo(() => {
    if (statsData) {
      return {
        all: statsData.all ?? 0,
        publish: statsData.publish ?? 0,
        draft: statsData.draft ?? 0,
        trash: statsData.trash ?? 0
      };
    }
    return {
      all: 0,
      publish: 0,
      draft: 0,
      trash: 0
    };
  }, [statsData]);
  const formatDate2 = (dateString) => {
    if (!dateString) return __("N/A", "yatra");
    try {
      const date2 = new Date(dateString);
      return date2.toLocaleDateString("en-US", {
        month: "short",
        day: "numeric",
        year: "numeric",
        hour: "2-digit",
        minute: "2-digit"
      });
    } catch {
      return dateString;
    }
  };
  const getStatusBadge = (status) => {
    const map2 = {
      publish: {
        className: "bg-green-100 text-green-700 dark:bg-green-900/20 dark:text-green-400",
        label: __("Publish", "yatra")
      },
      draft: {
        className: "bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-400",
        label: __("Draft", "yatra")
      },
      trash: {
        className: "bg-red-100 text-red-700 dark:bg-red-900/20 dark:text-red-400",
        label: __("Trash", "yatra")
      }
    };
    const info2 = map2[status] || map2.draft;
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "span",
      {
        className: `inline-flex items-center px-2 py-1 rounded-md text-xs font-medium ${info2.className}`,
        children: info2.label
      }
    );
  };
  const renderIcon = (icon) => {
    if (!icon) {
      return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-8 h-8 rounded bg-gray-100 dark:bg-gray-800 flex items-center justify-center", children: /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs text-gray-400 dark:text-gray-500", children: "—" }) });
    }
    if (icon.type === "image") {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        "img",
        {
          src: icon.value,
          alt: "",
          className: "w-8 h-8 rounded object-cover",
          onError: (e) => {
            const target2 = e.target;
            target2.style.display = "none";
            if (target2.parentElement) {
              target2.parentElement.innerHTML = '<div class="w-8 h-8 rounded bg-gray-100 dark:bg-gray-800 flex items-center justify-center"><span class="text-xs text-gray-400 dark:text-gray-500">—</span></div>';
            }
          }
        }
      );
    }
    return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-8 h-8 rounded bg-gray-100 dark:bg-gray-800 flex items-center justify-center", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
      IconSelector,
      {
        iconName: icon.value,
        provider: icon.provider ?? "yatra",
        className: "w-5 h-5 text-gray-600 dark:text-gray-400"
      }
    ) });
  };
  const handleEdit = (level) => {
    var _a;
    window.location.href = `${((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=trips&tab=difficulty-levels&action=edit&id=${level.id}`;
  };
  const handleCreate = () => {
    var _a;
    window.location.href = `${((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=trips&tab=difficulty-levels&action=create`;
  };
  const handleSort = (field) => {
    if (sortBy2 === field) {
      setSortOrder(sortOrder === "asc" ? "desc" : "asc");
    } else {
      setSortBy(field);
      setSortOrder("asc");
    }
  };
  const getSortIcon = (field) => {
    if (sortBy2 !== field) return null;
    return sortOrder === "asc" ? /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowUp, { className: "ml-1 w-3.5 h-3.5" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowDown, { className: "ml-1 w-3.5 h-3.5" });
  };
  const handleResetFilters = () => {
    setSearchTerm("");
    setStatusFilter("all");
    setSortBy("sorting");
    setSortOrder("asc");
    setPage(1);
  };
  const hasFilters = !!searchTerm || statusFilter !== "all" || sortBy2 !== "sorting" || sortOrder !== "asc";
  const toggleColumn = (columnKey) => {
    const newVisibleColumns = {
      ...visibleColumns,
      [columnKey]: !visibleColumns[columnKey]
    };
    setVisibleColumns(newVisibleColumns);
    localStorage.setItem(
      "yatra_difficulty_levels_columns",
      JSON.stringify(newVisibleColumns)
    );
  };
  const handleBulkApply = () => {
    if (!bulkAction) {
      showToast(__("Select a bulk action first.", "yatra"), "warning");
      return;
    }
    if (selectedIds.length === 0) {
      showToast(
        __("Select at least one difficulty level.", "yatra"),
        "warning"
      );
      return;
    }
    const performBulk = async () => {
      try {
        if (bulkAction === "delete") {
          await Promise.all(
            selectedIds.map(
              (id) => apiClient.delete(`/difficulty-levels/${id}`)
            )
          );
          showToast(
            __("Selected difficulty levels deleted successfully", "yatra"),
            "success"
          );
        } else if (bulkAction === "trash" || bulkAction === "draft" || bulkAction === "publish") {
          const status = bulkAction === "trash" ? "trash" : bulkAction === "draft" ? "draft" : "publish";
          await Promise.all(
            selectedIds.map(async (id) => {
              try {
                const levelResponse = await apiClient.get(
                  `/difficulty-levels/${id}`
                );
                const level = levelResponse;
                if (!level || !level.name) {
                  return;
                }
                await apiClient.put(`/difficulty-levels/${id}`, {
                  name: level.name,
                  slug: level.slug,
                  description: level.description,
                  icon: level.icon,
                  sorting: level.sorting,
                  status
                });
              } catch {
                throw new Error("bulk_item_failed");
              }
            })
          );
          const msgMap = {
            trash: __("Selected difficulty levels moved to trash", "yatra"),
            draft: __("Selected difficulty levels marked as draft", "yatra"),
            publish: __("Selected difficulty levels published", "yatra")
          };
          showToast(msgMap[bulkAction], "success");
        }
        queryClient2.invalidateQueries({ queryKey: ["difficulty-levels"] });
        queryClient2.invalidateQueries({
          queryKey: ["difficulty-levels-stats"]
        });
        setSelectedIds([]);
        setBulkAction("");
      } catch (error2) {
        const msgMapError = {
          delete: __("Failed to delete selected difficulty levels", "yatra"),
          trash: __(
            "Failed to move selected difficulty levels to trash",
            "yatra"
          ),
          draft: __(
            "Failed to mark selected difficulty levels as draft",
            "yatra"
          ),
          publish: __("Failed to publish selected difficulty levels", "yatra")
        };
        showToast((error2 == null ? void 0 : error2.message) || msgMapError[bulkAction], "error");
      }
    };
    void performBulk();
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      ConfirmationDialog,
      {
        isOpen: deleteConfirm.isOpen,
        onClose: () => setDeleteConfirm({ isOpen: false, level: null }),
        onConfirm: () => {
          if (deleteConfirm.level) {
            deleteMutation.mutate(deleteConfirm.level.id);
            setDeleteConfirm({ isOpen: false, level: null });
          }
        },
        title: __("Delete Difficulty Level", "yatra"),
        message: deleteConfirm.level ? __(
          'Are you sure you want to delete "{name}"? This action cannot be undone.',
          "yatra"
        ).replace("{name}", deleteConfirm.level.name) : __(
          "Are you sure you want to delete this difficulty level? This action cannot be undone.",
          "yatra"
        ),
        confirmText: __("Delete", "yatra"),
        cancelText: __("Cancel", "yatra"),
        variant: "danger",
        isLoading: deleteMutation.isPending
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      PageHeader,
      {
        title: __("Difficulty Levels", "yatra"),
        description: __(
          "Manage trip difficulty levels and their ordering",
          "yatra"
        ),
        actionCapability: "yatra_edit_trips",
        actions: /* @__PURE__ */ jsxRuntimeExports.jsxs(Button, { onClick: handleCreate, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Plus, { className: "w-4 h-4 mr-2" }),
          __("Add New", "yatra")
        ] })
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-3", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
      SearchFilterToolbar,
      {
        searchTerm,
        onSearchChange: setSearchTerm,
        statusFilter,
        onStatusChange: (value) => {
          setStatusFilter(value);
          setPage(1);
        },
        statusOptions: [
          { value: "all", label: __("All Status", "yatra") },
          { value: "publish", label: __("Published", "yatra") },
          { value: "draft", label: __("Draft", "yatra") }
        ],
        sortBy: sortBy2,
        onSortByChange: (value) => {
          setSortBy(value);
          setSortOrder("asc");
          setPage(1);
        },
        sortOrder,
        onSortOrderChange: (order) => {
          setSortOrder(order);
          setPage(1);
        },
        sortOptions: [
          { value: "sorting", label: __("Order", "yatra") },
          { value: "name", label: __("Name", "yatra") },
          { value: "created_at", label: __("Created", "yatra") }
        ],
        onResetFilters: handleResetFilters,
        hasFilters,
        placeholder: __("Search difficulty levels", "yatra")
      }
    ) }) }),
    !error && /* @__PURE__ */ jsxRuntimeExports.jsx(
      BulkActionToolbar,
      {
        selectedIds,
        bulkAction,
        setBulkAction,
        onApply: handleBulkApply,
        onClearSelection: () => setSelectedIds([]),
        statusFilter,
        setStatusFilter: (value) => {
          setStatusFilter(value);
          setPage(1);
          setSelectedIds([]);
          setBulkAction("");
        },
        statusOptions: [
          { key: "all", label: __("All", "yatra"), count: statusCounts.all },
          {
            key: "publish",
            label: __("Published", "yatra"),
            count: statusCounts.publish
          },
          {
            key: "draft",
            label: __("Draft", "yatra"),
            count: statusCounts.draft
          },
          {
            key: "trash",
            label: __("Trash", "yatra"),
            count: statusCounts.trash
          }
        ],
        showColumnsDropdown,
        setShowColumnsDropdown,
        columnOptions: [
          {
            key: "sorting",
            label: __("Order", "yatra"),
            visible: visibleColumns.sorting
          },
          {
            key: "name",
            label: __("Name", "yatra"),
            visible: visibleColumns.name
          },
          {
            key: "slug",
            label: __("Slug", "yatra"),
            visible: visibleColumns.slug
          },
          {
            key: "description",
            label: __("Description", "yatra"),
            visible: visibleColumns.description
          },
          {
            key: "status",
            label: __("Status", "yatra"),
            visible: visibleColumns.status
          },
          {
            key: "created_at",
            label: __("Created", "yatra"),
            visible: visibleColumns.created_at
          }
        ],
        onToggleColumn: toggleColumn,
        bulkMutationPending: false,
        totalItems: levels.length,
        bulkActionOptions: getDefaultBulkStatusOptions(statusFilter)
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-0", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
      Table,
      {
        data: levels,
        columns,
        actions,
        isLoading,
        isError: !!error,
        errorText: __("Failed to load difficulty levels", "yatra"),
        errorDescription: __(
          "We couldn’t connect to the difficulty levels service. Please refresh or try again shortly.",
          "We couldn’t connect to the difficulty levels service. Please refresh or try again shortly."
        ),
        onRetry: () => queryClient2.invalidateQueries({ queryKey: ["difficulty-levels"] }),
        errorDetails: errorContext.details,
        errorRequestInfo: errorContext.requestInfo,
        emptyText: __("No difficulty levels found", "yatra"),
        emptyDescription: __(
          "Get started by creating your first difficulty level to categorize trips by their physical challenge level.",
          "Get started by creating your first difficulty level to categorize trips by their physical challenge level."
        ),
        onCreateClick: handleCreate,
        onSort: handleSort,
        getSortIcon,
        selectedItemIds: selectedIds,
        onSelectItem: (id, checked) => {
          if (checked) {
            setSelectedIds([...selectedIds, id]);
          } else {
            setSelectedIds(
              selectedIds.filter((selectedId) => selectedId !== id)
            );
          }
        },
        onSelectAll: (checked) => {
          if (checked) {
            setSelectedIds(
              levels.map((level) => level.id)
            );
          } else {
            setSelectedIds([]);
          }
        },
        isAllSelected: levels.length > 0 && selectedIds.length === levels.length,
        getItemId: (level) => level.id,
        getItemStatus: (level) => level.status,
        statusFilter,
        skeletonRows: 5,
        capability: "yatra_edit_trips"
      }
    ) }) }),
    total > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-4", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
      Pagination,
      {
        currentPage: page,
        totalPages,
        totalItems: total,
        itemsPerPage: 10,
        onPageChange: (newPage) => setPage(newPage),
        itemName: __("difficulty levels", "yatra")
      }
    ) })
  ] });
};
const DifficultyLevelForm = () => {
  const queryClient2 = useQueryClient();
  const { can } = usePermissions();
  const { showToast } = useToast();
  const [formData, setFormData] = reactExports.useState({
    name: "",
    slug: "",
    description: "",
    icon: null,
    sorting: "",
    status: "publish"
  });
  const [errors, setErrors] = reactExports.useState({});
  const [isSubmitting, setIsSubmitting] = reactExports.useState(false);
  const [isSlugEditable, setIsSlugEditable] = reactExports.useState(false);
  const action = reactExports.useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get("action") || "create";
  }, []);
  const levelId = reactExports.useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get("id") ? parseInt(params.get("id") || "0", 10) : null;
  }, []);
  const isEditMode = action === "edit" && levelId !== null;
  const { data: levelData, isLoading: isLoadingLevel } = useQuery({
    queryKey: ["difficulty-level", levelId],
    queryFn: async () => {
      if (!levelId) return null;
      try {
        const response = await apiClient.get(`/difficulty-levels/${levelId}`);
        return response;
      } catch (error) {
        showToast(
          (error == null ? void 0 : error.message) || __("Failed to load difficulty level", "yatra"),
          "error"
        );
        throw error;
      }
    },
    enabled: isEditMode && can("yatra_view_trips")
  });
  reactExports.useEffect(() => {
    if (levelData && isEditMode) {
      setFormData({
        name: levelData.name || "",
        slug: levelData.slug || "",
        description: levelData.description || "",
        icon: levelData.icon || null,
        sorting: typeof levelData.sorting === "number" ? levelData.sorting : "",
        status: levelData.status || "publish"
      });
    }
  }, [levelData, isEditMode]);
  const handleNameChange = (value) => {
    if (!isEditMode && !isSlugEditable) {
      const newSlug = generateSlug(value);
      setFormData((prev) => ({
        ...prev,
        name: value,
        slug: newSlug
      }));
    } else {
      setFormData((prev) => ({ ...prev, name: value }));
    }
    if (errors.name) {
      setErrors((prev) => ({ ...prev, name: "" }));
    }
  };
  const handleSlugChange = (value) => {
    if (isSlugEditable) {
      setFormData((prev) => ({ ...prev, slug: value }));
      if (errors.slug) {
        setErrors((prev) => ({ ...prev, slug: "" }));
      }
    }
  };
  const handleToggleSlugEdit = () => {
    if (isSlugEditable) {
      const newSlug = generateSlug(formData.name);
      setFormData((prev) => ({ ...prev, slug: newSlug }));
    }
    setIsSlugEditable(!isSlugEditable);
  };
  const handleFieldChange = (field, value) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
    if (errors[field]) {
      setErrors((prev) => ({ ...prev, [field]: "" }));
    }
  };
  const validateForm = () => {
    const newErrors = {};
    if (!formData.name.trim()) {
      newErrors.name = __("Name is required", "yatra");
    }
    if (!formData.slug.trim()) {
      newErrors.slug = __("Slug is required", "yatra");
    } else if (!/^[\p{L}\p{N}-]+$/u.test(formData.slug)) {
      newErrors.slug = __(
        "Slug can only contain letters, numbers, and hyphens",
        "yatra"
      );
    }
    if (formData.sorting !== "" && Number(formData.sorting) < 0) {
      newErrors.sorting = __("Order must be a positive number", "yatra");
    }
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };
  const saveMutation = useMutation({
    mutationFn: async (data) => {
      const payload = {
        name: data.name.trim(),
        slug: data.slug.trim(),
        description: data.description,
        icon: data.icon,
        sorting: data.sorting === "" ? null : Number(data.sorting),
        status: data.status
      };
      if (isEditMode && isSlugEditable) {
        payload.preserve_slug = true;
      }
      if (isEditMode && levelId) {
        return await apiClient.put(`/difficulty-levels/${levelId}`, payload);
      }
      return await apiClient.post("/difficulty-levels", payload);
    },
    onSuccess: (response) => {
      var _a, _b;
      queryClient2.invalidateQueries({ queryKey: ["difficulty-levels"] });
      queryClient2.invalidateQueries({
        queryKey: ["difficulty-level", levelId]
      });
      showToast(
        isEditMode ? __("Difficulty level updated successfully", "yatra") : __("Difficulty level created successfully", "yatra"),
        "success"
      );
      setIsSubmitting(false);
      if (!isEditMode) {
        const newId = response == null ? void 0 : response.id;
        if (newId) {
          window.location.href = `${((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=trips&tab=difficulty-levels&action=edit&id=${newId}`;
        } else {
          window.location.href = `${((_b = window.yatraAdmin) == null ? void 0 : _b.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=trips&tab=difficulty-levels`;
        }
      }
    },
    onError: (error) => {
      const errorMessage = (error == null ? void 0 : error.message) || __("An error occurred while saving the difficulty level", "yatra");
      showToast(errorMessage, "error");
      setIsSubmitting(false);
    }
  });
  const handleSubmit = (e) => {
    e.preventDefault();
    if (!validateForm()) {
      showToast(__("Please fix the form errors", "yatra"), "warning");
      return;
    }
    setIsSubmitting(true);
    setErrors({});
    saveMutation.mutate(formData);
  };
  const handleCancel = () => {
    var _a;
    window.location.href = `${((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=trips&tab=difficulty-levels`;
  };
  if (isEditMode && isLoadingLevel) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg p-6", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-8 bg-gray-200 dark:bg-gray-700 rounded w-1/4 mb-2 animate-pulse" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-1/2 animate-pulse" })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-3 gap-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "lg:col-span-2 space-y-3", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "p-6 space-y-4", children: [
          [1, 2, 3].map((_, idx) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-24 mb-2 animate-pulse" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" })
          ] }, idx)),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-32 mb-2 animate-pulse" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-32 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" })
          ] })
        ] }) }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-3", children: [1, 2, 3].map((_, idx) => /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "p-6 space-y-4", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-24 mb-2 animate-pulse" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" })
        ] }) }, idx)) })
      ] })
    ] });
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      PageHeader,
      {
        title: isEditMode ? __("Edit Difficulty Level", "yatra") : __("Add Difficulty Level", "yatra"),
        description: isEditMode ? __("Update difficulty level information", "yatra") : __("Create a new trip difficulty level", "yatra"),
        actions: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Button,
          {
            variant: "outline",
            onClick: handleCancel,
            className: "flex items-center gap-2",
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowLeft, { className: "w-4 h-4" }),
              __("Back", "yatra")
            ]
          }
        )
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_edit_trips", children: /* @__PURE__ */ jsxRuntimeExports.jsx("form", { onSubmit: handleSubmit, children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-3 gap-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "lg:col-span-2 space-y-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Basic Information", "yatra") }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "label",
              {
                htmlFor: "name",
                className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                children: [
                  __("Name", "yatra"),
                  " ",
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
                ]
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              Input,
              {
                id: "name",
                type: "text",
                value: formData.name,
                onChange: (e) => handleNameChange(e.target.value),
                placeholder: __("Enter difficulty level name", "yatra"),
                className: errors.name ? "border-red-500" : "",
                required: true
              }
            ),
            errors.name && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm text-red-500", children: errors.name })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "label",
              {
                htmlFor: "slug",
                className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                children: [
                  __("Slug", "yatra"),
                  " ",
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
                ]
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Input,
                {
                  id: "slug",
                  type: "text",
                  value: formData.slug,
                  onChange: (e) => handleSlugChange(e.target.value),
                  placeholder: __("difficulty-slug", "yatra"),
                  className: `pr-10 ${errors.slug ? "border-red-500" : ""} ${!isSlugEditable ? "bg-gray-50 dark:bg-gray-800 cursor-not-allowed" : ""}`,
                  disabled: !isSlugEditable,
                  required: true
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "button",
                {
                  type: "button",
                  onClick: handleToggleSlugEdit,
                  className: "absolute right-2 top-1/2 -translate-y-1/2 p-1.5 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors rounded",
                  "aria-label": isSlugEditable ? __("Cancel editing slug", "yatra") : __("Edit slug", "yatra"),
                  children: isSlugEditable ? /* @__PURE__ */ jsxRuntimeExports.jsx(X, { className: "w-4 h-4" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(Pen, { className: "w-4 h-4" })
                }
              )
            ] }),
            errors.slug && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm text-red-500", children: errors.slug }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-xs text-gray-500 dark:text-gray-400", children: isSlugEditable ? __(
              "Manually editing slug. Click X to cancel and regenerate from name.",
              "yatra"
            ) : __(
              "Auto-generated from name. Click edit icon to customize.",
              "yatra"
            ) })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            RichTextEditor,
            {
              label: __("Description", "yatra"),
              value: formData.description || "",
              onChange: (value) => handleFieldChange("description", value),
              placeholder: __(
                "Describe this difficulty level (supports formatting, lists, links...)",
                "yatra"
              ),
              helperText: __(
                "Use formatting, bullet lists, and links to explain this difficulty level. HTML is supported.",
                "yatra"
              ),
              minHeight: 260,
              maxHeight: 600
            }
          )
        ] })
      ] }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Ordering & Status", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "label",
                {
                  htmlFor: "sorting",
                  className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                  children: __("Display Order", "yatra")
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Input,
                {
                  id: "sorting",
                  type: "number",
                  min: 0,
                  value: formData.sorting,
                  onChange: (e) => handleFieldChange(
                    "sorting",
                    e.target.value === "" ? "" : Number(e.target.value)
                  ),
                  placeholder: __("Auto", "yatra"),
                  className: errors.sorting ? "border-red-500" : ""
                }
              ),
              errors.sorting && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm text-red-500", children: errors.sorting }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-xs text-gray-500 dark:text-gray-400", children: __(
                "Lower numbers appear first. Leave blank to auto-assign.",
                "yatra"
              ) })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "label",
                {
                  htmlFor: "status",
                  className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                  children: __("Status", "yatra")
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsxs(
                Select,
                {
                  id: "status",
                  value: formData.status,
                  onChange: (e) => handleFieldChange("status", e.target.value),
                  className: "w-full",
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "draft", children: __("Draft", "yatra") }),
                    /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "publish", children: __("Publish", "yatra") }),
                    /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "trash", children: __("Trash", "yatra") })
                  ]
                }
              )
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Difficulty Level Icon or Image", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            IconPicker,
            {
              value: formData.icon,
              onChange: (value) => handleFieldChange("icon", value),
              label: __("Select Icon or Upload Image", "yatra"),
              helpText: __(
                "Choose a library icon or upload a custom image for this difficulty level.",
                "yatra"
              ),
              allowImageUpload: true,
              allowIconSelection: true,
              size: "md"
            }
          ) })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-3", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-2", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Button,
            {
              type: "submit",
              disabled: isSubmitting,
              className: "flex-1 flex items-center justify-center gap-2",
              children: isSubmitting ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Loader2, { className: "w-4 h-4 animate-spin" }),
                __("Saving...", "yatra")
              ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Save, { className: "w-4 h-4" }),
                isEditMode ? __("Update Difficulty Level", "yatra") : __("Create Difficulty Level", "yatra")
              ] })
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Button,
            {
              type: "button",
              variant: "outline",
              onClick: handleCancel,
              disabled: isSubmitting,
              children: __("Cancel", "yatra")
            }
          )
        ] }) }) }) })
      ] })
    ] }) }) })
  ] });
};
function getDateFormat() {
  var _a, _b;
  return ((_a = window == null ? void 0 : window.yatraAdmin) == null ? void 0 : _a.date_format) || ((_b = window == null ? void 0 : window.yatraAdmin) == null ? void 0 : _b.dateFormat) || "Y-m-d";
}
function getTimeFormat() {
  var _a, _b;
  return ((_a = window == null ? void 0 : window.yatraAdmin) == null ? void 0 : _a.time_format) || ((_b = window == null ? void 0 : window.yatraAdmin) == null ? void 0 : _b.timeFormat) || "H:i";
}
function formatDate$1(dateString, includeTime = false) {
  if (!dateString) return "-";
  try {
    const date2 = typeof dateString === "string" ? new Date(dateString) : dateString;
    if (isNaN(date2.getTime())) {
      return String(dateString);
    }
    const phpDateFormat = getDateFormat();
    const phpTimeFormat = getTimeFormat();
    const formattedDate = formatDatePart(date2, phpDateFormat);
    if (includeTime) {
      const formattedTime = formatTimePart(date2, phpTimeFormat);
      return `${formattedDate} ${formattedTime}`;
    }
    return formattedDate;
  } catch (e) {
    return String(dateString);
  }
}
function formatDatePart(date2, phpFormat) {
  const year = date2.getFullYear();
  const month = date2.getMonth();
  const day = date2.getDate();
  const monthNames = [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December"
  ];
  const monthShort = [
    "Jan",
    "Feb",
    "Mar",
    "Apr",
    "May",
    "Jun",
    "Jul",
    "Aug",
    "Sep",
    "Oct",
    "Nov",
    "Dec"
  ];
  const pad2 = (n) => n.toString().padStart(2, "0");
  const dayNames2 = [
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday"
  ];
  const dayShort = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
  const dayOfWeek = date2.getDay();
  switch (phpFormat) {
    case "Y-m-d":
      return `${year}-${pad2(month + 1)}-${pad2(day)}`;
    case "Y/m/d":
      return `${year}/${pad2(month + 1)}/${pad2(day)}`;
    case "m/d/Y":
      return `${pad2(month + 1)}/${pad2(day)}/${year}`;
    case "d/m/Y":
      return `${pad2(day)}/${pad2(month + 1)}/${year}`;
    case "d-m-Y":
      return `${pad2(day)}-${pad2(month + 1)}-${year}`;
    case "d.m.Y":
      return `${pad2(day)}.${pad2(month + 1)}.${year}`;
    case "M d, Y":
      return `${monthShort[month]} ${pad2(day)}, ${year}`;
    case "F d, Y":
      return `${monthNames[month]} ${pad2(day)}, ${year}`;
    case "d M Y":
      return `${pad2(day)} ${monthShort[month]} ${year}`;
    case "d F Y":
      return `${pad2(day)} ${monthNames[month]} ${year}`;
    case "M j, Y":
      return `${monthShort[month]} ${day}, ${year}`;
    case "F j, Y":
      return `${monthNames[month]} ${day}, ${year}`;
    case "j M Y":
      return `${day} ${monthShort[month]} ${year}`;
    case "j F Y":
      return `${day} ${monthNames[month]} ${year}`;
    case "Y M j":
      return `${year} ${monthShort[month]} ${day}`;
    case "Y F j":
      return `${year} ${monthNames[month]} ${day}`;
    case "l, F j, Y":
      return `${dayNames2[dayOfWeek]}, ${monthNames[month]} ${day}, ${year}`;
    case "D, M j, Y":
      return `${dayShort[dayOfWeek]}, ${monthShort[month]} ${day}, ${year}`;
    default:
      return `${year}-${pad2(month + 1)}-${pad2(day)}`;
  }
}
function formatTimePart(date2, phpFormat) {
  const hours = date2.getHours();
  const minutes = date2.getMinutes();
  const seconds = date2.getSeconds();
  const pad2 = (n) => n.toString().padStart(2, "0");
  const hours12 = hours % 12 || 12;
  const ampm = hours >= 12 ? "PM" : "AM";
  switch (phpFormat) {
    case "H:i":
      return `${pad2(hours)}:${pad2(minutes)}`;
    case "h:i A":
      return `${pad2(hours12)}:${pad2(minutes)} ${ampm}`;
    case "h:i a":
      return `${pad2(hours12)}:${pad2(minutes)} ${ampm.toLowerCase()}`;
    case "H:i:s":
      return `${pad2(hours)}:${pad2(minutes)}:${pad2(seconds)}`;
    case "h:i:s A":
      return `${pad2(hours12)}:${pad2(minutes)}:${pad2(seconds)} ${ampm}`;
    default:
      return `${pad2(hours)}:${pad2(minutes)}`;
  }
}
function formatDateForInput(dateString) {
  if (!dateString) return "";
  try {
    const date2 = typeof dateString === "string" ? new Date(dateString) : dateString;
    if (isNaN(date2.getTime())) {
      return "";
    }
    const year = date2.getFullYear();
    const month = (date2.getMonth() + 1).toString().padStart(2, "0");
    const day = date2.getDate().toString().padStart(2, "0");
    return `${year}-${month}-${day}`;
  } catch (e) {
    return "";
  }
}
const Bookings = () => {
  var _a, _b, _c;
  const [searchTerm, setSearchTerm] = reactExports.useState("");
  const [statusFilter, setStatusFilter] = reactExports.useState("all");
  const [paymentFilter, setPaymentFilter] = reactExports.useState("all");
  const [sortBy2, setSortBy] = reactExports.useState("booking_date");
  const [sortOrder, setSortOrder] = reactExports.useState("desc");
  const [page, setPage] = reactExports.useState(1);
  const [selectedIds, setSelectedIds] = reactExports.useState([]);
  const [bulkAction, setBulkAction] = reactExports.useState("");
  const [showColumnsDropdown, setShowColumnsDropdown] = reactExports.useState(false);
  const [isBulkPending, setIsBulkPending] = reactExports.useState(false);
  const [deleteDialogOpen, setDeleteDialogOpen] = reactExports.useState(false);
  const [bookingToDelete, setBookingToDelete] = reactExports.useState(null);
  const [visibleColumns, setVisibleColumns] = reactExports.useState(() => {
    if (typeof window === "undefined") {
      return {
        booking_number: true,
        customer: true,
        trip: true,
        travelers: true,
        booking_date: true,
        travel_date: true,
        amount: true,
        payment_status: true,
        booking_status: true
      };
    }
    const saved = window.localStorage.getItem("yatra-bookings-visible-columns");
    return saved ? JSON.parse(saved) : {
      booking_number: true,
      customer: true,
      trip: true,
      travelers: true,
      booking_date: true,
      travel_date: true,
      amount: true,
      payment_status: true,
      booking_status: true
    };
  });
  const queryClient2 = useQueryClient();
  const { can } = usePermissions();
  const { showToast } = useToast();
  const defaultCurrency = ((_a = window == null ? void 0 : window.yatraAdmin) == null ? void 0 : _a.currency) || ((_b = window == null ? void 0 : window.yatraBookingData) == null ? void 0 : _b.currency) || "USD";
  const translations = ((_c = window == null ? void 0 : window.yatraAdmin) == null ? void 0 : _c.translations) || {};
  const statsEnabled = can("yatra_view_bookings") !== false;
  const __2 = (text) => translations[text] || text;
  const BOOKINGS_PER_PAGE = 10;
  const queryParams = reactExports.useMemo(() => {
    const params = {
      page,
      per_page: BOOKINGS_PER_PAGE,
      orderby: sortBy2,
      order: sortOrder
    };
    if (searchTerm) {
      params.search = searchTerm;
    }
    if (statusFilter !== "all") {
      params.status = statusFilter;
    }
    if (paymentFilter !== "all") {
      params.payment_status = paymentFilter;
    }
    return params;
  }, [searchTerm, statusFilter, paymentFilter, sortBy2, sortOrder, page]);
  const canViewBookings = can("yatra_view_bookings") !== false;
  const { data, isLoading, error, refetch } = useQuery({
    queryKey: ["bookings", queryParams],
    queryFn: async () => {
      const urlParams = new URLSearchParams(window.location.search);
      if (urlParams.get("simulate_error") === "true") {
        throw new Error(
          "Simulated API error for testing error UI functionality"
        );
      }
      const params = new URLSearchParams();
      params.append("page", String(queryParams.page));
      params.append("per_page", String(queryParams.per_page));
      if (queryParams.search) {
        params.append("search", queryParams.search);
      }
      if (queryParams.status) {
        params.append("status", queryParams.status);
      }
      if (queryParams.payment_status) {
        params.append("payment_status", queryParams.payment_status);
      }
      return await apiService.getBookings({
        page: queryParams.page,
        per_page: queryParams.per_page,
        search: queryParams.search,
        status: queryParams.status,
        payment_status: queryParams.payment_status
      });
    },
    enabled: canViewBookings
  });
  const { data: statsRaw } = useQuery({
    queryKey: ["bookings-stats"],
    queryFn: async () => {
      return await apiService.getBookingsStats();
    },
    enabled: statsEnabled
  });
  const statsData = statsRaw ?? {};
  const totalBookings = (statsData == null ? void 0 : statsData.all) ?? 0;
  const confirmedCount = (statsData == null ? void 0 : statsData.confirmed) ?? 0;
  const pendingCount = (statsData == null ? void 0 : statsData.pending) ?? 0;
  const cancelledCount = (statsData == null ? void 0 : statsData.cancelled) ?? 0;
  const completedCount = (statsData == null ? void 0 : statsData.completed) ?? 0;
  const deleteMutation = useMutation({
    mutationFn: async (id) => {
      await apiService.deleteBooking(id);
    },
    onSuccess: () => {
      queryClient2.invalidateQueries({ queryKey: ["bookings"] });
      queryClient2.invalidateQueries({ queryKey: ["bookings-stats"] });
      showToast(__2("Booking deleted successfully"), "success");
    },
    onError: (error2) => {
      showToast((error2 == null ? void 0 : error2.message) || __2("Failed to delete booking"), "error");
    }
  });
  const bookings = (data == null ? void 0 : data.data) || [];
  const listMeta = (data == null ? void 0 : data.meta) ?? {};
  const total = Number(listMeta.total ?? (data == null ? void 0 : data.total) ?? 0);
  const perPage = Number(listMeta.per_page ?? (data == null ? void 0 : data.per_page) ?? BOOKINGS_PER_PAGE) || BOOKINGS_PER_PAGE;
  const totalPages = Math.max(
    1,
    Number(listMeta.total_pages) || (total > 0 ? Math.ceil(total / perPage) : 1)
  );
  const errorContext = getErrorContext(error);
  const apiErrorMessage = (data == null ? void 0 : data.error) || (data == null ? void 0 : data.message);
  const derivedErrorDetails = errorContext.details || (apiErrorMessage ? String(apiErrorMessage) : void 0) || (error ? String((error == null ? void 0 : error.message) || error) : void 0);
  const isBookingsError = !!error || !!apiErrorMessage;
  const formatDate2 = (dateString) => {
    return formatDate$1(dateString);
  };
  const formatPrice = (price, currencyCode = defaultCurrency) => formatYatraMoney(Number(price) || 0, currencyCode, {
    zeroAsUnknown: false
  });
  const getBookingStatusBadge = (status) => {
    const statusMap = {
      confirmed: {
        className: "bg-green-100 text-green-700 dark:bg-green-900/20 dark:text-green-400",
        label: __2("Confirmed")
      },
      pending: {
        className: "bg-yellow-100 text-yellow-700 dark:bg-yellow-900/20 dark:text-yellow-400",
        label: __2("Pending")
      },
      // Guest-checkout holding state: row exists but the customer hasn't
      // clicked the email-verification link yet, so the booking-created
      // fan-out (admin notify + customer confirmation) is deferred.
      // Visually amber-on-amber so it reads as "waiting on something
      // outside our control" — distinct from the regular yellow "pending"
      // (which means waiting on the operator).
      pending_verification: {
        className: "bg-amber-100 text-amber-800 dark:bg-amber-900/20 dark:text-amber-300 border border-amber-200 dark:border-amber-800",
        label: __2("Awaiting email verification")
      },
      cancelled: {
        className: "bg-red-100 text-red-700 dark:bg-red-900/20 dark:text-red-400",
        label: __2("Cancelled")
      },
      completed: {
        className: "bg-blue-100 text-blue-700 dark:bg-blue-900/20 dark:text-blue-400",
        label: __2("Completed")
      }
    };
    const statusInfo = statusMap[status] || {
      className: "bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-400",
      label: status
    };
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "span",
      {
        className: `inline-flex items-center px-2 py-1 rounded-md text-xs font-medium ${statusInfo.className}`,
        children: statusInfo.label
      }
    );
  };
  const getPaymentStatusBadge = (status) => {
    const statusMap = {
      paid: {
        className: "bg-green-100 text-green-700 dark:bg-green-900/20 dark:text-green-400",
        label: __2("Paid")
      },
      pending: {
        className: "bg-yellow-100 text-yellow-700 dark:bg-yellow-900/20 dark:text-yellow-400",
        label: __2("Pending")
      },
      partial: {
        className: "bg-orange-100 text-orange-700 dark:bg-orange-900/20 dark:text-orange-400",
        label: __2("Partial")
      },
      refunded: {
        className: "bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-400",
        label: __2("Refunded")
      }
    };
    const statusInfo = statusMap[status] || {
      className: "bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-400",
      label: status
    };
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "span",
      {
        className: `inline-flex items-center px-2 py-1 rounded-md text-xs font-medium ${statusInfo.className}`,
        children: statusInfo.label
      }
    );
  };
  const handleEdit = (booking) => {
    var _a2;
    window.location.href = `${((_a2 = window.yatraAdmin) == null ? void 0 : _a2.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=bookings&action=edit&id=${booking.id}`;
  };
  const handleDelete = (booking) => {
    setBookingToDelete(booking);
    setDeleteDialogOpen(true);
  };
  const confirmDelete = () => {
    if (bookingToDelete) {
      deleteMutation.mutate(bookingToDelete.id);
      setDeleteDialogOpen(false);
      setBookingToDelete(null);
    }
  };
  const cancelDelete = () => {
    setDeleteDialogOpen(false);
    setBookingToDelete(null);
  };
  const handleView = (booking) => {
    var _a2;
    window.location.href = `${((_a2 = window.yatraAdmin) == null ? void 0 : _a2.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=bookings&action=view&id=${booking.id}`;
  };
  const handleCreateBooking = () => {
    var _a2;
    window.location.href = `${((_a2 = window.yatraAdmin) == null ? void 0 : _a2.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=bookings&action=create`;
  };
  const handleResetFilters = () => {
    setSearchTerm("");
    setStatusFilter("all");
    setPaymentFilter("all");
    setSortBy("booking_date");
    setSortOrder("desc");
    setPage(1);
  };
  const handleSort = (field) => {
    if (sortBy2 === field) {
      setSortOrder(sortOrder === "asc" ? "desc" : "asc");
    } else {
      setSortBy(field);
      setSortOrder("desc");
    }
  };
  const getSortIcon = (field) => {
    if (sortBy2 !== field) {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowUpDown, { className: "w-3.5 h-3.5 ml-1 text-gray-400" });
    }
    return sortOrder === "asc" ? /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowUp, { className: "w-3.5 h-3.5 ml-1 text-gray-600 dark:text-gray-300" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowDown, { className: "w-3.5 h-3.5 ml-1 text-gray-600 dark:text-gray-300" });
  };
  const hasFilters = searchTerm || statusFilter !== "all" || paymentFilter !== "all" || sortBy2 !== "booking_date" || sortOrder !== "desc";
  const toggleColumn = (columnKey) => {
    const newVisibleColumns = {
      ...visibleColumns,
      [columnKey]: !visibleColumns[columnKey]
    };
    setVisibleColumns(newVisibleColumns);
    if (typeof window !== "undefined") {
      window.localStorage.setItem(
        "yatra-bookings-visible-columns",
        JSON.stringify(newVisibleColumns)
      );
    }
  };
  const handleSelectItem = (id, checked) => {
    setSelectedIds(
      (prev) => checked ? [...prev, id] : prev.filter((selectedId) => selectedId !== id)
    );
  };
  const handleSelectAll = (checked) => {
    if (checked) {
      setSelectedIds(bookings.map((booking) => booking.id));
    } else {
      setSelectedIds([]);
    }
  };
  const isAllSelected = bookings.length > 0 && selectedIds.length === bookings.length;
  const updateStatusForIds = async (ids, newStatus) => {
    await apiService.bulkUpdateStatus("bookings", ids, newStatus);
  };
  const handleBulkApply = async () => {
    if (!bulkAction || selectedIds.length === 0) {
      return;
    }
    try {
      setIsBulkPending(true);
      if (bulkAction === "delete") {
        await apiService.bulkDelete("bookings", selectedIds);
        showToast(__2("Selected bookings deleted successfully"), "success");
      } else {
        await updateStatusForIds(selectedIds, bulkAction);
        showToast(__2("Bulk booking status updated successfully"), "success");
      }
      queryClient2.invalidateQueries({ queryKey: ["bookings"] });
      queryClient2.invalidateQueries({ queryKey: ["bookings-stats"] });
      setSelectedIds([]);
      setBulkAction("");
    } catch (error2) {
      showToast(
        __2("Error: ") + ((error2 == null ? void 0 : error2.message) || __2("Failed to perform bulk action on bookings")),
        "error"
      );
    } finally {
      setIsBulkPending(false);
    }
  };
  const allBulkActionOptions = [
    { value: "confirmed", label: __2("Mark as Confirmed") },
    { value: "pending", label: __2("Mark as Pending") },
    { value: "cancelled", label: __2("Mark as Cancelled") },
    { value: "completed", label: __2("Mark as Completed") },
    { value: "delete", label: __2("Delete permanently") }
  ];
  const getBulkActionOptionsForStatus = (view) => {
    switch (view) {
      case "confirmed":
        return allBulkActionOptions.filter(
          (opt) => ["pending", "cancelled", "completed", "delete"].includes(opt.value)
        );
      case "pending":
        return allBulkActionOptions.filter(
          (opt) => ["confirmed", "cancelled", "completed", "delete"].includes(opt.value)
        );
      case "cancelled":
        return allBulkActionOptions.filter(
          (opt) => ["pending", "confirmed", "delete"].includes(opt.value)
        );
      case "completed":
        return allBulkActionOptions.filter(
          (opt) => ["confirmed", "cancelled", "delete"].includes(opt.value)
        );
      default:
        return allBulkActionOptions;
    }
  };
  const bulkActionOptions = getBulkActionOptionsForStatus(statusFilter);
  const statusOptions = [
    {
      value: "all",
      label: __2("All Status"),
      count: (statsData == null ? void 0 : statsData.all) ?? totalBookings
    },
    { value: "confirmed", label: __2("Confirmed"), count: confirmedCount },
    { value: "pending", label: __2("Pending"), count: pendingCount },
    { value: "cancelled", label: __2("Cancelled"), count: cancelledCount },
    { value: "completed", label: __2("Completed"), count: completedCount }
  ];
  const sortOptions = [
    { value: "booking_date", label: __2("Booking Date") },
    { value: "travel_date", label: __2("Travel Date") },
    { value: "booking_number", label: __2("Booking Number") },
    { value: "customer_name", label: __2("Customer") },
    { value: "trip_title", label: __2("Trip") },
    { value: "total_amount", label: __2("Amount") },
    { value: "booking_status", label: __2("Status") }
  ];
  const columnOptions = [
    {
      key: "booking_number",
      label: __2("Booking #"),
      visible: visibleColumns.booking_number
    },
    {
      key: "customer",
      label: __2("Customer"),
      visible: visibleColumns.customer
    },
    { key: "trip", label: __2("Trip"), visible: visibleColumns.trip },
    {
      key: "travelers",
      label: __2("Travelers"),
      visible: visibleColumns.travelers
    },
    {
      key: "booking_date",
      label: __2("Booking Date"),
      visible: visibleColumns.booking_date
    },
    {
      key: "travel_date",
      label: __2("Travel Date"),
      visible: visibleColumns.travel_date
    },
    { key: "amount", label: __2("Amount"), visible: visibleColumns.amount },
    {
      key: "payment_status",
      label: __2("Payment"),
      visible: visibleColumns.payment_status
    },
    {
      key: "booking_status",
      label: __2("Status"),
      visible: visibleColumns.booking_status
    }
  ];
  const columns = [
    {
      key: "booking_number",
      label: __2("Booking #"),
      sortable: true,
      visible: visibleColumns.booking_number,
      width: "w-[140px]",
      render: (booking) => /* @__PURE__ */ jsxRuntimeExports.jsx(
        "button",
        {
          type: "button",
          onClick: () => handleView(booking),
          className: "text-sm font-mono font-medium text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 hover:underline",
          children: booking.booking_number
        }
      )
    },
    {
      key: "customer",
      label: __2("Customer"),
      sortable: true,
      visible: visibleColumns.customer,
      render: (booking) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-medium", children: booking.customer_name || __2("Guest") }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs text-muted-foreground", children: booking.customer_email })
      ] })
    },
    {
      key: "trip",
      label: __2("Trip"),
      sortable: true,
      visible: visibleColumns.trip,
      render: (booking) => {
        var _a2;
        return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "a",
            {
              href: `${((_a2 = window.yatraAdmin) == null ? void 0 : _a2.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=trips&action=edit&id=${booking.trip_id}`,
              className: "font-medium text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300",
              children: booking.trip_title
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "ml-1 text-[11px] text-gray-400 dark:text-gray-500", children: booking.trip_id ? `(ID: ${booking.trip_id})` : "" })
        ] });
      }
    },
    {
      key: "travelers",
      label: __2("Travelers"),
      sortable: true,
      visible: visibleColumns.travelers,
      render: (booking) => /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-medium", children: booking.travelers ?? booking.travelers_count ?? 0 })
    },
    {
      key: "booking_date",
      label: __2("Booking Date"),
      sortable: true,
      visible: visibleColumns.booking_date,
      render: (booking) => /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: formatDate2(booking.booking_date) })
    },
    {
      key: "travel_date",
      label: __2("Travel Date"),
      sortable: true,
      visible: visibleColumns.travel_date,
      render: (booking) => /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: formatDate2(booking.travel_date) })
    },
    {
      key: "amount",
      label: __2("Amount"),
      sortable: true,
      visible: visibleColumns.amount,
      render: (booking) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-semibold", children: formatPrice(booking.total_amount, booking.currency) }),
        booking.amount_paid ? /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-xs text-muted-foreground", children: [
          __2("Paid: "),
          formatPrice(booking.amount_paid, booking.currency)
        ] }) : null
      ] })
    },
    {
      key: "payment_status",
      label: __2("Payment"),
      sortable: true,
      visible: visibleColumns.payment_status,
      render: (booking) => getPaymentStatusBadge(booking.payment_status)
    },
    {
      key: "booking_status",
      label: __2("Status"),
      sortable: true,
      visible: visibleColumns.booking_status,
      render: (booking) => getBookingStatusBadge(booking.booking_status)
    }
  ];
  const actions = [
    {
      key: "view",
      label: __2("View"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Eye, { className: "w-4 h-4" }),
      onClick: (booking) => handleView(booking),
      condition: () => can("yatra_view_bookings")
    },
    {
      key: "edit",
      label: __2("Edit"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(PenSquare, { className: "w-4 h-4" }),
      onClick: (booking) => handleEdit(booking),
      condition: () => can("yatra_edit_bookings")
    },
    {
      key: "mark_confirmed",
      label: __2("Mark as Confirmed"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowDown, { className: "w-4 h-4" }),
      onClick: async (booking) => {
        setIsBulkPending(true);
        try {
          await updateStatusForIds([booking.id], "confirmed");
          queryClient2.invalidateQueries({ queryKey: ["bookings"] });
          queryClient2.invalidateQueries({ queryKey: ["bookings-stats"] });
          showToast(__2("Booking status updated"), "success");
        } catch (error2) {
          showToast(
            (error2 == null ? void 0 : error2.message) || __2("Failed to update booking status"),
            "error"
          );
        } finally {
          setIsBulkPending(false);
        }
      },
      condition: (booking) => can("yatra_edit_bookings") && booking.booking_status !== "confirmed"
    },
    {
      key: "mark_pending",
      label: __2("Mark as Pending"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowUp, { className: "w-4 h-4" }),
      onClick: async (booking) => {
        setIsBulkPending(true);
        try {
          await updateStatusForIds([booking.id], "pending");
          queryClient2.invalidateQueries({ queryKey: ["bookings"] });
          queryClient2.invalidateQueries({ queryKey: ["bookings-stats"] });
          showToast(__2("Booking status updated"), "success");
        } catch (error2) {
          showToast(
            (error2 == null ? void 0 : error2.message) || __2("Failed to update booking status"),
            "error"
          );
        } finally {
          setIsBulkPending(false);
        }
      },
      condition: (booking) => can("yatra_edit_bookings") && booking.booking_status !== "pending"
    },
    {
      key: "mark_cancelled",
      label: __2("Mark as Cancelled"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowDown, { className: "w-4 h-4" }),
      onClick: async (booking) => {
        setIsBulkPending(true);
        try {
          await updateStatusForIds([booking.id], "cancelled");
          queryClient2.invalidateQueries({ queryKey: ["bookings"] });
          queryClient2.invalidateQueries({ queryKey: ["bookings-stats"] });
          showToast(__2("Booking status updated"), "success");
        } catch (error2) {
          showToast(
            (error2 == null ? void 0 : error2.message) || __2("Failed to update booking status"),
            "error"
          );
        } finally {
          setIsBulkPending(false);
        }
      },
      condition: (booking) => can("yatra_edit_bookings") && booking.booking_status !== "cancelled"
    },
    {
      key: "mark_completed",
      label: __2("Mark as Completed"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowDown, { className: "w-4 h-4" }),
      onClick: async (booking) => {
        setIsBulkPending(true);
        try {
          await updateStatusForIds([booking.id], "completed");
          queryClient2.invalidateQueries({ queryKey: ["bookings"] });
          queryClient2.invalidateQueries({ queryKey: ["bookings-stats"] });
          showToast(__2("Booking status updated"), "success");
        } catch (error2) {
          showToast(
            (error2 == null ? void 0 : error2.message) || __2("Failed to update booking status"),
            "error"
          );
        } finally {
          setIsBulkPending(false);
        }
      },
      condition: (booking) => can("yatra_edit_bookings") && booking.booking_status !== "completed"
    },
    {
      key: "delete",
      label: __2("Delete"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "w-4 h-4" }),
      onClick: (booking) => handleDelete(booking),
      variant: "destructive",
      condition: () => can("yatra_delete_bookings")
    }
  ];
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      PageHeader,
      {
        title: __2("Bookings"),
        description: __2("Manage customer bookings and reservations"),
        actions: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex items-center gap-2", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Button,
          {
            onClick: handleCreateBooking,
            className: "flex items-center gap-2",
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Plus, { className: "w-4 h-4" }),
              __2("Create Booking")
            ]
          }
        ) })
      }
    ),
    statsData && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-4 gap-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "p-4", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-muted-foreground", children: __2("Total Bookings") }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-2xl font-semibold", children: totalBookings })
      ] }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "p-4", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-muted-foreground", children: __2("Confirmed") }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-2xl font-semibold", children: confirmedCount })
      ] }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "p-4", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-muted-foreground", children: __2("Pending") }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-2xl font-semibold", children: pendingCount })
      ] }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "p-4", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-muted-foreground", children: __2("Cancelled") }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-2xl font-semibold", children: cancelledCount })
      ] }) })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-4", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col lg:flex-row gap-3 items-stretch lg:items-center w-full", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex-1 min-w-0", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        SearchFilterToolbar,
        {
          searchTerm,
          onSearchChange: setSearchTerm,
          statusFilter,
          onStatusChange: (value) => {
            setStatusFilter(value);
            setPage(1);
          },
          statusOptions,
          sortBy: sortBy2,
          onSortByChange: (field) => {
            setSortBy(field);
            setPage(1);
          },
          sortOrder,
          onSortOrderChange: (order) => {
            setSortOrder(order);
            setPage(1);
          },
          sortOptions,
          onResetFilters: handleResetFilters,
          hasFilters: !!hasFilters,
          placeholder: __2("Search bookings...")
        }
      ) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-full lg:w-auto lg:min-w-[160px]", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Select,
        {
          value: paymentFilter,
          onChange: (e) => {
            setPaymentFilter(e.target.value);
            setPage(1);
          },
          className: "w-full",
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "all", children: __2("All Payments") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "paid", children: __2("Paid") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "pending", children: __2("Pending") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "partial", children: __2("Partial") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "refunded", children: __2("Refunded") })
          ]
        }
      ) })
    ] }) }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_view_bookings", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        BulkActionToolbar,
        {
          selectedIds,
          bulkAction,
          setBulkAction,
          onApply: handleBulkApply,
          onClearSelection: () => setSelectedIds([]),
          statusFilter,
          setStatusFilter: (value) => {
            setStatusFilter(value);
            setPage(1);
          },
          statusOptions: [
            {
              key: "all",
              label: __2("All"),
              count: (statsData == null ? void 0 : statsData.all) ?? totalBookings
            },
            {
              key: "confirmed",
              label: __2("Confirmed"),
              count: confirmedCount
            },
            { key: "pending", label: __2("Pending"), count: pendingCount },
            {
              key: "cancelled",
              label: __2("Cancelled"),
              count: cancelledCount
            },
            {
              key: "completed",
              label: __2("Completed"),
              count: completedCount
            }
          ],
          showColumnsDropdown,
          setShowColumnsDropdown,
          columnOptions,
          onToggleColumn: toggleColumn,
          bulkMutationPending: isBulkPending,
          totalItems: total,
          bulkActionOptions
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-0", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        Table,
        {
          data: bookings,
          columns,
          actions,
          isLoading,
          isError: isBookingsError,
          errorText: __2("Error loading bookings"),
          errorDescription: __2(
            "We couldn't connect to the bookings service. Please refresh or try again shortly."
          ),
          errorDetails: derivedErrorDetails,
          errorRequestInfo: errorContext.requestInfo,
          onRetry: () => refetch(),
          emptyText: __2("No bookings found"),
          emptyDescription: hasFilters ? __2("Try adjusting your filters to see more results.") : __2("Get started by creating your first booking."),
          onCreateClick: can("yatra_edit_bookings") ? handleCreateBooking : void 0,
          onSort: handleSort,
          getSortIcon,
          selectedItemIds: selectedIds,
          onSelectItem: handleSelectItem,
          onSelectAll: handleSelectAll,
          isAllSelected,
          getItemId: (booking) => booking.id,
          skeletonRows: 5,
          capability: "yatra_view_bookings"
        }
      ) }) }),
      total > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-4", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        Pagination,
        {
          currentPage: page,
          totalPages,
          totalItems: total,
          itemsPerPage: perPage,
          onPageChange: (newPage) => setPage(newPage),
          itemName: __2("bookings")
        }
      ) })
    ] }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      ConfirmationDialog,
      {
        isOpen: deleteDialogOpen,
        onClose: cancelDelete,
        onConfirm: confirmDelete,
        title: __2("Delete Booking"),
        description: bookingToDelete ? __2(
          `Are you sure you want to delete booking "${bookingToDelete.booking_number}"? This action cannot be undone.`
        ) : __2("Are you sure you want to delete this booking?"),
        confirmText: __2("Delete"),
        cancelText: __2("Cancel"),
        variant: "danger",
        isLoading: deleteMutation.isPending,
        icon: /* @__PURE__ */ jsxRuntimeExports.jsx(AlertTriangle, { className: "w-6 h-6 text-red-500" })
      }
    )
  ] });
};
const Customers = () => {
  var _a, _b;
  const [searchTerm, setSearchTerm] = reactExports.useState("");
  const [statusFilter, setStatusFilter] = reactExports.useState("all");
  const [loyaltyFilter, setLoyaltyFilter] = reactExports.useState("all");
  const [sortBy2, setSortBy] = reactExports.useState("created_at");
  const [sortOrder, setSortOrder] = reactExports.useState("desc");
  const [page, setPage] = reactExports.useState(1);
  const [selectedIds, setSelectedIds] = reactExports.useState([]);
  const [bulkAction, setBulkAction] = reactExports.useState("");
  const [isBulkPending, setIsBulkPending] = reactExports.useState(false);
  const [deleteDialogOpen, setDeleteDialogOpen] = reactExports.useState(false);
  const [customerToDelete, setCustomerToDelete] = reactExports.useState(
    null
  );
  const [showColumnsDropdown, setShowColumnsDropdown] = reactExports.useState(false);
  const { can, isPro } = usePermissions();
  const queryClient2 = useQueryClient();
  const { showToast } = useToast();
  const translations = ((_a = window == null ? void 0 : window.yatraAdmin) == null ? void 0 : _a.translations) || {};
  const __2 = (text) => translations[text] || text;
  const baseAdminUrl = ((_b = window.yatraAdmin) == null ? void 0 : _b.adminUrl) || "";
  const [visibleColumns, setVisibleColumns] = reactExports.useState(() => {
    if (typeof window === "undefined") {
      return {
        customer: true,
        location: true,
        total_bookings: true,
        total_spent: true,
        loyalty: true,
        status: true,
        created_at: true
      };
    }
    const saved = window.localStorage.getItem(
      "yatra-customers-visible-columns"
    );
    return saved ? JSON.parse(saved) : {
      customer: true,
      location: true,
      total_bookings: true,
      total_spent: true,
      loyalty: true,
      status: true,
      created_at: true
    };
  });
  const queryParams = reactExports.useMemo(() => {
    const params = {
      page,
      per_page: 10,
      orderby: sortBy2,
      order: sortOrder
    };
    if (searchTerm) {
      params.search = searchTerm;
    }
    if (statusFilter !== "all") {
      params.status = statusFilter;
    }
    if (loyaltyFilter !== "all") {
      params.loyalty_tier = loyaltyFilter;
    }
    return params;
  }, [searchTerm, statusFilter, loyaltyFilter, sortBy2, sortOrder, page]);
  const { data, isLoading, error } = useQuery({
    queryKey: ["customers", queryParams],
    queryFn: async () => {
      const paramsObj = {};
      Object.entries(queryParams).forEach(([key2, value]) => {
        if (value !== void 0 && value !== null && value !== "") {
          paramsObj[key2] = value;
        }
      });
      return await apiService.getCustomers(paramsObj);
    },
    enabled: can("yatra_view_customers")
  });
  const { data: statsRaw } = useQuery({
    queryKey: ["customers-stats"],
    queryFn: async () => {
      return await apiService.getCustomerStats();
    },
    enabled: can("yatra_view_customers")
  });
  const statsData = statsRaw ?? {};
  const deleteMutation = useMutation({
    mutationFn: async (id) => {
      await apiService.deleteCustomer(id);
    },
    onSuccess: () => {
      queryClient2.invalidateQueries({ queryKey: ["customers"] });
      setDeleteDialogOpen(false);
      setCustomerToDelete(null);
      showToast(__2("Customer deleted successfully"), "success");
    },
    onError: (error2) => {
      showToast((error2 == null ? void 0 : error2.message) || __2("Failed to delete customer"), "error");
    }
  });
  const customers = (data == null ? void 0 : data.data) || [];
  const total = (data == null ? void 0 : data.total) || 0;
  const totalPages = (data == null ? void 0 : data.pages) || Math.ceil(total / 10);
  const errorContext = getErrorContext(error);
  const formatDate2 = (dateString) => {
    return formatDate$1(dateString);
  };
  const formatPrice = (price, currencyCode = "USD") => formatYatraMoney(Number(price) || 0, currencyCode, {
    zeroAsUnknown: false
  });
  const getStatusBadge = (status) => {
    const statusMap = {
      active: {
        className: "bg-green-100 text-green-700 dark:bg-green-900/20 dark:text-green-400",
        label: __2("Active")
      },
      inactive: {
        className: "bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-400",
        label: __2("Inactive")
      },
      blocked: {
        className: "bg-red-100 text-red-700 dark:bg-red-900/20 dark:text-red-400",
        label: __2("Blocked")
      }
    };
    const statusInfo = statusMap[status] || {
      className: "bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-400",
      label: status
    };
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "span",
      {
        className: `inline-flex items-center px-2 py-1 rounded-md text-xs font-medium ${statusInfo.className}`,
        children: statusInfo.label
      }
    );
  };
  const getLoyaltyBadge = (tier) => {
    const tierMap = {
      bronze: {
        className: "bg-amber-100 text-amber-700 dark:bg-amber-900/20 dark:text-amber-400",
        icon: "🥉"
      },
      silver: {
        className: "bg-gray-200 text-gray-700 dark:bg-gray-600 dark:text-gray-300",
        icon: "🥈"
      },
      gold: {
        className: "bg-yellow-100 text-yellow-700 dark:bg-yellow-900/20 dark:text-yellow-400",
        icon: "🥇"
      },
      platinum: {
        className: "bg-purple-100 text-purple-700 dark:bg-purple-900/20 dark:text-purple-400",
        icon: "💎"
      }
    };
    const tierInfo = tierMap[tier] || tierMap["bronze"];
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "span",
      {
        className: `inline-flex items-center gap-1 px-2 py-1 rounded-md text-xs font-medium ${tierInfo.className}`,
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: tierInfo.icon }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "capitalize", children: tier })
        ]
      }
    );
  };
  const handleEdit = (customer) => {
    window.location.href = `${baseAdminUrl}?page=yatra&subpage=customers&action=edit&id=${customer.id}`;
  };
  const handleDelete = (customer) => {
    setCustomerToDelete(customer);
    setDeleteDialogOpen(true);
  };
  const confirmDelete = () => {
    if (customerToDelete) {
      deleteMutation.mutate(customerToDelete.id);
    }
  };
  const handleView = (customer) => {
    window.location.href = `${baseAdminUrl}?page=yatra&subpage=customers&action=view&id=${customer.id}`;
  };
  const handleCreateCustomer = () => {
    window.location.href = `${baseAdminUrl}?page=yatra&subpage=customers&action=create`;
  };
  const handleResetFilters = () => {
    setSearchTerm("");
    setStatusFilter("all");
    setLoyaltyFilter("all");
    setSortBy("created_at");
    setSortOrder("desc");
    setPage(1);
  };
  const handleSort = (field) => {
    if (sortBy2 === field) {
      setSortOrder(sortOrder === "asc" ? "desc" : "asc");
    } else {
      setSortBy(field);
      setSortOrder("desc");
    }
  };
  const getSortIcon = (field) => {
    if (sortBy2 !== field) {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowUpDown, { className: "w-3.5 h-3.5 ml-1 text-gray-400" });
    }
    return sortOrder === "asc" ? /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowUp, { className: "w-3.5 h-3.5 ml-1 text-gray-600 dark:text-gray-300" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowDown, { className: "w-3.5 h-3.5 ml-1 text-gray-600 dark:text-gray-300" });
  };
  const hasFilters = searchTerm || statusFilter !== "all" || loyaltyFilter !== "all" || sortBy2 !== "created_at" || sortOrder !== "desc";
  const toggleColumn = (key2) => {
    const next = {
      ...visibleColumns,
      [key2]: !visibleColumns[key2]
    };
    setVisibleColumns(next);
    if (typeof window !== "undefined") {
      window.localStorage.setItem(
        "yatra-customers-visible-columns",
        JSON.stringify(next)
      );
    }
  };
  const handleSelectItem = (id, checked) => {
    setSelectedIds(
      (prev) => checked ? [...prev, id] : prev.filter((v) => v !== id)
    );
  };
  const handleSelectAll = (checked) => {
    if (checked) {
      setSelectedIds(customers.map((customer) => customer.id));
    } else {
      setSelectedIds([]);
    }
  };
  const isAllSelected = customers.length > 0 && selectedIds.length === customers.length;
  const updateStatusForIds = async (ids, newStatus) => {
    await Promise.all(
      ids.map(async (id) => {
        await apiService.updateCustomerStatus(id, newStatus);
      })
    );
  };
  const handleBulkApply = async () => {
    if (!bulkAction || selectedIds.length === 0) {
      return;
    }
    try {
      setIsBulkPending(true);
      if (bulkAction === "delete") {
        await Promise.all(
          selectedIds.map((id) => apiService.deleteCustomer(id))
        );
        showToast(__2("Selected customers deleted successfully"), "success");
      } else {
        await updateStatusForIds(selectedIds, bulkAction);
        showToast(__2("Customer statuses updated successfully"), "success");
      }
      queryClient2.invalidateQueries({ queryKey: ["customers"] });
      setSelectedIds([]);
      setBulkAction("");
    } catch (error2) {
      showToast(
        (error2 == null ? void 0 : error2.message) || __2("Failed to perform bulk action on customers"),
        "error"
      );
    } finally {
      setIsBulkPending(false);
    }
  };
  const allBulkActionOptions = [
    { value: "active", label: __2("Mark as Active") },
    { value: "inactive", label: __2("Mark as Inactive") },
    { value: "blocked", label: __2("Mark as Blocked") },
    { value: "delete", label: __2("Delete permanently") }
  ];
  const getBulkActionOptionsForStatus = (view) => {
    switch (view) {
      case "active":
        return allBulkActionOptions.filter(
          (opt) => ["inactive", "blocked", "delete"].includes(opt.value)
        );
      case "inactive":
        return allBulkActionOptions.filter(
          (opt) => ["active", "blocked", "delete"].includes(opt.value)
        );
      case "blocked":
        return allBulkActionOptions.filter(
          (opt) => ["active", "inactive", "delete"].includes(opt.value)
        );
      default:
        return allBulkActionOptions;
    }
  };
  const bulkActionOptions = getBulkActionOptionsForStatus(statusFilter);
  const statusOptions = [
    { value: "all", label: __2("All Status") },
    { value: "active", label: __2("Active") },
    { value: "inactive", label: __2("Inactive") },
    { value: "blocked", label: __2("Blocked") }
  ];
  const sortOptions = [
    { value: "created_at", label: __2("Registration Date") },
    { value: "name", label: __2("Name") },
    { value: "email", label: __2("Email") },
    { value: "country", label: __2("Country") },
    { value: "total_bookings", label: __2("Bookings") },
    { value: "total_spent", label: __2("Total Spent") },
    { value: "status", label: __2("Status") }
  ];
  const columnOptions = [
    {
      key: "customer",
      label: __2("Customer"),
      visible: visibleColumns.customer
    },
    {
      key: "location",
      label: __2("Location"),
      visible: visibleColumns.location
    },
    {
      key: "total_bookings",
      label: __2("Bookings"),
      visible: visibleColumns.total_bookings
    },
    {
      key: "total_spent",
      label: __2("Total Spent"),
      visible: visibleColumns.total_spent
    },
    { key: "loyalty", label: __2("Loyalty"), visible: visibleColumns.loyalty },
    { key: "status", label: __2("Status"), visible: visibleColumns.status },
    {
      key: "created_at",
      label: __2("Registered"),
      visible: visibleColumns.created_at
    }
  ];
  const columns = [
    {
      key: "customer",
      label: __2("Customer"),
      sortable: true,
      visible: visibleColumns.customer,
      render: (customer) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "font-medium text-gray-900 dark:text-white", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          "a",
          {
            href: `${baseAdminUrl}?page=yatra&subpage=customers&action=view&id=${customer.id}`,
            className: "hover:underline underline-offset-2 text-blue-600 dark:text-blue-400",
            children: customer.name || `${customer.first_name} ${customer.last_name}`
          }
        ) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-500 dark:text-gray-400", children: customer.email }),
        customer.phone && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1 text-xs text-gray-500 dark:text-gray-400 mt-0.5", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Phone, { className: "w-3 h-3" }),
          customer.phone
        ] })
      ] })
    },
    {
      key: "location",
      label: __2("Location"),
      sortable: true,
      visible: visibleColumns.location,
      render: (customer) => customer.country ? /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1 text-sm text-gray-600 dark:text-gray-400", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(MapPin, { className: "w-3.5 h-3.5" }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { children: [
          customer.city ? `${customer.city}, ` : "",
          customer.country
        ] })
      ] }) : /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-400", children: "-" })
    },
    isPro && {
      key: "total_bookings",
      label: __2("Bookings"),
      sortable: true,
      visible: visibleColumns.total_bookings,
      render: (customer) => /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-600 dark:text-gray-400", children: customer.total_bookings })
    },
    isPro && {
      key: "total_spent",
      label: __2("Total Spent"),
      sortable: true,
      visible: visibleColumns.total_spent,
      render: (customer) => /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-medium", children: formatPrice(customer.total_spent) })
    },
    {
      key: "loyalty",
      label: __2("Loyalty"),
      sortable: false,
      visible: visibleColumns.loyalty,
      render: (customer) => getLoyaltyBadge(customer.loyalty_tier || "bronze")
    },
    {
      key: "status",
      label: __2("Status"),
      sortable: true,
      visible: visibleColumns.status,
      render: (customer) => getStatusBadge(customer.status)
    },
    {
      key: "created_at",
      label: __2("Registered"),
      sortable: true,
      visible: visibleColumns.created_at,
      render: (customer) => /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-500 dark:text-gray-400 text-sm", children: formatDate2(customer.created_at) })
    }
  ].filter(Boolean);
  const actions = [
    {
      key: "view",
      label: __2("View"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Eye, { className: "w-4 h-4" }),
      onClick: (customer) => handleView(customer)
    },
    {
      key: "edit",
      label: __2("Edit"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(PenSquare, { className: "w-4 h-4" }),
      onClick: (customer) => handleEdit(customer),
      condition: () => can("yatra_edit_customers")
    },
    {
      key: "mark_active",
      label: __2("Mark as Active"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Check, { className: "w-4 h-4" }),
      onClick: async (customer) => {
        await updateStatusForIds([customer.id], "active");
        queryClient2.invalidateQueries({ queryKey: ["customers"] });
      },
      condition: (customer) => can("yatra_edit_customers") && customer.status !== "active"
    },
    {
      key: "mark_inactive",
      label: __2("Mark as Inactive"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(PauseCircle, { className: "w-4 h-4" }),
      onClick: async (customer) => {
        await updateStatusForIds([customer.id], "inactive");
        queryClient2.invalidateQueries({ queryKey: ["customers"] });
      },
      condition: (customer) => can("yatra_edit_customers") && customer.status !== "inactive"
    },
    {
      key: "mark_blocked",
      label: __2("Mark as Blocked"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(ShieldX, { className: "w-4 h-4" }),
      onClick: async (customer) => {
        await updateStatusForIds([customer.id], "blocked");
        queryClient2.invalidateQueries({ queryKey: ["customers"] });
      },
      condition: (customer) => can("yatra_edit_customers") && customer.status !== "blocked"
    },
    {
      key: "delete",
      label: __2("Delete"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "w-4 h-4" }),
      onClick: (customer) => handleDelete(customer),
      variant: "destructive",
      condition: () => can("yatra_delete_customers")
    }
  ];
  const renderSkeleton = () => /* @__PURE__ */ jsxRuntimeExports.jsxs(Table$1, { children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(TableHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(TableRow, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(TableHead, { className: "w-[250px]", children: __2("Customer") }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(TableHead, { children: __2("Location") }),
      isPro && /* @__PURE__ */ jsxRuntimeExports.jsx(TableHead, { children: __2("Bookings") }),
      isPro && /* @__PURE__ */ jsxRuntimeExports.jsx(TableHead, { children: __2("Total Spent") }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(TableHead, { children: __2("Loyalty") }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(TableHead, { children: __2("Status") }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(TableHead, { children: __2("Registered") }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(TableHead, { className: "text-right w-[100px]", children: __2("Actions") })
    ] }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(TableBody, { children: [...Array(5)].map((_, i) => /* @__PURE__ */ jsxRuntimeExports.jsxs(TableRow, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(TableCell, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-4 w-32" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-3 w-40" })
      ] }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(TableCell, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-4 w-24" }) }),
      isPro && /* @__PURE__ */ jsxRuntimeExports.jsx(TableCell, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-4 w-8" }) }),
      isPro && /* @__PURE__ */ jsxRuntimeExports.jsx(TableCell, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-4 w-16" }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(TableCell, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-6 w-16 rounded" }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(TableCell, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-6 w-14 rounded" }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(TableCell, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-4 w-20" }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(TableCell, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-end gap-1", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-8 w-8 rounded" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-8 w-8 rounded" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-8 w-8 rounded" })
      ] }) })
    ] }, i)) })
  ] });
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      PageHeader,
      {
        title: __2("Customers"),
        description: __2("Manage your customer database"),
        actionCapability: "yatra_edit_customers",
        actions: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Button,
          {
            onClick: handleCreateCustomer,
            className: "flex items-center gap-2",
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Plus, { className: "w-4 h-4" }),
              __2("Add New Customer")
            ]
          }
        )
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_view_customers", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-4", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-12 gap-4 items-center", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: isPro ? "lg:col-span-8" : "lg:col-span-12", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          SearchFilterToolbar,
          {
            searchTerm,
            onSearchChange: setSearchTerm,
            statusFilter,
            onStatusChange: (value) => {
              setStatusFilter(value);
              setPage(1);
            },
            statusOptions,
            sortBy: sortBy2,
            onSortByChange: (field) => {
              setSortBy(field);
              setPage(1);
            },
            sortOrder,
            onSortOrderChange: (order) => {
              setSortOrder(order);
              setPage(1);
            },
            sortOptions,
            onResetFilters: handleResetFilters,
            hasFilters: !!hasFilters,
            placeholder: __2("Search customers...")
          }
        ) }),
        isPro && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "lg:col-span-4", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Select,
          {
            value: loyaltyFilter,
            onChange: (e) => {
              setLoyaltyFilter(e.target.value);
              setPage(1);
            },
            className: "w-full",
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "all", children: __2("All Tiers") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "bronze", children: __2("Bronze") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "silver", children: __2("Silver") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "gold", children: __2("Gold") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "platinum", children: __2("Platinum") })
            ]
          }
        ) })
      ] }) }) }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_view_customers", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        BulkActionToolbar,
        {
          selectedIds,
          bulkAction,
          setBulkAction,
          onApply: handleBulkApply,
          onClearSelection: () => setSelectedIds([]),
          statusFilter,
          setStatusFilter: (value) => {
            setStatusFilter(value);
            setPage(1);
          },
          statusOptions: [
            { key: "all", label: __2("All"), count: (statsData == null ? void 0 : statsData.all) ?? 0 },
            {
              key: "active",
              label: __2("Active"),
              count: (statsData == null ? void 0 : statsData.active) ?? 0
            },
            {
              key: "inactive",
              label: __2("Inactive"),
              count: (statsData == null ? void 0 : statsData.inactive) ?? 0
            },
            {
              key: "blocked",
              label: __2("Blocked"),
              count: (statsData == null ? void 0 : statsData.blocked) ?? 0
            }
          ],
          showColumnsDropdown,
          setShowColumnsDropdown,
          columnOptions,
          onToggleColumn: toggleColumn,
          bulkMutationPending: isBulkPending,
          totalItems: total,
          bulkActionOptions
        }
      ) }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(ConditionalRender, { capability: "yatra_view_customers", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-0", children: isLoading ? renderSkeleton() : /* @__PURE__ */ jsxRuntimeExports.jsx(
          Table,
          {
            data: customers,
            columns,
            actions,
            isLoading,
            isError: !!error,
            errorText: __2("Error loading customers"),
            errorDetails: errorContext.details,
            errorRequestInfo: errorContext.requestInfo,
            errorDescription: __2(
              "We couldn’t connect to the customers service. Please refresh or try again shortly."
            ),
            onRetry: () => queryClient2.invalidateQueries({ queryKey: ["customers"] }),
            emptyText: __2("No customers found"),
            emptyDescription: hasFilters ? __2("Try adjusting your filters to see more results.") : __2("Customers will appear here when bookings are made"),
            onCreateClick: can("yatra_edit_customers") ? handleCreateCustomer : void 0,
            onSort: handleSort,
            getSortIcon,
            selectedItemIds: selectedIds,
            onSelectItem: handleSelectItem,
            onSelectAll: handleSelectAll,
            isAllSelected,
            getItemId: (customer) => customer.id,
            skeletonRows: 5,
            capability: "yatra_view_customers"
          }
        ) }) }),
        total > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-4", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          Pagination,
          {
            currentPage: page,
            totalPages,
            totalItems: total,
            itemsPerPage: 10,
            onPageChange: (newPage) => setPage(newPage),
            itemName: __2("customers")
          }
        ) })
      ] })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      ConfirmationDialog,
      {
        isOpen: deleteDialogOpen,
        onClose: () => setDeleteDialogOpen(false),
        onConfirm: confirmDelete,
        title: __2("Delete Customer"),
        description: customerToDelete ? __2(
          "Are you sure you want to delete this customer? This action cannot be undone."
        ) + ` (${customerToDelete.name || customerToDelete.email})` : __2(
          "Are you sure you want to delete this customer? This action cannot be undone."
        ),
        confirmText: __2("Delete"),
        cancelText: __2("Cancel"),
        variant: "danger",
        isLoading: deleteMutation.isPending
      }
    )
  ] });
};
const millisecondsInWeek = 6048e5;
const millisecondsInDay = 864e5;
const millisecondsInMinute = 6e4;
const millisecondsInHour = 36e5;
const millisecondsInSecond = 1e3;
const constructFromSymbol = Symbol.for("constructDateFrom");
function constructFrom(date2, value) {
  if (typeof date2 === "function") return date2(value);
  if (date2 && typeof date2 === "object" && constructFromSymbol in date2)
    return date2[constructFromSymbol](value);
  if (date2 instanceof Date) return new date2.constructor(value);
  return new Date(value);
}
function toDate(argument, context) {
  return constructFrom(context || argument, argument);
}
function addDays(date2, amount, options2) {
  const _date = toDate(date2, options2 == null ? void 0 : options2.in);
  if (isNaN(amount)) return constructFrom((options2 == null ? void 0 : options2.in) || date2, NaN);
  if (!amount) return _date;
  _date.setDate(_date.getDate() + amount);
  return _date;
}
function addMonths(date2, amount, options2) {
  const _date = toDate(date2, options2 == null ? void 0 : options2.in);
  if (isNaN(amount)) return constructFrom(date2, NaN);
  if (!amount) {
    return _date;
  }
  const dayOfMonth = _date.getDate();
  const endOfDesiredMonth = constructFrom(date2, _date.getTime());
  endOfDesiredMonth.setMonth(_date.getMonth() + amount + 1, 0);
  const daysInMonth = endOfDesiredMonth.getDate();
  if (dayOfMonth >= daysInMonth) {
    return endOfDesiredMonth;
  } else {
    _date.setFullYear(
      endOfDesiredMonth.getFullYear(),
      endOfDesiredMonth.getMonth(),
      dayOfMonth
    );
    return _date;
  }
}
let defaultOptions = {};
function getDefaultOptions$1() {
  return defaultOptions;
}
function startOfWeek(date2, options2) {
  var _a, _b, _c, _d;
  const defaultOptions2 = getDefaultOptions$1();
  const weekStartsOn = (options2 == null ? void 0 : options2.weekStartsOn) ?? ((_b = (_a = options2 == null ? void 0 : options2.locale) == null ? void 0 : _a.options) == null ? void 0 : _b.weekStartsOn) ?? defaultOptions2.weekStartsOn ?? ((_d = (_c = defaultOptions2.locale) == null ? void 0 : _c.options) == null ? void 0 : _d.weekStartsOn) ?? 0;
  const _date = toDate(date2, options2 == null ? void 0 : options2.in);
  const day = _date.getDay();
  const diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;
  _date.setDate(_date.getDate() - diff);
  _date.setHours(0, 0, 0, 0);
  return _date;
}
function startOfISOWeek(date2, options2) {
  return startOfWeek(date2, { ...options2, weekStartsOn: 1 });
}
function getISOWeekYear(date2, options2) {
  const _date = toDate(date2, options2 == null ? void 0 : options2.in);
  const year = _date.getFullYear();
  const fourthOfJanuaryOfNextYear = constructFrom(_date, 0);
  fourthOfJanuaryOfNextYear.setFullYear(year + 1, 0, 4);
  fourthOfJanuaryOfNextYear.setHours(0, 0, 0, 0);
  const startOfNextYear = startOfISOWeek(fourthOfJanuaryOfNextYear);
  const fourthOfJanuaryOfThisYear = constructFrom(_date, 0);
  fourthOfJanuaryOfThisYear.setFullYear(year, 0, 4);
  fourthOfJanuaryOfThisYear.setHours(0, 0, 0, 0);
  const startOfThisYear = startOfISOWeek(fourthOfJanuaryOfThisYear);
  if (_date.getTime() >= startOfNextYear.getTime()) {
    return year + 1;
  } else if (_date.getTime() >= startOfThisYear.getTime()) {
    return year;
  } else {
    return year - 1;
  }
}
function getTimezoneOffsetInMilliseconds(date2) {
  const _date = toDate(date2);
  const utcDate2 = new Date(
    Date.UTC(
      _date.getFullYear(),
      _date.getMonth(),
      _date.getDate(),
      _date.getHours(),
      _date.getMinutes(),
      _date.getSeconds(),
      _date.getMilliseconds()
    )
  );
  utcDate2.setUTCFullYear(_date.getFullYear());
  return +date2 - +utcDate2;
}
function normalizeDates(context, ...dates) {
  const normalize2 = constructFrom.bind(
    null,
    dates.find((date2) => typeof date2 === "object")
  );
  return dates.map(normalize2);
}
function startOfDay(date2, options2) {
  const _date = toDate(date2, options2 == null ? void 0 : options2.in);
  _date.setHours(0, 0, 0, 0);
  return _date;
}
function differenceInCalendarDays(laterDate, earlierDate, options2) {
  const [laterDate_, earlierDate_] = normalizeDates(
    options2 == null ? void 0 : options2.in,
    laterDate,
    earlierDate
  );
  const laterStartOfDay = startOfDay(laterDate_);
  const earlierStartOfDay = startOfDay(earlierDate_);
  const laterTimestamp = +laterStartOfDay - getTimezoneOffsetInMilliseconds(laterStartOfDay);
  const earlierTimestamp = +earlierStartOfDay - getTimezoneOffsetInMilliseconds(earlierStartOfDay);
  return Math.round((laterTimestamp - earlierTimestamp) / millisecondsInDay);
}
function startOfISOWeekYear(date2, options2) {
  const year = getISOWeekYear(date2, options2);
  const fourthOfJanuary = constructFrom(date2, 0);
  fourthOfJanuary.setFullYear(year, 0, 4);
  fourthOfJanuary.setHours(0, 0, 0, 0);
  return startOfISOWeek(fourthOfJanuary);
}
function constructNow(date2) {
  return constructFrom(date2, Date.now());
}
function isSameDay(laterDate, earlierDate, options2) {
  const [dateLeft_, dateRight_] = normalizeDates(
    options2 == null ? void 0 : options2.in,
    laterDate,
    earlierDate
  );
  return +startOfDay(dateLeft_) === +startOfDay(dateRight_);
}
function isDate(value) {
  return value instanceof Date || typeof value === "object" && Object.prototype.toString.call(value) === "[object Date]";
}
function isValid(date2) {
  return !(!isDate(date2) && typeof date2 !== "number" || isNaN(+toDate(date2)));
}
function endOfMonth(date2, options2) {
  const _date = toDate(date2, options2 == null ? void 0 : options2.in);
  const month = _date.getMonth();
  _date.setFullYear(_date.getFullYear(), month + 1, 0);
  _date.setHours(23, 59, 59, 999);
  return _date;
}
function normalizeInterval(context, interval) {
  const [start, end] = normalizeDates(context, interval.start, interval.end);
  return { start, end };
}
function eachDayOfInterval(interval, options2) {
  const { start, end } = normalizeInterval(options2 == null ? void 0 : options2.in, interval);
  let reversed = +start > +end;
  const endTime = reversed ? +start : +end;
  const date2 = reversed ? end : start;
  date2.setHours(0, 0, 0, 0);
  let step = 1;
  const dates = [];
  while (+date2 <= endTime) {
    dates.push(constructFrom(start, date2));
    date2.setDate(date2.getDate() + step);
    date2.setHours(0, 0, 0, 0);
  }
  return reversed ? dates.reverse() : dates;
}
function startOfMonth(date2, options2) {
  const _date = toDate(date2, options2 == null ? void 0 : options2.in);
  _date.setDate(1);
  _date.setHours(0, 0, 0, 0);
  return _date;
}
function startOfYear(date2, options2) {
  const date_ = toDate(date2, options2 == null ? void 0 : options2.in);
  date_.setFullYear(date_.getFullYear(), 0, 1);
  date_.setHours(0, 0, 0, 0);
  return date_;
}
function endOfWeek(date2, options2) {
  var _a, _b, _c, _d;
  const defaultOptions2 = getDefaultOptions$1();
  const weekStartsOn = (options2 == null ? void 0 : options2.weekStartsOn) ?? ((_b = (_a = options2 == null ? void 0 : options2.locale) == null ? void 0 : _a.options) == null ? void 0 : _b.weekStartsOn) ?? defaultOptions2.weekStartsOn ?? ((_d = (_c = defaultOptions2.locale) == null ? void 0 : _c.options) == null ? void 0 : _d.weekStartsOn) ?? 0;
  const _date = toDate(date2, options2 == null ? void 0 : options2.in);
  const day = _date.getDay();
  const diff = (day < weekStartsOn ? -7 : 0) + 6 - (day - weekStartsOn);
  _date.setDate(_date.getDate() + diff);
  _date.setHours(23, 59, 59, 999);
  return _date;
}
const formatDistanceLocale = {
  lessThanXSeconds: {
    one: "less than a second",
    other: "less than {{count}} seconds"
  },
  xSeconds: {
    one: "1 second",
    other: "{{count}} seconds"
  },
  halfAMinute: "half a minute",
  lessThanXMinutes: {
    one: "less than a minute",
    other: "less than {{count}} minutes"
  },
  xMinutes: {
    one: "1 minute",
    other: "{{count}} minutes"
  },
  aboutXHours: {
    one: "about 1 hour",
    other: "about {{count}} hours"
  },
  xHours: {
    one: "1 hour",
    other: "{{count}} hours"
  },
  xDays: {
    one: "1 day",
    other: "{{count}} days"
  },
  aboutXWeeks: {
    one: "about 1 week",
    other: "about {{count}} weeks"
  },
  xWeeks: {
    one: "1 week",
    other: "{{count}} weeks"
  },
  aboutXMonths: {
    one: "about 1 month",
    other: "about {{count}} months"
  },
  xMonths: {
    one: "1 month",
    other: "{{count}} months"
  },
  aboutXYears: {
    one: "about 1 year",
    other: "about {{count}} years"
  },
  xYears: {
    one: "1 year",
    other: "{{count}} years"
  },
  overXYears: {
    one: "over 1 year",
    other: "over {{count}} years"
  },
  almostXYears: {
    one: "almost 1 year",
    other: "almost {{count}} years"
  }
};
const formatDistance = (token, count, options2) => {
  let result;
  const tokenValue = formatDistanceLocale[token];
  if (typeof tokenValue === "string") {
    result = tokenValue;
  } else if (count === 1) {
    result = tokenValue.one;
  } else {
    result = tokenValue.other.replace("{{count}}", count.toString());
  }
  if (options2 == null ? void 0 : options2.addSuffix) {
    if (options2.comparison && options2.comparison > 0) {
      return "in " + result;
    } else {
      return result + " ago";
    }
  }
  return result;
};
function buildFormatLongFn(args) {
  return (options2 = {}) => {
    const width = options2.width ? String(options2.width) : args.defaultWidth;
    const format2 = args.formats[width] || args.formats[args.defaultWidth];
    return format2;
  };
}
const dateFormats = {
  full: "EEEE, MMMM do, y",
  long: "MMMM do, y",
  medium: "MMM d, y",
  short: "MM/dd/yyyy"
};
const timeFormats = {
  full: "h:mm:ss a zzzz",
  long: "h:mm:ss a z",
  medium: "h:mm:ss a",
  short: "h:mm a"
};
const dateTimeFormats = {
  full: "{{date}} 'at' {{time}}",
  long: "{{date}} 'at' {{time}}",
  medium: "{{date}}, {{time}}",
  short: "{{date}}, {{time}}"
};
const formatLong = {
  date: buildFormatLongFn({
    formats: dateFormats,
    defaultWidth: "full"
  }),
  time: buildFormatLongFn({
    formats: timeFormats,
    defaultWidth: "full"
  }),
  dateTime: buildFormatLongFn({
    formats: dateTimeFormats,
    defaultWidth: "full"
  })
};
const formatRelativeLocale = {
  lastWeek: "'last' eeee 'at' p",
  yesterday: "'yesterday at' p",
  today: "'today at' p",
  tomorrow: "'tomorrow at' p",
  nextWeek: "eeee 'at' p",
  other: "P"
};
const formatRelative = (token, _date, _baseDate, _options) => formatRelativeLocale[token];
function buildLocalizeFn(args) {
  return (value, options2) => {
    const context = (options2 == null ? void 0 : options2.context) ? String(options2.context) : "standalone";
    let valuesArray;
    if (context === "formatting" && args.formattingValues) {
      const defaultWidth = args.defaultFormattingWidth || args.defaultWidth;
      const width = (options2 == null ? void 0 : options2.width) ? String(options2.width) : defaultWidth;
      valuesArray = args.formattingValues[width] || args.formattingValues[defaultWidth];
    } else {
      const defaultWidth = args.defaultWidth;
      const width = (options2 == null ? void 0 : options2.width) ? String(options2.width) : args.defaultWidth;
      valuesArray = args.values[width] || args.values[defaultWidth];
    }
    const index = args.argumentCallback ? args.argumentCallback(value) : value;
    return valuesArray[index];
  };
}
const eraValues = {
  narrow: ["B", "A"],
  abbreviated: ["BC", "AD"],
  wide: ["Before Christ", "Anno Domini"]
};
const quarterValues = {
  narrow: ["1", "2", "3", "4"],
  abbreviated: ["Q1", "Q2", "Q3", "Q4"],
  wide: ["1st quarter", "2nd quarter", "3rd quarter", "4th quarter"]
};
const monthValues = {
  narrow: ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"],
  abbreviated: [
    "Jan",
    "Feb",
    "Mar",
    "Apr",
    "May",
    "Jun",
    "Jul",
    "Aug",
    "Sep",
    "Oct",
    "Nov",
    "Dec"
  ],
  wide: [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December"
  ]
};
const dayValues = {
  narrow: ["S", "M", "T", "W", "T", "F", "S"],
  short: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"],
  abbreviated: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
  wide: [
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday"
  ]
};
const dayPeriodValues = {
  narrow: {
    am: "a",
    pm: "p",
    midnight: "mi",
    noon: "n",
    morning: "morning",
    afternoon: "afternoon",
    evening: "evening",
    night: "night"
  },
  abbreviated: {
    am: "AM",
    pm: "PM",
    midnight: "midnight",
    noon: "noon",
    morning: "morning",
    afternoon: "afternoon",
    evening: "evening",
    night: "night"
  },
  wide: {
    am: "a.m.",
    pm: "p.m.",
    midnight: "midnight",
    noon: "noon",
    morning: "morning",
    afternoon: "afternoon",
    evening: "evening",
    night: "night"
  }
};
const formattingDayPeriodValues = {
  narrow: {
    am: "a",
    pm: "p",
    midnight: "mi",
    noon: "n",
    morning: "in the morning",
    afternoon: "in the afternoon",
    evening: "in the evening",
    night: "at night"
  },
  abbreviated: {
    am: "AM",
    pm: "PM",
    midnight: "midnight",
    noon: "noon",
    morning: "in the morning",
    afternoon: "in the afternoon",
    evening: "in the evening",
    night: "at night"
  },
  wide: {
    am: "a.m.",
    pm: "p.m.",
    midnight: "midnight",
    noon: "noon",
    morning: "in the morning",
    afternoon: "in the afternoon",
    evening: "in the evening",
    night: "at night"
  }
};
const ordinalNumber = (dirtyNumber, _options) => {
  const number2 = Number(dirtyNumber);
  const rem100 = number2 % 100;
  if (rem100 > 20 || rem100 < 10) {
    switch (rem100 % 10) {
      case 1:
        return number2 + "st";
      case 2:
        return number2 + "nd";
      case 3:
        return number2 + "rd";
    }
  }
  return number2 + "th";
};
const localize = {
  ordinalNumber,
  era: buildLocalizeFn({
    values: eraValues,
    defaultWidth: "wide"
  }),
  quarter: buildLocalizeFn({
    values: quarterValues,
    defaultWidth: "wide",
    argumentCallback: (quarter) => quarter - 1
  }),
  month: buildLocalizeFn({
    values: monthValues,
    defaultWidth: "wide"
  }),
  day: buildLocalizeFn({
    values: dayValues,
    defaultWidth: "wide"
  }),
  dayPeriod: buildLocalizeFn({
    values: dayPeriodValues,
    defaultWidth: "wide",
    formattingValues: formattingDayPeriodValues,
    defaultFormattingWidth: "wide"
  })
};
function buildMatchFn(args) {
  return (string2, options2 = {}) => {
    const width = options2.width;
    const matchPattern = width && args.matchPatterns[width] || args.matchPatterns[args.defaultMatchWidth];
    const matchResult = string2.match(matchPattern);
    if (!matchResult) {
      return null;
    }
    const matchedString = matchResult[0];
    const parsePatterns = width && args.parsePatterns[width] || args.parsePatterns[args.defaultParseWidth];
    const key2 = Array.isArray(parsePatterns) ? findIndex(parsePatterns, (pattern) => pattern.test(matchedString)) : (
      // [TODO] -- I challenge you to fix the type
      findKey(parsePatterns, (pattern) => pattern.test(matchedString))
    );
    let value;
    value = args.valueCallback ? args.valueCallback(key2) : key2;
    value = options2.valueCallback ? (
      // [TODO] -- I challenge you to fix the type
      options2.valueCallback(value)
    ) : value;
    const rest = string2.slice(matchedString.length);
    return { value, rest };
  };
}
function findKey(object2, predicate) {
  for (const key2 in object2) {
    if (Object.prototype.hasOwnProperty.call(object2, key2) && predicate(object2[key2])) {
      return key2;
    }
  }
  return void 0;
}
function findIndex(array2, predicate) {
  for (let key2 = 0; key2 < array2.length; key2++) {
    if (predicate(array2[key2])) {
      return key2;
    }
  }
  return void 0;
}
function buildMatchPatternFn(args) {
  return (string2, options2 = {}) => {
    const matchResult = string2.match(args.matchPattern);
    if (!matchResult) return null;
    const matchedString = matchResult[0];
    const parseResult = string2.match(args.parsePattern);
    if (!parseResult) return null;
    let value = args.valueCallback ? args.valueCallback(parseResult[0]) : parseResult[0];
    value = options2.valueCallback ? options2.valueCallback(value) : value;
    const rest = string2.slice(matchedString.length);
    return { value, rest };
  };
}
const matchOrdinalNumberPattern = /^(\d+)(th|st|nd|rd)?/i;
const parseOrdinalNumberPattern = /\d+/i;
const matchEraPatterns = {
  narrow: /^(b|a)/i,
  abbreviated: /^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,
  wide: /^(before christ|before common era|anno domini|common era)/i
};
const parseEraPatterns = {
  any: [/^b/i, /^(a|c)/i]
};
const matchQuarterPatterns = {
  narrow: /^[1234]/i,
  abbreviated: /^q[1234]/i,
  wide: /^[1234](th|st|nd|rd)? quarter/i
};
const parseQuarterPatterns = {
  any: [/1/i, /2/i, /3/i, /4/i]
};
const matchMonthPatterns = {
  narrow: /^[jfmasond]/i,
  abbreviated: /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,
  wide: /^(january|february|march|april|may|june|july|august|september|october|november|december)/i
};
const parseMonthPatterns = {
  narrow: [
    /^j/i,
    /^f/i,
    /^m/i,
    /^a/i,
    /^m/i,
    /^j/i,
    /^j/i,
    /^a/i,
    /^s/i,
    /^o/i,
    /^n/i,
    /^d/i
  ],
  any: [
    /^ja/i,
    /^f/i,
    /^mar/i,
    /^ap/i,
    /^may/i,
    /^jun/i,
    /^jul/i,
    /^au/i,
    /^s/i,
    /^o/i,
    /^n/i,
    /^d/i
  ]
};
const matchDayPatterns = {
  narrow: /^[smtwf]/i,
  short: /^(su|mo|tu|we|th|fr|sa)/i,
  abbreviated: /^(sun|mon|tue|wed|thu|fri|sat)/i,
  wide: /^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i
};
const parseDayPatterns = {
  narrow: [/^s/i, /^m/i, /^t/i, /^w/i, /^t/i, /^f/i, /^s/i],
  any: [/^su/i, /^m/i, /^tu/i, /^w/i, /^th/i, /^f/i, /^sa/i]
};
const matchDayPeriodPatterns = {
  narrow: /^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,
  any: /^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i
};
const parseDayPeriodPatterns = {
  any: {
    am: /^a/i,
    pm: /^p/i,
    midnight: /^mi/i,
    noon: /^no/i,
    morning: /morning/i,
    afternoon: /afternoon/i,
    evening: /evening/i,
    night: /night/i
  }
};
const match = {
  ordinalNumber: buildMatchPatternFn({
    matchPattern: matchOrdinalNumberPattern,
    parsePattern: parseOrdinalNumberPattern,
    valueCallback: (value) => parseInt(value, 10)
  }),
  era: buildMatchFn({
    matchPatterns: matchEraPatterns,
    defaultMatchWidth: "wide",
    parsePatterns: parseEraPatterns,
    defaultParseWidth: "any"
  }),
  quarter: buildMatchFn({
    matchPatterns: matchQuarterPatterns,
    defaultMatchWidth: "wide",
    parsePatterns: parseQuarterPatterns,
    defaultParseWidth: "any",
    valueCallback: (index) => index + 1
  }),
  month: buildMatchFn({
    matchPatterns: matchMonthPatterns,
    defaultMatchWidth: "wide",
    parsePatterns: parseMonthPatterns,
    defaultParseWidth: "any"
  }),
  day: buildMatchFn({
    matchPatterns: matchDayPatterns,
    defaultMatchWidth: "wide",
    parsePatterns: parseDayPatterns,
    defaultParseWidth: "any"
  }),
  dayPeriod: buildMatchFn({
    matchPatterns: matchDayPeriodPatterns,
    defaultMatchWidth: "any",
    parsePatterns: parseDayPeriodPatterns,
    defaultParseWidth: "any"
  })
};
const enUS = {
  code: "en-US",
  formatDistance,
  formatLong,
  formatRelative,
  localize,
  match,
  options: {
    weekStartsOn: 0,
    firstWeekContainsDate: 1
  }
};
function getDayOfYear(date2, options2) {
  const _date = toDate(date2, options2 == null ? void 0 : options2.in);
  const diff = differenceInCalendarDays(_date, startOfYear(_date));
  const dayOfYear = diff + 1;
  return dayOfYear;
}
function getISOWeek(date2, options2) {
  const _date = toDate(date2, options2 == null ? void 0 : options2.in);
  const diff = +startOfISOWeek(_date) - +startOfISOWeekYear(_date);
  return Math.round(diff / millisecondsInWeek) + 1;
}
function getWeekYear(date2, options2) {
  var _a, _b, _c, _d;
  const _date = toDate(date2, options2 == null ? void 0 : options2.in);
  const year = _date.getFullYear();
  const defaultOptions2 = getDefaultOptions$1();
  const firstWeekContainsDate = (options2 == null ? void 0 : options2.firstWeekContainsDate) ?? ((_b = (_a = options2 == null ? void 0 : options2.locale) == null ? void 0 : _a.options) == null ? void 0 : _b.firstWeekContainsDate) ?? defaultOptions2.firstWeekContainsDate ?? ((_d = (_c = defaultOptions2.locale) == null ? void 0 : _c.options) == null ? void 0 : _d.firstWeekContainsDate) ?? 1;
  const firstWeekOfNextYear = constructFrom((options2 == null ? void 0 : options2.in) || date2, 0);
  firstWeekOfNextYear.setFullYear(year + 1, 0, firstWeekContainsDate);
  firstWeekOfNextYear.setHours(0, 0, 0, 0);
  const startOfNextYear = startOfWeek(firstWeekOfNextYear, options2);
  const firstWeekOfThisYear = constructFrom((options2 == null ? void 0 : options2.in) || date2, 0);
  firstWeekOfThisYear.setFullYear(year, 0, firstWeekContainsDate);
  firstWeekOfThisYear.setHours(0, 0, 0, 0);
  const startOfThisYear = startOfWeek(firstWeekOfThisYear, options2);
  if (+_date >= +startOfNextYear) {
    return year + 1;
  } else if (+_date >= +startOfThisYear) {
    return year;
  } else {
    return year - 1;
  }
}
function startOfWeekYear(date2, options2) {
  var _a, _b, _c, _d;
  const defaultOptions2 = getDefaultOptions$1();
  const firstWeekContainsDate = (options2 == null ? void 0 : options2.firstWeekContainsDate) ?? ((_b = (_a = options2 == null ? void 0 : options2.locale) == null ? void 0 : _a.options) == null ? void 0 : _b.firstWeekContainsDate) ?? defaultOptions2.firstWeekContainsDate ?? ((_d = (_c = defaultOptions2.locale) == null ? void 0 : _c.options) == null ? void 0 : _d.firstWeekContainsDate) ?? 1;
  const year = getWeekYear(date2, options2);
  const firstWeek = constructFrom((options2 == null ? void 0 : options2.in) || date2, 0);
  firstWeek.setFullYear(year, 0, firstWeekContainsDate);
  firstWeek.setHours(0, 0, 0, 0);
  const _date = startOfWeek(firstWeek, options2);
  return _date;
}
function getWeek(date2, options2) {
  const _date = toDate(date2, options2 == null ? void 0 : options2.in);
  const diff = +startOfWeek(_date, options2) - +startOfWeekYear(_date, options2);
  return Math.round(diff / millisecondsInWeek) + 1;
}
function addLeadingZeros(number2, targetLength) {
  const sign2 = number2 < 0 ? "-" : "";
  const output = Math.abs(number2).toString().padStart(targetLength, "0");
  return sign2 + output;
}
const lightFormatters = {
  // Year
  y(date2, token) {
    const signedYear = date2.getFullYear();
    const year = signedYear > 0 ? signedYear : 1 - signedYear;
    return addLeadingZeros(token === "yy" ? year % 100 : year, token.length);
  },
  // Month
  M(date2, token) {
    const month = date2.getMonth();
    return token === "M" ? String(month + 1) : addLeadingZeros(month + 1, 2);
  },
  // Day of the month
  d(date2, token) {
    return addLeadingZeros(date2.getDate(), token.length);
  },
  // AM or PM
  a(date2, token) {
    const dayPeriodEnumValue = date2.getHours() / 12 >= 1 ? "pm" : "am";
    switch (token) {
      case "a":
      case "aa":
        return dayPeriodEnumValue.toUpperCase();
      case "aaa":
        return dayPeriodEnumValue;
      case "aaaaa":
        return dayPeriodEnumValue[0];
      case "aaaa":
      default:
        return dayPeriodEnumValue === "am" ? "a.m." : "p.m.";
    }
  },
  // Hour [1-12]
  h(date2, token) {
    return addLeadingZeros(date2.getHours() % 12 || 12, token.length);
  },
  // Hour [0-23]
  H(date2, token) {
    return addLeadingZeros(date2.getHours(), token.length);
  },
  // Minute
  m(date2, token) {
    return addLeadingZeros(date2.getMinutes(), token.length);
  },
  // Second
  s(date2, token) {
    return addLeadingZeros(date2.getSeconds(), token.length);
  },
  // Fraction of second
  S(date2, token) {
    const numberOfDigits = token.length;
    const milliseconds = date2.getMilliseconds();
    const fractionalSeconds = Math.trunc(
      milliseconds * Math.pow(10, numberOfDigits - 3)
    );
    return addLeadingZeros(fractionalSeconds, token.length);
  }
};
const dayPeriodEnum = {
  midnight: "midnight",
  noon: "noon",
  morning: "morning",
  afternoon: "afternoon",
  evening: "evening",
  night: "night"
};
const formatters = {
  // Era
  G: function(date2, token, localize2) {
    const era = date2.getFullYear() > 0 ? 1 : 0;
    switch (token) {
      case "G":
      case "GG":
      case "GGG":
        return localize2.era(era, { width: "abbreviated" });
      case "GGGGG":
        return localize2.era(era, { width: "narrow" });
      case "GGGG":
      default:
        return localize2.era(era, { width: "wide" });
    }
  },
  // Year
  y: function(date2, token, localize2) {
    if (token === "yo") {
      const signedYear = date2.getFullYear();
      const year = signedYear > 0 ? signedYear : 1 - signedYear;
      return localize2.ordinalNumber(year, { unit: "year" });
    }
    return lightFormatters.y(date2, token);
  },
  // Local week-numbering year
  Y: function(date2, token, localize2, options2) {
    const signedWeekYear = getWeekYear(date2, options2);
    const weekYear = signedWeekYear > 0 ? signedWeekYear : 1 - signedWeekYear;
    if (token === "YY") {
      const twoDigitYear = weekYear % 100;
      return addLeadingZeros(twoDigitYear, 2);
    }
    if (token === "Yo") {
      return localize2.ordinalNumber(weekYear, { unit: "year" });
    }
    return addLeadingZeros(weekYear, token.length);
  },
  // ISO week-numbering year
  R: function(date2, token) {
    const isoWeekYear = getISOWeekYear(date2);
    return addLeadingZeros(isoWeekYear, token.length);
  },
  // Extended year. This is a single number designating the year of this calendar system.
  // The main difference between `y` and `u` localizers are B.C. years:
  // | Year | `y` | `u` |
  // |------|-----|-----|
  // | AC 1 |   1 |   1 |
  // | BC 1 |   1 |   0 |
  // | BC 2 |   2 |  -1 |
  // Also `yy` always returns the last two digits of a year,
  // while `uu` pads single digit years to 2 characters and returns other years unchanged.
  u: function(date2, token) {
    const year = date2.getFullYear();
    return addLeadingZeros(year, token.length);
  },
  // Quarter
  Q: function(date2, token, localize2) {
    const quarter = Math.ceil((date2.getMonth() + 1) / 3);
    switch (token) {
      case "Q":
        return String(quarter);
      case "QQ":
        return addLeadingZeros(quarter, 2);
      case "Qo":
        return localize2.ordinalNumber(quarter, { unit: "quarter" });
      case "QQQ":
        return localize2.quarter(quarter, {
          width: "abbreviated",
          context: "formatting"
        });
      case "QQQQQ":
        return localize2.quarter(quarter, {
          width: "narrow",
          context: "formatting"
        });
      case "QQQQ":
      default:
        return localize2.quarter(quarter, {
          width: "wide",
          context: "formatting"
        });
    }
  },
  // Stand-alone quarter
  q: function(date2, token, localize2) {
    const quarter = Math.ceil((date2.getMonth() + 1) / 3);
    switch (token) {
      case "q":
        return String(quarter);
      case "qq":
        return addLeadingZeros(quarter, 2);
      case "qo":
        return localize2.ordinalNumber(quarter, { unit: "quarter" });
      case "qqq":
        return localize2.quarter(quarter, {
          width: "abbreviated",
          context: "standalone"
        });
      case "qqqqq":
        return localize2.quarter(quarter, {
          width: "narrow",
          context: "standalone"
        });
      case "qqqq":
      default:
        return localize2.quarter(quarter, {
          width: "wide",
          context: "standalone"
        });
    }
  },
  // Month
  M: function(date2, token, localize2) {
    const month = date2.getMonth();
    switch (token) {
      case "M":
      case "MM":
        return lightFormatters.M(date2, token);
      case "Mo":
        return localize2.ordinalNumber(month + 1, { unit: "month" });
      case "MMM":
        return localize2.month(month, {
          width: "abbreviated",
          context: "formatting"
        });
      case "MMMMM":
        return localize2.month(month, {
          width: "narrow",
          context: "formatting"
        });
      case "MMMM":
      default:
        return localize2.month(month, { width: "wide", context: "formatting" });
    }
  },
  // Stand-alone month
  L: function(date2, token, localize2) {
    const month = date2.getMonth();
    switch (token) {
      case "L":
        return String(month + 1);
      case "LL":
        return addLeadingZeros(month + 1, 2);
      case "Lo":
        return localize2.ordinalNumber(month + 1, { unit: "month" });
      case "LLL":
        return localize2.month(month, {
          width: "abbreviated",
          context: "standalone"
        });
      case "LLLLL":
        return localize2.month(month, {
          width: "narrow",
          context: "standalone"
        });
      case "LLLL":
      default:
        return localize2.month(month, { width: "wide", context: "standalone" });
    }
  },
  // Local week of year
  w: function(date2, token, localize2, options2) {
    const week = getWeek(date2, options2);
    if (token === "wo") {
      return localize2.ordinalNumber(week, { unit: "week" });
    }
    return addLeadingZeros(week, token.length);
  },
  // ISO week of year
  I: function(date2, token, localize2) {
    const isoWeek = getISOWeek(date2);
    if (token === "Io") {
      return localize2.ordinalNumber(isoWeek, { unit: "week" });
    }
    return addLeadingZeros(isoWeek, token.length);
  },
  // Day of the month
  d: function(date2, token, localize2) {
    if (token === "do") {
      return localize2.ordinalNumber(date2.getDate(), { unit: "date" });
    }
    return lightFormatters.d(date2, token);
  },
  // Day of year
  D: function(date2, token, localize2) {
    const dayOfYear = getDayOfYear(date2);
    if (token === "Do") {
      return localize2.ordinalNumber(dayOfYear, { unit: "dayOfYear" });
    }
    return addLeadingZeros(dayOfYear, token.length);
  },
  // Day of week
  E: function(date2, token, localize2) {
    const dayOfWeek = date2.getDay();
    switch (token) {
      case "E":
      case "EE":
      case "EEE":
        return localize2.day(dayOfWeek, {
          width: "abbreviated",
          context: "formatting"
        });
      case "EEEEE":
        return localize2.day(dayOfWeek, {
          width: "narrow",
          context: "formatting"
        });
      case "EEEEEE":
        return localize2.day(dayOfWeek, {
          width: "short",
          context: "formatting"
        });
      case "EEEE":
      default:
        return localize2.day(dayOfWeek, {
          width: "wide",
          context: "formatting"
        });
    }
  },
  // Local day of week
  e: function(date2, token, localize2, options2) {
    const dayOfWeek = date2.getDay();
    const localDayOfWeek = (dayOfWeek - options2.weekStartsOn + 8) % 7 || 7;
    switch (token) {
      case "e":
        return String(localDayOfWeek);
      case "ee":
        return addLeadingZeros(localDayOfWeek, 2);
      case "eo":
        return localize2.ordinalNumber(localDayOfWeek, { unit: "day" });
      case "eee":
        return localize2.day(dayOfWeek, {
          width: "abbreviated",
          context: "formatting"
        });
      case "eeeee":
        return localize2.day(dayOfWeek, {
          width: "narrow",
          context: "formatting"
        });
      case "eeeeee":
        return localize2.day(dayOfWeek, {
          width: "short",
          context: "formatting"
        });
      case "eeee":
      default:
        return localize2.day(dayOfWeek, {
          width: "wide",
          context: "formatting"
        });
    }
  },
  // Stand-alone local day of week
  c: function(date2, token, localize2, options2) {
    const dayOfWeek = date2.getDay();
    const localDayOfWeek = (dayOfWeek - options2.weekStartsOn + 8) % 7 || 7;
    switch (token) {
      case "c":
        return String(localDayOfWeek);
      case "cc":
        return addLeadingZeros(localDayOfWeek, token.length);
      case "co":
        return localize2.ordinalNumber(localDayOfWeek, { unit: "day" });
      case "ccc":
        return localize2.day(dayOfWeek, {
          width: "abbreviated",
          context: "standalone"
        });
      case "ccccc":
        return localize2.day(dayOfWeek, {
          width: "narrow",
          context: "standalone"
        });
      case "cccccc":
        return localize2.day(dayOfWeek, {
          width: "short",
          context: "standalone"
        });
      case "cccc":
      default:
        return localize2.day(dayOfWeek, {
          width: "wide",
          context: "standalone"
        });
    }
  },
  // ISO day of week
  i: function(date2, token, localize2) {
    const dayOfWeek = date2.getDay();
    const isoDayOfWeek = dayOfWeek === 0 ? 7 : dayOfWeek;
    switch (token) {
      case "i":
        return String(isoDayOfWeek);
      case "ii":
        return addLeadingZeros(isoDayOfWeek, token.length);
      case "io":
        return localize2.ordinalNumber(isoDayOfWeek, { unit: "day" });
      case "iii":
        return localize2.day(dayOfWeek, {
          width: "abbreviated",
          context: "formatting"
        });
      case "iiiii":
        return localize2.day(dayOfWeek, {
          width: "narrow",
          context: "formatting"
        });
      case "iiiiii":
        return localize2.day(dayOfWeek, {
          width: "short",
          context: "formatting"
        });
      case "iiii":
      default:
        return localize2.day(dayOfWeek, {
          width: "wide",
          context: "formatting"
        });
    }
  },
  // AM or PM
  a: function(date2, token, localize2) {
    const hours = date2.getHours();
    const dayPeriodEnumValue = hours / 12 >= 1 ? "pm" : "am";
    switch (token) {
      case "a":
      case "aa":
        return localize2.dayPeriod(dayPeriodEnumValue, {
          width: "abbreviated",
          context: "formatting"
        });
      case "aaa":
        return localize2.dayPeriod(dayPeriodEnumValue, {
          width: "abbreviated",
          context: "formatting"
        }).toLowerCase();
      case "aaaaa":
        return localize2.dayPeriod(dayPeriodEnumValue, {
          width: "narrow",
          context: "formatting"
        });
      case "aaaa":
      default:
        return localize2.dayPeriod(dayPeriodEnumValue, {
          width: "wide",
          context: "formatting"
        });
    }
  },
  // AM, PM, midnight, noon
  b: function(date2, token, localize2) {
    const hours = date2.getHours();
    let dayPeriodEnumValue;
    if (hours === 12) {
      dayPeriodEnumValue = dayPeriodEnum.noon;
    } else if (hours === 0) {
      dayPeriodEnumValue = dayPeriodEnum.midnight;
    } else {
      dayPeriodEnumValue = hours / 12 >= 1 ? "pm" : "am";
    }
    switch (token) {
      case "b":
      case "bb":
        return localize2.dayPeriod(dayPeriodEnumValue, {
          width: "abbreviated",
          context: "formatting"
        });
      case "bbb":
        return localize2.dayPeriod(dayPeriodEnumValue, {
          width: "abbreviated",
          context: "formatting"
        }).toLowerCase();
      case "bbbbb":
        return localize2.dayPeriod(dayPeriodEnumValue, {
          width: "narrow",
          context: "formatting"
        });
      case "bbbb":
      default:
        return localize2.dayPeriod(dayPeriodEnumValue, {
          width: "wide",
          context: "formatting"
        });
    }
  },
  // in the morning, in the afternoon, in the evening, at night
  B: function(date2, token, localize2) {
    const hours = date2.getHours();
    let dayPeriodEnumValue;
    if (hours >= 17) {
      dayPeriodEnumValue = dayPeriodEnum.evening;
    } else if (hours >= 12) {
      dayPeriodEnumValue = dayPeriodEnum.afternoon;
    } else if (hours >= 4) {
      dayPeriodEnumValue = dayPeriodEnum.morning;
    } else {
      dayPeriodEnumValue = dayPeriodEnum.night;
    }
    switch (token) {
      case "B":
      case "BB":
      case "BBB":
        return localize2.dayPeriod(dayPeriodEnumValue, {
          width: "abbreviated",
          context: "formatting"
        });
      case "BBBBB":
        return localize2.dayPeriod(dayPeriodEnumValue, {
          width: "narrow",
          context: "formatting"
        });
      case "BBBB":
      default:
        return localize2.dayPeriod(dayPeriodEnumValue, {
          width: "wide",
          context: "formatting"
        });
    }
  },
  // Hour [1-12]
  h: function(date2, token, localize2) {
    if (token === "ho") {
      let hours = date2.getHours() % 12;
      if (hours === 0) hours = 12;
      return localize2.ordinalNumber(hours, { unit: "hour" });
    }
    return lightFormatters.h(date2, token);
  },
  // Hour [0-23]
  H: function(date2, token, localize2) {
    if (token === "Ho") {
      return localize2.ordinalNumber(date2.getHours(), { unit: "hour" });
    }
    return lightFormatters.H(date2, token);
  },
  // Hour [0-11]
  K: function(date2, token, localize2) {
    const hours = date2.getHours() % 12;
    if (token === "Ko") {
      return localize2.ordinalNumber(hours, { unit: "hour" });
    }
    return addLeadingZeros(hours, token.length);
  },
  // Hour [1-24]
  k: function(date2, token, localize2) {
    let hours = date2.getHours();
    if (hours === 0) hours = 24;
    if (token === "ko") {
      return localize2.ordinalNumber(hours, { unit: "hour" });
    }
    return addLeadingZeros(hours, token.length);
  },
  // Minute
  m: function(date2, token, localize2) {
    if (token === "mo") {
      return localize2.ordinalNumber(date2.getMinutes(), { unit: "minute" });
    }
    return lightFormatters.m(date2, token);
  },
  // Second
  s: function(date2, token, localize2) {
    if (token === "so") {
      return localize2.ordinalNumber(date2.getSeconds(), { unit: "second" });
    }
    return lightFormatters.s(date2, token);
  },
  // Fraction of second
  S: function(date2, token) {
    return lightFormatters.S(date2, token);
  },
  // Timezone (ISO-8601. If offset is 0, output is always `'Z'`)
  X: function(date2, token, _localize) {
    const timezoneOffset = date2.getTimezoneOffset();
    if (timezoneOffset === 0) {
      return "Z";
    }
    switch (token) {
      case "X":
        return formatTimezoneWithOptionalMinutes(timezoneOffset);
      case "XXXX":
      case "XX":
        return formatTimezone(timezoneOffset);
      case "XXXXX":
      case "XXX":
      default:
        return formatTimezone(timezoneOffset, ":");
    }
  },
  // Timezone (ISO-8601. If offset is 0, output is `'+00:00'` or equivalent)
  x: function(date2, token, _localize) {
    const timezoneOffset = date2.getTimezoneOffset();
    switch (token) {
      case "x":
        return formatTimezoneWithOptionalMinutes(timezoneOffset);
      case "xxxx":
      case "xx":
        return formatTimezone(timezoneOffset);
      case "xxxxx":
      case "xxx":
      default:
        return formatTimezone(timezoneOffset, ":");
    }
  },
  // Timezone (GMT)
  O: function(date2, token, _localize) {
    const timezoneOffset = date2.getTimezoneOffset();
    switch (token) {
      case "O":
      case "OO":
      case "OOO":
        return "GMT" + formatTimezoneShort(timezoneOffset, ":");
      case "OOOO":
      default:
        return "GMT" + formatTimezone(timezoneOffset, ":");
    }
  },
  // Timezone (specific non-location)
  z: function(date2, token, _localize) {
    const timezoneOffset = date2.getTimezoneOffset();
    switch (token) {
      case "z":
      case "zz":
      case "zzz":
        return "GMT" + formatTimezoneShort(timezoneOffset, ":");
      case "zzzz":
      default:
        return "GMT" + formatTimezone(timezoneOffset, ":");
    }
  },
  // Seconds timestamp
  t: function(date2, token, _localize) {
    const timestamp = Math.trunc(+date2 / 1e3);
    return addLeadingZeros(timestamp, token.length);
  },
  // Milliseconds timestamp
  T: function(date2, token, _localize) {
    return addLeadingZeros(+date2, token.length);
  }
};
function formatTimezoneShort(offset, delimiter = "") {
  const sign2 = offset > 0 ? "-" : "+";
  const absOffset = Math.abs(offset);
  const hours = Math.trunc(absOffset / 60);
  const minutes = absOffset % 60;
  if (minutes === 0) {
    return sign2 + String(hours);
  }
  return sign2 + String(hours) + delimiter + addLeadingZeros(minutes, 2);
}
function formatTimezoneWithOptionalMinutes(offset, delimiter) {
  if (offset % 60 === 0) {
    const sign2 = offset > 0 ? "-" : "+";
    return sign2 + addLeadingZeros(Math.abs(offset) / 60, 2);
  }
  return formatTimezone(offset, delimiter);
}
function formatTimezone(offset, delimiter = "") {
  const sign2 = offset > 0 ? "-" : "+";
  const absOffset = Math.abs(offset);
  const hours = addLeadingZeros(Math.trunc(absOffset / 60), 2);
  const minutes = addLeadingZeros(absOffset % 60, 2);
  return sign2 + hours + delimiter + minutes;
}
const dateLongFormatter = (pattern, formatLong2) => {
  switch (pattern) {
    case "P":
      return formatLong2.date({ width: "short" });
    case "PP":
      return formatLong2.date({ width: "medium" });
    case "PPP":
      return formatLong2.date({ width: "long" });
    case "PPPP":
    default:
      return formatLong2.date({ width: "full" });
  }
};
const timeLongFormatter = (pattern, formatLong2) => {
  switch (pattern) {
    case "p":
      return formatLong2.time({ width: "short" });
    case "pp":
      return formatLong2.time({ width: "medium" });
    case "ppp":
      return formatLong2.time({ width: "long" });
    case "pppp":
    default:
      return formatLong2.time({ width: "full" });
  }
};
const dateTimeLongFormatter = (pattern, formatLong2) => {
  const matchResult = pattern.match(/(P+)(p+)?/) || [];
  const datePattern = matchResult[1];
  const timePattern = matchResult[2];
  if (!timePattern) {
    return dateLongFormatter(pattern, formatLong2);
  }
  let dateTimeFormat;
  switch (datePattern) {
    case "P":
      dateTimeFormat = formatLong2.dateTime({ width: "short" });
      break;
    case "PP":
      dateTimeFormat = formatLong2.dateTime({ width: "medium" });
      break;
    case "PPP":
      dateTimeFormat = formatLong2.dateTime({ width: "long" });
      break;
    case "PPPP":
    default:
      dateTimeFormat = formatLong2.dateTime({ width: "full" });
      break;
  }
  return dateTimeFormat.replace("{{date}}", dateLongFormatter(datePattern, formatLong2)).replace("{{time}}", timeLongFormatter(timePattern, formatLong2));
};
const longFormatters = {
  p: timeLongFormatter,
  P: dateTimeLongFormatter
};
const dayOfYearTokenRE = /^D+$/;
const weekYearTokenRE = /^Y+$/;
const throwTokens = ["D", "DD", "YY", "YYYY"];
function isProtectedDayOfYearToken(token) {
  return dayOfYearTokenRE.test(token);
}
function isProtectedWeekYearToken(token) {
  return weekYearTokenRE.test(token);
}
function warnOrThrowProtectedError(token, format2, input) {
  const _message = message(token, format2, input);
  console.warn(_message);
  if (throwTokens.includes(token)) throw new RangeError(_message);
}
function message(token, format2, input) {
  const subject = token[0] === "Y" ? "years" : "days of the month";
  return `Use \`${token.toLowerCase()}\` instead of \`${token}\` (in \`${format2}\`) for formatting ${subject} to the input \`${input}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`;
}
const formattingTokensRegExp$1 = /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g;
const longFormattingTokensRegExp$1 = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g;
const escapedStringRegExp$1 = /^'([^]*?)'?$/;
const doubleQuoteRegExp$1 = /''/g;
const unescapedLatinCharacterRegExp$1 = /[a-zA-Z]/;
function format(date2, formatStr, options2) {
  var _a, _b, _c, _d;
  const defaultOptions2 = getDefaultOptions$1();
  const locale2 = defaultOptions2.locale ?? enUS;
  const firstWeekContainsDate = defaultOptions2.firstWeekContainsDate ?? ((_b = (_a = defaultOptions2.locale) == null ? void 0 : _a.options) == null ? void 0 : _b.firstWeekContainsDate) ?? 1;
  const weekStartsOn = defaultOptions2.weekStartsOn ?? ((_d = (_c = defaultOptions2.locale) == null ? void 0 : _c.options) == null ? void 0 : _d.weekStartsOn) ?? 0;
  const originalDate = toDate(date2, options2 == null ? void 0 : options2.in);
  if (!isValid(originalDate)) {
    throw new RangeError("Invalid time value");
  }
  let parts = formatStr.match(longFormattingTokensRegExp$1).map((substring) => {
    const firstCharacter = substring[0];
    if (firstCharacter === "p" || firstCharacter === "P") {
      const longFormatter = longFormatters[firstCharacter];
      return longFormatter(substring, locale2.formatLong);
    }
    return substring;
  }).join("").match(formattingTokensRegExp$1).map((substring) => {
    if (substring === "''") {
      return { isToken: false, value: "'" };
    }
    const firstCharacter = substring[0];
    if (firstCharacter === "'") {
      return { isToken: false, value: cleanEscapedString$1(substring) };
    }
    if (formatters[firstCharacter]) {
      return { isToken: true, value: substring };
    }
    if (firstCharacter.match(unescapedLatinCharacterRegExp$1)) {
      throw new RangeError(
        "Format string contains an unescaped latin alphabet character `" + firstCharacter + "`"
      );
    }
    return { isToken: false, value: substring };
  });
  if (locale2.localize.preprocessor) {
    parts = locale2.localize.preprocessor(originalDate, parts);
  }
  const formatterOptions = {
    firstWeekContainsDate,
    weekStartsOn,
    locale: locale2
  };
  return parts.map((part) => {
    if (!part.isToken) return part.value;
    const token = part.value;
    if (isProtectedWeekYearToken(token) || isProtectedDayOfYearToken(token)) {
      warnOrThrowProtectedError(token, formatStr, String(date2));
    }
    const formatter = formatters[token[0]];
    return formatter(originalDate, token, locale2.localize, formatterOptions);
  }).join("");
}
function cleanEscapedString$1(input) {
  const matched = input.match(escapedStringRegExp$1);
  if (!matched) {
    return input;
  }
  return matched[1].replace(doubleQuoteRegExp$1, "'");
}
function getDefaultOptions() {
  return Object.assign({}, getDefaultOptions$1());
}
function getISODay(date2, options2) {
  const day = toDate(date2, options2 == null ? void 0 : options2.in).getDay();
  return day === 0 ? 7 : day;
}
function transpose(date2, constructor) {
  const date_ = isConstructor(constructor) ? new constructor(0) : constructFrom(constructor, 0);
  date_.setFullYear(date2.getFullYear(), date2.getMonth(), date2.getDate());
  date_.setHours(
    date2.getHours(),
    date2.getMinutes(),
    date2.getSeconds(),
    date2.getMilliseconds()
  );
  return date_;
}
function isConstructor(constructor) {
  var _a;
  return typeof constructor === "function" && ((_a = constructor.prototype) == null ? void 0 : _a.constructor) === constructor;
}
const TIMEZONE_UNIT_PRIORITY = 10;
class Setter {
  constructor() {
    __publicField(this, "subPriority", 0);
  }
  validate(_utcDate, _options) {
    return true;
  }
}
class ValueSetter extends Setter {
  constructor(value, validateValue, setValue, priority, subPriority) {
    super();
    this.value = value;
    this.validateValue = validateValue;
    this.setValue = setValue;
    this.priority = priority;
    if (subPriority) {
      this.subPriority = subPriority;
    }
  }
  validate(date2, options2) {
    return this.validateValue(date2, this.value, options2);
  }
  set(date2, flags, options2) {
    return this.setValue(date2, flags, this.value, options2);
  }
}
class DateTimezoneSetter extends Setter {
  constructor(context, reference) {
    super();
    __publicField(this, "priority", TIMEZONE_UNIT_PRIORITY);
    __publicField(this, "subPriority", -1);
    this.context = context || ((date2) => constructFrom(reference, date2));
  }
  set(date2, flags) {
    if (flags.timestampIsSet) return date2;
    return constructFrom(date2, transpose(date2, this.context));
  }
}
class Parser {
  run(dateString, token, match2, options2) {
    const result = this.parse(dateString, token, match2, options2);
    if (!result) {
      return null;
    }
    return {
      setter: new ValueSetter(
        result.value,
        this.validate,
        this.set,
        this.priority,
        this.subPriority
      ),
      rest: result.rest
    };
  }
  validate(_utcDate, _value, _options) {
    return true;
  }
}
class EraParser extends Parser {
  constructor() {
    super(...arguments);
    __publicField(this, "priority", 140);
    __publicField(this, "incompatibleTokens", ["R", "u", "t", "T"]);
  }
  parse(dateString, token, match2) {
    switch (token) {
      case "G":
      case "GG":
      case "GGG":
        return match2.era(dateString, { width: "abbreviated" }) || match2.era(dateString, { width: "narrow" });
      case "GGGGG":
        return match2.era(dateString, { width: "narrow" });
      case "GGGG":
      default:
        return match2.era(dateString, { width: "wide" }) || match2.era(dateString, { width: "abbreviated" }) || match2.era(dateString, { width: "narrow" });
    }
  }
  set(date2, flags, value) {
    flags.era = value;
    date2.setFullYear(value, 0, 1);
    date2.setHours(0, 0, 0, 0);
    return date2;
  }
}
const numericPatterns = {
  month: /^(1[0-2]|0?\d)/,
  // 0 to 12
  date: /^(3[0-1]|[0-2]?\d)/,
  // 0 to 31
  dayOfYear: /^(36[0-6]|3[0-5]\d|[0-2]?\d?\d)/,
  // 0 to 366
  week: /^(5[0-3]|[0-4]?\d)/,
  // 0 to 53
  hour23h: /^(2[0-3]|[0-1]?\d)/,
  // 0 to 23
  hour24h: /^(2[0-4]|[0-1]?\d)/,
  // 0 to 24
  hour11h: /^(1[0-1]|0?\d)/,
  // 0 to 11
  hour12h: /^(1[0-2]|0?\d)/,
  // 0 to 12
  minute: /^[0-5]?\d/,
  // 0 to 59
  second: /^[0-5]?\d/,
  // 0 to 59
  singleDigit: /^\d/,
  // 0 to 9
  twoDigits: /^\d{1,2}/,
  // 0 to 99
  threeDigits: /^\d{1,3}/,
  // 0 to 999
  fourDigits: /^\d{1,4}/,
  // 0 to 9999
  anyDigitsSigned: /^-?\d+/,
  singleDigitSigned: /^-?\d/,
  // 0 to 9, -0 to -9
  twoDigitsSigned: /^-?\d{1,2}/,
  // 0 to 99, -0 to -99
  threeDigitsSigned: /^-?\d{1,3}/,
  // 0 to 999, -0 to -999
  fourDigitsSigned: /^-?\d{1,4}/
  // 0 to 9999, -0 to -9999
};
const timezonePatterns = {
  basicOptionalMinutes: /^([+-])(\d{2})(\d{2})?|Z/,
  basic: /^([+-])(\d{2})(\d{2})|Z/,
  basicOptionalSeconds: /^([+-])(\d{2})(\d{2})((\d{2}))?|Z/,
  extended: /^([+-])(\d{2}):(\d{2})|Z/,
  extendedOptionalSeconds: /^([+-])(\d{2}):(\d{2})(:(\d{2}))?|Z/
};
function mapValue(parseFnResult, mapFn) {
  if (!parseFnResult) {
    return parseFnResult;
  }
  return {
    value: mapFn(parseFnResult.value),
    rest: parseFnResult.rest
  };
}
function parseNumericPattern(pattern, dateString) {
  const matchResult = dateString.match(pattern);
  if (!matchResult) {
    return null;
  }
  return {
    value: parseInt(matchResult[0], 10),
    rest: dateString.slice(matchResult[0].length)
  };
}
function parseTimezonePattern(pattern, dateString) {
  const matchResult = dateString.match(pattern);
  if (!matchResult) {
    return null;
  }
  if (matchResult[0] === "Z") {
    return {
      value: 0,
      rest: dateString.slice(1)
    };
  }
  const sign2 = matchResult[1] === "+" ? 1 : -1;
  const hours = matchResult[2] ? parseInt(matchResult[2], 10) : 0;
  const minutes = matchResult[3] ? parseInt(matchResult[3], 10) : 0;
  const seconds = matchResult[5] ? parseInt(matchResult[5], 10) : 0;
  return {
    value: sign2 * (hours * millisecondsInHour + minutes * millisecondsInMinute + seconds * millisecondsInSecond),
    rest: dateString.slice(matchResult[0].length)
  };
}
function parseAnyDigitsSigned(dateString) {
  return parseNumericPattern(numericPatterns.anyDigitsSigned, dateString);
}
function parseNDigits(n, dateString) {
  switch (n) {
    case 1:
      return parseNumericPattern(numericPatterns.singleDigit, dateString);
    case 2:
      return parseNumericPattern(numericPatterns.twoDigits, dateString);
    case 3:
      return parseNumericPattern(numericPatterns.threeDigits, dateString);
    case 4:
      return parseNumericPattern(numericPatterns.fourDigits, dateString);
    default:
      return parseNumericPattern(new RegExp("^\\d{1," + n + "}"), dateString);
  }
}
function parseNDigitsSigned(n, dateString) {
  switch (n) {
    case 1:
      return parseNumericPattern(numericPatterns.singleDigitSigned, dateString);
    case 2:
      return parseNumericPattern(numericPatterns.twoDigitsSigned, dateString);
    case 3:
      return parseNumericPattern(numericPatterns.threeDigitsSigned, dateString);
    case 4:
      return parseNumericPattern(numericPatterns.fourDigitsSigned, dateString);
    default:
      return parseNumericPattern(new RegExp("^-?\\d{1," + n + "}"), dateString);
  }
}
function dayPeriodEnumToHours(dayPeriod) {
  switch (dayPeriod) {
    case "morning":
      return 4;
    case "evening":
      return 17;
    case "pm":
    case "noon":
    case "afternoon":
      return 12;
    case "am":
    case "midnight":
    case "night":
    default:
      return 0;
  }
}
function normalizeTwoDigitYear(twoDigitYear, currentYear) {
  const isCommonEra = currentYear > 0;
  const absCurrentYear = isCommonEra ? currentYear : 1 - currentYear;
  let result;
  if (absCurrentYear <= 50) {
    result = twoDigitYear || 100;
  } else {
    const rangeEnd = absCurrentYear + 50;
    const rangeEndCentury = Math.trunc(rangeEnd / 100) * 100;
    const isPreviousCentury = twoDigitYear >= rangeEnd % 100;
    result = twoDigitYear + rangeEndCentury - (isPreviousCentury ? 100 : 0);
  }
  return isCommonEra ? result : 1 - result;
}
function isLeapYearIndex$1(year) {
  return year % 400 === 0 || year % 4 === 0 && year % 100 !== 0;
}
class YearParser extends Parser {
  constructor() {
    super(...arguments);
    __publicField(this, "priority", 130);
    __publicField(this, "incompatibleTokens", ["Y", "R", "u", "w", "I", "i", "e", "c", "t", "T"]);
  }
  parse(dateString, token, match2) {
    const valueCallback = (year) => ({
      year,
      isTwoDigitYear: token === "yy"
    });
    switch (token) {
      case "y":
        return mapValue(parseNDigits(4, dateString), valueCallback);
      case "yo":
        return mapValue(
          match2.ordinalNumber(dateString, {
            unit: "year"
          }),
          valueCallback
        );
      default:
        return mapValue(parseNDigits(token.length, dateString), valueCallback);
    }
  }
  validate(_date, value) {
    return value.isTwoDigitYear || value.year > 0;
  }
  set(date2, flags, value) {
    const currentYear = date2.getFullYear();
    if (value.isTwoDigitYear) {
      const normalizedTwoDigitYear = normalizeTwoDigitYear(
        value.year,
        currentYear
      );
      date2.setFullYear(normalizedTwoDigitYear, 0, 1);
      date2.setHours(0, 0, 0, 0);
      return date2;
    }
    const year = !("era" in flags) || flags.era === 1 ? value.year : 1 - value.year;
    date2.setFullYear(year, 0, 1);
    date2.setHours(0, 0, 0, 0);
    return date2;
  }
}
class LocalWeekYearParser extends Parser {
  constructor() {
    super(...arguments);
    __publicField(this, "priority", 130);
    __publicField(this, "incompatibleTokens", [
      "y",
      "R",
      "u",
      "Q",
      "q",
      "M",
      "L",
      "I",
      "d",
      "D",
      "i",
      "t",
      "T"
    ]);
  }
  parse(dateString, token, match2) {
    const valueCallback = (year) => ({
      year,
      isTwoDigitYear: token === "YY"
    });
    switch (token) {
      case "Y":
        return mapValue(parseNDigits(4, dateString), valueCallback);
      case "Yo":
        return mapValue(
          match2.ordinalNumber(dateString, {
            unit: "year"
          }),
          valueCallback
        );
      default:
        return mapValue(parseNDigits(token.length, dateString), valueCallback);
    }
  }
  validate(_date, value) {
    return value.isTwoDigitYear || value.year > 0;
  }
  set(date2, flags, value, options2) {
    const currentYear = getWeekYear(date2, options2);
    if (value.isTwoDigitYear) {
      const normalizedTwoDigitYear = normalizeTwoDigitYear(
        value.year,
        currentYear
      );
      date2.setFullYear(
        normalizedTwoDigitYear,
        0,
        options2.firstWeekContainsDate
      );
      date2.setHours(0, 0, 0, 0);
      return startOfWeek(date2, options2);
    }
    const year = !("era" in flags) || flags.era === 1 ? value.year : 1 - value.year;
    date2.setFullYear(year, 0, options2.firstWeekContainsDate);
    date2.setHours(0, 0, 0, 0);
    return startOfWeek(date2, options2);
  }
}
class ISOWeekYearParser extends Parser {
  constructor() {
    super(...arguments);
    __publicField(this, "priority", 130);
    __publicField(this, "incompatibleTokens", [
      "G",
      "y",
      "Y",
      "u",
      "Q",
      "q",
      "M",
      "L",
      "w",
      "d",
      "D",
      "e",
      "c",
      "t",
      "T"
    ]);
  }
  parse(dateString, token) {
    if (token === "R") {
      return parseNDigitsSigned(4, dateString);
    }
    return parseNDigitsSigned(token.length, dateString);
  }
  set(date2, _flags, value) {
    const firstWeekOfYear = constructFrom(date2, 0);
    firstWeekOfYear.setFullYear(value, 0, 4);
    firstWeekOfYear.setHours(0, 0, 0, 0);
    return startOfISOWeek(firstWeekOfYear);
  }
}
class ExtendedYearParser extends Parser {
  constructor() {
    super(...arguments);
    __publicField(this, "priority", 130);
    __publicField(this, "incompatibleTokens", ["G", "y", "Y", "R", "w", "I", "i", "e", "c", "t", "T"]);
  }
  parse(dateString, token) {
    if (token === "u") {
      return parseNDigitsSigned(4, dateString);
    }
    return parseNDigitsSigned(token.length, dateString);
  }
  set(date2, _flags, value) {
    date2.setFullYear(value, 0, 1);
    date2.setHours(0, 0, 0, 0);
    return date2;
  }
}
class QuarterParser extends Parser {
  constructor() {
    super(...arguments);
    __publicField(this, "priority", 120);
    __publicField(this, "incompatibleTokens", [
      "Y",
      "R",
      "q",
      "M",
      "L",
      "w",
      "I",
      "d",
      "D",
      "i",
      "e",
      "c",
      "t",
      "T"
    ]);
  }
  parse(dateString, token, match2) {
    switch (token) {
      case "Q":
      case "QQ":
        return parseNDigits(token.length, dateString);
      case "Qo":
        return match2.ordinalNumber(dateString, { unit: "quarter" });
      case "QQQ":
        return match2.quarter(dateString, {
          width: "abbreviated",
          context: "formatting"
        }) || match2.quarter(dateString, {
          width: "narrow",
          context: "formatting"
        });
      case "QQQQQ":
        return match2.quarter(dateString, {
          width: "narrow",
          context: "formatting"
        });
      case "QQQQ":
      default:
        return match2.quarter(dateString, {
          width: "wide",
          context: "formatting"
        }) || match2.quarter(dateString, {
          width: "abbreviated",
          context: "formatting"
        }) || match2.quarter(dateString, {
          width: "narrow",
          context: "formatting"
        });
    }
  }
  validate(_date, value) {
    return value >= 1 && value <= 4;
  }
  set(date2, _flags, value) {
    date2.setMonth((value - 1) * 3, 1);
    date2.setHours(0, 0, 0, 0);
    return date2;
  }
}
class StandAloneQuarterParser extends Parser {
  constructor() {
    super(...arguments);
    __publicField(this, "priority", 120);
    __publicField(this, "incompatibleTokens", [
      "Y",
      "R",
      "Q",
      "M",
      "L",
      "w",
      "I",
      "d",
      "D",
      "i",
      "e",
      "c",
      "t",
      "T"
    ]);
  }
  parse(dateString, token, match2) {
    switch (token) {
      case "q":
      case "qq":
        return parseNDigits(token.length, dateString);
      case "qo":
        return match2.ordinalNumber(dateString, { unit: "quarter" });
      case "qqq":
        return match2.quarter(dateString, {
          width: "abbreviated",
          context: "standalone"
        }) || match2.quarter(dateString, {
          width: "narrow",
          context: "standalone"
        });
      case "qqqqq":
        return match2.quarter(dateString, {
          width: "narrow",
          context: "standalone"
        });
      case "qqqq":
      default:
        return match2.quarter(dateString, {
          width: "wide",
          context: "standalone"
        }) || match2.quarter(dateString, {
          width: "abbreviated",
          context: "standalone"
        }) || match2.quarter(dateString, {
          width: "narrow",
          context: "standalone"
        });
    }
  }
  validate(_date, value) {
    return value >= 1 && value <= 4;
  }
  set(date2, _flags, value) {
    date2.setMonth((value - 1) * 3, 1);
    date2.setHours(0, 0, 0, 0);
    return date2;
  }
}
class MonthParser extends Parser {
  constructor() {
    super(...arguments);
    __publicField(this, "incompatibleTokens", [
      "Y",
      "R",
      "q",
      "Q",
      "L",
      "w",
      "I",
      "D",
      "i",
      "e",
      "c",
      "t",
      "T"
    ]);
    __publicField(this, "priority", 110);
  }
  parse(dateString, token, match2) {
    const valueCallback = (value) => value - 1;
    switch (token) {
      case "M":
        return mapValue(
          parseNumericPattern(numericPatterns.month, dateString),
          valueCallback
        );
      case "MM":
        return mapValue(parseNDigits(2, dateString), valueCallback);
      case "Mo":
        return mapValue(
          match2.ordinalNumber(dateString, {
            unit: "month"
          }),
          valueCallback
        );
      case "MMM":
        return match2.month(dateString, {
          width: "abbreviated",
          context: "formatting"
        }) || match2.month(dateString, { width: "narrow", context: "formatting" });
      case "MMMMM":
        return match2.month(dateString, {
          width: "narrow",
          context: "formatting"
        });
      case "MMMM":
      default:
        return match2.month(dateString, { width: "wide", context: "formatting" }) || match2.month(dateString, {
          width: "abbreviated",
          context: "formatting"
        }) || match2.month(dateString, { width: "narrow", context: "formatting" });
    }
  }
  validate(_date, value) {
    return value >= 0 && value <= 11;
  }
  set(date2, _flags, value) {
    date2.setMonth(value, 1);
    date2.setHours(0, 0, 0, 0);
    return date2;
  }
}
class StandAloneMonthParser extends Parser {
  constructor() {
    super(...arguments);
    __publicField(this, "priority", 110);
    __publicField(this, "incompatibleTokens", [
      "Y",
      "R",
      "q",
      "Q",
      "M",
      "w",
      "I",
      "D",
      "i",
      "e",
      "c",
      "t",
      "T"
    ]);
  }
  parse(dateString, token, match2) {
    const valueCallback = (value) => value - 1;
    switch (token) {
      case "L":
        return mapValue(
          parseNumericPattern(numericPatterns.month, dateString),
          valueCallback
        );
      case "LL":
        return mapValue(parseNDigits(2, dateString), valueCallback);
      case "Lo":
        return mapValue(
          match2.ordinalNumber(dateString, {
            unit: "month"
          }),
          valueCallback
        );
      case "LLL":
        return match2.month(dateString, {
          width: "abbreviated",
          context: "standalone"
        }) || match2.month(dateString, { width: "narrow", context: "standalone" });
      case "LLLLL":
        return match2.month(dateString, {
          width: "narrow",
          context: "standalone"
        });
      case "LLLL":
      default:
        return match2.month(dateString, { width: "wide", context: "standalone" }) || match2.month(dateString, {
          width: "abbreviated",
          context: "standalone"
        }) || match2.month(dateString, { width: "narrow", context: "standalone" });
    }
  }
  validate(_date, value) {
    return value >= 0 && value <= 11;
  }
  set(date2, _flags, value) {
    date2.setMonth(value, 1);
    date2.setHours(0, 0, 0, 0);
    return date2;
  }
}
function setWeek(date2, week, options2) {
  const date_ = toDate(date2, options2 == null ? void 0 : options2.in);
  const diff = getWeek(date_, options2) - week;
  date_.setDate(date_.getDate() - diff * 7);
  return toDate(date_, options2 == null ? void 0 : options2.in);
}
class LocalWeekParser extends Parser {
  constructor() {
    super(...arguments);
    __publicField(this, "priority", 100);
    __publicField(this, "incompatibleTokens", [
      "y",
      "R",
      "u",
      "q",
      "Q",
      "M",
      "L",
      "I",
      "d",
      "D",
      "i",
      "t",
      "T"
    ]);
  }
  parse(dateString, token, match2) {
    switch (token) {
      case "w":
        return parseNumericPattern(numericPatterns.week, dateString);
      case "wo":
        return match2.ordinalNumber(dateString, { unit: "week" });
      default:
        return parseNDigits(token.length, dateString);
    }
  }
  validate(_date, value) {
    return value >= 1 && value <= 53;
  }
  set(date2, _flags, value, options2) {
    return startOfWeek(setWeek(date2, value, options2), options2);
  }
}
function setISOWeek(date2, week, options2) {
  const _date = toDate(date2, options2 == null ? void 0 : options2.in);
  const diff = getISOWeek(_date, options2) - week;
  _date.setDate(_date.getDate() - diff * 7);
  return _date;
}
class ISOWeekParser extends Parser {
  constructor() {
    super(...arguments);
    __publicField(this, "priority", 100);
    __publicField(this, "incompatibleTokens", [
      "y",
      "Y",
      "u",
      "q",
      "Q",
      "M",
      "L",
      "w",
      "d",
      "D",
      "e",
      "c",
      "t",
      "T"
    ]);
  }
  parse(dateString, token, match2) {
    switch (token) {
      case "I":
        return parseNumericPattern(numericPatterns.week, dateString);
      case "Io":
        return match2.ordinalNumber(dateString, { unit: "week" });
      default:
        return parseNDigits(token.length, dateString);
    }
  }
  validate(_date, value) {
    return value >= 1 && value <= 53;
  }
  set(date2, _flags, value) {
    return startOfISOWeek(setISOWeek(date2, value));
  }
}
const DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
const DAYS_IN_MONTH_LEAP_YEAR = [
  31,
  29,
  31,
  30,
  31,
  30,
  31,
  31,
  30,
  31,
  30,
  31
];
class DateParser extends Parser {
  constructor() {
    super(...arguments);
    __publicField(this, "priority", 90);
    __publicField(this, "subPriority", 1);
    __publicField(this, "incompatibleTokens", [
      "Y",
      "R",
      "q",
      "Q",
      "w",
      "I",
      "D",
      "i",
      "e",
      "c",
      "t",
      "T"
    ]);
  }
  parse(dateString, token, match2) {
    switch (token) {
      case "d":
        return parseNumericPattern(numericPatterns.date, dateString);
      case "do":
        return match2.ordinalNumber(dateString, { unit: "date" });
      default:
        return parseNDigits(token.length, dateString);
    }
  }
  validate(date2, value) {
    const year = date2.getFullYear();
    const isLeapYear = isLeapYearIndex$1(year);
    const month = date2.getMonth();
    if (isLeapYear) {
      return value >= 1 && value <= DAYS_IN_MONTH_LEAP_YEAR[month];
    } else {
      return value >= 1 && value <= DAYS_IN_MONTH[month];
    }
  }
  set(date2, _flags, value) {
    date2.setDate(value);
    date2.setHours(0, 0, 0, 0);
    return date2;
  }
}
class DayOfYearParser extends Parser {
  constructor() {
    super(...arguments);
    __publicField(this, "priority", 90);
    __publicField(this, "subpriority", 1);
    __publicField(this, "incompatibleTokens", [
      "Y",
      "R",
      "q",
      "Q",
      "M",
      "L",
      "w",
      "I",
      "d",
      "E",
      "i",
      "e",
      "c",
      "t",
      "T"
    ]);
  }
  parse(dateString, token, match2) {
    switch (token) {
      case "D":
      case "DD":
        return parseNumericPattern(numericPatterns.dayOfYear, dateString);
      case "Do":
        return match2.ordinalNumber(dateString, { unit: "date" });
      default:
        return parseNDigits(token.length, dateString);
    }
  }
  validate(date2, value) {
    const year = date2.getFullYear();
    const isLeapYear = isLeapYearIndex$1(year);
    if (isLeapYear) {
      return value >= 1 && value <= 366;
    } else {
      return value >= 1 && value <= 365;
    }
  }
  set(date2, _flags, value) {
    date2.setMonth(0, value);
    date2.setHours(0, 0, 0, 0);
    return date2;
  }
}
function setDay(date2, day, options2) {
  var _a, _b, _c, _d;
  const defaultOptions2 = getDefaultOptions$1();
  const weekStartsOn = (options2 == null ? void 0 : options2.weekStartsOn) ?? ((_b = (_a = options2 == null ? void 0 : options2.locale) == null ? void 0 : _a.options) == null ? void 0 : _b.weekStartsOn) ?? defaultOptions2.weekStartsOn ?? ((_d = (_c = defaultOptions2.locale) == null ? void 0 : _c.options) == null ? void 0 : _d.weekStartsOn) ?? 0;
  const date_ = toDate(date2, options2 == null ? void 0 : options2.in);
  const currentDay = date_.getDay();
  const remainder = day % 7;
  const dayIndex = (remainder + 7) % 7;
  const delta = 7 - weekStartsOn;
  const diff = day < 0 || day > 6 ? day - (currentDay + delta) % 7 : (dayIndex + delta) % 7 - (currentDay + delta) % 7;
  return addDays(date_, diff, options2);
}
class DayParser extends Parser {
  constructor() {
    super(...arguments);
    __publicField(this, "priority", 90);
    __publicField(this, "incompatibleTokens", ["D", "i", "e", "c", "t", "T"]);
  }
  parse(dateString, token, match2) {
    switch (token) {
      case "E":
      case "EE":
      case "EEE":
        return match2.day(dateString, {
          width: "abbreviated",
          context: "formatting"
        }) || match2.day(dateString, { width: "short", context: "formatting" }) || match2.day(dateString, { width: "narrow", context: "formatting" });
      case "EEEEE":
        return match2.day(dateString, {
          width: "narrow",
          context: "formatting"
        });
      case "EEEEEE":
        return match2.day(dateString, { width: "short", context: "formatting" }) || match2.day(dateString, { width: "narrow", context: "formatting" });
      case "EEEE":
      default:
        return match2.day(dateString, { width: "wide", context: "formatting" }) || match2.day(dateString, {
          width: "abbreviated",
          context: "formatting"
        }) || match2.day(dateString, { width: "short", context: "formatting" }) || match2.day(dateString, { width: "narrow", context: "formatting" });
    }
  }
  validate(_date, value) {
    return value >= 0 && value <= 6;
  }
  set(date2, _flags, value, options2) {
    date2 = setDay(date2, value, options2);
    date2.setHours(0, 0, 0, 0);
    return date2;
  }
}
class LocalDayParser extends Parser {
  constructor() {
    super(...arguments);
    __publicField(this, "priority", 90);
    __publicField(this, "incompatibleTokens", [
      "y",
      "R",
      "u",
      "q",
      "Q",
      "M",
      "L",
      "I",
      "d",
      "D",
      "E",
      "i",
      "c",
      "t",
      "T"
    ]);
  }
  parse(dateString, token, match2, options2) {
    const valueCallback = (value) => {
      const wholeWeekDays = Math.floor((value - 1) / 7) * 7;
      return (value + options2.weekStartsOn + 6) % 7 + wholeWeekDays;
    };
    switch (token) {
      case "e":
      case "ee":
        return mapValue(parseNDigits(token.length, dateString), valueCallback);
      case "eo":
        return mapValue(
          match2.ordinalNumber(dateString, {
            unit: "day"
          }),
          valueCallback
        );
      case "eee":
        return match2.day(dateString, {
          width: "abbreviated",
          context: "formatting"
        }) || match2.day(dateString, { width: "short", context: "formatting" }) || match2.day(dateString, { width: "narrow", context: "formatting" });
      case "eeeee":
        return match2.day(dateString, {
          width: "narrow",
          context: "formatting"
        });
      case "eeeeee":
        return match2.day(dateString, { width: "short", context: "formatting" }) || match2.day(dateString, { width: "narrow", context: "formatting" });
      case "eeee":
      default:
        return match2.day(dateString, { width: "wide", context: "formatting" }) || match2.day(dateString, {
          width: "abbreviated",
          context: "formatting"
        }) || match2.day(dateString, { width: "short", context: "formatting" }) || match2.day(dateString, { width: "narrow", context: "formatting" });
    }
  }
  validate(_date, value) {
    return value >= 0 && value <= 6;
  }
  set(date2, _flags, value, options2) {
    date2 = setDay(date2, value, options2);
    date2.setHours(0, 0, 0, 0);
    return date2;
  }
}
class StandAloneLocalDayParser extends Parser {
  constructor() {
    super(...arguments);
    __publicField(this, "priority", 90);
    __publicField(this, "incompatibleTokens", [
      "y",
      "R",
      "u",
      "q",
      "Q",
      "M",
      "L",
      "I",
      "d",
      "D",
      "E",
      "i",
      "e",
      "t",
      "T"
    ]);
  }
  parse(dateString, token, match2, options2) {
    const valueCallback = (value) => {
      const wholeWeekDays = Math.floor((value - 1) / 7) * 7;
      return (value + options2.weekStartsOn + 6) % 7 + wholeWeekDays;
    };
    switch (token) {
      case "c":
      case "cc":
        return mapValue(parseNDigits(token.length, dateString), valueCallback);
      case "co":
        return mapValue(
          match2.ordinalNumber(dateString, {
            unit: "day"
          }),
          valueCallback
        );
      case "ccc":
        return match2.day(dateString, {
          width: "abbreviated",
          context: "standalone"
        }) || match2.day(dateString, { width: "short", context: "standalone" }) || match2.day(dateString, { width: "narrow", context: "standalone" });
      case "ccccc":
        return match2.day(dateString, {
          width: "narrow",
          context: "standalone"
        });
      case "cccccc":
        return match2.day(dateString, { width: "short", context: "standalone" }) || match2.day(dateString, { width: "narrow", context: "standalone" });
      case "cccc":
      default:
        return match2.day(dateString, { width: "wide", context: "standalone" }) || match2.day(dateString, {
          width: "abbreviated",
          context: "standalone"
        }) || match2.day(dateString, { width: "short", context: "standalone" }) || match2.day(dateString, { width: "narrow", context: "standalone" });
    }
  }
  validate(_date, value) {
    return value >= 0 && value <= 6;
  }
  set(date2, _flags, value, options2) {
    date2 = setDay(date2, value, options2);
    date2.setHours(0, 0, 0, 0);
    return date2;
  }
}
function setISODay(date2, day, options2) {
  const date_ = toDate(date2, options2 == null ? void 0 : options2.in);
  const currentDay = getISODay(date_, options2);
  const diff = day - currentDay;
  return addDays(date_, diff, options2);
}
class ISODayParser extends Parser {
  constructor() {
    super(...arguments);
    __publicField(this, "priority", 90);
    __publicField(this, "incompatibleTokens", [
      "y",
      "Y",
      "u",
      "q",
      "Q",
      "M",
      "L",
      "w",
      "d",
      "D",
      "E",
      "e",
      "c",
      "t",
      "T"
    ]);
  }
  parse(dateString, token, match2) {
    const valueCallback = (value) => {
      if (value === 0) {
        return 7;
      }
      return value;
    };
    switch (token) {
      case "i":
      case "ii":
        return parseNDigits(token.length, dateString);
      case "io":
        return match2.ordinalNumber(dateString, { unit: "day" });
      case "iii":
        return mapValue(
          match2.day(dateString, {
            width: "abbreviated",
            context: "formatting"
          }) || match2.day(dateString, {
            width: "short",
            context: "formatting"
          }) || match2.day(dateString, {
            width: "narrow",
            context: "formatting"
          }),
          valueCallback
        );
      case "iiiii":
        return mapValue(
          match2.day(dateString, {
            width: "narrow",
            context: "formatting"
          }),
          valueCallback
        );
      case "iiiiii":
        return mapValue(
          match2.day(dateString, {
            width: "short",
            context: "formatting"
          }) || match2.day(dateString, {
            width: "narrow",
            context: "formatting"
          }),
          valueCallback
        );
      case "iiii":
      default:
        return mapValue(
          match2.day(dateString, {
            width: "wide",
            context: "formatting"
          }) || match2.day(dateString, {
            width: "abbreviated",
            context: "formatting"
          }) || match2.day(dateString, {
            width: "short",
            context: "formatting"
          }) || match2.day(dateString, {
            width: "narrow",
            context: "formatting"
          }),
          valueCallback
        );
    }
  }
  validate(_date, value) {
    return value >= 1 && value <= 7;
  }
  set(date2, _flags, value) {
    date2 = setISODay(date2, value);
    date2.setHours(0, 0, 0, 0);
    return date2;
  }
}
class AMPMParser extends Parser {
  constructor() {
    super(...arguments);
    __publicField(this, "priority", 80);
    __publicField(this, "incompatibleTokens", ["b", "B", "H", "k", "t", "T"]);
  }
  parse(dateString, token, match2) {
    switch (token) {
      case "a":
      case "aa":
      case "aaa":
        return match2.dayPeriod(dateString, {
          width: "abbreviated",
          context: "formatting"
        }) || match2.dayPeriod(dateString, {
          width: "narrow",
          context: "formatting"
        });
      case "aaaaa":
        return match2.dayPeriod(dateString, {
          width: "narrow",
          context: "formatting"
        });
      case "aaaa":
      default:
        return match2.dayPeriod(dateString, {
          width: "wide",
          context: "formatting"
        }) || match2.dayPeriod(dateString, {
          width: "abbreviated",
          context: "formatting"
        }) || match2.dayPeriod(dateString, {
          width: "narrow",
          context: "formatting"
        });
    }
  }
  set(date2, _flags, value) {
    date2.setHours(dayPeriodEnumToHours(value), 0, 0, 0);
    return date2;
  }
}
class AMPMMidnightParser extends Parser {
  constructor() {
    super(...arguments);
    __publicField(this, "priority", 80);
    __publicField(this, "incompatibleTokens", ["a", "B", "H", "k", "t", "T"]);
  }
  parse(dateString, token, match2) {
    switch (token) {
      case "b":
      case "bb":
      case "bbb":
        return match2.dayPeriod(dateString, {
          width: "abbreviated",
          context: "formatting"
        }) || match2.dayPeriod(dateString, {
          width: "narrow",
          context: "formatting"
        });
      case "bbbbb":
        return match2.dayPeriod(dateString, {
          width: "narrow",
          context: "formatting"
        });
      case "bbbb":
      default:
        return match2.dayPeriod(dateString, {
          width: "wide",
          context: "formatting"
        }) || match2.dayPeriod(dateString, {
          width: "abbreviated",
          context: "formatting"
        }) || match2.dayPeriod(dateString, {
          width: "narrow",
          context: "formatting"
        });
    }
  }
  set(date2, _flags, value) {
    date2.setHours(dayPeriodEnumToHours(value), 0, 0, 0);
    return date2;
  }
}
class DayPeriodParser extends Parser {
  constructor() {
    super(...arguments);
    __publicField(this, "priority", 80);
    __publicField(this, "incompatibleTokens", ["a", "b", "t", "T"]);
  }
  parse(dateString, token, match2) {
    switch (token) {
      case "B":
      case "BB":
      case "BBB":
        return match2.dayPeriod(dateString, {
          width: "abbreviated",
          context: "formatting"
        }) || match2.dayPeriod(dateString, {
          width: "narrow",
          context: "formatting"
        });
      case "BBBBB":
        return match2.dayPeriod(dateString, {
          width: "narrow",
          context: "formatting"
        });
      case "BBBB":
      default:
        return match2.dayPeriod(dateString, {
          width: "wide",
          context: "formatting"
        }) || match2.dayPeriod(dateString, {
          width: "abbreviated",
          context: "formatting"
        }) || match2.dayPeriod(dateString, {
          width: "narrow",
          context: "formatting"
        });
    }
  }
  set(date2, _flags, value) {
    date2.setHours(dayPeriodEnumToHours(value), 0, 0, 0);
    return date2;
  }
}
class Hour1to12Parser extends Parser {
  constructor() {
    super(...arguments);
    __publicField(this, "priority", 70);
    __publicField(this, "incompatibleTokens", ["H", "K", "k", "t", "T"]);
  }
  parse(dateString, token, match2) {
    switch (token) {
      case "h":
        return parseNumericPattern(numericPatterns.hour12h, dateString);
      case "ho":
        return match2.ordinalNumber(dateString, { unit: "hour" });
      default:
        return parseNDigits(token.length, dateString);
    }
  }
  validate(_date, value) {
    return value >= 1 && value <= 12;
  }
  set(date2, _flags, value) {
    const isPM = date2.getHours() >= 12;
    if (isPM && value < 12) {
      date2.setHours(value + 12, 0, 0, 0);
    } else if (!isPM && value === 12) {
      date2.setHours(0, 0, 0, 0);
    } else {
      date2.setHours(value, 0, 0, 0);
    }
    return date2;
  }
}
class Hour0to23Parser extends Parser {
  constructor() {
    super(...arguments);
    __publicField(this, "priority", 70);
    __publicField(this, "incompatibleTokens", ["a", "b", "h", "K", "k", "t", "T"]);
  }
  parse(dateString, token, match2) {
    switch (token) {
      case "H":
        return parseNumericPattern(numericPatterns.hour23h, dateString);
      case "Ho":
        return match2.ordinalNumber(dateString, { unit: "hour" });
      default:
        return parseNDigits(token.length, dateString);
    }
  }
  validate(_date, value) {
    return value >= 0 && value <= 23;
  }
  set(date2, _flags, value) {
    date2.setHours(value, 0, 0, 0);
    return date2;
  }
}
class Hour0To11Parser extends Parser {
  constructor() {
    super(...arguments);
    __publicField(this, "priority", 70);
    __publicField(this, "incompatibleTokens", ["h", "H", "k", "t", "T"]);
  }
  parse(dateString, token, match2) {
    switch (token) {
      case "K":
        return parseNumericPattern(numericPatterns.hour11h, dateString);
      case "Ko":
        return match2.ordinalNumber(dateString, { unit: "hour" });
      default:
        return parseNDigits(token.length, dateString);
    }
  }
  validate(_date, value) {
    return value >= 0 && value <= 11;
  }
  set(date2, _flags, value) {
    const isPM = date2.getHours() >= 12;
    if (isPM && value < 12) {
      date2.setHours(value + 12, 0, 0, 0);
    } else {
      date2.setHours(value, 0, 0, 0);
    }
    return date2;
  }
}
class Hour1To24Parser extends Parser {
  constructor() {
    super(...arguments);
    __publicField(this, "priority", 70);
    __publicField(this, "incompatibleTokens", ["a", "b", "h", "H", "K", "t", "T"]);
  }
  parse(dateString, token, match2) {
    switch (token) {
      case "k":
        return parseNumericPattern(numericPatterns.hour24h, dateString);
      case "ko":
        return match2.ordinalNumber(dateString, { unit: "hour" });
      default:
        return parseNDigits(token.length, dateString);
    }
  }
  validate(_date, value) {
    return value >= 1 && value <= 24;
  }
  set(date2, _flags, value) {
    const hours = value <= 24 ? value % 24 : value;
    date2.setHours(hours, 0, 0, 0);
    return date2;
  }
}
class MinuteParser extends Parser {
  constructor() {
    super(...arguments);
    __publicField(this, "priority", 60);
    __publicField(this, "incompatibleTokens", ["t", "T"]);
  }
  parse(dateString, token, match2) {
    switch (token) {
      case "m":
        return parseNumericPattern(numericPatterns.minute, dateString);
      case "mo":
        return match2.ordinalNumber(dateString, { unit: "minute" });
      default:
        return parseNDigits(token.length, dateString);
    }
  }
  validate(_date, value) {
    return value >= 0 && value <= 59;
  }
  set(date2, _flags, value) {
    date2.setMinutes(value, 0, 0);
    return date2;
  }
}
class SecondParser extends Parser {
  constructor() {
    super(...arguments);
    __publicField(this, "priority", 50);
    __publicField(this, "incompatibleTokens", ["t", "T"]);
  }
  parse(dateString, token, match2) {
    switch (token) {
      case "s":
        return parseNumericPattern(numericPatterns.second, dateString);
      case "so":
        return match2.ordinalNumber(dateString, { unit: "second" });
      default:
        return parseNDigits(token.length, dateString);
    }
  }
  validate(_date, value) {
    return value >= 0 && value <= 59;
  }
  set(date2, _flags, value) {
    date2.setSeconds(value, 0);
    return date2;
  }
}
class FractionOfSecondParser extends Parser {
  constructor() {
    super(...arguments);
    __publicField(this, "priority", 30);
    __publicField(this, "incompatibleTokens", ["t", "T"]);
  }
  parse(dateString, token) {
    const valueCallback = (value) => Math.trunc(value * Math.pow(10, -token.length + 3));
    return mapValue(parseNDigits(token.length, dateString), valueCallback);
  }
  set(date2, _flags, value) {
    date2.setMilliseconds(value);
    return date2;
  }
}
class ISOTimezoneWithZParser extends Parser {
  constructor() {
    super(...arguments);
    __publicField(this, "priority", 10);
    __publicField(this, "incompatibleTokens", ["t", "T", "x"]);
  }
  parse(dateString, token) {
    switch (token) {
      case "X":
        return parseTimezonePattern(
          timezonePatterns.basicOptionalMinutes,
          dateString
        );
      case "XX":
        return parseTimezonePattern(timezonePatterns.basic, dateString);
      case "XXXX":
        return parseTimezonePattern(
          timezonePatterns.basicOptionalSeconds,
          dateString
        );
      case "XXXXX":
        return parseTimezonePattern(
          timezonePatterns.extendedOptionalSeconds,
          dateString
        );
      case "XXX":
      default:
        return parseTimezonePattern(timezonePatterns.extended, dateString);
    }
  }
  set(date2, flags, value) {
    if (flags.timestampIsSet) return date2;
    return constructFrom(
      date2,
      date2.getTime() - getTimezoneOffsetInMilliseconds(date2) - value
    );
  }
}
class ISOTimezoneParser extends Parser {
  constructor() {
    super(...arguments);
    __publicField(this, "priority", 10);
    __publicField(this, "incompatibleTokens", ["t", "T", "X"]);
  }
  parse(dateString, token) {
    switch (token) {
      case "x":
        return parseTimezonePattern(
          timezonePatterns.basicOptionalMinutes,
          dateString
        );
      case "xx":
        return parseTimezonePattern(timezonePatterns.basic, dateString);
      case "xxxx":
        return parseTimezonePattern(
          timezonePatterns.basicOptionalSeconds,
          dateString
        );
      case "xxxxx":
        return parseTimezonePattern(
          timezonePatterns.extendedOptionalSeconds,
          dateString
        );
      case "xxx":
      default:
        return parseTimezonePattern(timezonePatterns.extended, dateString);
    }
  }
  set(date2, flags, value) {
    if (flags.timestampIsSet) return date2;
    return constructFrom(
      date2,
      date2.getTime() - getTimezoneOffsetInMilliseconds(date2) - value
    );
  }
}
class TimestampSecondsParser extends Parser {
  constructor() {
    super(...arguments);
    __publicField(this, "priority", 40);
    __publicField(this, "incompatibleTokens", "*");
  }
  parse(dateString) {
    return parseAnyDigitsSigned(dateString);
  }
  set(date2, _flags, value) {
    return [constructFrom(date2, value * 1e3), { timestampIsSet: true }];
  }
}
class TimestampMillisecondsParser extends Parser {
  constructor() {
    super(...arguments);
    __publicField(this, "priority", 20);
    __publicField(this, "incompatibleTokens", "*");
  }
  parse(dateString) {
    return parseAnyDigitsSigned(dateString);
  }
  set(date2, _flags, value) {
    return [constructFrom(date2, value), { timestampIsSet: true }];
  }
}
const parsers = {
  G: new EraParser(),
  y: new YearParser(),
  Y: new LocalWeekYearParser(),
  R: new ISOWeekYearParser(),
  u: new ExtendedYearParser(),
  Q: new QuarterParser(),
  q: new StandAloneQuarterParser(),
  M: new MonthParser(),
  L: new StandAloneMonthParser(),
  w: new LocalWeekParser(),
  I: new ISOWeekParser(),
  d: new DateParser(),
  D: new DayOfYearParser(),
  E: new DayParser(),
  e: new LocalDayParser(),
  c: new StandAloneLocalDayParser(),
  i: new ISODayParser(),
  a: new AMPMParser(),
  b: new AMPMMidnightParser(),
  B: new DayPeriodParser(),
  h: new Hour1to12Parser(),
  H: new Hour0to23Parser(),
  K: new Hour0To11Parser(),
  k: new Hour1To24Parser(),
  m: new MinuteParser(),
  s: new SecondParser(),
  S: new FractionOfSecondParser(),
  X: new ISOTimezoneWithZParser(),
  x: new ISOTimezoneParser(),
  t: new TimestampSecondsParser(),
  T: new TimestampMillisecondsParser()
};
const formattingTokensRegExp = /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g;
const longFormattingTokensRegExp = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g;
const escapedStringRegExp = /^'([^]*?)'?$/;
const doubleQuoteRegExp = /''/g;
const notWhitespaceRegExp = /\S/;
const unescapedLatinCharacterRegExp = /[a-zA-Z]/;
function parse(dateStr, formatStr, referenceDate, options2) {
  var _a, _b, _c, _d;
  const invalidDate = () => constructFrom(referenceDate, NaN);
  const defaultOptions2 = getDefaultOptions();
  const locale2 = defaultOptions2.locale ?? enUS;
  const firstWeekContainsDate = defaultOptions2.firstWeekContainsDate ?? ((_b = (_a = defaultOptions2.locale) == null ? void 0 : _a.options) == null ? void 0 : _b.firstWeekContainsDate) ?? 1;
  const weekStartsOn = defaultOptions2.weekStartsOn ?? ((_d = (_c = defaultOptions2.locale) == null ? void 0 : _c.options) == null ? void 0 : _d.weekStartsOn) ?? 0;
  const subFnOptions = {
    firstWeekContainsDate,
    weekStartsOn,
    locale: locale2
  };
  const setters = [new DateTimezoneSetter(options2 == null ? void 0 : options2.in, referenceDate)];
  const tokens = formatStr.match(longFormattingTokensRegExp).map((substring) => {
    const firstCharacter = substring[0];
    if (firstCharacter in longFormatters) {
      const longFormatter = longFormatters[firstCharacter];
      return longFormatter(substring, locale2.formatLong);
    }
    return substring;
  }).join("").match(formattingTokensRegExp);
  const usedTokens = [];
  for (let token of tokens) {
    if (isProtectedWeekYearToken(token)) {
      warnOrThrowProtectedError(token, formatStr, dateStr);
    }
    if (isProtectedDayOfYearToken(token)) {
      warnOrThrowProtectedError(token, formatStr, dateStr);
    }
    const firstCharacter = token[0];
    const parser = parsers[firstCharacter];
    if (parser) {
      const { incompatibleTokens } = parser;
      if (Array.isArray(incompatibleTokens)) {
        const incompatibleToken = usedTokens.find(
          (usedToken) => incompatibleTokens.includes(usedToken.token) || usedToken.token === firstCharacter
        );
        if (incompatibleToken) {
          throw new RangeError(
            `The format string mustn't contain \`${incompatibleToken.fullToken}\` and \`${token}\` at the same time`
          );
        }
      } else if (parser.incompatibleTokens === "*" && usedTokens.length > 0) {
        throw new RangeError(
          `The format string mustn't contain \`${token}\` and any other token at the same time`
        );
      }
      usedTokens.push({ token: firstCharacter, fullToken: token });
      const parseResult = parser.run(
        dateStr,
        token,
        locale2.match,
        subFnOptions
      );
      if (!parseResult) {
        return invalidDate();
      }
      setters.push(parseResult.setter);
      dateStr = parseResult.rest;
    } else {
      if (firstCharacter.match(unescapedLatinCharacterRegExp)) {
        throw new RangeError(
          "Format string contains an unescaped latin alphabet character `" + firstCharacter + "`"
        );
      }
      if (token === "''") {
        token = "'";
      } else if (firstCharacter === "'") {
        token = cleanEscapedString(token);
      }
      if (dateStr.indexOf(token) === 0) {
        dateStr = dateStr.slice(token.length);
      } else {
        return invalidDate();
      }
    }
  }
  if (dateStr.length > 0 && notWhitespaceRegExp.test(dateStr)) {
    return invalidDate();
  }
  const uniquePrioritySetters = setters.map((setter) => setter.priority).sort((a2, b) => b - a2).filter((priority, index, array2) => array2.indexOf(priority) === index).map(
    (priority) => setters.filter((setter) => setter.priority === priority).sort((a2, b) => b.subPriority - a2.subPriority)
  ).map((setterArray) => setterArray[0]);
  let date2 = toDate(referenceDate, options2 == null ? void 0 : options2.in);
  if (isNaN(+date2)) return invalidDate();
  const flags = {};
  for (const setter of uniquePrioritySetters) {
    if (!setter.validate(date2, subFnOptions)) {
      return invalidDate();
    }
    const result = setter.set(date2, flags, subFnOptions);
    if (Array.isArray(result)) {
      date2 = result[0];
      Object.assign(flags, result[1]);
    } else {
      date2 = result;
    }
  }
  return date2;
}
function cleanEscapedString(input) {
  return input.match(escapedStringRegExp)[1].replace(doubleQuoteRegExp, "'");
}
function isSameMonth(laterDate, earlierDate, options2) {
  const [laterDate_, earlierDate_] = normalizeDates(
    options2 == null ? void 0 : options2.in,
    laterDate,
    earlierDate
  );
  return laterDate_.getFullYear() === earlierDate_.getFullYear() && laterDate_.getMonth() === earlierDate_.getMonth();
}
function isToday(date2, options2) {
  return isSameDay(
    constructFrom(date2, date2),
    constructNow(date2)
  );
}
function isWithinInterval(date2, interval, options2) {
  const time2 = +toDate(date2, options2 == null ? void 0 : options2.in);
  const [startTime, endTime] = [
    +toDate(interval.start, options2 == null ? void 0 : options2.in),
    +toDate(interval.end, options2 == null ? void 0 : options2.in)
  ].sort((a2, b) => a2 - b);
  return time2 >= startTime && time2 <= endTime;
}
function parseISO(argument, options2) {
  const invalidDate = () => constructFrom(options2 == null ? void 0 : options2.in, NaN);
  const additionalDigits = 2;
  const dateStrings = splitDateString(argument);
  let date2;
  if (dateStrings.date) {
    const parseYearResult = parseYear(dateStrings.date, additionalDigits);
    date2 = parseDate(parseYearResult.restDateString, parseYearResult.year);
  }
  if (!date2 || isNaN(+date2)) return invalidDate();
  const timestamp = +date2;
  let time2 = 0;
  let offset;
  if (dateStrings.time) {
    time2 = parseTime(dateStrings.time);
    if (isNaN(time2)) return invalidDate();
  }
  if (dateStrings.timezone) {
    offset = parseTimezone(dateStrings.timezone);
    if (isNaN(offset)) return invalidDate();
  } else {
    const tmpDate = new Date(timestamp + time2);
    const result = toDate(0, options2 == null ? void 0 : options2.in);
    result.setFullYear(
      tmpDate.getUTCFullYear(),
      tmpDate.getUTCMonth(),
      tmpDate.getUTCDate()
    );
    result.setHours(
      tmpDate.getUTCHours(),
      tmpDate.getUTCMinutes(),
      tmpDate.getUTCSeconds(),
      tmpDate.getUTCMilliseconds()
    );
    return result;
  }
  return toDate(timestamp + time2 + offset, options2 == null ? void 0 : options2.in);
}
const patterns = {
  dateTimeDelimiter: /[T ]/,
  timeZoneDelimiter: /[Z ]/i,
  timezone: /([Z+-].*)$/
};
const dateRegex = /^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/;
const timeRegex = /^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/;
const timezoneRegex = /^([+-])(\d{2})(?::?(\d{2}))?$/;
function splitDateString(dateString) {
  const dateStrings = {};
  const array2 = dateString.split(patterns.dateTimeDelimiter);
  let timeString;
  if (array2.length > 2) {
    return dateStrings;
  }
  if (/:/.test(array2[0])) {
    timeString = array2[0];
  } else {
    dateStrings.date = array2[0];
    timeString = array2[1];
    if (patterns.timeZoneDelimiter.test(dateStrings.date)) {
      dateStrings.date = dateString.split(patterns.timeZoneDelimiter)[0];
      timeString = dateString.substr(
        dateStrings.date.length,
        dateString.length
      );
    }
  }
  if (timeString) {
    const token = patterns.timezone.exec(timeString);
    if (token) {
      dateStrings.time = timeString.replace(token[1], "");
      dateStrings.timezone = token[1];
    } else {
      dateStrings.time = timeString;
    }
  }
  return dateStrings;
}
function parseYear(dateString, additionalDigits) {
  const regex = new RegExp(
    "^(?:(\\d{4}|[+-]\\d{" + (4 + additionalDigits) + "})|(\\d{2}|[+-]\\d{" + (2 + additionalDigits) + "})$)"
  );
  const captures = dateString.match(regex);
  if (!captures) return { year: NaN, restDateString: "" };
  const year = captures[1] ? parseInt(captures[1]) : null;
  const century = captures[2] ? parseInt(captures[2]) : null;
  return {
    year: century === null ? year : century * 100,
    restDateString: dateString.slice((captures[1] || captures[2]).length)
  };
}
function parseDate(dateString, year) {
  if (year === null) return /* @__PURE__ */ new Date(NaN);
  const captures = dateString.match(dateRegex);
  if (!captures) return /* @__PURE__ */ new Date(NaN);
  const isWeekDate = !!captures[4];
  const dayOfYear = parseDateUnit(captures[1]);
  const month = parseDateUnit(captures[2]) - 1;
  const day = parseDateUnit(captures[3]);
  const week = parseDateUnit(captures[4]);
  const dayOfWeek = parseDateUnit(captures[5]) - 1;
  if (isWeekDate) {
    if (!validateWeekDate(year, week, dayOfWeek)) {
      return /* @__PURE__ */ new Date(NaN);
    }
    return dayOfISOWeekYear(year, week, dayOfWeek);
  } else {
    const date2 = /* @__PURE__ */ new Date(0);
    if (!validateDate(year, month, day) || !validateDayOfYearDate(year, dayOfYear)) {
      return /* @__PURE__ */ new Date(NaN);
    }
    date2.setUTCFullYear(year, month, Math.max(dayOfYear, day));
    return date2;
  }
}
function parseDateUnit(value) {
  return value ? parseInt(value) : 1;
}
function parseTime(timeString) {
  const captures = timeString.match(timeRegex);
  if (!captures) return NaN;
  const hours = parseTimeUnit(captures[1]);
  const minutes = parseTimeUnit(captures[2]);
  const seconds = parseTimeUnit(captures[3]);
  if (!validateTime(hours, minutes, seconds)) {
    return NaN;
  }
  return hours * millisecondsInHour + minutes * millisecondsInMinute + seconds * 1e3;
}
function parseTimeUnit(value) {
  return value && parseFloat(value.replace(",", ".")) || 0;
}
function parseTimezone(timezoneString) {
  if (timezoneString === "Z") return 0;
  const captures = timezoneString.match(timezoneRegex);
  if (!captures) return 0;
  const sign2 = captures[1] === "+" ? -1 : 1;
  const hours = parseInt(captures[2]);
  const minutes = captures[3] && parseInt(captures[3]) || 0;
  if (!validateTimezone(hours, minutes)) {
    return NaN;
  }
  return sign2 * (hours * millisecondsInHour + minutes * millisecondsInMinute);
}
function dayOfISOWeekYear(isoWeekYear, week, day) {
  const date2 = /* @__PURE__ */ new Date(0);
  date2.setUTCFullYear(isoWeekYear, 0, 4);
  const fourthOfJanuaryDay = date2.getUTCDay() || 7;
  const diff = (week - 1) * 7 + day + 1 - fourthOfJanuaryDay;
  date2.setUTCDate(date2.getUTCDate() + diff);
  return date2;
}
const daysInMonths = [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
function isLeapYearIndex(year) {
  return year % 400 === 0 || year % 4 === 0 && year % 100 !== 0;
}
function validateDate(year, month, date2) {
  return month >= 0 && month <= 11 && date2 >= 1 && date2 <= (daysInMonths[month] || (isLeapYearIndex(year) ? 29 : 28));
}
function validateDayOfYearDate(year, dayOfYear) {
  return dayOfYear >= 1 && dayOfYear <= (isLeapYearIndex(year) ? 366 : 365);
}
function validateWeekDate(_year, week, day) {
  return week >= 1 && week <= 53 && day >= 0 && day <= 6;
}
function validateTime(hours, minutes, seconds) {
  if (hours === 24) {
    return minutes === 0 && seconds === 0;
  }
  return seconds >= 0 && seconds < 60 && minutes >= 0 && minutes < 60 && hours >= 0 && hours < 25;
}
function validateTimezone(_hours, minutes) {
  return minutes >= 0 && minutes <= 59;
}
function subMonths(date2, amount, options2) {
  return addMonths(date2, -1, options2);
}
const Calendar = ({
  selected,
  onSelect,
  disabled,
  minDate,
  maxDate,
  className = ""
}) => {
  const [currentMonth, setCurrentMonth] = reactExports.useState(/* @__PURE__ */ new Date());
  const monthStart = startOfMonth(currentMonth);
  const monthEnd = endOfMonth(currentMonth);
  const calendarStart = startOfWeek(monthStart, { weekStartsOn: 0 });
  const calendarEnd = endOfWeek(monthEnd, { weekStartsOn: 0 });
  const days = eachDayOfInterval({ start: calendarStart, end: calendarEnd });
  const isDateDisabled = (date2) => {
    if (disabled && disabled(date2)) return true;
    if (minDate && date2 < minDate) return true;
    if (maxDate && date2 > maxDate) return true;
    return false;
  };
  const handleDateClick = (date2) => {
    if (isDateDisabled(date2)) return;
    onSelect == null ? void 0 : onSelect(date2);
  };
  const previousMonth = () => {
    setCurrentMonth(subMonths(currentMonth));
  };
  const nextMonth = () => {
    setCurrentMonth(addMonths(currentMonth, 1));
  };
  const weekDays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: `p-3 ${className}`, children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between mb-4", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        "button",
        {
          type: "button",
          onClick: previousMonth,
          className: "p-1 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-md transition-colors",
          children: /* @__PURE__ */ jsxRuntimeExports.jsx(ChevronLeft, { className: "w-4 h-4" })
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-sm font-semibold text-gray-900 dark:text-white", children: format(currentMonth, "MMMM yyyy") }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        "button",
        {
          type: "button",
          onClick: nextMonth,
          className: "p-1 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-md transition-colors",
          children: /* @__PURE__ */ jsxRuntimeExports.jsx(ChevronRight, { className: "w-4 h-4" })
        }
      )
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid grid-cols-7 gap-1 mb-2", children: weekDays.map((day) => /* @__PURE__ */ jsxRuntimeExports.jsx(
      "div",
      {
        className: "text-xs font-medium text-gray-500 dark:text-gray-400 text-center py-2",
        children: day
      },
      day
    )) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid grid-cols-7 gap-1", children: days.map((day, dayIdx) => {
      const isCurrentMonth = isSameMonth(day, currentMonth);
      const isSelected = selected && isSameDay(day, selected);
      const isTodayDate = isToday(day);
      const isDisabled = isDateDisabled(day);
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        "button",
        {
          type: "button",
          onClick: () => handleDateClick(day),
          disabled: isDisabled,
          className: `
                h-9 w-9 text-sm rounded-md transition-colors
                ${isCurrentMonth ? "text-gray-900 dark:text-white" : "text-gray-400 dark:text-gray-600"}
                ${isSelected ? "bg-blue-600 text-white hover:bg-blue-700" : isTodayDate ? "bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 font-semibold" : "hover:bg-gray-100 dark:hover:bg-gray-700"}
                ${isDisabled ? "opacity-50 cursor-not-allowed" : "cursor-pointer"}
              `,
          children: format(day, "d")
        },
        dayIdx
      );
    }) })
  ] });
};
const PopoverContext = reactExports.createContext({
  open: false,
  setOpen: () => {
  },
  triggerRef: { current: null }
});
const Popover = ({
  children,
  open: controlledOpen,
  onOpenChange
}) => {
  const [internalOpen, setInternalOpen] = reactExports.useState(false);
  const triggerRef = reactExports.useRef(null);
  const open = controlledOpen !== void 0 ? controlledOpen : internalOpen;
  const setOpen = reactExports.useCallback(
    (newOpen) => {
      if (controlledOpen === void 0) {
        setInternalOpen(newOpen);
      }
      onOpenChange == null ? void 0 : onOpenChange(newOpen);
    },
    [controlledOpen, onOpenChange]
  );
  return /* @__PURE__ */ jsxRuntimeExports.jsx(PopoverContext.Provider, { value: { open, setOpen, triggerRef }, children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "relative", children }) });
};
const PopoverTrigger = ({ children, asChild }) => {
  const { open, setOpen, triggerRef } = reactExports.useContext(PopoverContext);
  if (asChild && reactExports.isValidElement(children)) {
    return reactExports.cloneElement(children, {
      ref: (node) => {
        triggerRef.current = node;
        if (typeof children.ref === "function") {
          children.ref(node);
        }
      },
      onClick: () => setOpen(!open)
    });
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    "div",
    {
      ref: (node) => {
        triggerRef.current = node;
      },
      onClick: () => setOpen(!open),
      className: "cursor-pointer",
      children
    }
  );
};
const PopoverContent = ({ children, className = "", align = "start", side = "bottom" }) => {
  const { open, setOpen, triggerRef } = reactExports.useContext(PopoverContext);
  const contentRef = reactExports.useRef(null);
  const [position, setPosition] = reactExports.useState(null);
  reactExports.useEffect(() => {
    if (!open || !triggerRef.current) {
      setPosition(null);
      return;
    }
    const calculatePosition = () => {
      if (!triggerRef.current) return;
      const triggerRect = triggerRef.current.getBoundingClientRect();
      const viewportWidth = window.innerWidth;
      const viewportHeight = window.innerHeight;
      const scrollX = window.scrollX;
      const scrollY = window.scrollY;
      const estimatedWidth = 320;
      const estimatedHeight = 300;
      let top = 0;
      let left = 0;
      if (side === "bottom") {
        top = triggerRect.bottom + scrollY + 8;
        if (top + estimatedHeight > scrollY + viewportHeight) {
          top = triggerRect.top + scrollY - estimatedHeight - 8;
        }
      } else if (side === "top") {
        top = triggerRect.top + scrollY - estimatedHeight - 8;
        if (top < scrollY) {
          top = triggerRect.bottom + scrollY + 8;
        }
      } else if (side === "right") {
        top = triggerRect.top + scrollY;
        left = triggerRect.right + scrollX + 8;
        if (left + estimatedWidth > scrollX + viewportWidth) {
          left = triggerRect.left + scrollX - estimatedWidth - 8;
        }
      } else if (side === "left") {
        top = triggerRect.top + scrollY;
        left = triggerRect.left + scrollX - estimatedWidth - 8;
        if (left < scrollX) {
          left = triggerRect.right + scrollX + 8;
        }
      }
      if (side === "top" || side === "bottom") {
        if (align === "start") {
          left = triggerRect.left + scrollX;
        } else if (align === "center") {
          left = triggerRect.left + scrollX + triggerRect.width / 2 - estimatedWidth / 2;
        } else if (align === "end") {
          left = triggerRect.right + scrollX - estimatedWidth;
        }
        if (left < scrollX) {
          left = scrollX + 8;
        } else if (left + estimatedWidth > scrollX + viewportWidth) {
          left = scrollX + viewportWidth - estimatedWidth - 8;
        }
      }
      if (top < scrollY) {
        top = scrollY + 8;
      } else if (top + estimatedHeight > scrollY + viewportHeight) {
        top = scrollY + viewportHeight - estimatedHeight - 8;
      }
      setPosition({ top, left });
      requestAnimationFrame(() => {
        if (!contentRef.current || !triggerRef.current) return;
        const contentRect = contentRef.current.getBoundingClientRect();
        const currentTop = top;
        const currentLeft = left;
        let refinedTop = currentTop;
        let refinedLeft = currentLeft;
        if (refinedTop + contentRect.height > scrollY + viewportHeight) {
          refinedTop = scrollY + viewportHeight - contentRect.height - 8;
        }
        if (refinedTop < scrollY) {
          refinedTop = scrollY + 8;
        }
        if (refinedLeft + contentRect.width > scrollX + viewportWidth) {
          refinedLeft = scrollX + viewportWidth - contentRect.width - 8;
        }
        if (refinedLeft < scrollX) {
          refinedLeft = scrollX + 8;
        }
        if (refinedTop !== currentTop || refinedLeft !== currentLeft) {
          setPosition({ top: refinedTop, left: refinedLeft });
        }
      });
    };
    calculatePosition();
    const handleResize = () => calculatePosition();
    const handleScroll = () => calculatePosition();
    window.addEventListener("resize", handleResize);
    window.addEventListener("scroll", handleScroll, true);
    return () => {
      window.removeEventListener("resize", handleResize);
      window.removeEventListener("scroll", handleScroll, true);
    };
  }, [open, align, side]);
  reactExports.useEffect(() => {
    if (!open) return;
    const handleClickOutside = (event) => {
      if (contentRef.current && !contentRef.current.contains(event.target)) {
        if (triggerRef.current && triggerRef.current.contains(event.target)) {
          return;
        }
        setOpen(false);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, [open, setOpen]);
  if (!open) return null;
  const initialPosition = position || { top: 0, left: 0 };
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    "div",
    {
      ref: contentRef,
      className: `fixed z-[9999] w-72 rounded-md border border-gray-200 bg-white p-4 shadow-lg dark:border-gray-700 dark:bg-gray-800 ${className}`,
      style: {
        top: `${initialPosition.top}px`,
        left: `${initialPosition.left}px`,
        visibility: position ? "visible" : "hidden"
      },
      children
    }
  );
};
const DatePicker = ({
  value,
  onChange,
  placeholder = "Select date",
  disabled = false,
  minDate,
  maxDate,
  className = "",
  error = false
}) => {
  const [open, setOpen] = reactExports.useState(false);
  let selectedDate = void 0;
  if (value && value.trim()) {
    try {
      const parsed = parse(value, "yyyy-MM-dd", /* @__PURE__ */ new Date());
      if (!isNaN(parsed.getTime())) {
        selectedDate = parsed;
      }
    } catch (e) {
      selectedDate = void 0;
    }
  }
  const handleSelect = (date2) => {
    if (date2) {
      onChange == null ? void 0 : onChange(format(date2, "yyyy-MM-dd"));
      setOpen(false);
    }
  };
  let displayValue = "";
  if (selectedDate && !isNaN(selectedDate.getTime())) {
    try {
      displayValue = format(selectedDate, "MMM dd, yyyy");
    } catch (e) {
      displayValue = "";
    }
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(Popover, { open, onOpenChange: setOpen, children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(PopoverTrigger, { asChild: true, children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
      Button,
      {
        type: "button",
        variant: "outline",
        disabled,
        className: `w-full justify-start text-left font-normal ${error ? "border-red-500" : ""} ${!displayValue ? "text-gray-500" : ""} ${className}`,
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Calendar$1, { className: "mr-2 h-4 w-4" }),
          displayValue || /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-500", children: placeholder })
        ]
      }
    ) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(PopoverContent, { className: "w-auto p-0", align: "start", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
      Calendar,
      {
        selected: selectedDate,
        onSelect: handleSelect,
        minDate,
        maxDate
      }
    ) })
  ] });
};
const CustomerForm = () => {
  var _a;
  const queryClient2 = useQueryClient();
  const { showToast } = useToast();
  const baseAdminUrl = ((_a = window.yatraAdmin) == null ? void 0 : _a.adminUrl) || "";
  const [formData, setFormData] = reactExports.useState({
    first_name: "",
    last_name: "",
    email: "",
    phone: "",
    secondary_phone: "",
    country: "",
    city: "",
    state: "",
    address: "",
    postal_code: "",
    nationality: "",
    date_of_birth: "",
    gender: "",
    emergency_name: "",
    emergency_phone: "",
    emergency_relationship: "",
    dietary_requirements: "",
    medical_conditions: "",
    special_needs: "",
    newsletter_optin: false,
    marketing_optin: false,
    status: "active",
    notes: "",
    loyalty_tier: "bronze",
    loyalty_points: 0
  });
  const [errors, setErrors] = reactExports.useState({});
  const [isSubmitting, setIsSubmitting] = reactExports.useState(false);
  const action = reactExports.useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get("action") || "create";
  }, []);
  const customerId = reactExports.useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get("id") ? parseInt(params.get("id") || "0") : null;
  }, []);
  const isEditMode = action === "edit" && customerId !== null;
  const { data: customerData, isLoading: isLoadingCustomer } = useQuery({
    queryKey: ["customer", customerId],
    queryFn: async () => {
      if (!customerId) return null;
      const response = await apiService.getCustomer(customerId);
      const data = (response == null ? void 0 : response.data) ?? response;
      const emergency = data.emergency_contact || {};
      return {
        first_name: data.first_name || "",
        last_name: data.last_name || "",
        email: data.email || "",
        phone: data.phone || "",
        secondary_phone: data.secondary_phone || "",
        country: data.country || "",
        city: data.city || "",
        state: data.state || "",
        address: data.address || "",
        postal_code: data.postal_code || "",
        nationality: data.nationality || "",
        date_of_birth: data.date_of_birth || "",
        gender: data.gender || "",
        emergency_name: data.emergency_name || emergency.name || "",
        emergency_phone: data.emergency_phone || emergency.phone || "",
        emergency_relationship: data.emergency_relationship || emergency.relationship || "",
        dietary_requirements: data.dietary_requirements || "",
        medical_conditions: data.medical_conditions || "",
        special_needs: data.special_needs || "",
        newsletter_optin: Boolean(data.newsletter_optin),
        marketing_optin: Boolean(data.marketing_optin),
        status: data.status || "active",
        notes: data.notes || "",
        loyalty_tier: data.loyalty_tier || "bronze",
        loyalty_points: typeof data.loyalty_points === "number" ? data.loyalty_points : parseInt(data.loyalty_points || "0", 10) || 0
      };
    },
    enabled: isEditMode
  });
  reactExports.useEffect(() => {
    if (customerData && isEditMode) {
      setFormData(customerData);
    }
  }, [customerData, isEditMode]);
  const handleFieldChange = (field, value) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
    if (errors[field]) {
      setErrors((prev) => ({ ...prev, [field]: "" }));
    }
  };
  const validateForm = () => {
    const newErrors = {};
    if (!formData.first_name.trim()) {
      newErrors.first_name = __("First name is required", "yatra");
    }
    if (!formData.email.trim()) {
      newErrors.email = __("Email is required", "yatra");
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
      newErrors.email = __("Invalid email address", "yatra");
    }
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };
  const saveMutation = useMutation({
    mutationFn: async (data) => {
      const payload = { ...data };
      if (isEditMode && customerId) {
        return await apiService.updateCustomer(customerId, payload);
      } else {
        throw new Error(
          "Creating customers directly is not supported. Customers are created when bookings are made."
        );
      }
    },
    onSuccess: () => {
      queryClient2.invalidateQueries({ queryKey: ["customers"] });
      queryClient2.invalidateQueries({ queryKey: ["customer", customerId] });
      setIsSubmitting(false);
      showToast(__("Customer updated successfully", "yatra"), "success");
    },
    onError: (error) => {
      const errorMessage = (error == null ? void 0 : error.message) || __("An error occurred while saving the customer", "yatra");
      setErrors({ submit: errorMessage });
      setIsSubmitting(false);
      showToast(errorMessage, "error");
    }
  });
  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!validateForm()) {
      return;
    }
    setIsSubmitting(true);
    setErrors({});
    saveMutation.mutate(formData);
  };
  const handleCancel = () => {
    window.location.href = `${baseAdminUrl}?page=yatra&subpage=customers`;
  };
  const renderSkeleton = () => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-3 gap-3", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "lg:col-span-2 space-y-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-5 w-40" }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-2 gap-3", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-4 w-20" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-9 w-full" })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-4 w-20" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-9 w-full" })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-4 w-24" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-9 w-full" })
        ] })
      ] })
    ] }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-5 w-20" }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-9 w-full" }) })
    ] }) })
  ] });
  if (isEditMode && isLoadingCustomer) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        PageHeader,
        {
          title: __("Edit Customer", "yatra"),
          description: __("Loading...", "yatra"),
          actions: /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Button,
            {
              variant: "outline",
              onClick: handleCancel,
              className: "flex items-center gap-2",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowLeft, { className: "w-4 h-4" }),
                __("Back", "yatra")
              ]
            }
          )
        }
      ),
      renderSkeleton()
    ] });
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      PageHeader,
      {
        title: isEditMode ? __("Edit Customer", "yatra") : __("Add New Customer", "yatra"),
        description: isEditMode ? __("Update customer information", "yatra") : __("Create a new customer profile", "yatra"),
        actions: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Button,
          {
            variant: "outline",
            onClick: handleCancel,
            className: "flex items-center gap-2",
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowLeft, { className: "w-4 h-4" }),
              __("Back", "yatra")
            ]
          }
        )
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_edit_customers", children: /* @__PURE__ */ jsxRuntimeExports.jsx("form", { onSubmit: handleSubmit, children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-3 gap-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "lg:col-span-2 space-y-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Personal Information", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-3", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs(
                  "label",
                  {
                    htmlFor: "first_name",
                    className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                    children: [
                      __("First Name", "yatra"),
                      " ",
                      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
                    ]
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Input,
                  {
                    id: "first_name",
                    type: "text",
                    value: formData.first_name,
                    onChange: (e) => handleFieldChange("first_name", e.target.value),
                    placeholder: __("Enter first name", "yatra"),
                    className: errors.first_name ? "border-red-500" : "",
                    required: true
                  }
                ),
                errors.first_name && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm text-red-500", children: errors.first_name })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "label",
                  {
                    htmlFor: "last_name",
                    className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                    children: __("Last Name", "yatra")
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Input,
                  {
                    id: "last_name",
                    type: "text",
                    value: formData.last_name,
                    onChange: (e) => handleFieldChange("last_name", e.target.value),
                    placeholder: __("Enter last name", "yatra")
                  }
                )
              ] })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs(
                "label",
                {
                  htmlFor: "email",
                  className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                  children: [
                    __("Email Address", "yatra"),
                    " ",
                    /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
                  ]
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Input,
                {
                  id: "email",
                  type: "email",
                  value: formData.email,
                  onChange: (e) => handleFieldChange("email", e.target.value),
                  placeholder: __("customer@example.com", "yatra"),
                  className: errors.email ? "border-red-500" : "",
                  required: true,
                  disabled: isEditMode
                }
              ),
              errors.email && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm text-red-500", children: errors.email })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-3", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "label",
                  {
                    htmlFor: "phone",
                    className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                    children: __("Phone Number", "yatra")
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Input,
                  {
                    id: "phone",
                    type: "tel",
                    value: formData.phone,
                    onChange: (e) => handleFieldChange("phone", e.target.value),
                    placeholder: __("+1234567890", "yatra")
                  }
                )
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "label",
                  {
                    htmlFor: "secondary_phone",
                    className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                    children: __("Secondary Phone", "yatra")
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Input,
                  {
                    id: "secondary_phone",
                    type: "tel",
                    value: formData.secondary_phone,
                    onChange: (e) => handleFieldChange("secondary_phone", e.target.value),
                    placeholder: __("+1234567890", "yatra")
                  }
                )
              ] })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-3", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "label",
                  {
                    htmlFor: "date_of_birth",
                    className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                    children: __("Date of Birth", "yatra")
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  DatePicker,
                  {
                    value: formData.date_of_birth,
                    onChange: (value) => handleFieldChange("date_of_birth", value),
                    placeholder: __("Select date of birth", "yatra")
                  }
                )
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "label",
                  {
                    htmlFor: "gender",
                    className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                    children: __("Gender", "yatra")
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsxs(
                  Select,
                  {
                    id: "gender",
                    value: formData.gender,
                    onChange: (e) => handleFieldChange("gender", e.target.value),
                    children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "", children: __("Select gender", "yatra") }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "male", children: __("Male", "yatra") }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "female", children: __("Female", "yatra") }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "other", children: __("Other", "yatra") }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "prefer_not_to_say", children: __("Prefer not to say", "yatra") })
                    ]
                  }
                )
              ] })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "label",
                {
                  htmlFor: "nationality",
                  className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                  children: __("Nationality", "yatra")
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Input,
                {
                  id: "nationality",
                  type: "text",
                  value: formData.nationality,
                  onChange: (e) => handleFieldChange("nationality", e.target.value),
                  placeholder: __("Enter nationality", "yatra")
                }
              )
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Address Information", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "label",
                {
                  htmlFor: "address",
                  className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                  children: __("Street Address", "yatra")
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Input,
                {
                  id: "address",
                  type: "text",
                  value: formData.address,
                  onChange: (e) => handleFieldChange("address", e.target.value),
                  placeholder: __("Enter street address", "yatra")
                }
              )
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-3", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "label",
                  {
                    htmlFor: "city",
                    className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                    children: __("City", "yatra")
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Input,
                  {
                    id: "city",
                    type: "text",
                    value: formData.city,
                    onChange: (e) => handleFieldChange("city", e.target.value),
                    placeholder: __("Enter city", "yatra")
                  }
                )
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "label",
                  {
                    htmlFor: "state",
                    className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                    children: __("State/Province", "yatra")
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Input,
                  {
                    id: "state",
                    type: "text",
                    value: formData.state,
                    onChange: (e) => handleFieldChange("state", e.target.value),
                    placeholder: __("Enter state", "yatra")
                  }
                )
              ] })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-3", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "label",
                  {
                    htmlFor: "country",
                    className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                    children: __("Country", "yatra")
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Input,
                  {
                    id: "country",
                    type: "text",
                    value: formData.country,
                    onChange: (e) => handleFieldChange("country", e.target.value),
                    placeholder: __("Enter country", "yatra")
                  }
                )
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "label",
                  {
                    htmlFor: "postal_code",
                    className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                    children: __("Postal Code", "yatra")
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Input,
                  {
                    id: "postal_code",
                    type: "text",
                    value: formData.postal_code,
                    onChange: (e) => handleFieldChange("postal_code", e.target.value),
                    placeholder: __("Enter postal code", "yatra")
                  }
                )
              ] })
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Emergency Contact", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "space-y-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-3 gap-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "label",
                {
                  htmlFor: "emergency_name",
                  className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                  children: __("Contact Name", "yatra")
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Input,
                {
                  id: "emergency_name",
                  type: "text",
                  value: formData.emergency_name,
                  onChange: (e) => handleFieldChange("emergency_name", e.target.value),
                  placeholder: __("Full name", "yatra")
                }
              )
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "label",
                {
                  htmlFor: "emergency_phone",
                  className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                  children: __("Contact Phone", "yatra")
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Input,
                {
                  id: "emergency_phone",
                  type: "tel",
                  value: formData.emergency_phone,
                  onChange: (e) => handleFieldChange("emergency_phone", e.target.value),
                  placeholder: __("+1234567890", "yatra")
                }
              )
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "label",
                {
                  htmlFor: "emergency_relationship",
                  className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                  children: __("Relationship", "yatra")
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Input,
                {
                  id: "emergency_relationship",
                  type: "text",
                  value: formData.emergency_relationship,
                  onChange: (e) => handleFieldChange(
                    "emergency_relationship",
                    e.target.value
                  ),
                  placeholder: __("e.g., Spouse, Parent", "yatra")
                }
              )
            ] })
          ] }) })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Special Requirements", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "label",
                {
                  htmlFor: "dietary_requirements",
                  className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                  children: __("Dietary Requirements", "yatra")
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Input,
                {
                  id: "dietary_requirements",
                  type: "text",
                  value: formData.dietary_requirements,
                  onChange: (e) => handleFieldChange(
                    "dietary_requirements",
                    e.target.value
                  ),
                  placeholder: __("e.g., Vegetarian, Gluten-free", "yatra")
                }
              )
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "label",
                {
                  htmlFor: "medical_conditions",
                  className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                  children: __("Medical Conditions", "yatra")
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "textarea",
                {
                  id: "medical_conditions",
                  value: formData.medical_conditions,
                  onChange: (e) => handleFieldChange("medical_conditions", e.target.value),
                  placeholder: __(
                    "Any relevant medical conditions",
                    "yatra"
                  ),
                  rows: 2,
                  className: "flex w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm ring-offset-white file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-gray-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 dark:border-gray-600 dark:bg-gray-800 dark:ring-offset-gray-900 dark:placeholder:text-gray-400 dark:focus-visible:ring-blue-400 resize-none"
                }
              )
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "label",
                {
                  htmlFor: "special_needs",
                  className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                  children: __("Special Needs", "yatra")
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "textarea",
                {
                  id: "special_needs",
                  value: formData.special_needs,
                  onChange: (e) => handleFieldChange("special_needs", e.target.value),
                  placeholder: __(
                    "Any special accommodations needed",
                    "yatra"
                  ),
                  rows: 2,
                  className: "flex w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm ring-offset-white file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-gray-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 dark:border-gray-600 dark:bg-gray-800 dark:ring-offset-gray-900 dark:placeholder:text-gray-400 dark:focus-visible:ring-blue-400 resize-none"
                }
              )
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Internal Notes", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            "textarea",
            {
              id: "notes",
              value: formData.notes,
              onChange: (e) => handleFieldChange("notes", e.target.value),
              placeholder: __(
                "Enter any internal notes about this customer (not visible to customer)",
                "yatra"
              ),
              rows: 4,
              className: "flex w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm ring-offset-white file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-gray-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 dark:border-gray-600 dark:bg-gray-800 dark:ring-offset-gray-900 dark:placeholder:text-gray-400 dark:focus-visible:ring-blue-400 resize-none"
            }
          ) })
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Status", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "space-y-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "label",
              {
                htmlFor: "status",
                className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                children: __("Customer Status", "yatra")
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              Select,
              {
                id: "status",
                value: formData.status,
                onChange: (e) => handleFieldChange("status", e.target.value),
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "active", children: __("Active", "yatra") }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "inactive", children: __("Inactive", "yatra") }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "blocked", children: __("Blocked", "yatra") })
                ]
              }
            )
          ] }) })
        ] }),
        isEditMode && /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Loyalty", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "label",
                {
                  htmlFor: "loyalty_tier",
                  className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                  children: __("Loyalty Tier", "yatra")
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsxs(
                Select,
                {
                  id: "loyalty_tier",
                  value: formData.loyalty_tier,
                  onChange: (e) => handleFieldChange("loyalty_tier", e.target.value),
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "bronze", children: __("🥉 Bronze", "yatra") }),
                    /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "silver", children: __("🥈 Silver", "yatra") }),
                    /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "gold", children: __("🥇 Gold", "yatra") }),
                    /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "platinum", children: __("💎 Platinum", "yatra") })
                  ]
                }
              )
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "label",
                {
                  htmlFor: "loyalty_points",
                  className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                  children: __("Loyalty Points", "yatra")
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Input,
                {
                  id: "loyalty_points",
                  type: "number",
                  min: 0,
                  value: formData.loyalty_points,
                  onChange: (e) => handleFieldChange(
                    "loyalty_points",
                    parseInt(e.target.value) || 0
                  )
                }
              )
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Preferences", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("label", { className: "flex items-center gap-2 cursor-pointer", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "input",
                {
                  type: "checkbox",
                  checked: formData.newsletter_optin,
                  onChange: (e) => handleFieldChange("newsletter_optin", e.target.checked),
                  className: "rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm text-gray-700 dark:text-gray-300", children: __("Subscribe to newsletter", "yatra") })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("label", { className: "flex items-center gap-2 cursor-pointer", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "input",
                {
                  type: "checkbox",
                  checked: formData.marketing_optin,
                  onChange: (e) => handleFieldChange("marketing_optin", e.target.checked),
                  className: "rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm text-gray-700 dark:text-gray-300", children: __("Receive marketing emails", "yatra") })
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
          errors.submit && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-2 text-sm text-red-500 bg-red-50 dark:bg-red-900/20 rounded-md", children: errors.submit }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              Button,
              {
                type: "submit",
                disabled: isSubmitting,
                className: "flex-1 flex items-center justify-center gap-2",
                children: isSubmitting ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(Loader2, { className: "w-4 h-4 animate-spin" }),
                  __("Saving...", "yatra")
                ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(Save, { className: "w-4 h-4" }),
                  isEditMode ? __("Update Customer", "yatra") : __("Create Customer", "yatra")
                ] })
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              Button,
              {
                type: "button",
                variant: "outline",
                onClick: handleCancel,
                disabled: isSubmitting,
                children: __("Cancel", "yatra")
              }
            )
          ] })
        ] }) }) })
      ] })
    ] }) }) })
  ] });
};
const CustomerSummaryCard = ({ customerId }) => {
  var _a, _b, _c, _d;
  const [includeSensitive, setIncludeSensitive] = reactExports.useState(false);
  const [summary, setSummary] = reactExports.useState(null);
  const mutation = useMutation({
    mutationFn: () => aiApi.getCustomerSummary(customerId, includeSensitive),
    onSuccess: (resp) => {
      var _a2;
      setSummary(String(((_a2 = resp.data) == null ? void 0 : _a2.text) ?? "").trim());
    }
  });
  if (!isAiEligible() || !isAiModuleEnabled()) {
    return null;
  }
  const ready = isAiReady();
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start justify-between gap-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(CardTitle, { className: "flex items-center gap-2 text-base", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Sparkles, { className: "h-4 w-4 text-blue-600 dark:text-blue-300" }),
          __("AI Customer Summary", "yatra")
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-xs text-gray-500 dark:text-gray-400", children: __(
          "A 3-line operator-facing snapshot — status, last trip, anything notable for ops.",
          "yatra"
        ) })
      ] }),
      !summary && /* @__PURE__ */ jsxRuntimeExports.jsx(
        Button,
        {
          type: "button",
          size: "sm",
          onClick: () => mutation.mutate(),
          disabled: mutation.isPending || !ready,
          className: "bg-blue-600 text-white hover:bg-blue-700",
          children: mutation.isPending ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Loader2, { className: "mr-2 h-3.5 w-3.5 animate-spin" }),
            __("Generating…", "yatra")
          ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Sparkles, { className: "mr-1.5 h-3.5 w-3.5" }),
            __("Generate summary", "yatra")
          ] })
        }
      )
    ] }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3", children: [
      !ready && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "rounded-md border border-amber-200 bg-amber-50/40 p-3 text-xs text-amber-800 dark:border-amber-500/40 dark:bg-amber-900/20 dark:text-amber-200", children: __(
        "Configure an AI provider key under Yatra → AI Assistant to enable this.",
        "yatra"
      ) }),
      !summary && /* @__PURE__ */ jsxRuntimeExports.jsxs("label", { className: "flex cursor-pointer items-start gap-2 rounded-md border border-gray-200 p-2.5 text-xs hover:bg-gray-50 dark:border-gray-700 dark:hover:bg-gray-800/60", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "input",
          {
            type: "checkbox",
            checked: includeSensitive,
            onChange: (e) => setIncludeSensitive(e.target.checked),
            className: "mt-0.5"
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1.5 font-medium text-gray-900 dark:text-white", children: [
            includeSensitive ? /* @__PURE__ */ jsxRuntimeExports.jsx(Shield, { className: "h-3.5 w-3.5 text-amber-500" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(ShieldOff, { className: "h-3.5 w-3.5 text-gray-400" }),
            __(
              "Include sensitive fields (medical, dietary, notes)",
              "yatra"
            )
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-0.5 text-gray-500 dark:text-gray-400", children: __(
            "Off by default. When on, the customer's health and preference details flow to the AI for this generation only.",
            "yatra"
          ) })
        ] })
      ] }),
      mutation.isError && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "rounded-md border border-red-200 bg-red-50 p-3 text-xs text-red-700 dark:border-red-500/40 dark:bg-red-900/20 dark:text-red-300", children: ((_c = (_b = (_a = mutation.error) == null ? void 0 : _a.response) == null ? void 0 : _b.data) == null ? void 0 : _c.message) || ((_d = mutation.error) == null ? void 0 : _d.message) || __("AI request failed.", "yatra") }),
      summary && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "whitespace-pre-wrap text-sm leading-relaxed text-gray-900 dark:text-white", children: summary }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex justify-end", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Button,
          {
            type: "button",
            variant: "ghost",
            size: "sm",
            onClick: () => {
              setSummary(null);
            },
            className: "text-xs text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200",
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(RefreshCw, { className: "mr-1.5 h-3 w-3" }),
              __("Regenerate", "yatra")
            ]
          }
        ) })
      ] })
    ] })
  ] });
};
const ViewCustomer = () => {
  var _a;
  const { can, isPro } = usePermissions();
  const baseAdminUrl = ((_a = window.yatraAdmin) == null ? void 0 : _a.adminUrl) || "";
  const customerId = reactExports.useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get("id") ? parseInt(params.get("id") || "0") : null;
  }, []);
  const {
    data: customer,
    isLoading,
    error
  } = useQuery({
    queryKey: ["customer", customerId],
    queryFn: async () => {
      if (!customerId) throw new Error("No customer ID");
      const response = await apiService.getCustomer(customerId);
      const data = (response == null ? void 0 : response.data) ?? response;
      const emergency = data.emergency_contact || {};
      return {
        ...data,
        emergency_name: data.emergency_name ?? emergency.name ?? null,
        emergency_phone: data.emergency_phone ?? emergency.phone ?? null,
        emergency_relationship: data.emergency_relationship ?? emergency.relationship ?? null
      };
    },
    enabled: !!customerId && can("yatra_view_customers")
  });
  const { data: bookings, isLoading: isLoadingBookings } = useQuery({
    queryKey: ["customer-bookings", customerId],
    queryFn: async () => {
      if (!customerId) return [];
      const json = await apiService.getCustomerBookings(customerId);
      if (Array.isArray(json)) {
        return json;
      }
      if (json && Array.isArray(json.data)) {
        return json.data;
      }
      return [];
    },
    enabled: !!customerId && can("yatra_view_bookings")
  });
  const formatDate2 = (dateString) => {
    return formatDate$1(dateString);
  };
  const formatShortDate = (dateString) => {
    return formatDate$1(dateString);
  };
  const formatPrice = (price, currencyCode = "USD") => formatYatraMoney(Number(price) || 0, currencyCode, {
    zeroAsUnknown: false
  });
  const getStatusBadge = (status) => {
    const statusMap = {
      active: {
        className: "bg-green-100 text-green-700 dark:bg-green-900/20 dark:text-green-400",
        label: __("Active", "yatra")
      },
      inactive: {
        className: "bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-400",
        label: __("Inactive", "yatra")
      },
      blocked: {
        className: "bg-red-100 text-red-700 dark:bg-red-900/20 dark:text-red-400",
        label: __("Blocked", "yatra")
      }
    };
    const statusInfo = statusMap[status] || {
      className: "bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-400",
      label: status
    };
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "span",
      {
        className: `inline-flex items-center px-3 py-1 rounded-md text-sm font-medium ${statusInfo.className}`,
        children: statusInfo.label
      }
    );
  };
  const getBookingStatusBadge = (status) => {
    const statusMap = {
      confirmed: {
        className: "bg-green-100 text-green-700 dark:bg-green-900/20 dark:text-green-400",
        label: __("Confirmed", "yatra")
      },
      completed: {
        className: "bg-blue-100 text-blue-700 dark:bg-blue-900/20 dark:text-blue-400",
        label: __("Completed", "yatra")
      },
      pending: {
        className: "bg-yellow-100 text-yellow-700 dark:bg-yellow-900/20 dark:text-yellow-400",
        label: __("Pending", "yatra")
      },
      cancelled: {
        className: "bg-red-100 text-red-700 dark:bg-red-900/20 dark:text-red-400",
        label: __("Cancelled", "yatra")
      }
    };
    const statusInfo = statusMap[status] || {
      className: "bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-400",
      label: status
    };
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "span",
      {
        className: `inline-flex items-center px-2 py-1 rounded-md text-xs font-medium ${statusInfo.className}`,
        children: statusInfo.label
      }
    );
  };
  const getLoyaltyBadge = (tier) => {
    const tierMap = {
      bronze: {
        className: "bg-amber-100 text-amber-700 dark:bg-amber-900/20 dark:text-amber-400",
        icon: "🥉"
      },
      silver: {
        className: "bg-gray-200 text-gray-700 dark:bg-gray-600 dark:text-gray-300",
        icon: "🥈"
      },
      gold: {
        className: "bg-yellow-100 text-yellow-700 dark:bg-yellow-900/20 dark:text-yellow-400",
        icon: "🥇"
      },
      platinum: {
        className: "bg-purple-100 text-purple-700 dark:bg-purple-900/20 dark:text-purple-400",
        icon: "💎"
      }
    };
    const tierInfo = tierMap[tier] || tierMap["bronze"];
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "span",
      {
        className: `inline-flex items-center gap-1 px-3 py-1 rounded-md text-sm font-medium ${tierInfo.className}`,
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: tierInfo.icon }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "capitalize", children: tier })
        ]
      }
    );
  };
  const handleBack = () => {
    window.location.href = `${baseAdminUrl}?page=yatra&subpage=customers`;
  };
  const handleEdit = () => {
    window.location.href = `${baseAdminUrl}?page=yatra&subpage=customers&action=edit&id=${customerId}`;
  };
  const handleViewBooking = (bookingId) => {
    window.location.href = `${baseAdminUrl}?page=yatra&subpage=bookings&action=view&id=${bookingId}`;
  };
  const renderSkeleton = () => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-3 gap-3", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "lg:col-span-2 space-y-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-5 w-40" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-6 w-16 rounded" })
      ] }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-4", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-6 w-48" }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-2 gap-4", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-3 w-20" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-4 w-36" })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-3 w-20" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-4 w-28" })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-3 w-16" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-4 w-64" })
        ] })
      ] })
    ] }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-5 w-24" }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-3 w-20" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-8 w-12" })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-3 w-20" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-8 w-20" })
        ] })
      ] })
    ] }) })
  ] });
  if (isLoading) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        PageHeader,
        {
          title: __("Customer Details", "yatra"),
          description: __("Loading...", "yatra"),
          actions: /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Button,
            {
              variant: "outline",
              onClick: handleBack,
              className: "flex items-center gap-2",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowLeft, { className: "w-4 h-4" }),
                __("Back", "yatra")
              ]
            }
          )
        }
      ),
      renderSkeleton()
    ] });
  }
  if (error || !customer) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        PageHeader,
        {
          title: __("Customer Not Found", "yatra"),
          description: __(
            "The customer you are looking for does not exist",
            "yatra"
          ),
          actions: /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Button,
            {
              variant: "outline",
              onClick: handleBack,
              className: "flex items-center gap-2",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowLeft, { className: "w-4 h-4" }),
                __("Back to Customers", "yatra")
              ]
            }
          )
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "p-8 text-center", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(AlertCircle, { className: "w-12 h-12 mx-auto mb-3 text-red-400" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-red-500", children: __("Error loading customer or customer not found", "yatra") })
      ] }) })
    ] });
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      PageHeader,
      {
        title: __("Customer Details", "yatra"),
        description: __("View complete customer information", "yatra"),
        actions: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_edit_customers", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(Button, { onClick: handleEdit, className: "flex items-center gap-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(PenSquare, { className: "w-4 h-4" }),
            __("Edit Customer", "yatra")
          ] }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Button,
            {
              variant: "outline",
              onClick: handleBack,
              className: "flex items-center gap-2",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowLeft, { className: "w-4 h-4" }),
                __("Back", "yatra")
              ]
            }
          )
        ] })
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_view_customers", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-3 gap-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "lg:col-span-2 space-y-3", children: [
        (customer == null ? void 0 : customer.id) && /* @__PURE__ */ jsxRuntimeExports.jsx(CustomerSummaryCard, { customerId: customer.id }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Customer Overview", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-2", children: [
              getStatusBadge(customer.status),
              getLoyaltyBadge(customer.loyalty_tier || "bronze")
            ] })
          ] }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-4", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1 flex items-center gap-1", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(User, { className: "w-3 h-3" }),
                __("Full Name", "yatra")
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-lg font-semibold text-gray-900 dark:text-white", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                "a",
                {
                  href: `${baseAdminUrl}?page=yatra&subpage=customers&action=view&id=${customer.id}`,
                  className: "hover:underline text-primary-600 dark:text-primary-400",
                  children: customer.name || `${customer.first_name} ${customer.last_name}`
                }
              ) })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-4", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1 flex items-center gap-1", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(Mail, { className: "w-3 h-3" }),
                  __("Email Address", "yatra")
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-900 dark:text-white", children: customer.email })
              ] }),
              customer.phone && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1 flex items-center gap-1", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(Phone, { className: "w-3 h-3" }),
                  __("Phone Number", "yatra")
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-sm text-gray-900 dark:text-white", children: [
                  customer.phone,
                  customer.secondary_phone && /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-gray-500 ml-2", children: [
                    "/ ",
                    customer.secondary_phone
                  ] })
                ] })
              ] })
            ] }),
            customer.address && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1 flex items-center gap-1", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(MapPin, { className: "w-3 h-3" }),
                __("Address", "yatra")
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-sm text-gray-900 dark:text-white", children: [
                customer.address,
                customer.city && `, ${customer.city}`,
                customer.state && `, ${customer.state}`,
                customer.postal_code && ` ${customer.postal_code}`
              ] })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-3 gap-4", children: [
              customer.country && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1 flex items-center gap-1", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(Globe, { className: "w-3 h-3" }),
                  __("Country", "yatra")
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-900 dark:text-white", children: customer.country })
              ] }),
              customer.nationality && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1", children: __("Nationality", "yatra") }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-900 dark:text-white", children: customer.nationality })
              ] }),
              customer.date_of_birth && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1", children: __("Date of Birth", "yatra") }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-900 dark:text-white", children: formatShortDate(customer.date_of_birth) })
              ] })
            ] })
          ] })
        ] }),
        customer.emergency_name && /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardTitle, { className: "text-base flex items-center gap-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(AlertCircle, { className: "w-4 h-4 text-red-500" }),
            __("Emergency Contact", "yatra")
          ] }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-3 gap-4", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1", children: __("Name", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-900 dark:text-white", children: customer.emergency_name })
            ] }),
            customer.emergency_phone && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1", children: __("Phone", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-900 dark:text-white", children: customer.emergency_phone })
            ] }),
            customer.emergency_relationship && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1", children: __("Relationship", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-900 dark:text-white", children: customer.emergency_relationship })
            ] })
          ] }) })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Booking History", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-0", children: isLoadingBookings ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-4 space-y-2", children: [...Array(3)].map((_, i) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-4", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-4 w-24" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-4 w-40" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-4 w-20" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-4 w-16" })
          ] }, i)) }) : !bookings || bookings.length === 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-8 text-center text-gray-500 dark:text-gray-400", children: __("No bookings yet", "yatra") }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(Table$1, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(TableHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(TableRow, { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(TableHead, { children: __("Reference", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(TableHead, { children: __("Trip", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(TableHead, { children: __("Travel Date", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(TableHead, { children: __("Amount", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(TableHead, { children: __("Status", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(TableHead, { className: "text-right", children: __("Actions", "yatra") })
            ] }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(TableBody, { children: bookings.map((booking) => /* @__PURE__ */ jsxRuntimeExports.jsxs(TableRow, { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(TableCell, { className: "font-medium text-gray-900 dark:text-white", children: booking.reference }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(TableCell, { className: "text-gray-900 dark:text-white", children: booking.trip_title }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(TableCell, { className: "text-gray-500 dark:text-gray-400 text-sm", children: formatShortDate(booking.travel_date) }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(TableCell, { className: "font-medium", children: formatPrice(
                booking.total_amount,
                booking.currency
              ) }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(TableCell, { children: getBookingStatusBadge(booking.status) }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(TableCell, { className: "text-right", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                Button,
                {
                  variant: "ghost",
                  size: "sm",
                  onClick: () => handleViewBooking(booking.id),
                  className: "h-8",
                  children: __("View", "yatra")
                }
              ) })
            ] }, booking.id)) })
          ] }) })
        ] }),
        customer.notes && /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardTitle, { className: "text-base flex items-center gap-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(FileText, { className: "w-4 h-4" }),
            __("Internal Notes", "yatra")
          ] }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { children: /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-700 dark:text-gray-300 whitespace-pre-wrap", children: customer.notes }) })
        ] }),
        (customer.dietary_requirements || customer.medical_conditions || customer.special_needs) && /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Special Requirements", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3", children: [
            customer.dietary_requirements && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1", children: __("Dietary Requirements", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-900 dark:text-white", children: customer.dietary_requirements })
            ] }),
            customer.medical_conditions && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1", children: __("Medical Conditions", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-900 dark:text-white", children: customer.medical_conditions })
            ] }),
            customer.special_needs && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1", children: __("Special Needs", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-900 dark:text-white", children: customer.special_needs })
            ] })
          ] })
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
        isPro && /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Statistics", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1 flex items-center gap-1", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Users, { className: "w-3 h-3" }),
                __("Total Bookings", "yatra")
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-2xl font-semibold text-gray-900 dark:text-white", children: customer.total_bookings || 0 })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1 flex items-center gap-1", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(DollarSign, { className: "w-3 h-3" }),
                __("Total Spent", "yatra")
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-2xl font-semibold text-gray-900 dark:text-white", children: formatPrice(customer.total_spent || 0) })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1 flex items-center gap-1", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Users, { className: "w-3 h-3" }),
                __("Total Travelers", "yatra")
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-2xl font-semibold text-gray-900 dark:text-white", children: customer.total_travelers || 0 })
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardTitle, { className: "text-base flex items-center gap-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Award, { className: "w-4 h-4" }),
            __("Loyalty", "yatra")
          ] }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1", children: __("Current Tier", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: getLoyaltyBadge(customer.loyalty_tier || "bronze") })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1", children: __("Points", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-xl font-semibold text-gray-900 dark:text-white", children: customer.loyalty_points || 0 })
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Timeline", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1 flex items-center gap-1", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Calendar$1, { className: "w-3 h-3" }),
                __("Registered", "yatra")
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-900 dark:text-white", children: formatDate2(customer.created_at) })
            ] }),
            customer.last_booking_date && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1", children: __("Last Booking", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-900 dark:text-white", children: formatShortDate(customer.last_booking_date) })
            ] }),
            customer.last_travel_date && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1", children: __("Last Travel", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-900 dark:text-white", children: formatShortDate(customer.last_travel_date) })
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Preferences", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between text-sm", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-600 dark:text-gray-400", children: __("Newsletter", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "span",
                {
                  className: customer.newsletter_optin ? "text-green-600" : "text-gray-400",
                  children: customer.newsletter_optin ? __("Subscribed", "yatra") : __("Not subscribed", "yatra")
                }
              )
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between text-sm", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-600 dark:text-gray-400", children: __("Marketing", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "span",
                {
                  className: customer.marketing_optin ? "text-green-600" : "text-gray-400",
                  children: customer.marketing_optin ? __("Opted in", "yatra") : __("Opted out", "yatra")
                }
              )
            ] })
          ] })
        ] })
      ] })
    ] }) })
  ] });
};
const Reviews = () => {
  const [searchTerm, setSearchTerm] = reactExports.useState("");
  const [statusFilter, setStatusFilter] = reactExports.useState("all");
  const [ratingFilter, setRatingFilter] = reactExports.useState("all");
  const [sortBy2, setSortBy] = reactExports.useState("created_at");
  const [sortOrder, setSortOrder] = reactExports.useState("desc");
  const [page, setPage] = reactExports.useState(1);
  const [deleteConfirm, setDeleteConfirm] = reactExports.useState({
    isOpen: false,
    review: null
  });
  const [selectedIds, setSelectedIds] = reactExports.useState([]);
  const [bulkAction, setBulkAction] = reactExports.useState("");
  const [showColumnsDropdown, setShowColumnsDropdown] = reactExports.useState(false);
  const [visibleColumns, setVisibleColumns] = reactExports.useState(() => {
    if (typeof window === "undefined") {
      return {
        trip: true,
        customer: true,
        rating: true,
        review: true,
        status: true,
        date: true
      };
    }
    const saved = window.localStorage.getItem("yatra-reviews-visible-columns");
    return saved ? JSON.parse(saved) : {
      trip: true,
      customer: true,
      rating: true,
      review: true,
      status: true,
      date: true
    };
  });
  const queryClient2 = useQueryClient();
  const { can } = usePermissions();
  const queryParams = reactExports.useMemo(() => {
    const params = {
      page,
      per_page: 10,
      orderby: sortBy2,
      order: sortOrder
    };
    if (searchTerm) {
      params.search = searchTerm;
    }
    if (statusFilter !== "all") {
      params.status = statusFilter;
    }
    if (ratingFilter !== "all") {
      params.rating = ratingFilter;
    }
    return params;
  }, [searchTerm, statusFilter, ratingFilter, sortBy2, sortOrder, page]);
  const { data, isLoading, error } = useQuery({
    queryKey: ["reviews", queryParams],
    queryFn: async () => {
      const response = await apiClient.get("/reviews", { params: queryParams });
      const reviews2 = ((response == null ? void 0 : response.data) || []).map((item) => ({
        id: item.id,
        trip_id: item.trip_id,
        trip_title: item.trip_title || "Unknown Trip",
        trip_slug: item.trip_slug || "",
        customer_name: item.customer_name || item.author_name || "Anonymous",
        customer_email: item.customer_email || item.author_email || "",
        rating: item.rating,
        title: item.title || "",
        comment: item.comment || item.content || "",
        status: item.status || "pending",
        verified: item.verified || false,
        created_at: item.created_at || ""
      }));
      return {
        data: reviews2,
        total: (response == null ? void 0 : response.total) || 0,
        page: (response == null ? void 0 : response.page) || page,
        per_page: (response == null ? void 0 : response.per_page) || 10
      };
    },
    enabled: can("yatra_view_reviews")
  });
  const deleteMutation = useMutation({
    mutationFn: async (id) => {
      return await apiClient.delete(`/reviews/${id}`);
    },
    onSuccess: () => {
      queryClient2.invalidateQueries({ queryKey: ["reviews"] });
    }
  });
  const reviews = (data == null ? void 0 : data.data) || [];
  const total = (data == null ? void 0 : data.total) || 0;
  const totalPages = Math.ceil(total / 10);
  const errorContext = getErrorContext(error);
  const formatDate2 = (dateString) => {
    return formatDate$1(dateString);
  };
  const renderStars = (rating) => {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-0.5", children: [
      [1, 2, 3, 4, 5].map((star2) => /* @__PURE__ */ jsxRuntimeExports.jsx(
        Star,
        {
          className: `w-4 h-4 ${star2 <= rating ? "fill-yellow-400 text-yellow-400" : "fill-gray-300 text-gray-300 dark:fill-gray-600 dark:text-gray-600"}`
        },
        star2
      )),
      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "ml-1 text-sm text-gray-600 dark:text-gray-400", children: rating })
    ] });
  };
  const getStatusBadge = (status) => {
    const statusMap = {
      approved: {
        className: "bg-green-100 text-green-700 dark:bg-green-900/20 dark:text-green-400",
        label: __("Approved", "yatra")
      },
      pending: {
        className: "bg-yellow-100 text-yellow-700 dark:bg-yellow-900/20 dark:text-yellow-400",
        label: __("Pending", "yatra")
      },
      spam: {
        className: "bg-red-100 text-red-700 dark:bg-red-900/20 dark:text-red-400",
        label: __("Spam", "yatra")
      },
      trash: {
        className: "bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-400",
        label: __("Trash", "yatra")
      }
    };
    const statusInfo = statusMap[status] || {
      className: "bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-400",
      label: status
    };
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "span",
      {
        className: `inline-flex items-center px-2 py-1 rounded-md text-xs font-medium ${statusInfo.className}`,
        children: statusInfo.label
      }
    );
  };
  const handleEdit = (review) => {
    var _a;
    window.location.href = `${((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=reviews&action=edit&id=${review.id}`;
  };
  const handleDelete = (review) => {
    setDeleteConfirm({ isOpen: true, review });
  };
  const confirmDelete = () => {
    if (deleteConfirm.review) {
      deleteMutation.mutate(deleteConfirm.review.id);
      setDeleteConfirm({ isOpen: false, review: null });
    }
  };
  const handleView = (review) => {
    var _a;
    window.location.href = `${((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=reviews&action=view&id=${review.id}`;
  };
  const handleCreateReview = () => {
    var _a;
    window.location.href = `${((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=reviews&action=create`;
  };
  const handleResetFilters = () => {
    setSearchTerm("");
    setStatusFilter("all");
    setRatingFilter("all");
    setSortBy("created_at");
    setSortOrder("desc");
    setPage(1);
  };
  const handleSort = (field) => {
    if (sortBy2 === field) {
      setSortOrder(sortOrder === "asc" ? "desc" : "asc");
    } else {
      setSortBy(field);
      setSortOrder("desc");
    }
  };
  const getSortIcon = (field) => {
    if (sortBy2 !== field) {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowUpDown, { className: "w-3.5 h-3.5 ml-1 text-gray-400" });
    }
    return sortOrder === "asc" ? /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowUp, { className: "w-3.5 h-3.5 ml-1 text-gray-600 dark:text-gray-300" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowDown, { className: "w-3.5 h-3.5 ml-1 text-gray-600 dark:text-gray-300" });
  };
  const hasFilters = searchTerm || statusFilter !== "all" || ratingFilter !== "all" || sortBy2 !== "created_at" || sortOrder !== "desc";
  const bulkActionOptions = reactExports.useMemo(() => {
    if (statusFilter === "trash") {
      return [{ value: "delete", label: __("Delete Permanently", "yatra") }];
    }
    if (statusFilter === "spam") {
      return [
        { value: "mark_trash", label: __("Move to Trash", "yatra") },
        { value: "delete", label: __("Delete Permanently", "yatra") }
      ];
    }
    return [
      { value: "mark_approved", label: __("Mark as Approved", "yatra") },
      { value: "mark_pending", label: __("Mark as Pending", "yatra") },
      { value: "mark_spam", label: __("Mark as Spam", "yatra") },
      { value: "mark_trash", label: __("Move to Trash", "yatra") },
      { value: "delete", label: __("Delete Permanently", "yatra") }
    ];
  }, [statusFilter]);
  const handleBulkApply = () => {
    if (!bulkAction || selectedIds.length === 0) {
      return;
    }
    const run = async () => {
      try {
        await apiService.bulkReviewsAction(bulkAction, selectedIds);
        queryClient2.invalidateQueries({ queryKey: ["reviews"] });
      } catch (error2) {
        console.error("Bulk review action error", error2);
      } finally {
        setSelectedIds([]);
        setBulkAction("");
      }
    };
    void run();
  };
  const toggleColumn = (columnKey) => {
    const newVisible = {
      ...visibleColumns,
      [columnKey]: !visibleColumns[columnKey]
    };
    setVisibleColumns(newVisible);
    if (typeof window !== "undefined") {
      window.localStorage.setItem(
        "yatra-reviews-visible-columns",
        JSON.stringify(newVisible)
      );
    }
  };
  const columnOptions = [
    { key: "trip", label: __("Trip", "yatra"), visible: visibleColumns.trip },
    {
      key: "customer",
      label: __("Customer", "yatra"),
      visible: visibleColumns.customer
    },
    {
      key: "rating",
      label: __("Rating", "yatra"),
      visible: visibleColumns.rating
    },
    {
      key: "review",
      label: __("Review", "yatra"),
      visible: visibleColumns.review
    },
    {
      key: "status",
      label: __("Status", "yatra"),
      visible: visibleColumns.status
    },
    { key: "date", label: __("Date", "yatra"), visible: visibleColumns.date }
  ];
  const handleApprove = async (review) => {
    await apiService.updateReviewStatus(review.id, "approved");
    queryClient2.invalidateQueries({ queryKey: ["reviews"] });
  };
  const handleMarkPending = async (review) => {
    await apiService.updateReviewStatus(review.id, "pending");
    queryClient2.invalidateQueries({ queryKey: ["reviews"] });
  };
  const handleMarkSpam = async (review) => {
    await apiService.updateReviewStatus(review.id, "spam");
    queryClient2.invalidateQueries({ queryKey: ["reviews"] });
  };
  const handleMarkTrash = async (review) => {
    await apiService.updateReviewStatus(review.id, "trash");
    queryClient2.invalidateQueries({ queryKey: ["reviews"] });
  };
  const actions = [
    {
      key: "view",
      label: __("View", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Eye, { className: "w-4 h-4" }),
      onClick: (review) => handleView(review),
      condition: () => can("yatra_view_reviews")
    },
    {
      key: "approve",
      label: __("Approve", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Star, { className: "w-4 h-4" }),
      onClick: (review) => handleApprove(review),
      condition: (review) => can("yatra_edit_reviews") && review.status !== "approved"
    },
    {
      key: "mark_pending",
      label: __("Mark as Pending", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(PenSquare, { className: "w-4 h-4" }),
      onClick: (review) => handleMarkPending(review),
      condition: (review) => can("yatra_edit_reviews") && review.status !== "pending"
    },
    {
      key: "edit",
      label: __("Edit", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(PenSquare, { className: "w-4 h-4" }),
      onClick: (review) => handleEdit(review),
      condition: () => can("yatra_edit_reviews")
    },
    {
      key: "mark_spam",
      label: __("Mark as Spam", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "w-4 h-4" }),
      onClick: (review) => handleMarkSpam(review),
      condition: (review) => can("yatra_edit_reviews") && review.status !== "spam"
    },
    {
      key: "mark_trash",
      label: __("Move to Trash", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "w-4 h-4" }),
      onClick: (review) => handleMarkTrash(review),
      condition: (review) => can("yatra_edit_reviews") && review.status !== "trash"
    },
    {
      key: "delete",
      label: __("Delete Permanently", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "w-4 h-4" }),
      onClick: (review) => handleDelete(review),
      variant: "destructive",
      condition: () => can("yatra_delete_reviews")
    }
  ];
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      ConfirmationDialog,
      {
        isOpen: deleteConfirm.isOpen,
        onClose: () => setDeleteConfirm({ isOpen: false, review: null }),
        onConfirm: confirmDelete,
        title: __("Delete Review", "yatra"),
        message: deleteConfirm.review ? __(
          'Are you sure you want to delete this review by "{name}"? This action cannot be undone.',
          "yatra"
        ).replace("{name}", deleteConfirm.review.customer_name) : __(
          "Are you sure you want to delete this review? This action cannot be undone.",
          "yatra"
        ),
        confirmText: __("Delete", "yatra"),
        cancelText: __("Cancel", "yatra"),
        variant: "danger",
        isLoading: deleteMutation.isPending
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      PageHeader,
      {
        title: __("Reviews", "yatra"),
        description: __("Manage customer reviews and ratings", "yatra"),
        actionCapability: "yatra_edit_reviews",
        actions: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Button,
          {
            onClick: handleCreateReview,
            className: "flex items-center gap-2",
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Plus, { className: "w-4 h-4" }),
              __("Add New Review", "yatra")
            ]
          }
        )
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col lg:flex-row gap-2 items-stretch lg:items-center", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative min-w-0 w-full lg:w-12 lg:flex-[2]", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Search, { className: "absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          Input,
          {
            type: "text",
            placeholder: __("Search reviews...", "yatra"),
            value: searchTerm,
            onChange: (e) => setSearchTerm(e.target.value),
            className: "pl-10 w-full"
          }
        )
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Select,
        {
          value: statusFilter,
          onChange: (e) => setStatusFilter(e.target.value),
          className: "w-full lg:flex-1",
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "all", children: __("All Status", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "approved", children: __("Approved", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "pending", children: __("Pending", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "spam", children: __("Spam", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "trash", children: __("Trash", "yatra") })
          ]
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Select,
        {
          value: ratingFilter,
          onChange: (e) => setRatingFilter(e.target.value),
          className: "w-full lg:flex-1",
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "all", children: __("All Ratings", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "5", children: __("5 Stars", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "4", children: __("4 Stars", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "3", children: __("3 Stars", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "2", children: __("2 Stars", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "1", children: __("1 Star", "yatra") })
          ]
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Select,
        {
          value: sortBy2,
          onChange: (e) => setSortBy(e.target.value),
          className: "w-full lg:flex-1",
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "created_at", children: __("Date", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "trip_title", children: __("Trip", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "customer_name", children: __("Customer", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "rating", children: __("Rating", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "status", children: __("Status", "yatra") })
          ]
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Button,
        {
          variant: "outline",
          onClick: () => setSortOrder(sortOrder === "asc" ? "desc" : "asc"),
          className: "h-11 px-4 flex items-center gap-1.5 flex-shrink-0",
          title: sortOrder === "asc" ? __("Ascending", "yatra") : __("Descending", "yatra"),
          children: [
            sortOrder === "asc" ? /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowUp, { className: "w-4 h-4" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowDown, { className: "w-4 h-4" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm", children: sortOrder === "asc" ? __("Asc", "yatra") : __("Desc", "yatra") })
          ]
        }
      ),
      hasFilters && /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Button,
        {
          variant: "outline",
          onClick: handleResetFilters,
          className: "flex items-center gap-2 h-11 flex-shrink-0",
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(X, { className: "w-4 h-4" }),
            __("Reset", "yatra")
          ]
        }
      )
    ] }) }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      BulkActionToolbar,
      {
        selectedIds,
        bulkAction,
        setBulkAction,
        onApply: handleBulkApply,
        onClearSelection: () => setSelectedIds([]),
        statusFilter,
        setStatusFilter: (value) => {
          setStatusFilter(value);
          setPage(1);
          setSelectedIds([]);
          setBulkAction("");
        },
        statusOptions: [
          { key: "all", label: __("All", "yatra"), count: total },
          {
            key: "approved",
            label: __("Approved", "yatra"),
            count: reviews.filter((r2) => r2.status === "approved").length
          },
          {
            key: "pending",
            label: __("Pending", "yatra"),
            count: reviews.filter((r2) => r2.status === "pending").length
          },
          {
            key: "spam",
            label: __("Spam", "yatra"),
            count: reviews.filter((r2) => r2.status === "spam").length
          },
          {
            key: "trash",
            label: __("Trash", "yatra"),
            count: reviews.filter((r2) => r2.status === "trash").length
          }
        ],
        showColumnsDropdown,
        setShowColumnsDropdown,
        columnOptions,
        onToggleColumn: toggleColumn,
        bulkMutationPending: deleteMutation.isPending,
        totalItems: reviews.length,
        bulkActionOptions
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-0 overflow-x-auto", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
      Table,
      {
        data: reviews,
        columns: [
          visibleColumns.trip && {
            key: "trip",
            label: __("Trip", "yatra"),
            render: (review) => {
              var _a;
              return review.trip_id ? /* @__PURE__ */ jsxRuntimeExports.jsx(
                "a",
                {
                  href: `${((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=trips&action=edit&id=${review.trip_id}`,
                  className: "font-medium text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300 hover:underline",
                  children: review.trip_title
                }
              ) : /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-medium text-gray-500 dark:text-gray-400", children: review.trip_title });
            }
          },
          visibleColumns.customer && {
            key: "customer",
            label: __("Customer", "yatra"),
            render: (review) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "font-medium text-gray-900 dark:text-white", children: review.customer_name }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-xs text-gray-500 dark:text-gray-400", children: review.customer_email }),
              review.verified && /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-blue-100 text-blue-700 dark:bg-blue-900/20 dark:text-blue-400 mt-1", children: __("Verified", "yatra") })
            ] })
          },
          visibleColumns.rating && {
            key: "rating",
            label: __("Rating", "yatra"),
            render: (review) => renderStars(review.rating)
          },
          visibleColumns.review && {
            key: "review",
            label: __("Review", "yatra"),
            render: (review) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "font-medium text-gray-900 dark:text-white mb-1", children: review.title }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-600 dark:text-gray-400 line-clamp-2", children: review.content })
            ] })
          },
          visibleColumns.status && {
            key: "status",
            label: __("Status", "yatra"),
            render: (review) => getStatusBadge(review.status)
          },
          visibleColumns.date && {
            key: "date",
            label: __("Date", "yatra"),
            render: (review) => /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-500 dark:text-gray-400 text-sm", children: formatDate2(review.created_at) })
          }
        ].filter(Boolean),
        actions,
        isLoading,
        isError: !!error,
        errorText: __("Error loading reviews", "yatra"),
        errorDescription: __(
          "We couldn’t connect to the reviews service. Please refresh or try again shortly.",
          "We couldn’t connect to the reviews service. Please refresh or try again shortly."
        ),
        onRetry: () => queryClient2.invalidateQueries({ queryKey: ["reviews"] }),
        errorDetails: errorContext.details,
        errorRequestInfo: errorContext.requestInfo,
        emptyText: __("No reviews found", "yatra"),
        emptyDescription: __(
          "When customers submit reviews, they will appear here.",
          "yatra"
        ),
        onSort: handleSort,
        getSortIcon,
        selectedItemIds: selectedIds,
        onSelectItem: (id, checked) => {
          if (checked) {
            setSelectedIds(
              (prev) => prev.includes(id) ? prev : [...prev, id]
            );
          } else {
            setSelectedIds(
              (prev) => prev.filter((existingId) => existingId !== id)
            );
          }
        },
        onSelectAll: (checked) => {
          if (checked) {
            setSelectedIds(reviews.map((r2) => r2.id));
          } else {
            setSelectedIds([]);
          }
        },
        isAllSelected: reviews.length > 0 && selectedIds.length === reviews.length,
        getItemId: (review) => review.id,
        capability: "yatra_view_reviews",
        skeletonRows: 5
      }
    ) }) }),
    total > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx(
      Pagination,
      {
        currentPage: page,
        totalPages,
        totalItems: total,
        itemsPerPage: 10,
        onPageChange: setPage,
        itemName: __("Review", "yatra")
      }
    )
  ] });
};
const ReviewForm = () => {
  const queryClient2 = useQueryClient();
  const { can } = usePermissions();
  const [formData, setFormData] = reactExports.useState({
    trip_id: "",
    customer_name: "",
    customer_email: "",
    rating: "5",
    title: "",
    comment: "",
    status: "pending",
    verified: false
  });
  const [errors, setErrors] = reactExports.useState({});
  const [isSubmitting, setIsSubmitting] = reactExports.useState(false);
  const action = reactExports.useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get("action") || "create";
  }, []);
  const reviewId = reactExports.useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get("id") ? parseInt(params.get("id") || "0") : null;
  }, []);
  const isEditMode = action === "edit" && reviewId !== null;
  const { data: tripsData } = useQuery({
    queryKey: ["trips-list"],
    queryFn: async () => {
      const response = await apiClient.get("/trips", {
        params: {
          per_page: 100,
          status: "all"
          // Get all trips including drafts
        }
      });
      const trips2 = ((response == null ? void 0 : response.data) || []).map((trip) => ({
        id: trip.id,
        title: trip.title || "Untitled Trip"
      }));
      return { data: trips2 };
    },
    enabled: can("yatra_view_trips")
  });
  const { data: reviewData, isLoading: isLoadingReview } = useQuery({
    queryKey: ["review", reviewId],
    queryFn: async () => {
      if (!reviewId) return null;
      const response = await apiClient.get(`/reviews/${reviewId}`);
      const review = (response == null ? void 0 : response.data) || response;
      return {
        id: review.id,
        trip_id: review.trip_id,
        customer_name: review.customer_name || review.author_name || "",
        customer_email: review.customer_email || review.author_email || "",
        rating: review.rating,
        title: review.title || "",
        comment: review.comment || review.content || "",
        status: review.status || "pending",
        verified: review.verified || false
      };
    },
    enabled: isEditMode && can("yatra_view_reviews")
  });
  reactExports.useEffect(() => {
    var _a, _b;
    if (reviewData && isEditMode) {
      setFormData({
        trip_id: ((_a = reviewData.trip_id) == null ? void 0 : _a.toString()) || "",
        customer_name: reviewData.customer_name || "",
        customer_email: reviewData.customer_email || "",
        rating: ((_b = reviewData.rating) == null ? void 0 : _b.toString()) || "5",
        title: reviewData.title || "",
        comment: reviewData.comment || "",
        status: reviewData.status || "pending",
        verified: reviewData.verified || false
      });
    }
  }, [reviewData, isEditMode]);
  const handleFieldChange = (field, value) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
    if (errors[field]) {
      setErrors((prev) => ({ ...prev, [field]: "" }));
    }
  };
  const renderStarRating = (rating) => {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1", children: [
      [1, 2, 3, 4, 5].map((star2) => /* @__PURE__ */ jsxRuntimeExports.jsx(
        "button",
        {
          type: "button",
          onClick: () => handleFieldChange("rating", star2.toString()),
          className: "focus:outline-none",
          children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            Star,
            {
              className: `w-6 h-6 transition-colors ${star2 <= rating ? "fill-yellow-400 text-yellow-400" : "fill-gray-300 text-gray-300 dark:fill-gray-600 dark:text-gray-600 hover:fill-yellow-200 hover:text-yellow-200"}`
            }
          )
        },
        star2
      )),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "ml-2 text-sm text-gray-600 dark:text-gray-400", children: [
        rating,
        " ",
        __("stars", "yatra")
      ] })
    ] });
  };
  const validateForm = () => {
    const newErrors = {};
    if (!formData.trip_id) {
      newErrors.trip_id = __("Trip is required", "yatra");
    }
    if (!formData.customer_name.trim()) {
      newErrors.customer_name = __("Customer name is required", "yatra");
    }
    if (!formData.customer_email.trim()) {
      newErrors.customer_email = __("Email is required", "yatra");
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.customer_email)) {
      newErrors.customer_email = __("Invalid email address", "yatra");
    }
    if (!formData.rating || parseInt(formData.rating) < 1 || parseInt(formData.rating) > 5) {
      newErrors.rating = __("Rating must be between 1 and 5", "yatra");
    }
    if (!formData.title.trim()) {
      newErrors.title = __("Review title is required", "yatra");
    }
    if (!formData.comment.trim()) {
      newErrors.comment = __("Review comment is required", "yatra");
    }
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };
  const saveMutation = useMutation({
    mutationFn: async (data) => {
      const payload = {
        trip_id: parseInt(data.trip_id),
        customer_name: data.customer_name.trim(),
        customer_email: data.customer_email.trim(),
        rating: parseInt(data.rating),
        title: data.title.trim(),
        comment: data.comment.trim(),
        status: data.status,
        verified: data.verified
      };
      if (isEditMode && reviewId) {
        return await apiClient.put(`/reviews/${reviewId}`, payload);
      } else {
        return await apiClient.post("/reviews", payload);
      }
    },
    onSuccess: () => {
      var _a;
      queryClient2.invalidateQueries({ queryKey: ["reviews"] });
      window.location.href = `${((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=reviews`;
    },
    onError: (error) => {
      const errorMessage = (error == null ? void 0 : error.message) || __("An error occurred while saving the review", "yatra");
      setErrors({ submit: errorMessage });
      setIsSubmitting(false);
    }
  });
  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!validateForm()) {
      return;
    }
    setIsSubmitting(true);
    setErrors({});
    saveMutation.mutate(formData);
  };
  const handleCancel = () => {
    var _a;
    window.location.href = `${((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=reviews`;
  };
  if (isEditMode && isLoadingReview) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-center p-8", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(Loader2, { className: "w-6 h-6 animate-spin text-gray-400" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "ml-2 text-gray-600 dark:text-gray-400", children: __("Loading review...", "yatra") })
    ] });
  }
  const trips = (tripsData == null ? void 0 : tripsData.data) || [];
  const currentRating = parseInt(formData.rating);
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      PageHeader,
      {
        title: isEditMode ? __("Edit Review", "yatra") : __("Add New Review", "yatra"),
        description: isEditMode ? __("Update review information", "yatra") : __("Create a new customer review", "yatra"),
        actions: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Button,
          {
            variant: "outline",
            onClick: handleCancel,
            className: "flex items-center gap-2",
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowLeft, { className: "w-4 h-4" }),
              __("Back", "yatra")
            ]
          }
        )
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_edit_reviews", children: /* @__PURE__ */ jsxRuntimeExports.jsx("form", { onSubmit: handleSubmit, children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-3 gap-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "lg:col-span-2 space-y-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Review Details", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs(
                "label",
                {
                  htmlFor: "trip_id",
                  className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                  children: [
                    __("Trip", "yatra"),
                    " ",
                    /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
                  ]
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsxs(
                Select,
                {
                  id: "trip_id",
                  value: formData.trip_id,
                  onChange: (e) => handleFieldChange("trip_id", e.target.value),
                  className: errors.trip_id ? "border-red-500" : "",
                  required: true,
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "", children: __("Select a trip", "yatra") }),
                    trips.map((trip) => /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: trip.id, children: trip.title }, trip.id))
                  ]
                }
              ),
              errors.trip_id && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm text-red-500", children: errors.trip_id })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5", children: [
                __("Rating", "yatra"),
                " ",
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
              ] }),
              renderStarRating(currentRating),
              errors.rating && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm text-red-500", children: errors.rating })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs(
                "label",
                {
                  htmlFor: "title",
                  className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                  children: [
                    __("Review Title", "yatra"),
                    " ",
                    /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
                  ]
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Input,
                {
                  id: "title",
                  type: "text",
                  value: formData.title,
                  onChange: (e) => handleFieldChange("title", e.target.value),
                  placeholder: __("Enter review title", "yatra"),
                  className: errors.title ? "border-red-500" : "",
                  required: true
                }
              ),
              errors.title && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm text-red-500", children: errors.title })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs(
                "label",
                {
                  htmlFor: "comment",
                  className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                  children: [
                    __("Review Comment", "yatra"),
                    " ",
                    /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
                  ]
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "textarea",
                {
                  id: "comment",
                  value: formData.comment,
                  onChange: (e) => handleFieldChange("comment", e.target.value),
                  placeholder: __("Enter review comment", "yatra"),
                  rows: 6,
                  className: `flex w-full rounded-md border ${errors.comment ? "border-red-500" : "border-gray-300"} bg-white px-3 py-2 text-sm ring-offset-white file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-gray-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 dark:border-gray-600 dark:bg-gray-800 dark:ring-offset-gray-900 dark:placeholder:text-gray-400 dark:focus-visible:ring-blue-400 resize-none`,
                  required: true
                }
              ),
              errors.comment && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm text-red-500", children: errors.comment })
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Customer Information", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "space-y-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs(
                "label",
                {
                  htmlFor: "customer_name",
                  className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                  children: [
                    __("Customer Name", "yatra"),
                    " ",
                    /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
                  ]
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Input,
                {
                  id: "customer_name",
                  type: "text",
                  value: formData.customer_name,
                  onChange: (e) => handleFieldChange("customer_name", e.target.value),
                  placeholder: __("Enter customer name", "yatra"),
                  className: errors.customer_name ? "border-red-500" : "",
                  required: true
                }
              ),
              errors.customer_name && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm text-red-500", children: errors.customer_name })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs(
                "label",
                {
                  htmlFor: "customer_email",
                  className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                  children: [
                    __("Customer Email", "yatra"),
                    " ",
                    /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
                  ]
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Input,
                {
                  id: "customer_email",
                  type: "email",
                  value: formData.customer_email,
                  onChange: (e) => handleFieldChange("customer_email", e.target.value),
                  placeholder: __("customer@example.com", "yatra"),
                  className: errors.customer_email ? "border-red-500" : "",
                  required: true
                }
              ),
              errors.customer_email && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm text-red-500", children: errors.customer_email })
            ] })
          ] }) })
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Status", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "label",
                {
                  htmlFor: "status",
                  className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                  children: __("Review Status", "yatra")
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsxs(
                Select,
                {
                  id: "status",
                  value: formData.status,
                  onChange: (e) => handleFieldChange("status", e.target.value),
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "pending", children: __("Pending", "yatra") }),
                    /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "approved", children: __("Approved", "yatra") }),
                    /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "spam", children: __("Spam", "yatra") }),
                    /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "trash", children: __("Trash", "yatra") })
                  ]
                }
              )
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "input",
                {
                  type: "checkbox",
                  id: "verified",
                  checked: formData.verified,
                  onChange: (e) => handleFieldChange("verified", e.target.checked),
                  className: "w-4 h-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "label",
                {
                  htmlFor: "verified",
                  className: "text-sm font-medium text-gray-700 dark:text-gray-300",
                  children: __("Verified Purchase", "yatra")
                }
              )
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
          errors.submit && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-2 text-sm text-red-500 bg-red-50 dark:bg-red-900/20 rounded-md", children: errors.submit }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              Button,
              {
                type: "submit",
                disabled: isSubmitting,
                className: "flex-1 flex items-center justify-center gap-2",
                children: isSubmitting ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(Loader2, { className: "w-4 h-4 animate-spin" }),
                  __("Saving...", "yatra")
                ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(Save, { className: "w-4 h-4" }),
                  isEditMode ? __("Update Review", "yatra") : __("Create Review", "yatra")
                ] })
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              Button,
              {
                type: "button",
                variant: "outline",
                onClick: handleCancel,
                disabled: isSubmitting,
                children: __("Cancel", "yatra")
              }
            )
          ] })
        ] }) }) })
      ] })
    ] }) }) })
  ] });
};
const ViewReview = () => {
  var _a;
  const { can } = usePermissions();
  const reviewId = reactExports.useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get("id") ? parseInt(params.get("id") || "0") : null;
  }, []);
  const {
    data: review,
    isLoading,
    error
  } = useQuery({
    queryKey: ["review", reviewId],
    queryFn: async () => {
      if (!reviewId) return null;
      const response = await apiClient.get(`/reviews/${reviewId}`);
      const data = (response == null ? void 0 : response.data) || response;
      return {
        id: data.id,
        trip_id: data.trip_id,
        trip_title: data.trip_title || "Unknown Trip",
        trip_slug: data.trip_slug || "",
        customer_name: data.customer_name || data.author_name || "Anonymous",
        customer_email: data.customer_email || data.author_email || "",
        customer_location: data.customer_location || data.author_location || "",
        rating: data.rating,
        title: data.title || "",
        content: data.content || "",
        status: data.status || "pending",
        verified: data.verified || false,
        created_at: data.created_at || "",
        updated_at: data.updated_at || ""
      };
    },
    enabled: !!reviewId && can("yatra_view_reviews")
  });
  const formatDate2 = (dateString) => {
    return new Date(dateString).toLocaleDateString("en-US", {
      weekday: "long",
      year: "numeric",
      month: "long",
      day: "numeric"
    });
  };
  const renderStars = (rating) => {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1", children: [
      [1, 2, 3, 4, 5].map((star2) => /* @__PURE__ */ jsxRuntimeExports.jsx(
        Star,
        {
          className: `w-6 h-6 ${star2 <= rating ? "fill-yellow-400 text-yellow-400" : "fill-gray-300 text-gray-300 dark:fill-gray-600 dark:text-gray-600"}`
        },
        star2
      )),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "ml-2 text-lg font-semibold text-gray-900 dark:text-white", children: [
        rating,
        " ",
        __("out of 5", "yatra")
      ] })
    ] });
  };
  const getStatusBadge = (status) => {
    const statusMap = {
      approved: {
        className: "bg-green-100 text-green-700 dark:bg-green-900/20 dark:text-green-400",
        label: __("Approved", "yatra")
      },
      pending: {
        className: "bg-yellow-100 text-yellow-700 dark:bg-yellow-900/20 dark:text-yellow-400",
        label: __("Pending", "yatra")
      },
      spam: {
        className: "bg-red-100 text-red-700 dark:bg-red-900/20 dark:text-red-400",
        label: __("Spam", "yatra")
      },
      trash: {
        className: "bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-400",
        label: __("Trash", "yatra")
      }
    };
    const statusInfo = statusMap[status] || {
      className: "bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-400",
      label: status
    };
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "span",
      {
        className: `inline-flex items-center px-3 py-1 rounded-md text-sm font-medium ${statusInfo.className}`,
        children: statusInfo.label
      }
    );
  };
  const handleBack = () => {
    var _a2;
    window.location.href = `${((_a2 = window.yatraAdmin) == null ? void 0 : _a2.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=reviews`;
  };
  const handleEdit = () => {
    var _a2;
    window.location.href = `${((_a2 = window.yatraAdmin) == null ? void 0 : _a2.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=reviews&action=edit&id=${reviewId}`;
  };
  if (isLoading) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        PageHeader,
        {
          title: __("Review Details", "yatra"),
          description: __("View complete review information", "yatra"),
          actions: /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Button,
            {
              variant: "outline",
              onClick: handleBack,
              className: "flex items-center gap-2",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowLeft, { className: "w-4 h-4" }),
                __("Back", "yatra")
              ]
            }
          )
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-3 gap-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "lg:col-span-2 space-y-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-5 w-32 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-6 w-20 bg-gray-200 dark:bg-gray-700 rounded-full animate-pulse" })
          ] }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-4", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-3 w-12 bg-gray-200 dark:bg-gray-700 rounded animate-pulse mb-2" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-6 w-48 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-3 w-12 bg-gray-200 dark:bg-gray-700 rounded animate-pulse mb-2" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex gap-1", children: [...Array(5)].map((_, i) => /* @__PURE__ */ jsxRuntimeExports.jsx(
                "div",
                {
                  className: "h-6 w-6 bg-gray-200 dark:bg-gray-700 rounded animate-pulse"
                },
                i
              )) })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-3 w-20 bg-gray-200 dark:bg-gray-700 rounded animate-pulse mb-2" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-6 w-64 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-3 w-24 bg-gray-200 dark:bg-gray-700 rounded animate-pulse mb-2" }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 w-full bg-gray-200 dark:bg-gray-700 rounded animate-pulse" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 w-full bg-gray-200 dark:bg-gray-700 rounded animate-pulse" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 w-3/4 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" })
              ] })
            ] })
          ] })
        ] }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-5 w-40 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-3 w-24 bg-gray-200 dark:bg-gray-700 rounded animate-pulse mb-1" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 w-32 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-3 w-24 bg-gray-200 dark:bg-gray-700 rounded animate-pulse mb-1" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 w-40 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" })
              ] })
            ] })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-5 w-20 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "space-y-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-3 w-16 bg-gray-200 dark:bg-gray-700 rounded animate-pulse mb-1" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 w-36 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" })
            ] }) })
          ] })
        ] })
      ] })
    ] });
  }
  if (error || !review) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        PageHeader,
        {
          title: __("Review Not Found", "yatra"),
          description: __(
            "The review you are looking for does not exist",
            "yatra"
          ),
          actions: /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Button,
            {
              variant: "outline",
              onClick: handleBack,
              className: "flex items-center gap-2",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowLeft, { className: "w-4 h-4" }),
                __("Back to Reviews", "yatra")
              ]
            }
          )
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-8 text-center text-red-500", children: __("Error loading review or review not found", "yatra") }) })
    ] });
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      PageHeader,
      {
        title: __("Review Details", "yatra"),
        description: __("View complete review information", "yatra"),
        actions: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_edit_reviews", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(Button, { onClick: handleEdit, className: "flex items-center gap-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(PenSquare, { className: "w-4 h-4" }),
            __("Edit Review", "yatra")
          ] }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Button,
            {
              variant: "outline",
              onClick: handleBack,
              className: "flex items-center gap-2",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowLeft, { className: "w-4 h-4" }),
                __("Back", "yatra")
              ]
            }
          )
        ] })
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_view_reviews", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-3 gap-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "lg:col-span-2 space-y-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Review Overview", "yatra") }),
          getStatusBadge(review.status)
        ] }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-4", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1", children: __("Trip", "yatra") }),
            review.trip_id ? /* @__PURE__ */ jsxRuntimeExports.jsx(
              "a",
              {
                href: `${((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=trips&action=edit&id=${review.trip_id}`,
                className: "text-lg font-semibold text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300 hover:underline",
                children: review.trip_title
              }
            ) : /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-lg font-semibold text-gray-900 dark:text-white", children: review.trip_title })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-2", children: __("Rating", "yatra") }),
            renderStars(review.rating)
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1", children: __("Review Title", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-lg font-semibold text-gray-900 dark:text-white", children: review.title })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-2", children: __("Review Comment", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-700 dark:text-gray-300 whitespace-pre-wrap leading-relaxed", children: review.content })
          ] })
        ] })
      ] }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Customer Information", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1", children: __("Customer Name", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm font-medium text-gray-900 dark:text-white", children: review.customer_name })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1 flex items-center gap-1", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Mail, { className: "w-3 h-3" }),
                __("Email Address", "yatra")
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-900 dark:text-white", children: review.customer_email || /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-400", children: __("Not provided", "yatra") }) })
            ] }),
            review.customer_location && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1 flex items-center gap-1", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(MapPin, { className: "w-3 h-3" }),
                __("Location", "yatra")
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-900 dark:text-white", children: review.customer_location })
            ] }),
            review.verified && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "inline-flex items-center px-2 py-1 rounded-md text-xs font-medium bg-blue-100 text-blue-700 dark:bg-blue-900/20 dark:text-blue-400", children: __("Verified Purchase", "yatra") }) })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Timeline", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1 flex items-center gap-1", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Calendar$1, { className: "w-3 h-3" }),
                __("Created", "yatra")
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-900 dark:text-white", children: formatDate2(review.created_at) })
            ] }),
            review.updated_at && review.updated_at !== review.created_at && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1", children: __("Last Updated", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-900 dark:text-white", children: formatDate2(review.updated_at) })
            ] })
          ] })
        ] })
      ] })
    ] }) })
  ] });
};
const MIGRATION_NOTICE_KEY = "yatra_migration_notice_dismissed_at";
const Tools = () => {
  var _a, _b, _c;
  const [activeTab, setActiveTab] = reactExports.useState("export-import");
  const [isExporting, setIsExporting] = reactExports.useState(false);
  const [isImporting, setIsImporting] = reactExports.useState(false);
  const [selectedExportData, setSelectedExportData] = reactExports.useState([
    "trips",
    "destinations",
    "activities",
    "bookings",
    "customers"
  ]);
  const [selectedImportData, setSelectedImportData] = reactExports.useState([]);
  const [isDragOver, setIsDragOver] = reactExports.useState(false);
  const [showExportModal, setShowExportModal] = reactExports.useState(false);
  const [showImportModal, setShowImportModal] = reactExports.useState(false);
  const [showDeleteModal, setShowDeleteModal] = reactExports.useState(false);
  const [showClearLogsModal, setShowClearLogsModal] = reactExports.useState(false);
  const [pendingImportFile, setPendingImportFile] = reactExports.useState(null);
  const [systemStatus, setSystemStatus] = reactExports.useState(null);
  const [logs, setLogs] = reactExports.useState({});
  const [selectedLogType, setSelectedLogType] = reactExports.useState("error");
  const [isLoadingStatus, setIsLoadingStatus] = reactExports.useState(false);
  const [isLoadingLogs, setIsLoadingLogs] = reactExports.useState(false);
  const [isLoadingJobs, setIsLoadingJobs] = reactExports.useState(false);
  const [allJobs, setAllJobs] = reactExports.useState([]);
  const [isClearingCache, setIsClearingCache] = reactExports.useState(false);
  const [showCacheModal, setShowCacheModal] = reactExports.useState(false);
  const [cacheData, setCacheData] = reactExports.useState([]);
  const [isLoadingCache, setIsLoadingCache] = reactExports.useState(false);
  const [cronJobs, setCronJobs] = reactExports.useState([]);
  const [cronInfo, setCronInfo] = reactExports.useState(null);
  const [isLoadingCronJobs, setIsLoadingCronJobs] = reactExports.useState(false);
  const [runningCronJob, setRunningCronJob] = reactExports.useState(null);
  const [migrationStatus, setMigrationStatus] = reactExports.useState(null);
  const [isLoadingMigration, setIsLoadingMigration] = reactExports.useState(false);
  const [migrationProgress, setMigrationProgress] = reactExports.useState(null);
  const [isMigrating, setIsMigrating] = reactExports.useState(false);
  const [isStartingMigration, setIsStartingMigration] = reactExports.useState(false);
  const migrationPollingRef = reactExports.useRef(
    null
  );
  const [showMigrationConfirm, setShowMigrationConfirm] = reactExports.useState(false);
  const [showMigrationCompleteNotice, setShowMigrationCompleteNotice] = reactExports.useState(true);
  const [isImportingSampleData, setIsImportingSampleData] = reactExports.useState(false);
  const [sampleDataStatus, setSampleDataStatus] = reactExports.useState(null);
  const [sampleDataJob, setSampleDataJob] = reactExports.useState(null);
  const { showToast } = useToast();
  reactExports.useEffect(() => {
    const allowed = /* @__PURE__ */ new Set([
      "export-import",
      "jobs",
      "system-status",
      "logs",
      "migration"
    ]);
    try {
      const params = new URLSearchParams(window.location.search);
      const t = params.get("tools_tab");
      if (t && allowed.has(t)) {
        setActiveTab(t);
      }
    } catch {
    }
  }, []);
  const formatBytes = (bytes) => {
    if (bytes === 0) return "0 Bytes";
    const k2 = 1024;
    const sizes = ["Bytes", "KB", "MB", "GB"];
    const i = Math.floor(Math.log(bytes) / Math.log(k2));
    return parseFloat((bytes / Math.pow(k2, i)).toFixed(2)) + " " + sizes[i];
  };
  reactExports.useEffect(() => {
    if (!(migrationProgress == null ? void 0 : migrationProgress.started_at) || !(migrationProgress == null ? void 0 : migrationProgress.all_complete)) {
      setShowMigrationCompleteNotice(false);
      if (typeof window !== "undefined") {
        window.localStorage.removeItem(MIGRATION_NOTICE_KEY);
      }
      return;
    }
    if (typeof window === "undefined") {
      setShowMigrationCompleteNotice(true);
      return;
    }
    const dismissedAt = window.localStorage.getItem(MIGRATION_NOTICE_KEY);
    if (dismissedAt && dismissedAt === migrationProgress.started_at) {
      setShowMigrationCompleteNotice(false);
    } else {
      setShowMigrationCompleteNotice(true);
    }
  }, [migrationProgress == null ? void 0 : migrationProgress.started_at, migrationProgress == null ? void 0 : migrationProgress.all_complete]);
  reactExports.useEffect(() => {
    const loadSampleDataStatus = async () => {
      try {
        const status = await apiService.getSampleDataStatus();
        setSampleDataStatus(status);
      } catch (error) {
        console.error("Failed to load sample data status:", error);
      }
    };
    loadSampleDataStatus();
  }, []);
  const [exportJob, setExportJob] = reactExports.useState(null);
  const [importJob, setImportJob] = reactExports.useState(null);
  const pollingIntervalRef = reactExports.useRef(
    null
  );
  const logTypes = [
    { key: "error", label: "Error Logs", icon: XCircle },
    { key: "payment", label: "Payment Logs", icon: CheckCircle },
    { key: "booking", label: "Booking Logs", icon: FileText },
    { key: "system", label: "System Logs", icon: Server }
  ];
  const dataTypes = [
    {
      key: "all",
      label: "All Yatra data",
      description: "Complete backup: all tables, settings, itinerary, payments, and Pro data (if present)",
      icon: Database
    },
    {
      key: "trips",
      label: "Trips",
      description: "All trip packages, itineraries, and details",
      icon: MapPin
    },
    {
      key: "destinations",
      label: "Destinations",
      description: "Travel destinations and locations",
      icon: Globe
    },
    {
      key: "activities",
      label: "Activities",
      description: "Trip activities and experiences",
      icon: Activity
    },
    {
      key: "categories",
      label: "Trip Categories",
      description: "Trip categorization and taxonomy",
      icon: Folder
    },
    {
      key: "difficulty_levels",
      label: "Difficulty Levels",
      description: "Trip difficulty classifications",
      icon: Mountain
    },
    {
      key: "bookings",
      label: "Bookings",
      description: "Customer bookings and reservations",
      icon: Calendar$1
    },
    {
      key: "customers",
      label: "Customers",
      description: "Customer profiles and CRM data",
      icon: Users
    },
    {
      key: "travelers",
      label: "Travelers",
      description: "Individual traveler information",
      icon: UserCheck
    },
    {
      key: "payments",
      label: "Payments",
      description: "Payment transactions and history",
      icon: CreditCard
    },
    {
      key: "reviews",
      label: "Reviews",
      description: "Trip reviews and ratings",
      icon: Star
    },
    {
      key: "enquiries",
      label: "Enquiries",
      description: "Customer enquiries and leads",
      icon: MessageSquare
    },
    {
      key: "discounts",
      label: "Discounts",
      description: "Discount codes and promotions",
      icon: Tag
    },
    {
      key: "availability",
      label: "Availability",
      description: "Trip availability and schedules",
      icon: BarChart3
    },
    {
      key: "itinerary",
      label: "Itinerary Items",
      description: "Itinerary items and types",
      icon: List
    },
    {
      key: "settings",
      label: "Settings",
      description: "Plugin configuration and settings",
      icon: Settings$1
    }
  ];
  const loadSystemStatus = async () => {
    setIsLoadingStatus(true);
    try {
      const data = await apiService.getSystemStatus();
      setSystemStatus(data);
    } catch (error) {
      console.error("Failed to load system status:", error);
    } finally {
      setIsLoadingStatus(false);
    }
  };
  const loadActiveJobs = async () => {
    try {
      const jobs = await apiService.getActiveJobs();
      if (Array.isArray(jobs) && jobs.length > 0) {
        const exportJobData = jobs.find((j) => j.type === "export");
        const importJobData = jobs.find((j) => j.type === "import");
        if (exportJobData) {
          setExportJob(exportJobData);
          if (exportJobData.status === "pending" || exportJobData.status === "running") {
            setIsExporting(true);
            pollJobStatus(exportJobData.id, "export");
          }
        }
        if (importJobData) {
          setImportJob(importJobData);
          if (importJobData.status === "pending" || importJobData.status === "running") {
            setIsImporting(true);
            pollJobStatus(importJobData.id, "import");
          }
        }
      }
    } catch (error) {
      console.error("Failed to load active jobs:", error);
    }
  };
  reactExports.useEffect(() => {
    loadActiveJobs();
    if (activeTab === "system-status") {
      loadSystemStatus();
    }
  }, [activeTab]);
  const loadLogs = async (type, page = 1) => {
    setIsLoadingLogs(true);
    try {
      const data = await apiService.getLogs(type, page);
      if (data.logs && Array.isArray(data.logs)) {
        const logsData = data;
        setLogs((prev) => ({ ...prev, [type]: logsData }));
      }
    } catch (error) {
      console.error("Failed to load logs:", error);
    } finally {
      setIsLoadingLogs(false);
    }
  };
  const selectableDataTypes = dataTypes.filter((dt) => dt.key !== "all");
  const handleExportDataToggle = (dataType) => {
    if (dataType === "all") {
      setSelectedExportData((prev) => prev.includes("all") ? [] : ["all"]);
      return;
    }
    setSelectedExportData((prev) => {
      const withoutAll = prev.filter((t) => t !== "all");
      return withoutAll.includes(dataType) ? withoutAll.filter((t) => t !== dataType) : [...withoutAll, dataType];
    });
  };
  const handleExportSelectAll = () => {
    const keys2 = selectableDataTypes.map((dt) => dt.key);
    const allRegularSelected = keys2.length > 0 && keys2.every((k2) => selectedExportData.includes(k2)) && !selectedExportData.includes("all");
    const onlyAll = selectedExportData.length === 1 && selectedExportData.includes("all");
    if (allRegularSelected || onlyAll) {
      setSelectedExportData([]);
    } else {
      setSelectedExportData(keys2);
    }
  };
  const handleImportDataToggle = (dataType) => {
    if (dataType === "all") {
      setSelectedImportData((prev) => prev.includes("all") ? [] : ["all"]);
      return;
    }
    setSelectedImportData((prev) => {
      const withoutAll = prev.filter((t) => t !== "all");
      return withoutAll.includes(dataType) ? withoutAll.filter((t) => t !== dataType) : [...withoutAll, dataType];
    });
  };
  const handleImportSelectAll = () => {
    const keys2 = selectableDataTypes.map((dt) => dt.key);
    const allRegularSelected = keys2.length > 0 && keys2.every((k2) => selectedImportData.includes(k2)) && !selectedImportData.includes("all");
    const onlyAll = selectedImportData.length === 1 && selectedImportData.includes("all");
    if (allRegularSelected || onlyAll) {
      setSelectedImportData([]);
    } else {
      setSelectedImportData(keys2);
    }
  };
  const handleExportClick = () => {
    setShowExportModal(true);
  };
  const handleExport = async () => {
    if (selectedExportData.length === 0) {
      alert("Please select at least one data type to export.");
      return;
    }
    setIsExporting(true);
    setShowExportModal(false);
    try {
      const data = await apiService.createExportJob({
        data_types: selectedExportData
      });
      const jobId = data.job_id;
      pollJobStatus(jobId, "export");
    } catch (error) {
      console.error("Export error:", error);
      alert("Export failed. Please try again.");
      setIsExporting(false);
    }
  };
  const stopPolling = () => {
    if (pollingIntervalRef.current) {
      clearInterval(pollingIntervalRef.current);
      pollingIntervalRef.current = null;
    }
  };
  const pollJobStatus = (jobId, type) => {
    const endpoint = type === "export" ? "export-job" : "import-job";
    const poll = async () => {
      try {
        const jobData = await apiService.performJobAction(
          endpoint,
          jobId
        );
        if (jobData) {
          if (type === "export") {
            setExportJob(jobData);
          } else {
            setImportJob(jobData);
          }
          if (jobData.status === "completed" || jobData.status === "failed") {
            stopPolling();
            if (type === "export") {
              setIsExporting(false);
            } else {
              setIsImporting(false);
            }
            if (jobData.status === "failed") {
              alert(
                `${type === "export" ? "Export" : "Import"} failed: ${jobData.error || "Unknown error"}`
              );
            }
          }
        }
      } catch (error) {
        console.error("Failed to poll job status:", error);
      }
    };
    stopPolling();
    poll();
    pollingIntervalRef.current = setInterval(poll, 2e3);
  };
  const handleDownloadExport = async () => {
    if (!exportJob || exportJob.status !== "completed") return;
    try {
      const blob = await apiService.downloadExportJobBlob(exportJob.id);
      const url = window.URL.createObjectURL(blob);
      const a2 = document.createElement("a");
      a2.style.display = "none";
      a2.href = url;
      a2.download = `yatra-export-${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}.json`;
      document.body.appendChild(a2);
      a2.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a2);
      await apiService.deleteExportJob(exportJob.id);
      setExportJob(null);
    } catch (error) {
      console.error("Download error:", error);
      alert("Download failed. Please try again.");
    }
  };
  const handleDeleteClick = () => {
    if (!exportJob) return;
    setShowDeleteModal(true);
  };
  const handleCancelDelete = () => {
    setShowDeleteModal(false);
  };
  const handleConfirmDelete = async () => {
    if (!exportJob) return;
    setShowDeleteModal(false);
    try {
      await apiService.deleteExportJob(exportJob.id);
      setExportJob(null);
    } catch (error) {
      console.error("Delete error:", error);
      alert("Failed to delete export file.");
    }
  };
  reactExports.useEffect(() => {
    if (activeTab === "logs") {
      loadLogs(selectedLogType);
    }
  }, [activeTab, selectedLogType]);
  const processFile = async (file) => {
    if (selectedImportData.length === 0) {
      alert("Please select at least one data type to import.");
      return;
    }
    setIsImporting(true);
    try {
      const formData = new FormData();
      formData.append("file", file);
      formData.append("data_types", JSON.stringify(selectedImportData));
      const data = await apiService.createImportJob(formData);
      const jobId = data.job_id;
      pollJobStatus(jobId, "import");
      setSelectedImportData([]);
    } catch (error) {
      console.error("Import error:", error);
      alert("Import failed. Please check the file format and try again.");
      setIsImporting(false);
    }
  };
  const handleImport = async (event) => {
    var _a2;
    const file = (_a2 = event.target.files) == null ? void 0 : _a2[0];
    if (!file) return;
    setPendingImportFile(file);
    setShowImportModal(true);
    event.target.value = "";
  };
  const handleDragOver = (e) => {
    e.preventDefault();
    setIsDragOver(true);
  };
  const handleDragLeave = (e) => {
    e.preventDefault();
    setIsDragOver(false);
  };
  const handleDrop = async (e) => {
    e.preventDefault();
    setIsDragOver(false);
    const files = Array.from(e.dataTransfer.files);
    const jsonFile = files.find(
      (file) => file.type === "application/json" || file.name.endsWith(".json")
    );
    if (!jsonFile) {
      alert("Please drop a valid JSON file.");
      return;
    }
    setPendingImportFile(jsonFile);
    setShowImportModal(true);
  };
  const handleImportConfirm = async () => {
    if (!pendingImportFile) return;
    setShowImportModal(false);
    await processFile(pendingImportFile);
    setPendingImportFile(null);
    setSelectedImportData([]);
  };
  const handleClearLogs = () => {
    setShowClearLogsModal(true);
  };
  const confirmClearLogs = async () => {
    try {
      const data = await apiService.clearLogs(selectedLogType);
      if (data.success) {
        showToast(data.message || "Logs cleared successfully", "success");
        setLogs((prev) => ({
          ...prev,
          [selectedLogType]: {
            logs: [],
            total: 0,
            page: 1,
            per_page: 50,
            pages: 0
          }
        }));
      } else {
        showToast(data.message || "Failed to clear logs", "error");
      }
    } catch (error) {
      console.error("Failed to clear logs:", error);
      showToast("Failed to clear logs. Please try again.", "error");
    }
  };
  const copyLogToClipboard = async (log2) => {
    const logText = `[${log2.timestamp}] ${log2.level.toUpperCase()}: ${log2.message}${log2.context ? "\nContext: " + JSON.stringify(log2.context, null, 2) : ""}`;
    try {
      await navigator.clipboard.writeText(logText);
    } catch (error) {
      console.error("Failed to copy log:", error);
      const textArea = document.createElement("textarea");
      textArea.value = logText;
      document.body.appendChild(textArea);
      textArea.select();
      document.execCommand("copy");
      document.body.removeChild(textArea);
    }
  };
  const copyAllLogsToClipboard = async () => {
    const currentLogs = logs[selectedLogType];
    if (!(currentLogs == null ? void 0 : currentLogs.logs) || currentLogs.logs.length === 0) return;
    const allLogsText = currentLogs.logs.map(
      (log2) => `[${log2.timestamp}] ${log2.level.toUpperCase()}: ${log2.message}${log2.context ? "\nContext: " + JSON.stringify(log2.context, null, 2) : ""}`
    ).join("\n\n");
    try {
      await navigator.clipboard.writeText(allLogsText);
    } catch (error) {
      console.error("Failed to copy all logs:", error);
      const textArea = document.createElement("textarea");
      textArea.value = allLogsText;
      document.body.appendChild(textArea);
      textArea.select();
      document.execCommand("copy");
      document.body.removeChild(textArea);
    }
  };
  const handleImportSampleData = async () => {
    setIsImportingSampleData(true);
    setSampleDataJob({ progress: 0 });
    try {
      const response = await apiService.importSampleData({
        data_types: [],
        // Not used anymore - imports all data types
        overwrite: false
      });
      if (response.success) {
        setSampleDataJob({ ...response.data, progress: 100 });
        const data = response.data || {};
        const message2 = `Successfully imported: ${data.trips || 0} trips, ${data.classifications || 0} classifications, ${data.items || 0} items, ${data.trip_classifications || 0} trip assignments, ${data.discounts || 0} discounts, ${data.availability_dates || 0} availability dates, ${data.availability_rules || 0} rules, ${data.itinerary_days || 0} itinerary days, ${data.itinerary_entries || 0} itinerary entries`;
        showToast(message2, "success");
        const statusResponse = await apiService.getSampleDataStatus();
        setSampleDataStatus(statusResponse);
      } else {
        throw new Error(response.message || __("Import failed"));
      }
    } catch (error) {
      console.error("Sample data import error:", error);
      showToast(
        error.message || __("Failed to import sample data. Please try again."),
        "error"
      );
    } finally {
      setIsImportingSampleData(false);
      setTimeout(() => setSampleDataJob(null), 3e3);
    }
  };
  const getStatusBadge = (status) => {
    switch (status) {
      case "pass":
        return /* @__PURE__ */ jsxRuntimeExports.jsxs(Badge, { variant: "success", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CheckCircle, { className: "w-3 h-3 mr-1" }),
          "Pass"
        ] });
      case "warning":
        return /* @__PURE__ */ jsxRuntimeExports.jsxs(Badge, { variant: "warning", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(AlertCircle, { className: "w-3 h-3 mr-1" }),
          "Warning"
        ] });
      case "fail":
        return /* @__PURE__ */ jsxRuntimeExports.jsxs(Badge, { variant: "error", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(XCircle, { className: "w-3 h-3 mr-1" }),
          "Fail"
        ] });
      default:
        return /* @__PURE__ */ jsxRuntimeExports.jsx(Badge, { variant: "outline", children: "Unknown" });
    }
  };
  const getLogLevelBadge = (level) => {
    switch (level.toLowerCase()) {
      case "error":
        return /* @__PURE__ */ jsxRuntimeExports.jsx(Badge, { variant: "error", children: "Error" });
      case "warning":
        return /* @__PURE__ */ jsxRuntimeExports.jsx(Badge, { variant: "warning", children: "Warning" });
      case "info":
        return /* @__PURE__ */ jsxRuntimeExports.jsx(Badge, { variant: "info", children: "Info" });
      default:
        return /* @__PURE__ */ jsxRuntimeExports.jsx(Badge, { variant: "outline", children: level });
    }
  };
  const loadAllJobs = async () => {
    setIsLoadingJobs(true);
    try {
      const data = await apiService.getAllJobs();
      setAllJobs(Array.isArray(data) ? data : []);
    } catch (error) {
      console.error("Failed to load jobs:", error);
    } finally {
      setIsLoadingJobs(false);
    }
  };
  const loadCronJobs = async () => {
    setIsLoadingCronJobs(true);
    try {
      const data = await apiService.getCronJobs();
      setCronJobs((data == null ? void 0 : data.cron_jobs) || []);
      setCronInfo({
        wp_cron_disabled: (data == null ? void 0 : data.wp_cron_disabled) || false,
        alternate_cron: (data == null ? void 0 : data.alternate_cron) || false
      });
    } catch (error) {
      console.error("Failed to load cron jobs:", error);
    } finally {
      setIsLoadingCronJobs(false);
    }
  };
  const handleRunCronJob = async (hook) => {
    setRunningCronJob(hook);
    try {
      const data = await apiService.runCronJob(hook);
      if (data.success) {
        showToast(
          data.message || `Cron job "${hook}" executed successfully`,
          "success"
        );
        loadCronJobs();
      } else {
        showToast(data.message || "Failed to run cron job", "error");
      }
    } catch (error) {
      console.error("Failed to run cron job:", error);
      showToast("Failed to run cron job", "error");
    } finally {
      setRunningCronJob(null);
    }
  };
  const loadCacheData = async () => {
    setIsLoadingCache(true);
    try {
      const data = await apiService.getCacheView();
      if (data.success && data.data) {
        setCacheData(data.data.cache_data || []);
        showToast(data.message || "Cache data loaded successfully", "success");
      } else {
        showToast(data.message || "Failed to load cache data", "error");
      }
    } catch (error) {
      console.error("Failed to load cache data:", error);
      showToast("Failed to load cache data", "error");
    } finally {
      setIsLoadingCache(false);
    }
  };
  const clearCacheItem = async (key2, type) => {
    try {
      const data = await apiService.clearCacheItem(key2, type);
      if (data.success) {
        setCacheData((prev) => prev.filter((item) => item.key !== key2));
        showToast(
          data.message || `Cache item "${key2}" cleared successfully`,
          "success"
        );
      } else {
        showToast(data.message || "Failed to clear cache item", "error");
      }
    } catch (error) {
      console.error("Failed to clear cache item:", error);
      showToast("Failed to clear cache item", "error");
    }
  };
  const clearAllCache = async () => {
    setIsClearingCache(true);
    try {
      const data = await apiService.clearCache();
      if (window.yatraQueryClient && typeof window.yatraQueryClient.invalidateQueries === "function") {
        window.yatraQueryClient.invalidateQueries();
      }
      if (data.success) {
        showToast(
          "All caches cleared successfully! Please refresh the page to see the changes.",
          "success"
        );
      } else {
        let errorMessage = "Failed to clear caches";
        if (data.message && !data.message.includes("success")) {
          errorMessage += ": " + data.message;
        }
        showToast(errorMessage, "error");
      }
    } catch (error) {
      console.error("Failed to clear caches:", error);
      showToast("Failed to clear caches. Please try again.", "error");
    } finally {
      setIsClearingCache(false);
    }
  };
  const loadMigrationStatus = async () => {
    setIsLoadingMigration(true);
    try {
      const data = await apiService.getMigrationStatus();
      setMigrationStatus(data);
    } catch (error) {
      console.error("Failed to load migration status:", error);
      showToast("Failed to load migration status", "error");
    } finally {
      setIsLoadingMigration(false);
    }
  };
  const loadMigrationProgress = async () => {
    try {
      const data = await apiService.getMigrationProgress();
      setMigrationProgress(data);
      if (data.any_running && !data.all_complete) {
        setIsMigrating(true);
        if (!migrationPollingRef.current) {
          migrationPollingRef.current = setInterval(
            loadMigrationProgress,
            3e3
          );
        }
      } else if (data.all_complete && data.started_at) {
        setIsMigrating(false);
        stopMigrationPolling();
      }
    } catch (error) {
      console.error("Failed to load migration progress:", error);
    }
  };
  const startMigrationPolling = () => {
    if (migrationPollingRef.current) {
      clearInterval(migrationPollingRef.current);
    }
    loadMigrationProgress();
    migrationPollingRef.current = setInterval(loadMigrationProgress, 1e3);
  };
  const stopMigrationPolling = () => {
    if (migrationPollingRef.current) {
      clearInterval(migrationPollingRef.current);
      migrationPollingRef.current = null;
    }
  };
  const handleMigrateAll = async (force = false) => {
    setIsMigrating(true);
    setIsStartingMigration(true);
    try {
      const data = await apiService.runMigrationAll({ force });
      if (data.success) {
        showToast(
          "Migration started for all data types. Processing in background...",
          "success"
        );
        if (Array.isArray(data.warnings) && data.warnings.length > 0) {
          showToast(String(data.warnings[0]), "warning");
        }
        await loadMigrationProgress();
        startMigrationPolling();
        setIsStartingMigration(false);
      } else {
        showToast(data.error || data.message || "Migration failed", "error");
        setIsMigrating(false);
        setIsStartingMigration(false);
      }
    } catch (error) {
      console.error("Migration error:", error);
      showToast("Migration failed. Please try again.", "error");
      setIsMigrating(false);
      setIsStartingMigration(false);
    }
  };
  const handleCancelMigration = async () => {
    if (!confirm(
      "Are you sure you want to cancel the migration? This will stop all ongoing migrations."
    )) {
      return;
    }
    try {
      const data = await apiService.cancelMigration();
      if (data.success) {
        showToast("Migration cancelled successfully", "success");
        setIsMigrating(false);
        stopMigrationPolling();
        loadMigrationStatus();
      } else {
        showToast(data.error || "Failed to cancel migration", "error");
      }
    } catch (error) {
      console.error("Cancel migration error:", error);
      showToast("Failed to cancel migration", "error");
    }
  };
  reactExports.useEffect(() => {
    if (activeTab === "system-status") {
      loadSystemStatus();
    } else if (activeTab === "logs") {
      loadLogs(selectedLogType);
    } else if (activeTab === "jobs") {
      loadAllJobs();
      loadCronJobs();
    } else if (activeTab === "migration") {
      loadMigrationStatus();
      loadMigrationProgress();
    }
    return () => {
      if (activeTab === "migration") {
        stopMigrationPolling();
      }
    };
  }, [activeTab, selectedLogType]);
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between mb-6", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("h1", { className: "text-2xl font-bold text-gray-900 dark:text-white", children: "Tools" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-gray-600 dark:text-gray-400", children: "Export/Import data, check system status, and view logs" })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Button,
          {
            onClick: () => window.open("/wp-admin/admin.php?page=yatra-setup", "_blank"),
            variant: "outline",
            className: "flex items-center gap-2",
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Settings$1, { className: "w-4 h-4" }),
              "Setup Wizard"
            ]
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Button,
          {
            onClick: clearAllCache,
            variant: "outline",
            className: "flex items-center gap-2",
            disabled: isClearingCache,
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                RefreshCw,
                {
                  className: `w-4 h-4 ${isClearingCache ? "animate-spin" : ""}`
                }
              ),
              isClearingCache ? "Clearing..." : "Clear Cache"
            ]
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Button,
          {
            onClick: () => {
              setShowCacheModal(true);
              loadCacheData();
            },
            variant: "outline",
            className: "flex items-center gap-2",
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Eye, { className: "w-4 h-4" }),
              "View Cache"
            ]
          }
        )
      ] })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-6", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-1 mb-8", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("nav", { className: "flex space-x-1", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "button",
          {
            onClick: () => setActiveTab("export-import"),
            className: `flex-1 py-3 px-6 rounded-md font-medium text-sm flex items-center justify-center gap-3 transition-all duration-200 ${activeTab === "export-import" ? "bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-400 shadow-sm" : "text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-700/50"}`,
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Download, { className: "w-5 h-5" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: "Export/Import" })
            ]
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "button",
          {
            onClick: () => setActiveTab("jobs"),
            className: `flex-1 py-3 px-6 rounded-md font-medium text-sm flex items-center justify-center gap-3 transition-all duration-200 ${activeTab === "jobs" ? "bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-400 shadow-sm" : "text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-700/50"}`,
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(List, { className: "w-5 h-5" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: "Jobs" })
            ]
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "button",
          {
            onClick: () => setActiveTab("system-status"),
            className: `flex-1 py-3 px-6 rounded-md font-medium text-sm flex items-center justify-center gap-3 transition-all duration-200 ${activeTab === "system-status" ? "bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-400 shadow-sm" : "text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-700/50"}`,
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Server, { className: "w-5 h-5" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: "System Status" })
            ]
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "button",
          {
            onClick: () => setActiveTab("logs"),
            className: `flex-1 py-3 px-6 rounded-md font-medium text-sm flex items-center justify-center gap-3 transition-all duration-200 ${activeTab === "logs" ? "bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-400 shadow-sm" : "text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-700/50"}`,
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(FileText, { className: "w-5 h-5" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: "Logs" })
            ]
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "button",
          {
            onClick: () => setActiveTab("migration"),
            className: `flex-1 py-3 px-6 rounded-md font-medium text-sm flex items-center justify-center gap-3 transition-all duration-200 ${activeTab === "migration" ? "bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-400 shadow-sm" : "text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-700/50"}`,
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Database, { className: "w-5 h-5" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: "Migration" })
            ]
          }
        )
      ] }) }),
      activeTab === "export-import" && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-8", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-8", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { className: "p-8", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-4 mb-6", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-3 bg-blue-50 dark:bg-blue-900/20 rounded-lg", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Download, { className: "w-6 h-6 text-blue-600 dark:text-blue-400" }) }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-xl font-semibold text-gray-900 dark:text-white", children: "Export Data" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-500 dark:text-gray-400", children: "Download your data" })
              ] })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-gray-600 dark:text-gray-400 mb-6 leading-relaxed", children: "Export your Yatra data for backup or migration purposes. Click the button below to select which data types to export." }),
            exportJob && (exportJob.status === "pending" || exportJob.status === "running") && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mb-4 p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between mb-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm font-medium text-blue-700 dark:text-blue-400", children: exportJob.status === "pending" ? "Queued..." : "Exporting..." }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-sm text-blue-600 dark:text-blue-400", children: [
                  exportJob.progress,
                  "%"
                ] })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-full bg-blue-200 dark:bg-blue-800 rounded-full h-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                "div",
                {
                  className: "bg-blue-600 dark:bg-blue-400 h-2 rounded-full transition-all duration-300",
                  style: { width: `${exportJob.progress}%` }
                }
              ) }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "text-xs text-blue-600 dark:text-blue-400 mt-2", children: [
                exportJob.processed_records,
                " /",
                " ",
                exportJob.total_records,
                " records processed"
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400 mt-1", children: "Processing in background. You can close this page and come back later." })
            ] }),
            exportJob && exportJob.status === "completed" && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mb-4 p-4 bg-green-50 dark:bg-green-900/20 rounded-lg", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2 mb-3", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(CheckCircle, { className: "w-5 h-5 text-green-600 dark:text-green-400" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm font-medium text-green-700 dark:text-green-400", children: "Export completed successfully!" })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs(
                  Button,
                  {
                    onClick: handleDownloadExport,
                    className: "flex-1",
                    variant: "outline",
                    children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx(Download, { className: "w-4 h-4 mr-2" }),
                      "Download"
                    ]
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Button,
                  {
                    onClick: handleDeleteClick,
                    variant: "outline",
                    className: "text-red-600 hover:text-red-700 hover:bg-red-50 dark:text-red-400 dark:hover:bg-red-900/20",
                    children: /* @__PURE__ */ jsxRuntimeExports.jsx(XCircle, { className: "w-4 h-4" })
                  }
                )
              ] })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              Button,
              {
                onClick: handleExportClick,
                disabled: isExporting || !!(exportJob && (exportJob.status === "pending" || exportJob.status === "running")),
                className: "w-full py-3",
                size: "lg",
                children: isExporting ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(RefreshCw, { className: "w-5 h-5 mr-3 animate-spin" }),
                  "Starting export..."
                ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(Download, { className: "w-5 h-5 mr-3" }),
                  "Select Data Types to Export"
                ] })
              }
            )
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { className: "p-8", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-4 mb-6", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-3 bg-green-50 dark:bg-green-900/20 rounded-lg", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Upload, { className: "w-6 h-6 text-green-600 dark:text-green-400" }) }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-xl font-semibold text-gray-900 dark:text-white", children: "Import Data" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-500 dark:text-gray-400", children: "Restore from backup" })
              ] })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-gray-600 dark:text-gray-400 mb-6 leading-relaxed", children: "Import Yatra data from a previously exported JSON file. Drop your file below or click to browse." }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "div",
              {
                onDragOver: handleDragOver,
                onDragLeave: handleDragLeave,
                onDrop: handleDrop,
                className: `relative border-2 border-dashed rounded-lg p-8 text-center transition-all duration-200 ${isDragOver ? "border-green-400 bg-green-50 dark:bg-green-900/20" : "border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-800 hover:border-green-400 hover:bg-green-50 dark:hover:bg-green-900/20"} ${isImporting ? "pointer-events-none opacity-50" : ""}`,
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "input",
                    {
                      type: "file",
                      accept: ".json",
                      onChange: handleImport,
                      disabled: isImporting,
                      className: "absolute inset-0 w-full h-full opacity-0 cursor-pointer disabled:cursor-not-allowed"
                    }
                  ),
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col items-center gap-4", children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "div",
                      {
                        className: `p-4 rounded-full ${isDragOver ? "bg-green-100 dark:bg-green-900/30" : "bg-gray-100 dark:bg-gray-700"}`,
                        children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                          Upload,
                          {
                            className: `w-8 h-8 ${isDragOver ? "text-green-600 dark:text-green-400" : "text-gray-400 dark:text-gray-500"}`
                          }
                        )
                      }
                    ),
                    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-lg font-medium text-gray-900 dark:text-white mb-2", children: isDragOver ? "Drop your JSON file here" : "Drop JSON file or click to browse" }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-500 dark:text-gray-400", children: "Supports JSON files exported from Yatra" })
                    ] })
                  ] })
                ]
              }
            ),
            importJob && (importJob.status === "pending" || importJob.status === "running") && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-4 p-4 bg-green-50 dark:bg-green-900/20 rounded-lg", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between mb-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm font-medium text-green-700 dark:text-green-400", children: importJob.status === "pending" ? "Queued..." : "Importing..." }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-sm text-green-600 dark:text-green-400", children: [
                  importJob.progress,
                  "%"
                ] })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-full bg-green-200 dark:bg-green-800 rounded-full h-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                "div",
                {
                  className: "bg-green-600 dark:bg-green-400 h-2 rounded-full transition-all duration-300",
                  style: { width: `${importJob.progress}%` }
                }
              ) }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "text-xs text-green-600 dark:text-green-400 mt-2", children: [
                importJob.processed_records,
                " /",
                " ",
                importJob.total_records,
                " records processed"
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400 mt-1", children: "Processing in background. You can close this page and come back later." })
            ] }),
            importJob && importJob.status === "completed" && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-4 p-4 bg-green-50 dark:bg-green-900/20 rounded-lg", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2 mb-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(CheckCircle, { className: "w-5 h-5 text-green-600 dark:text-green-400" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm font-medium text-green-700 dark:text-green-400", children: "Import completed successfully!" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "button",
                  {
                    onClick: async () => {
                      if (!importJob) return;
                      try {
                        await apiService.deleteImportJob(importJob.id);
                      } catch (e) {
                        console.error("Error deleting import job:", e);
                      }
                      setImportJob(null);
                    },
                    className: "ml-auto text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300",
                    children: /* @__PURE__ */ jsxRuntimeExports.jsx(XCircle, { className: "w-4 h-4" })
                  }
                )
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-sm text-green-700 dark:text-green-400 mb-2", children: [
                "Total: ",
                /* @__PURE__ */ jsxRuntimeExports.jsx("strong", { children: importJob.processed_records }),
                " ",
                "records imported"
              ] }),
              importJob.import_stats && Object.keys(importJob.import_stats).length > 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-2 border-t border-green-200 dark:border-green-800 pt-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-xs font-medium text-green-700 dark:text-green-400 mb-2", children: "Import Details:" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid grid-cols-1 gap-1", children: Object.entries(importJob.import_stats).map(
                  ([dataType, stats]) => {
                    const dataTypeObj = dataTypes.find(
                      (dt) => dt.key === dataType
                    );
                    const Icon = (dataTypeObj == null ? void 0 : dataTypeObj.icon) || FileText;
                    return /* @__PURE__ */ jsxRuntimeExports.jsxs(
                      "div",
                      {
                        className: "flex items-center justify-between text-xs",
                        children: [
                          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1", children: [
                            /* @__PURE__ */ jsxRuntimeExports.jsx(Icon, { className: "w-3 h-3 text-green-600 dark:text-green-400" }),
                            /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "capitalize", children: [
                              dataType.replace("_", " "),
                              ":"
                            ] })
                          ] }),
                          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-green-700 dark:text-green-400", children: stats.imported }),
                            stats.failed > 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-red-600 dark:text-red-400 ml-1", children: [
                              "(",
                              stats.failed,
                              " failed)"
                            ] })
                          ] })
                        ]
                      },
                      dataType
                    );
                  }
                ) })
              ] })
            ] }),
            importJob && importJob.status === "failed" && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-4 p-4 bg-red-50 dark:bg-red-900/20 rounded-lg", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(XCircle, { className: "w-5 h-5 text-red-600 dark:text-red-400" }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-sm font-medium text-red-700 dark:text-red-400", children: [
                "Import failed: ",
                importJob.error || "Unknown error"
              ] })
            ] }) }),
            isImporting && !importJob && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-center gap-3 text-sm text-gray-600 dark:text-gray-400 bg-blue-50 dark:bg-blue-900/20 p-4 rounded-lg mt-4", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(RefreshCw, { className: "w-5 h-5 animate-spin" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: "Starting import..." })
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { className: "p-6 bg-yellow-50 dark:bg-yellow-900/20 border-yellow-200 dark:border-yellow-800", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start gap-4", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-2 bg-yellow-100 dark:bg-yellow-900/30 rounded-lg", children: /* @__PURE__ */ jsxRuntimeExports.jsx(AlertCircle, { className: "w-5 h-5 text-yellow-600 dark:text-yellow-400" }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("h4", { className: "font-semibold text-yellow-800 dark:text-yellow-200 mb-2", children: "Important Notice" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-yellow-700 dark:text-yellow-300 leading-relaxed", children: "Importing data will create new records. Existing data will not be overwritten. Always backup your database before importing data to prevent any potential data loss." })
          ] })
        ] }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { className: "p-8", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-4 mb-6", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-3 bg-purple-50 dark:bg-purple-900/20 rounded-lg", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Database, { className: "w-6 h-6 text-purple-600 dark:text-purple-400" }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-xl font-semibold text-gray-900 dark:text-white", children: "Import Sample Data" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-500 dark:text-gray-400", children: "Quick setup with demo content" })
            ] })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-gray-600 dark:text-gray-400 mb-6 leading-relaxed", children: "Quickly populate your Yatra site with sample trips, categories, destinations, and more. Perfect for testing and demonstration purposes." }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-4 mb-6", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4 mb-4", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("h4", { className: "font-semibold text-blue-900 dark:text-blue-100 mb-2 flex items-center gap-2", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(CheckCircle, { className: "w-4 h-4" }),
              "The following data will be imported automatically:"
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-2 text-sm text-blue-800 dark:text-blue-200", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(MapPin, { className: "w-4 h-4" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: "11 Sample Trips (multi-day & single-day)" })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Tag, { className: "w-4 h-4" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: "8 Categories" })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Activity, { className: "w-4 h-4" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: "10 Activities" })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Globe, { className: "w-4 h-4" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: "10 Destinations" })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Mountain, { className: "w-4 h-4" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: "6 Difficulty Levels" })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Settings$1, { className: "w-4 h-4" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: "8 Attributes" })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(List, { className: "w-4 h-4" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: "6 Itinerary Item Types" })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Users, { className: "w-4 h-4" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: "8 Traveler Categories" })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Tag, { className: "w-4 h-4" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: "8 Discount Codes" })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Calendar$1, { className: "w-4 h-4" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: "21 Availability Dates" })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(RefreshCw, { className: "w-4 h-4" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: "9 Availability Rules" })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(FileText, { className: "w-4 h-4" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: "31 Itinerary Days" })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(List, { className: "w-4 h-4" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: "25 Itinerary Entries" })
              ] })
            ] })
          ] }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex gap-3", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            Button,
            {
              onClick: handleImportSampleData,
              disabled: isImportingSampleData,
              className: "flex-1",
              size: "lg",
              children: isImportingSampleData ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(RefreshCw, { className: "w-5 h-5 mr-2 animate-spin" }),
                "Importing..."
              ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Download, { className: "w-5 h-5 mr-2" }),
                "Import Sample Data"
              ] })
            }
          ) })
        ] })
      ] }),
      activeTab === "system-status" && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-6", children: isLoadingStatus ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid grid-cols-1 lg:grid-cols-2 gap-6", children: [...Array(4)].map((_, index) => /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { className: "p-6", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-4", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-5 h-5 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-5 bg-gray-200 dark:bg-gray-700 rounded animate-pulse w-32" })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-3", children: [...Array(4)].map((_2, i) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "div",
          {
            className: "flex justify-between items-center",
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded animate-pulse w-24" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded animate-pulse w-16" })
            ]
          },
          i
        )) })
      ] }) }, index)) }) : systemStatus ? /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-2 gap-6", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { className: "p-6", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("h3", { className: "text-lg font-semibold mb-4 flex items-center gap-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Server, { className: "w-5 h-5" }),
            "PHP Information"
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-600 dark:text-gray-400", children: "Version:" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-medium", children: systemStatus.php.version })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-600 dark:text-gray-400", children: "Memory Limit:" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-medium", children: systemStatus.php.memory_limit })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-600 dark:text-gray-400", children: "Max Execution Time:" }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "font-medium", children: [
                systemStatus.php.max_execution_time,
                "s"
              ] })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-600 dark:text-gray-400", children: "Upload Max Size:" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-medium", children: systemStatus.php.upload_max_filesize })
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { className: "p-6", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-lg font-semibold mb-4", children: "WordPress Information" }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-600 dark:text-gray-400", children: "Version:" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-medium", children: systemStatus.wordpress.version })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-600 dark:text-gray-400", children: "Multisite:" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-medium", children: systemStatus.wordpress.multisite ? "Yes" : "No" })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-600 dark:text-gray-400", children: "Debug Mode:" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-medium", children: systemStatus.wordpress.debug_mode ? "Enabled" : "Disabled" })
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { className: "p-6", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-lg font-semibold mb-4", children: "Requirements Check" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-3", children: Object.entries(systemStatus.requirements).map(
            ([key2, req]) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "div",
              {
                className: "flex items-center justify-between",
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-medium capitalize", children: key2.replace("_", " ") }),
                    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-sm text-gray-600 dark:text-gray-400", children: [
                      "Required: ",
                      req.required,
                      " | Current: ",
                      req.current
                    ] })
                  ] }),
                  getStatusBadge(req.status)
                ]
              },
              key2
            )
          ) })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { className: "p-6", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-lg font-semibold mb-4", children: "PHP Extensions" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid grid-cols-2 gap-3", children: Object.entries(systemStatus.extensions).map(
            ([ext, loaded]) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "div",
              {
                className: "flex items-center justify-between",
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-medium", children: ext }),
                  loaded ? /* @__PURE__ */ jsxRuntimeExports.jsxs(Badge, { variant: "success", children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(CheckCircle, { className: "w-3 h-3 mr-1" }),
                    "Loaded"
                  ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(Badge, { variant: "error", children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(XCircle, { className: "w-3 h-3 mr-1" }),
                    "Missing"
                  ] })
                ]
              },
              ext
            )
          ) })
        ] })
      ] }) : /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { className: "p-6", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-center", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(XCircle, { className: "w-12 h-12 text-red-500 mx-auto mb-4" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { children: "Failed to load system status" }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Button, { onClick: loadSystemStatus, className: "mt-4", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(RefreshCw, { className: "w-4 h-4 mr-2" }),
          "Retry"
        ] })
      ] }) }) }),
      activeTab === "jobs" && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-6", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { className: "overflow-hidden", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-2 bg-purple-100 dark:bg-purple-900/30 rounded-lg", children: /* @__PURE__ */ jsxRuntimeExports.jsx(List, { className: "w-5 h-5 text-purple-600 dark:text-purple-400" }) }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-base font-semibold text-gray-900 dark:text-white", children: "Export & Import Jobs" }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "text-xs text-gray-500 dark:text-gray-400", children: [
                  allJobs.length,
                  " job",
                  allJobs.length !== 1 ? "s" : "",
                  " in history"
                ] })
              ] })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              Button,
              {
                variant: "outline",
                size: "sm",
                onClick: loadAllJobs,
                disabled: isLoadingJobs,
                children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                  RefreshCw,
                  {
                    className: `w-4 h-4 ${isLoadingJobs ? "animate-spin" : ""}`
                  }
                )
              }
            )
          ] }),
          isLoadingJobs ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-4 space-y-3", children: [...Array(3)].map((_, index) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "div",
            {
              className: "flex items-center justify-between py-3 animate-pulse",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3 flex-1", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-8 h-8 bg-gray-200 dark:bg-gray-700 rounded" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1", children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-32 h-4 bg-gray-200 dark:bg-gray-700 rounded mb-2" }),
                    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-48 h-3 bg-gray-200 dark:bg-gray-700 rounded" })
                  ] })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-20 h-6 bg-gray-200 dark:bg-gray-700 rounded" })
              ]
            },
            index
          )) }) : allJobs.length > 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "divide-y divide-gray-100 dark:divide-gray-800", children: allJobs.map((job) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "div",
            {
              className: "p-4 hover:bg-gray-50 dark:hover:bg-gray-800/50 transition-colors",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between gap-4", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3 min-w-0 flex-1", children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "div",
                      {
                        className: `p-2 rounded-lg flex-shrink-0 ${job.type === "export" ? "bg-blue-100 dark:bg-blue-900/30" : "bg-green-100 dark:bg-green-900/30"}`,
                        children: job.type === "export" ? /* @__PURE__ */ jsxRuntimeExports.jsx(Download, { className: "w-4 h-4 text-blue-600 dark:text-blue-400" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(Upload, { className: "w-4 h-4 text-green-600 dark:text-green-400" })
                      }
                    ),
                    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "min-w-0 flex-1", children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2 flex-wrap", children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "font-medium text-sm text-gray-900 dark:text-white", children: [
                          job.type === "export" ? "Export" : "Import",
                          " #",
                          job.id.slice(-6)
                        ] }),
                        /* @__PURE__ */ jsxRuntimeExports.jsxs(
                          "span",
                          {
                            className: `inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium ${job.status === "completed" ? "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400" : job.status === "running" ? "bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400" : job.status === "pending" ? "bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400" : "bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400"}`,
                            children: [
                              job.status === "running" && /* @__PURE__ */ jsxRuntimeExports.jsx(RefreshCw, { className: "w-3 h-3 mr-1 animate-spin" }),
                              job.status.charAt(0).toUpperCase() + job.status.slice(1)
                            ]
                          }
                        )
                      ] }),
                      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3 mt-1 text-xs text-gray-500 dark:text-gray-400", children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: new Date(job.created_at).toLocaleDateString() }),
                        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: "•" }),
                        /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { children: [
                          job.processed_records || 0,
                          "/",
                          job.total_records || 0,
                          " records"
                        ] }),
                        job.status === "running" && /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: "•" }),
                          /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-blue-600 dark:text-blue-400", children: [
                            job.progress,
                            "%"
                          ] })
                        ] })
                      ] })
                    ] })
                  ] }),
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2 flex-shrink-0", children: [
                    job.status === "running" && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-24 h-1.5 bg-gray-200 dark:bg-gray-700 rounded-full overflow-hidden", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "div",
                      {
                        className: "h-full bg-blue-500 rounded-full transition-all",
                        style: { width: `${job.progress}%` }
                      }
                    ) }),
                    job.type === "export" && job.status === "completed" && job.file_url && /* @__PURE__ */ jsxRuntimeExports.jsxs(
                      "a",
                      {
                        href: job.file_url,
                        download: true,
                        className: "text-xs font-medium text-blue-600 hover:text-blue-700 dark:text-blue-400 flex items-center gap-1",
                        children: [
                          /* @__PURE__ */ jsxRuntimeExports.jsx(Download, { className: "w-3 h-3" }),
                          "Download"
                        ]
                      }
                    )
                  ] })
                ] }),
                job.error && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-2 ml-11 p-2 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded text-xs text-red-700 dark:text-red-400", children: job.error })
              ]
            },
            job.id
          )) }) : /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-center py-8 px-4", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(List, { className: "w-10 h-10 text-gray-300 dark:text-gray-600 mx-auto mb-2" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-500 dark:text-gray-400", children: "No export/import jobs yet" })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { className: "overflow-hidden", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-2 bg-blue-100 dark:bg-blue-900/30 rounded-lg", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Activity, { className: "w-5 h-5 text-blue-600 dark:text-blue-400" }) }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-base font-semibold text-gray-900 dark:text-white", children: "Scheduled Tasks" }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "text-xs text-gray-500 dark:text-gray-400", children: [
                  cronJobs.length,
                  " active cron job",
                  cronJobs.length !== 1 ? "s" : ""
                ] })
              ] })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              Button,
              {
                variant: "outline",
                size: "sm",
                onClick: loadCronJobs,
                disabled: isLoadingCronJobs,
                children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                  RefreshCw,
                  {
                    className: `w-4 h-4 ${isLoadingCronJobs ? "animate-spin" : ""}`
                  }
                )
              }
            )
          ] }),
          (cronInfo == null ? void 0 : cronInfo.wp_cron_disabled) && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "px-4 py-3 bg-amber-50 dark:bg-amber-900/20 border-b border-amber-200 dark:border-amber-800", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(AlertTriangle, { className: "w-4 h-4 text-amber-600 dark:text-amber-400 flex-shrink-0" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm text-amber-800 dark:text-amber-400", children: "WP-Cron is disabled. A server-side cron is required." })
          ] }) }),
          isLoadingCronJobs ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-4 space-y-3", children: [...Array(3)].map((_, index) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "div",
            {
              className: "flex items-center justify-between py-3 animate-pulse",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-48 h-4 bg-gray-200 dark:bg-gray-700 rounded mb-2" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-32 h-3 bg-gray-200 dark:bg-gray-700 rounded" })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-20 h-8 bg-gray-200 dark:bg-gray-700 rounded" })
              ]
            },
            index
          )) }) : cronJobs.length > 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "divide-y divide-gray-100 dark:divide-gray-800", children: cronJobs.map((cron, index) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "div",
            {
              className: `flex items-center justify-between px-4 py-3 hover:bg-gray-50 dark:hover:bg-gray-800/50 transition-colors ${cron.is_overdue ? "bg-red-50/50 dark:bg-red-900/10" : ""}`,
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3 min-w-0 flex-1", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "div",
                    {
                      className: `w-2 h-2 rounded-full flex-shrink-0 ${cron.is_overdue ? "bg-red-500" : "bg-green-500"}`
                    }
                  ),
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "min-w-0 flex-1", children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2 flex-wrap", children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-medium text-sm text-gray-900 dark:text-white truncate", children: cron.hook.replace("yatra_", "").replace(/_/g, " ").replace(/\b\w/g, (l) => l.toUpperCase()) }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("code", { className: "text-xs font-mono text-gray-500 dark:text-gray-400 bg-gray-100 dark:bg-gray-700 px-1.5 py-0.5 rounded", children: cron.schedule || "once" }),
                      cron.is_overdue && /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400", children: "Overdue" })
                    ] }),
                    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3 mt-1 text-xs text-gray-500 dark:text-gray-400", children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsxs(
                        "span",
                        {
                          className: "flex items-center gap-1 cursor-help",
                          title: cron.next_run_formatted,
                          children: [
                            /* @__PURE__ */ jsxRuntimeExports.jsx(Calendar$1, { className: "w-3 h-3" }),
                            cron.next_run_relative
                          ]
                        }
                      ),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "hidden sm:inline", children: "•" }),
                      /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "hidden sm:flex items-center gap-1", children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsx(RefreshCw, { className: "w-3 h-3" }),
                        cron.schedule_label
                      ] })
                    ] }),
                    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-0.5 text-xs text-gray-400 dark:text-gray-500 font-mono", children: cron.hook })
                  ] })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Button,
                  {
                    variant: "ghost",
                    size: "sm",
                    onClick: () => handleRunCronJob(cron.hook),
                    disabled: runningCronJob === cron.hook,
                    className: "ml-2 text-blue-600 hover:text-blue-700 hover:bg-blue-50 dark:text-blue-400 dark:hover:bg-blue-900/20",
                    children: runningCronJob === cron.hook ? /* @__PURE__ */ jsxRuntimeExports.jsx(RefreshCw, { className: "w-4 h-4 animate-spin" }) : /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs font-medium", children: "Run" })
                  }
                )
              ]
            },
            `${cron.hook}-${index}`
          )) }) : /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-center py-8 px-4", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Activity, { className: "w-10 h-10 text-gray-300 dark:text-gray-600 mx-auto mb-2" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-500 dark:text-gray-400", children: "No scheduled tasks" })
          ] })
        ] })
      ] }),
      activeTab === "migration" && /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { className: "p-6", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between mb-6", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-2 bg-purple-100 dark:bg-purple-900/20 rounded-lg", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Database, { className: "w-5 h-5 text-purple-600 dark:text-purple-400" }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-lg font-semibold text-gray-900 dark:text-white", children: "Data Migration" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-500 dark:text-gray-400", children: "Migrate from Yatra 2.x to 3.0" })
            ] })
          ] }),
          (migrationStatus == null ? void 0 : migrationStatus.has_old_data) && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
            (isMigrating || isStartingMigration) && !(migrationProgress == null ? void 0 : migrationProgress.all_complete) && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "hidden sm:flex items-center gap-2 text-xs text-gray-600 dark:text-gray-300 mr-1", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(RefreshCw, { className: "w-4 h-4 animate-spin text-purple-600 dark:text-purple-400" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: "Migration running" })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              Button,
              {
                variant: "outline",
                size: "sm",
                onClick: () => {
                  loadMigrationStatus();
                  if (isMigrating) loadMigrationProgress();
                },
                disabled: (isMigrating || isStartingMigration) && !(migrationProgress == null ? void 0 : migrationProgress.all_complete),
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    RefreshCw,
                    {
                      className: `w-4 h-4 mr-2 ${isMigrating && !(migrationProgress == null ? void 0 : migrationProgress.all_complete) ? "animate-spin" : ""}`
                    }
                  ),
                  "Refresh"
                ]
              }
            ),
            isMigrating && !(migrationProgress == null ? void 0 : migrationProgress.all_complete) && /* @__PURE__ */ jsxRuntimeExports.jsxs(
              Button,
              {
                variant: "destructive",
                size: "sm",
                onClick: handleCancelMigration,
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(XCircle, { className: "w-4 h-4 mr-2" }),
                  "Cancel"
                ]
              }
            ),
            !isMigrating && /* @__PURE__ */ jsxRuntimeExports.jsxs(
              Button,
              {
                onClick: () => setShowMigrationConfirm(true),
                className: "bg-purple-600 hover:bg-purple-700",
                size: "sm",
                disabled: isStartingMigration,
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(Database, { className: "w-4 h-4 mr-2" }),
                  (migrationProgress == null ? void 0 : migrationProgress.all_complete) && (migrationProgress == null ? void 0 : migrationProgress.started_at) ? "Migrate Again" : "Start Migration"
                ]
              }
            )
          ] })
        ] }),
        (migrationStatus == null ? void 0 : migrationStatus.has_old_data) && (() => {
          const pm = (migrationProgress == null ? void 0 : migrationProgress.pro_migration) ?? (migrationStatus == null ? void 0 : migrationStatus.pro_migration);
          if (!pm || pm.ready) {
            return null;
          }
          return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mb-6 p-4 rounded-lg border border-amber-200 dark:border-amber-800 bg-amber-50 dark:bg-amber-900/20 flex gap-3 items-start", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(AlertTriangle, { className: "w-5 h-5 text-amber-600 dark:text-amber-400 shrink-0 mt-0.5" }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "min-w-0", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("h4", { className: "font-medium text-amber-900 dark:text-amber-200", children: __(
                "Yatra Pro 3.0+ required for full migration",
                "yatra"
              ) }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-amber-800 dark:text-amber-300/90 mt-1", children: pm.warning_message }),
              pm.multiple_pro_plugins && Array.isArray(pm.active_pro_plugins) && pm.active_pro_plugins.length > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx("ul", { className: "text-xs text-amber-800 dark:text-amber-300/80 mt-2 list-disc pl-5 space-y-0.5", children: pm.active_pro_plugins.map(
                (p) => /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { children: [
                  p.file,
                  p.version != null && p.version !== "" ? ` (${p.version})` : ""
                ] }, p.file)
              ) })
            ] })
          ] });
        })(),
        isLoadingMigration ? /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-4", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 w-48 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4", children: [1, 2, 3, 4, 5, 6].map((i) => /* @__PURE__ */ jsxRuntimeExports.jsx(
            "div",
            {
              className: "h-32 bg-gray-100 dark:bg-gray-800 rounded-lg animate-pulse"
            },
            i
          )) })
        ] }) : (migrationStatus == null ? void 0 : migrationStatus.has_old_data) ? /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-6", children: [
          (migrationProgress == null ? void 0 : migrationProgress.all_complete) && (migrationProgress == null ? void 0 : migrationProgress.started_at) && Object.keys(migrationProgress.progress || {}).length > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "bg-green-50 dark:bg-green-900/10 border border-green-200 dark:border-green-800 rounded-lg p-4", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start gap-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CheckCircle, { className: "w-5 h-5 text-green-600 dark:text-green-400 mt-0.5" }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("h4", { className: "font-medium text-green-900 dark:text-green-300", children: "Migration Completed Successfully!" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-green-700 dark:text-green-400 mt-1", children: "All data has been migrated from Yatra 2.x to 3.0" })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "button",
              {
                onClick: () => {
                  setIsMigrating(false);
                  setMigrationProgress(null);
                },
                className: "text-green-600 hover:text-green-800 dark:text-green-400 dark:hover:text-green-300",
                children: /* @__PURE__ */ jsxRuntimeExports.jsx(X, { className: "w-4 h-4" })
              }
            )
          ] }) }),
          (isMigrating || isStartingMigration) && (!migrationProgress || !migrationProgress.started_at || Object.keys(migrationProgress.progress || {}).length === 0) && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "bg-blue-50 dark:bg-blue-900/10 border border-blue-200 dark:border-blue-800 rounded-lg p-4", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(RefreshCw, { className: "w-5 h-5 text-blue-600 dark:text-blue-400 animate-spin" }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "font-medium text-blue-900 dark:text-blue-300", children: "Starting migration…" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-blue-700 dark:text-blue-400", children: "Initializing background tasks and loading progress." })
            ] })
          ] }) }),
          migrationProgress && !migrationProgress.all_complete && migrationProgress.started_at && Object.keys(migrationProgress.progress || {}).length > 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-blue-50 dark:bg-blue-900/10 border border-blue-200 dark:border-blue-800 rounded-lg p-4", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between mb-4", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(RefreshCw, { className: "w-5 h-5 text-blue-600 dark:text-blue-400 animate-spin" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-medium text-blue-900 dark:text-blue-300", children: "Migration in Progress" })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "button",
                {
                  onClick: () => {
                    setIsMigrating(false);
                    setMigrationProgress(null);
                  },
                  className: "text-gray-400 hover:text-gray-600 dark:hover:text-gray-300",
                  children: /* @__PURE__ */ jsxRuntimeExports.jsx(X, { className: "w-4 h-4" })
                }
              )
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mb-4", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between text-sm mb-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-700 dark:text-gray-300", children: "Overall Progress" }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "font-medium text-gray-900 dark:text-white", children: [
                  (() => {
                    const total = Object.values(
                      migrationProgress.progress || {}
                    ).reduce(
                      (sum, p) => sum + (p.total || 0),
                      0
                    );
                    const processed = Object.values(
                      migrationProgress.progress || {}
                    ).reduce(
                      (sum, p) => sum + (p.migrated || 0) + (p.skipped || 0) + (p.failed || 0),
                      0
                    );
                    return total > 0 ? Math.round(processed / total * 100) : 0;
                  })(),
                  "%"
                ] })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-full bg-blue-200 dark:bg-blue-800 rounded-full h-3 overflow-hidden", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                "div",
                {
                  className: "h-full bg-blue-600 dark:bg-blue-400 transition-all duration-500",
                  style: {
                    width: `${(() => {
                      const total = Object.values(
                        migrationProgress.progress || {}
                      ).reduce(
                        (sum, p) => sum + (p.total || 0),
                        0
                      );
                      const processed = Object.values(
                        migrationProgress.progress || {}
                      ).reduce(
                        (sum, p) => sum + (p.migrated || 0) + (p.skipped || 0) + (p.failed || 0),
                        0
                      );
                      return total > 0 ? Math.round(processed / total * 100) : 0;
                    })()}%`
                  }
                }
              ) })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("h5", { className: "text-sm font-medium text-gray-700 dark:text-gray-300", children: "Progress by Data Type" }),
              Object.entries(migrationProgress.progress || {}).map(
                ([key2, progress]) => {
                  var _a2;
                  const dataInfo = (_a2 = migrationStatus == null ? void 0 : migrationStatus.old_data) == null ? void 0 : _a2[key2];
                  if (!dataInfo || progress.total === 0) return null;
                  const percentage = progress.total > 0 ? Math.round(
                    ((progress.migrated || 0) + (progress.skipped || 0) + (progress.failed || 0)) / progress.total * 100
                  ) : 0;
                  return /* @__PURE__ */ jsxRuntimeExports.jsxs(
                    "div",
                    {
                      className: "bg-white dark:bg-gray-800 rounded-lg p-3 border border-gray-200 dark:border-gray-700",
                      children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between mb-2", children: [
                          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
                            progress.status === "running" ? /* @__PURE__ */ jsxRuntimeExports.jsx(RefreshCw, { className: "w-4 h-4 text-blue-600 dark:text-blue-400 animate-spin" }) : progress.status === "completed" ? /* @__PURE__ */ jsxRuntimeExports.jsx(CheckCircle, { className: "w-4 h-4 text-green-600 dark:text-green-400" }) : /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-4 h-4 rounded-full border-2 border-gray-300 dark:border-gray-600" }),
                            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm font-medium text-gray-900 dark:text-white", children: dataInfo.label })
                          ] }),
                          /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-sm text-gray-600 dark:text-gray-400", children: [
                            (progress.migrated || 0) + (progress.skipped || 0) + (progress.failed || 0),
                            "/",
                            progress.total
                          ] })
                        ] }),
                        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2 overflow-hidden mb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                          "div",
                          {
                            className: `h-full transition-all duration-300 ${progress.status === "completed" ? "bg-green-500" : progress.status === "running" ? "bg-blue-500" : "bg-gray-400"}`,
                            style: { width: `${percentage}%` }
                          }
                        ) }),
                        (progress.migrated || 0) + (progress.skipped || 0) + (progress.failed || 0) > 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3 text-xs", children: [
                          progress.migrated > 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-green-600 dark:text-green-400", children: [
                            "✓ ",
                            progress.migrated,
                            " migrated"
                          ] }),
                          progress.skipped > 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-yellow-600 dark:text-yellow-400", children: [
                            "⊘ ",
                            progress.skipped,
                            " skipped"
                          ] }),
                          progress.failed > 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-red-600 dark:text-red-400", children: [
                            "✗ ",
                            progress.failed,
                            " failed"
                          ] })
                        ] })
                      ]
                    },
                    key2
                  );
                }
              )
            ] })
          ] }),
          (migrationProgress == null ? void 0 : migrationProgress.all_complete) && (migrationProgress == null ? void 0 : migrationProgress.started_at) && Object.keys(migrationProgress.progress || {}).length > 0 && (() => {
            const totalMigrated = Object.values(
              migrationProgress.progress || {}
            ).reduce(
              (sum, p) => sum + (p.migrated || 0),
              0
            );
            const totalSkipped = Object.values(
              migrationProgress.progress || {}
            ).reduce(
              (sum, p) => sum + (p.skipped || 0),
              0
            );
            const totalFailed = Object.values(
              migrationProgress.progress || {}
            ).reduce((sum, p) => sum + (p.failed || 0), 0);
            return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg p-4", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between mb-4", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("h4", { className: "font-medium text-gray-900 dark:text-white", children: "Migration Summary" }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3 text-sm", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-green-600 dark:text-green-400", children: [
                    "✓ ",
                    totalMigrated,
                    " migrated"
                  ] }),
                  totalSkipped > 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-yellow-600 dark:text-yellow-400", children: [
                    "⊘ ",
                    totalSkipped,
                    " skipped"
                  ] }),
                  totalFailed > 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-red-600 dark:text-red-400", children: [
                    "✗ ",
                    totalFailed,
                    " failed"
                  ] })
                ] })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-2", children: Object.entries(migrationProgress.progress || {}).map(
                ([key2, progress]) => {
                  var _a2;
                  const dataInfo = (_a2 = migrationStatus == null ? void 0 : migrationStatus.old_data) == null ? void 0 : _a2[key2];
                  if (!dataInfo) return null;
                  const totalProcessed = (progress.migrated || 0) + (progress.skipped || 0) + (progress.failed || 0);
                  if (totalProcessed === 0) return null;
                  return /* @__PURE__ */ jsxRuntimeExports.jsxs(
                    "div",
                    {
                      className: "flex items-center justify-between py-2 border-b border-gray-100 dark:border-gray-700 last:border-0",
                      children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm text-gray-700 dark:text-gray-300", children: dataInfo.label }),
                        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3 text-xs", children: [
                          progress.migrated > 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-green-600 dark:text-green-400", children: [
                            "✓ ",
                            progress.migrated
                          ] }),
                          progress.skipped > 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-yellow-600 dark:text-yellow-400", children: [
                            "⊘ ",
                            progress.skipped
                          ] }),
                          progress.failed > 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-red-600 dark:text-red-400", children: [
                            "✗ ",
                            progress.failed
                          ] })
                        ] })
                      ]
                    },
                    key2
                  );
                }
              ) })
            ] });
          })(),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4", children: Object.entries(migrationStatus.old_data || {}).map(
            ([key2, data]) => /* @__PURE__ */ jsxRuntimeExports.jsx(
              "div",
              {
                className: "bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg p-4 hover:shadow-md transition-shadow",
                children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start justify-between", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1", children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx("h4", { className: "font-medium text-gray-900 dark:text-white", children: data.label }),
                    /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400 mt-1", children: data.description }),
                    /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-400 dark:text-gray-500 mt-2", children: data.table })
                  ] }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(Badge, { className: "bg-purple-100 dark:bg-purple-900/20 text-purple-700 dark:text-purple-400", children: data.count })
                ] })
              },
              key2
            )
          ) })
        ] }) : (
          // No Data State
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-center py-12", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CheckCircle, { className: "w-12 h-12 text-green-500 mx-auto mb-3" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-base font-medium text-gray-900 dark:text-white mb-1", children: "No Migration Needed" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-500 dark:text-gray-400", children: "Your database is up to date" })
          ] })
        )
      ] }),
      activeTab === "logs" && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-6", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex flex-wrap gap-2", children: logTypes.map((type) => {
          const Icon = type.icon;
          return /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Button,
            {
              variant: selectedLogType === type.key ? "default" : "outline",
              onClick: () => setSelectedLogType(type.key),
              className: "flex items-center gap-2",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Icon, { className: "w-4 h-4" }),
                type.label
              ]
            },
            type.key
          );
        }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { className: "p-6", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between mb-4", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("h3", { className: "text-lg font-semibold capitalize", children: [
              selectedLogType,
              " Logs"
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-2", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs(
                Button,
                {
                  variant: "outline",
                  size: "sm",
                  onClick: () => loadLogs(selectedLogType),
                  disabled: isLoadingLogs,
                  className: "flex items-center gap-2",
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(
                      RefreshCw,
                      {
                        className: `w-4 h-4 ${isLoadingLogs ? "animate-spin" : ""}`
                      }
                    ),
                    "Refresh"
                  ]
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsxs(
                Button,
                {
                  variant: "outline",
                  size: "sm",
                  onClick: copyAllLogsToClipboard,
                  disabled: !((_a = logs[selectedLogType]) == null ? void 0 : _a.logs) || logs[selectedLogType].logs.length === 0,
                  className: "flex items-center gap-2",
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(Copy, { className: "w-4 h-4" }),
                    "Copy All"
                  ]
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsxs(
                Button,
                {
                  variant: "destructive",
                  size: "sm",
                  onClick: () => handleClearLogs(),
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "w-4 h-4 mr-2" }),
                    "Clear Logs"
                  ]
                }
              )
            ] })
          ] }),
          isLoadingLogs ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-4", children: [...Array(3)].map((_, index) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "div",
            {
              className: "border rounded-lg p-4 bg-gray-50 dark:bg-gray-800 animate-pulse",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex items-start justify-between mb-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-16 h-5 bg-gray-200 dark:bg-gray-700 rounded" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-32 h-4 bg-gray-200 dark:bg-gray-700 rounded" })
                ] }) }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-3/4 h-4 bg-gray-200 dark:bg-gray-700 rounded mb-2" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-1/2 h-3 bg-gray-200 dark:bg-gray-700 rounded" })
              ]
            },
            index
          )) }) : ((_c = (_b = logs[selectedLogType]) == null ? void 0 : _b.logs) == null ? void 0 : _c.length) > 0 ? logs[selectedLogType].logs.map((log2) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "div",
            {
              className: "border rounded-lg p-4 bg-gray-50 dark:bg-gray-800",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start justify-between mb-2", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
                    getLogLevelBadge(log2.level),
                    /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm text-gray-600 dark:text-gray-400", children: new Date(log2.timestamp).toLocaleString() })
                  ] }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    Button,
                    {
                      variant: "ghost",
                      size: "sm",
                      onClick: () => copyLogToClipboard(log2),
                      className: "text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 p-1 h-6 w-6",
                      children: /* @__PURE__ */ jsxRuntimeExports.jsx(Copy, { className: "w-3 h-3" })
                    }
                  )
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm font-medium mb-2", children: log2.message }),
                log2.context && Object.keys(log2.context).length > 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs("details", { className: "text-xs", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("summary", { className: "cursor-pointer text-gray-600 dark:text-gray-400", children: "View Context" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("pre", { className: "mt-2 p-2 bg-gray-100 dark:bg-gray-700 rounded text-xs overflow-auto", children: JSON.stringify(log2.context, null, 2) })
                ] })
              ]
            },
            log2.id
          )) : /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-center py-8 text-gray-500 dark:text-gray-400", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(AlertCircle, { className: "w-12 h-12 mx-auto mb-2 opacity-50" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { children: "No logs found for this type" })
          ] })
        ] })
      ] }),
      showExportModal && /* @__PURE__ */ jsxRuntimeExports.jsx(
        "div",
        {
          className: "fixed top-0 left-0 right-0 bottom-0 backdrop-blur-sm bg-white/30 dark:bg-black/30 z-50",
          style: { margin: 0, padding: 0 },
          children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 bg-white dark:bg-gray-800 rounded-xl shadow-2xl border border-gray-200 dark:border-gray-700 w-full max-w-2xl max-h-[85vh] overflow-hidden mx-4", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-xl font-semibold text-gray-900 dark:text-white", children: "Select Data Types to Export" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "button",
                {
                  onClick: () => setShowExportModal(false),
                  className: "text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 p-1 rounded-full hover:bg-gray-100 dark:hover:bg-gray-700",
                  children: /* @__PURE__ */ jsxRuntimeExports.jsx(XCircle, { className: "w-5 h-5" })
                }
              )
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "p-6 overflow-y-auto max-h-[60vh]", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mb-4 pb-3 border-b border-gray-200 dark:border-gray-700", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("label", { className: "flex items-center gap-3 p-3 hover:bg-blue-50 dark:hover:bg-blue-900/20 rounded-lg cursor-pointer transition-colors", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "input",
                  {
                    type: "checkbox",
                    checked: selectableDataTypes.length > 0 && selectableDataTypes.every(
                      (dt) => selectedExportData.includes(dt.key)
                    ) && !selectedExportData.includes("all"),
                    onChange: handleExportSelectAll,
                    className: "rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm font-semibold text-blue-700 dark:text-blue-400", children: selectableDataTypes.length > 0 && selectableDataTypes.every(
                    (dt) => selectedExportData.includes(dt.key)
                  ) && !selectedExportData.includes("all") ? "Deselect All" : "Select All" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-xs text-gray-500 dark:text-gray-400", children: [
                    "(",
                    selectableDataTypes.length,
                    " individual types)"
                  ] })
                ] })
              ] }) }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid grid-cols-1 gap-1", children: dataTypes.map((dataType) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
                "label",
                {
                  className: "flex items-start gap-3 p-3 hover:bg-gray-50 dark:hover:bg-gray-700/50 rounded-lg cursor-pointer transition-colors",
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "input",
                      {
                        type: "checkbox",
                        checked: selectedExportData.includes(dataType.key),
                        onChange: () => handleExportDataToggle(dataType.key),
                        className: "mt-1 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                      }
                    ),
                    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1 min-w-0", children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsx(dataType.icon, { className: "w-4 h-4 text-blue-600 dark:text-blue-400" }),
                        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm font-medium text-gray-900 dark:text-white", children: dataType.label })
                      ] }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400 mt-1", children: dataType.description })
                    ] })
                  ]
                },
                dataType.key
              )) })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between p-6 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "text-sm text-gray-600 dark:text-gray-400", children: [
                selectedExportData.length,
                " data types selected"
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-3", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Button,
                  {
                    variant: "outline",
                    onClick: () => setShowExportModal(false),
                    children: "Cancel"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsxs(
                  Button,
                  {
                    onClick: handleExport,
                    disabled: selectedExportData.length === 0,
                    children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx(Download, { className: "w-4 h-4 mr-2" }),
                      "Export Selected Data"
                    ]
                  }
                )
              ] })
            ] })
          ] })
        }
      ),
      showDeleteModal && /* @__PURE__ */ jsxRuntimeExports.jsx(
        "div",
        {
          className: "fixed top-0 left-0 right-0 bottom-0 backdrop-blur-sm bg-white/30 dark:bg-black/30 z-50",
          style: { margin: 0, padding: 0 },
          children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 bg-white dark:bg-gray-800 rounded-xl shadow-2xl border border-gray-200 dark:border-gray-700 w-full max-w-md overflow-hidden mx-4", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-xl font-semibold text-gray-900 dark:text-white", children: "Confirm Deletion" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "button",
                {
                  onClick: handleCancelDelete,
                  className: "text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 p-1 rounded-full hover:bg-gray-100 dark:hover:bg-gray-700",
                  children: /* @__PURE__ */ jsxRuntimeExports.jsx(XCircle, { className: "w-5 h-5" })
                }
              )
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-6", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start gap-3 mb-4", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-2 bg-red-100 dark:bg-red-900/30 rounded-full", children: /* @__PURE__ */ jsxRuntimeExports.jsx(AlertTriangle, { className: "w-6 h-6 text-red-600 dark:text-red-400" }) }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("h4", { className: "text-lg font-medium text-gray-900 dark:text-white mb-1", children: "Delete Export File?" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-600 dark:text-gray-400", children: "This action cannot be undone. The export file will be permanently deleted from the server." })
              ] })
            ] }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex items-center justify-end p-6 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-3", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { variant: "outline", onClick: handleCancelDelete, children: "Cancel" }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs(
                Button,
                {
                  onClick: handleConfirmDelete,
                  className: "bg-red-600 hover:bg-red-700 text-white",
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "w-4 h-4 mr-2" }),
                    "Delete File"
                  ]
                }
              )
            ] }) })
          ] })
        }
      ),
      showClearLogsModal && /* @__PURE__ */ jsxRuntimeExports.jsx(
        "div",
        {
          className: "fixed top-0 left-0 right-0 bottom-0 backdrop-blur-sm bg-white/30 dark:bg-black/30 z-50",
          style: { margin: 0, padding: 0 },
          children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 bg-white dark:bg-gray-800 rounded-xl shadow-2xl border border-gray-200 dark:border-gray-700 w-full max-w-md overflow-hidden mx-4", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-xl font-semibold text-gray-900 dark:text-white", children: "Clear Logs" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "button",
                {
                  onClick: () => setShowClearLogsModal(false),
                  className: "text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 p-1 rounded-full hover:bg-gray-100 dark:hover:bg-gray-700",
                  children: /* @__PURE__ */ jsxRuntimeExports.jsx(XCircle, { className: "w-5 h-5" })
                }
              )
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-6", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start gap-3 mb-4", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-2 bg-orange-100 dark:bg-orange-900/30 rounded-full", children: /* @__PURE__ */ jsxRuntimeExports.jsx(AlertTriangle, { className: "w-6 h-6 text-orange-600 dark:text-orange-400" }) }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("h4", { className: "text-lg font-medium text-gray-900 dark:text-white mb-1", children: [
                  "Clear ",
                  selectedLogType,
                  " logs?"
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "text-sm text-gray-600 dark:text-gray-400", children: [
                  "This action cannot be undone. All ",
                  selectedLogType,
                  " logs will be permanently deleted from the server."
                ] })
              ] })
            ] }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex items-center justify-end p-6 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-3", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Button,
                {
                  variant: "outline",
                  onClick: () => setShowClearLogsModal(false),
                  children: "Cancel"
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsxs(
                Button,
                {
                  onClick: confirmClearLogs,
                  className: "bg-orange-600 hover:bg-orange-700 text-white",
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "w-4 h-4 mr-2" }),
                    "Clear Logs"
                  ]
                }
              )
            ] }) })
          ] })
        }
      ),
      showImportModal && pendingImportFile && /* @__PURE__ */ jsxRuntimeExports.jsx(
        "div",
        {
          className: "fixed top-0 left-0 right-0 bottom-0 backdrop-blur-sm bg-white/30 dark:bg-black/30 z-50",
          style: { margin: 0, padding: 0 },
          children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 bg-white dark:bg-gray-800 rounded-xl shadow-2xl border border-gray-200 dark:border-gray-700 w-full max-w-2xl max-h-[85vh] overflow-hidden mx-4", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-xl font-semibold text-gray-900 dark:text-white", children: "Select Data Types to Import" }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "text-sm text-gray-500 dark:text-gray-400 mt-1", children: [
                  "File: ",
                  pendingImportFile.name
                ] })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "button",
                {
                  onClick: () => {
                    setShowImportModal(false);
                    setPendingImportFile(null);
                  },
                  className: "text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 p-1 rounded-full hover:bg-gray-100 dark:hover:bg-gray-700",
                  children: /* @__PURE__ */ jsxRuntimeExports.jsx(XCircle, { className: "w-5 h-5" })
                }
              )
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "p-6 overflow-y-auto max-h-[60vh]", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mb-4 pb-3 border-b border-gray-200 dark:border-gray-700", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("label", { className: "flex items-center gap-3 p-3 hover:bg-green-50 dark:hover:bg-green-900/20 rounded-lg cursor-pointer transition-colors", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "input",
                  {
                    type: "checkbox",
                    checked: selectableDataTypes.length > 0 && selectableDataTypes.every(
                      (dt) => selectedImportData.includes(dt.key)
                    ) && !selectedImportData.includes("all"),
                    onChange: handleImportSelectAll,
                    className: "rounded border-gray-300 text-green-600 focus:ring-green-500"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm font-semibold text-green-700 dark:text-green-400", children: selectableDataTypes.length > 0 && selectableDataTypes.every(
                    (dt) => selectedImportData.includes(dt.key)
                  ) && !selectedImportData.includes("all") ? "Deselect All" : "Select All" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-xs text-gray-500 dark:text-gray-400", children: [
                    "(",
                    selectableDataTypes.length,
                    " individual types)"
                  ] })
                ] })
              ] }) }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid grid-cols-1 gap-1", children: dataTypes.map((dataType) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
                "label",
                {
                  className: "flex items-start gap-3 p-3 hover:bg-gray-50 dark:hover:bg-gray-700/50 rounded-lg cursor-pointer transition-colors",
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "input",
                      {
                        type: "checkbox",
                        checked: selectedImportData.includes(dataType.key),
                        onChange: () => handleImportDataToggle(dataType.key),
                        className: "mt-1 rounded border-gray-300 text-green-600 focus:ring-green-500"
                      }
                    ),
                    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1 min-w-0", children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsx(dataType.icon, { className: "w-4 h-4 text-green-600 dark:text-green-400" }),
                        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm font-medium text-gray-900 dark:text-white", children: dataType.label })
                      ] }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400 mt-1", children: dataType.description })
                    ] })
                  ]
                },
                dataType.key
              )) })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between p-6 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "text-sm text-gray-600 dark:text-gray-400", children: [
                selectedImportData.length,
                " data types selected"
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-3", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Button,
                  {
                    variant: "outline",
                    onClick: () => {
                      setShowImportModal(false);
                      setPendingImportFile(null);
                    },
                    children: "Cancel"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsxs(
                  Button,
                  {
                    onClick: handleImportConfirm,
                    disabled: selectedImportData.length === 0,
                    children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx(Upload, { className: "w-4 h-4 mr-2" }),
                      "Import Selected Data"
                    ]
                  }
                )
              ] })
            ] })
          ] })
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        Modal,
        {
          isOpen: showMigrationConfirm,
          onClose: () => setShowMigrationConfirm(false),
          title: __("Migrate All Data"),
          description: __(
            "This process runs in the background and may take several minutes. Please back up your database before proceeding."
          ),
          size: "md",
          footer: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 w-full", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              Button,
              {
                variant: "outline",
                onClick: () => setShowMigrationConfirm(false),
                className: "w-full sm:w-auto",
                children: __("Cancel")
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col sm:flex-row gap-3 w-full sm:w-auto", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Button,
                {
                  variant: "destructive",
                  onClick: () => {
                    setShowMigrationConfirm(false);
                    handleMigrateAll(true);
                  },
                  className: "w-full sm:w-auto",
                  children: __("Re-migrate All")
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Button,
                {
                  onClick: () => {
                    setShowMigrationConfirm(false);
                    handleMigrateAll(false);
                  },
                  className: "w-full sm:w-auto",
                  children: __("Start Migration")
                }
              )
            ] })
          ] }),
          children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-4 text-sm text-gray-600 dark:text-gray-300", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { children: __(
              "All legacy data types will be migrated to the new Yatra 3.0 database structure. The migration runs asynchronously via WordPress cron."
            ) }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "p-3 bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-md flex items-start gap-3", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(AlertCircle, { className: "w-5 h-5 text-yellow-600 dark:text-yellow-400" }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "font-medium text-yellow-800 dark:text-yellow-200", children: __("Important") }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm", children: __(
                  "Keep this tab open to monitor progress. Use “Re-migrate All” only if you need to reprocess items that were already migrated."
                ) })
              ] })
            ] }),
            (migrationStatus == null ? void 0 : migrationStatus.pro_migration) && !migrationStatus.pro_migration.ready && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "p-3 bg-amber-50 dark:bg-amber-900/20 border border-amber-300 dark:border-amber-800 rounded-md flex items-start gap-3", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(AlertTriangle, { className: "w-5 h-5 text-amber-600 dark:text-amber-400 shrink-0" }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "font-medium text-amber-900 dark:text-amber-200", children: __("Yatra Pro", "yatra") }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm text-amber-800 dark:text-amber-300/90", children: migrationStatus.pro_migration.warning_message })
              ] })
            ] })
          ] })
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        Modal,
        {
          isOpen: showCacheModal,
          onClose: () => setShowCacheModal(false),
          title: "View Cache Data",
          size: "lg",
          children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-4", children: isLoadingCache ? /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-center py-8", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(RefreshCw, { className: "w-6 h-6 animate-spin mr-2" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: "Loading cache data..." })
          ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between mb-4", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "text-sm text-gray-600 dark:text-gray-400", children: [
                cacheData.length,
                " cache items found"
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs(
                Button,
                {
                  variant: "outline",
                  size: "sm",
                  onClick: loadCacheData,
                  disabled: isLoadingCache,
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(
                      RefreshCw,
                      {
                        className: `w-4 h-4 mr-1 ${isLoadingCache ? "animate-spin" : ""}`
                      }
                    ),
                    "Refresh"
                  ]
                }
              )
            ] }),
            cacheData.length === 0 ? /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-center py-8 text-gray-500 dark:text-gray-400", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Database, { className: "w-12 h-12 mx-auto mb-4 opacity-50" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { children: "No cache data found" })
            ] }) : /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "overflow-x-auto", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("table", { className: "w-full text-sm", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("thead", { children: /* @__PURE__ */ jsxRuntimeExports.jsxs("tr", { className: "border-b border-gray-200 dark:border-gray-700", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("th", { className: "text-left p-3 font-medium text-gray-900 dark:text-white", children: "Cache Key" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("th", { className: "text-left p-3 font-medium text-gray-900 dark:text-white", children: "Type" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("th", { className: "text-left p-3 font-medium text-gray-900 dark:text-white", children: "Size" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("th", { className: "text-left p-3 font-medium text-gray-900 dark:text-white", children: "Created" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("th", { className: "text-left p-3 font-medium text-gray-900 dark:text-white", children: "Expires" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("th", { className: "text-left p-3 font-medium text-gray-900 dark:text-white", children: "Actions" })
              ] }) }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("tbody", { children: cacheData.map((item, index) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
                "tr",
                {
                  className: "border-b border-gray-100 dark:border-gray-800 hover:bg-gray-50 dark:hover:bg-gray-800/50",
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsxs("td", { className: "p-3", children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx(
                        "div",
                        {
                          className: "max-w-md truncate font-mono text-xs font-semibold",
                          title: item.key,
                          children: item.key
                        }
                      ),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-xs text-gray-600 dark:text-gray-300 mt-2 max-h-32 overflow-auto bg-gray-50 dark:bg-gray-900 p-2 rounded border border-gray-200 dark:border-gray-700", children: /* @__PURE__ */ jsxRuntimeExports.jsx("pre", { className: "whitespace-pre-wrap break-words font-mono text-xs", children: item.value }) })
                    ] }),
                    /* @__PURE__ */ jsxRuntimeExports.jsx("td", { className: "p-3", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                      Badge,
                      {
                        variant: item.type === "transient" ? "default" : "outline",
                        children: item.type
                      }
                    ) }),
                    /* @__PURE__ */ jsxRuntimeExports.jsx("td", { className: "p-3 text-gray-600 dark:text-gray-400", children: formatBytes(item.size) }),
                    /* @__PURE__ */ jsxRuntimeExports.jsx("td", { className: "p-3 text-gray-600 dark:text-gray-400 text-xs", children: item.created_at }),
                    /* @__PURE__ */ jsxRuntimeExports.jsx("td", { className: "p-3 text-gray-600 dark:text-gray-400 text-xs", children: item.expires_at }),
                    /* @__PURE__ */ jsxRuntimeExports.jsx("td", { className: "p-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
                      Button,
                      {
                        variant: "outline",
                        size: "sm",
                        onClick: () => clearCacheItem(item.key, item.type),
                        className: "text-red-600 hover:text-red-700 border-red-200 hover:bg-red-50",
                        children: [
                          /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "w-3 h-3 mr-1" }),
                          "Clear"
                        ]
                      }
                    ) })
                  ]
                },
                index
              )) })
            ] }) })
          ] }) })
        }
      )
    ] })
  ] });
};
const ItemTypes = () => {
  var _a;
  const [searchTerm, setSearchTerm] = reactExports.useState("");
  const [statusFilter, setStatusFilter] = reactExports.useState("all");
  const [sortBy2, setSortBy] = reactExports.useState("id");
  const [sortOrder, setSortOrder] = reactExports.useState("desc");
  const [page, setPage] = reactExports.useState(1);
  const [selectedIds, setSelectedIds] = reactExports.useState([]);
  const [bulkAction, setBulkAction] = reactExports.useState("");
  const [showColumnsDropdown, setShowColumnsDropdown] = reactExports.useState(false);
  const [bulkMutationPending, setBulkMutationPending] = reactExports.useState(false);
  const [deleteConfirm, setDeleteConfirm] = reactExports.useState({
    isOpen: false,
    itemType: null
  });
  const [statusActionConfirm, setStatusActionConfirm] = reactExports.useState({
    isOpen: false,
    itemType: null,
    action: null
  });
  const updateItemTypeStatus = async (itemType, status) => {
    await apiClient.put(`/item-types/${itemType.id}`, {
      // Required for validation
      name: itemType.name,
      // Preserve current slug and other fields so a status change doesn't mutate core data
      slug: itemType.slug,
      description: itemType.description,
      color: itemType.color,
      status,
      preserve_slug: true
    });
  };
  const queryClient2 = useQueryClient();
  const { can } = usePermissions();
  const { showToast } = useToast();
  const baseAdminUrl = ((_a = window.yatraAdmin) == null ? void 0 : _a.adminUrl) || "";
  const queryParams = reactExports.useMemo(() => {
    const params = {
      page,
      per_page: 10,
      orderby: sortBy2,
      order: sortOrder
    };
    if (searchTerm) {
      params.search = searchTerm;
    }
    if (statusFilter !== "all") {
      params.status = statusFilter;
    }
    return params;
  }, [searchTerm, statusFilter, sortBy2, sortOrder, page]);
  const { data: statsData } = useQuery({
    queryKey: ["item-types-stats"],
    queryFn: async () => {
      try {
        const response = await apiClient.get("/item-types/stats");
        return response;
      } catch (error2) {
        return { all: 0, publish: 0, draft: 0, trash: 0 };
      }
    },
    enabled: can("yatra_view_trips")
  });
  const { data, isLoading, error } = useQuery({
    queryKey: ["item-types", queryParams],
    queryFn: async () => {
      try {
        const response = await apiClient.get("/item-types", {
          params: queryParams
        });
        return response;
      } catch (error2) {
        showToast(
          (error2 == null ? void 0 : error2.message) || __("Failed to load item types", "yatra"),
          "error"
        );
        throw error2;
      }
    },
    enabled: can("yatra_view_trips")
  });
  const deleteMutation = useMutation({
    mutationFn: async (id) => {
      return await apiClient.delete(`/item-types/${id}`);
    },
    onSuccess: () => {
      queryClient2.invalidateQueries({ queryKey: ["item-types"] });
      queryClient2.invalidateQueries({ queryKey: ["item-types-stats"] });
      showToast(__("Item type deleted successfully", "yatra"), "success");
      setDeleteConfirm({ isOpen: false, itemType: null });
    },
    onError: (error2) => {
      showToast(
        (error2 == null ? void 0 : error2.message) || __("Failed to delete item type", "yatra"),
        "error"
      );
    }
  });
  const itemTypes = (data == null ? void 0 : data.data) || [];
  const total = (data == null ? void 0 : data.total) || 0;
  const totalPages = Math.ceil(total / 10);
  const errorContext = getErrorContext(error);
  const apiErrorMessage = (data == null ? void 0 : data.error) || (data == null ? void 0 : data.message);
  const derivedErrorDetails = errorContext.details || (apiErrorMessage ? String(apiErrorMessage) : void 0) || (error ? String((error == null ? void 0 : error.message) || error) : void 0);
  const isItemTypesError = !!error || !!apiErrorMessage;
  const formatDate2 = (dateString) => {
    if (!dateString) return __("N/A", "yatra");
    try {
      const date2 = new Date(dateString);
      return date2.toLocaleDateString("en-US", {
        month: "short",
        day: "numeric",
        year: "numeric",
        hour: "2-digit",
        minute: "2-digit"
      });
    } catch (e) {
      return dateString;
    }
  };
  const getStatusBadge = (status) => {
    const statusMap = {
      publish: {
        className: "bg-green-100 text-green-700 dark:bg-green-900/20 dark:text-green-400",
        label: __("Publish", "yatra")
      },
      draft: {
        className: "bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-400",
        label: __("Draft", "yatra")
      },
      trash: {
        className: "bg-red-100 text-red-700 dark:bg-red-900/20 dark:text-red-400",
        label: __("Trash", "yatra")
      }
    };
    const statusInfo = statusMap[status] || {
      className: "bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-400",
      label: status
    };
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "span",
      {
        className: `inline-flex items-center px-2 py-1 rounded-md text-xs font-medium ${statusInfo.className}`,
        children: statusInfo.label
      }
    );
  };
  const formatUser = (userId, userName) => {
    if (userName) {
      return userName;
    }
    return `User #${userId}`;
  };
  const renderIcon = (icon) => {
    if (!icon) {
      return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-10 h-10 rounded-lg bg-gray-100 dark:bg-gray-800 flex items-center justify-center", children: /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs text-gray-400 dark:text-gray-500", children: "—" }) });
    }
    if (typeof icon === "object" && icon !== null) {
      const iconValue = icon;
      if (iconValue.type === "image") {
        return /* @__PURE__ */ jsxRuntimeExports.jsx(
          "img",
          {
            src: iconValue.value,
            alt: "",
            className: "w-10 h-10 rounded-lg object-cover",
            onError: (e) => {
              const target2 = e.target;
              target2.style.display = "none";
              if (target2.parentElement) {
                target2.parentElement.innerHTML = '<div class="w-10 h-10 rounded-lg bg-gray-100 dark:bg-gray-800 flex items-center justify-center"><span class="text-xs text-gray-400 dark:text-gray-500">—</span></div>';
              }
            }
          }
        );
      } else {
        const raw = iconValue.provider;
        const provider = raw === "fa-solid" || raw === "fa-regular" ? raw : "yatra";
        return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-10 h-10 rounded-lg bg-gray-100 dark:bg-gray-800 flex items-center justify-center", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          IconSelector,
          {
            iconName: iconValue.value,
            provider,
            className: "w-5 h-5 text-gray-700 dark:text-gray-300"
          }
        ) });
      }
    }
    return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-10 h-10 rounded-lg bg-gray-100 dark:bg-gray-800 flex items-center justify-center", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
      IconSelector,
      {
        iconName: icon,
        className: "w-5 h-5 text-gray-700 dark:text-gray-300"
      }
    ) });
  };
  const handleCreate = () => {
    window.location.href = `${baseAdminUrl}?page=yatra&subpage=itinerary&tab=item-types&action=create`;
  };
  const handleEdit = (itemType) => {
    window.location.href = `${baseAdminUrl}?page=yatra&subpage=itinerary&tab=item-types&action=edit&id=${itemType.id}`;
  };
  const handleDelete = (itemType) => {
    setDeleteConfirm({ isOpen: true, itemType });
  };
  const confirmDelete = () => {
    if (deleteConfirm.itemType) {
      deleteMutation.mutate(deleteConfirm.itemType.id);
    }
  };
  const handleResetFilters = () => {
    setSearchTerm("");
    setStatusFilter("all");
    setSortBy("name");
    setSortOrder("asc");
    setPage(1);
  };
  const handleSort = (field) => {
    if (sortBy2 === field) {
      setSortOrder(sortOrder === "asc" ? "desc" : "asc");
    } else {
      setSortBy(field);
      setSortOrder("asc");
    }
  };
  const getSortIcon = (field) => {
    if (sortBy2 !== field) {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowUpDown, { className: "w-3.5 h-3.5 ml-1 text-gray-400" });
    }
    return sortOrder === "asc" ? /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowUp, { className: "w-3.5 h-3.5 ml-1 text-gray-600 dark:text-gray-300" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowDown, { className: "w-3.5 h-3.5 ml-1 text-gray-600 dark:text-gray-300" });
  };
  const hasFilters = searchTerm || statusFilter !== "all" || sortBy2 !== "name" || sortOrder !== "asc";
  const [visibleColumns, setVisibleColumns] = reactExports.useState(
    {
      type: true,
      description: true,
      status: true,
      items: true,
      date: true,
      author: true
    }
  );
  const toggleColumn = (columnKey) => {
    setVisibleColumns((prev) => ({
      ...prev,
      [columnKey]: !prev[columnKey]
    }));
  };
  const columnOptions = [
    { key: "type", label: __("Type", "yatra"), visible: visibleColumns.type },
    {
      key: "description",
      label: __("Description", "yatra"),
      visible: visibleColumns.description
    },
    {
      key: "status",
      label: __("Status", "yatra"),
      visible: visibleColumns.status
    },
    {
      key: "items",
      label: __("Items", "yatra"),
      visible: visibleColumns.items
    },
    { key: "date", label: __("Date", "yatra"), visible: visibleColumns.date },
    {
      key: "author",
      label: __("Author", "yatra"),
      visible: visibleColumns.author
    }
  ];
  const isAllSelected = itemTypes.length > 0 && selectedIds.length === itemTypes.length;
  const handleSelectItem = (id, checked) => {
    setSelectedIds(
      (prev) => checked ? [...prev, id] : prev.filter((existingId) => existingId !== id)
    );
  };
  const handleSelectAll = (checked) => {
    if (checked) {
      setSelectedIds(itemTypes.map((itemType) => itemType.id));
    } else {
      setSelectedIds([]);
    }
  };
  const handleClearSelection = () => {
    setSelectedIds([]);
  };
  const statusCounts = reactExports.useMemo(() => {
    if (statsData) {
      return {
        all: statsData.all ?? 0,
        publish: statsData.publish ?? 0,
        draft: statsData.draft ?? 0,
        trash: statsData.trash ?? 0
      };
    }
    return {
      all: 0,
      publish: 0,
      draft: 0,
      trash: 0
    };
  }, [statsData]);
  const statusOptions = [
    { key: "all", label: __("All", "yatra"), count: statusCounts.all },
    { key: "draft", label: __("Draft", "yatra"), count: statusCounts.draft },
    {
      key: "publish",
      label: __("Publish", "yatra"),
      count: statusCounts.publish
    },
    { key: "trash", label: __("Trash", "yatra"), count: statusCounts.trash }
  ];
  const bulkActionOptions = reactExports.useMemo(() => {
    if (statusFilter === "trash") {
      return [
        { value: "restore", label: __("Restore to Draft", "yatra") },
        { value: "delete", label: __("Delete Permanently", "yatra") }
      ];
    }
    return [
      { value: "publish", label: __("Mark as Published", "yatra") },
      { value: "draft", label: __("Mark as Draft", "yatra") },
      { value: "trash", label: __("Move to Trash", "yatra") },
      { value: "delete", label: __("Delete Permanently", "yatra") }
    ];
  }, [statusFilter]);
  const handleBulkApply = async () => {
    if (!bulkAction || selectedIds.length === 0) {
      showToast(
        __("Please select item types and a bulk action first.", "yatra"),
        "error"
      );
      return;
    }
    try {
      setBulkMutationPending(true);
      const selectedItemTypes = itemTypes.filter(
        (itemType) => selectedIds.includes(itemType.id)
      );
      if (bulkAction === "delete") {
        await Promise.all(
          selectedIds.map((id) => apiClient.delete(`/item-types/${id}`))
        );
        showToast(__("Item types deleted successfully", "yatra"), "success");
      } else if (bulkAction === "publish") {
        await Promise.all(
          selectedItemTypes.map(
            (itemType) => updateItemTypeStatus(itemType, "publish")
          )
        );
        showToast(__("Item types marked as published", "yatra"), "success");
      } else if (bulkAction === "draft") {
        const targetStatus = "draft";
        await Promise.all(
          selectedItemTypes.map(
            (itemType) => updateItemTypeStatus(itemType, targetStatus)
          )
        );
        showToast(
          statusFilter === "trash" ? __("Item types restored to draft", "yatra") : __("Item types marked as draft", "yatra"),
          "success"
        );
      } else if (bulkAction === "trash") {
        await Promise.all(
          selectedItemTypes.map(
            (itemType) => updateItemTypeStatus(itemType, "trash")
          )
        );
        showToast(__("Item types moved to trash", "yatra"), "success");
      } else if (bulkAction === "restore") {
        await Promise.all(
          selectedItemTypes.map(
            (itemType) => updateItemTypeStatus(itemType, "draft")
          )
        );
        showToast(__("Item types restored to draft", "yatra"), "success");
      }
      await queryClient2.invalidateQueries({ queryKey: ["item-types"] });
      await queryClient2.invalidateQueries({ queryKey: ["item-types-stats"] });
      setSelectedIds([]);
      setBulkAction("");
    } catch (error2) {
      showToast(__("Bulk action failed", "yatra"), "error");
    } finally {
      setBulkMutationPending(false);
    }
  };
  const columns = [
    {
      key: "type",
      label: __("Type", "yatra"),
      sortable: true,
      width: "w-[200px]",
      visible: visibleColumns.type,
      render: (itemType) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3", children: [
        renderIcon(itemType.icon),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "font-medium text-gray-900 dark:text-white", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            "a",
            {
              href: `${baseAdminUrl}?page=yatra&subpage=itinerary&tab=item-types&action=edit&id=${itemType.id}`,
              className: "hover:underline underline-offset-2 text-blue-600 dark:text-blue-400",
              children: itemType.name
            }
          ) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-xs text-gray-500 dark:text-gray-400 mt-0.5", children: itemType.slug })
        ] })
      ] })
    },
    {
      key: "description",
      label: __("Description", "yatra"),
      sortable: false,
      width: "w-[200px]",
      render: (itemType) => /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-600 dark:text-gray-400 text-sm line-clamp-2", children: itemType.description || __("No description", "yatra") })
    },
    {
      key: "status",
      label: __("Status", "yatra"),
      sortable: true,
      width: "w-[100px]",
      visible: visibleColumns.status,
      render: (itemType) => getStatusBadge(itemType.status)
    },
    {
      key: "items",
      label: __("Items", "yatra"),
      sortable: false,
      width: "w-[100px]",
      visible: visibleColumns.items,
      render: (itemType) => /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-center", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Badge, { variant: "outline", className: "font-medium", children: itemType.items_count ?? 0 }) })
    },
    {
      key: "date",
      label: __("Date", "yatra"),
      sortable: true,
      width: "w-[150px]",
      visible: visibleColumns.date,
      render: (itemType) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-gray-500 dark:text-gray-400 text-sm", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: formatDate2(itemType.created_at) }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-xs text-gray-400 dark:text-gray-500 mt-0.5", children: [
          __("Updated", "yatra"),
          ": ",
          formatDate2(itemType.updated_at)
        ] })
      ] })
    },
    {
      key: "author",
      label: __("Author", "yatra"),
      sortable: false,
      width: "w-[150px]",
      visible: visibleColumns.author,
      render: (itemType) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-gray-600 dark:text-gray-400 text-sm", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: formatUser(itemType.created_by, itemType.created_by_name) }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-xs text-gray-400 dark:text-gray-500 mt-0.5", children: [
          __("Updated by", "yatra"),
          ":",
          " ",
          formatUser(itemType.updated_by, itemType.updated_by_name)
        ] })
      ] })
    }
  ];
  const tableActions = reactExports.useMemo(() => {
    const actions = [];
    if (can("yatra_edit_trips")) {
      actions.push({
        key: "edit",
        label: __("Edit", "yatra"),
        icon: /* @__PURE__ */ jsxRuntimeExports.jsx(PenSquare, { className: "w-4 h-4" }),
        onClick: (itemType) => handleEdit(itemType)
      });
      actions.push({
        key: "publish",
        label: __("Mark as Published", "yatra"),
        icon: /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowUp, { className: "w-4 h-4" }),
        onClick: (itemType) => {
          setStatusActionConfirm({ isOpen: true, itemType, action: "publish" });
        },
        condition: (itemType) => itemType.status !== "publish" && itemType.status !== "trash"
      });
      actions.push({
        key: "draft",
        label: __("Mark as Draft", "yatra"),
        icon: /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowDown, { className: "w-4 h-4" }),
        onClick: (itemType) => {
          setStatusActionConfirm({ isOpen: true, itemType, action: "draft" });
        },
        condition: (itemType) => itemType.status !== "draft" && itemType.status !== "trash"
      });
      actions.push({
        key: "trash",
        label: __("Move to Trash", "yatra"),
        icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "w-4 h-4" }),
        onClick: (itemType) => {
          setStatusActionConfirm({ isOpen: true, itemType, action: "trash" });
        },
        condition: (itemType) => itemType.status !== "trash"
      });
      actions.push({
        key: "restore",
        label: __("Restore to Draft", "yatra"),
        icon: /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowUp, { className: "w-4 h-4" }),
        onClick: (itemType) => {
          setStatusActionConfirm({ isOpen: true, itemType, action: "restore" });
        },
        condition: (itemType) => itemType.status === "trash"
      });
    }
    if (can("yatra_delete_trips")) {
      actions.push({
        key: "delete",
        label: __("Delete Permanently", "yatra"),
        icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "w-4 h-4" }),
        onClick: (itemType) => handleDelete(itemType),
        variant: "destructive",
        condition: (itemType) => itemType.status === "trash"
      });
    }
    return actions;
  }, [can, queryClient2, showToast]);
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      ConfirmationDialog,
      {
        isOpen: deleteConfirm.isOpen,
        onClose: () => setDeleteConfirm({ isOpen: false, itemType: null }),
        onConfirm: confirmDelete,
        title: __("Delete Item Type", "yatra"),
        message: deleteConfirm.itemType ? __(
          'Are you sure you want to delete "{name}"? This action cannot be undone.',
          "yatra"
        ).replace("{name}", deleteConfirm.itemType.name) : __(
          "Are you sure you want to delete this item type? This action cannot be undone.",
          "yatra"
        ),
        confirmText: __("Delete", "yatra"),
        cancelText: __("Cancel", "yatra"),
        variant: "danger",
        isLoading: deleteMutation.isPending
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      ConfirmationDialog,
      {
        isOpen: statusActionConfirm.isOpen,
        onClose: () => setStatusActionConfirm({
          isOpen: false,
          itemType: null,
          action: null
        }),
        onConfirm: async () => {
          const { itemType, action } = statusActionConfirm;
          if (!itemType || !action) {
            return;
          }
          const targetStatus = action === "restore" ? "draft" : action;
          await updateItemTypeStatus(
            itemType,
            targetStatus
          );
          const successMessage = action === "publish" ? __("Item type marked as published.", "yatra") : action === "draft" || action === "restore" ? __("Item type marked as draft.", "yatra") : __("Item type moved to trash.", "yatra");
          showToast(successMessage, "success");
          queryClient2.invalidateQueries({ queryKey: ["item-types"] });
          queryClient2.invalidateQueries({ queryKey: ["item-types-stats"] });
          setStatusActionConfirm({
            isOpen: false,
            itemType: null,
            action: null
          });
        },
        title: (() => {
          switch (statusActionConfirm.action) {
            case "publish":
              return __("Publish Item Type", "yatra");
            case "draft":
              return __("Mark as Draft", "yatra");
            case "trash":
              return __("Move to Trash", "yatra");
            case "restore":
              return __("Restore Item Type", "yatra");
            default:
              return __("Confirm Action", "yatra");
          }
        })(),
        message: (() => {
          var _a2;
          const name = ((_a2 = statusActionConfirm.itemType) == null ? void 0 : _a2.name) || "";
          switch (statusActionConfirm.action) {
            case "publish":
              return __(
                'Are you sure you want to publish "{name}"?',
                "yatra"
              ).replace("{name}", name);
            case "draft":
              return __(
                'Are you sure you want to mark "{name}" as draft?',
                "yatra"
              ).replace("{name}", name);
            case "trash":
              return __(
                'Are you sure you want to move "{name}" to trash?',
                "yatra"
              ).replace("{name}", name);
            case "restore":
              return __(
                'Are you sure you want to restore "{name}" to draft?',
                "yatra"
              ).replace("{name}", name);
            default:
              return __(
                "Are you sure you want to perform this action?",
                "yatra"
              );
          }
        })(),
        confirmText: (() => {
          switch (statusActionConfirm.action) {
            case "publish":
              return __("Publish", "yatra");
            case "draft":
            case "restore":
              return __("Mark as Draft", "yatra");
            case "trash":
              return __("Move to Trash", "yatra");
            default:
              return __("Confirm", "yatra");
          }
        })(),
        cancelText: __("Cancel", "yatra"),
        variant: "warning",
        isLoading: false
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      PageHeader,
      {
        title: __("Item Types", "yatra"),
        description: __(
          "Manage categories for itinerary items like Activity, Meal, Accommodation, etc.",
          "yatra"
        ),
        actionCapability: "yatra_edit_trips",
        actions: /* @__PURE__ */ jsxRuntimeExports.jsxs(Button, { onClick: handleCreate, className: "flex items-center gap-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Plus, { className: "w-4 h-4" }),
          __("Add New Type", "yatra")
        ] })
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col md:flex-row gap-2 items-stretch md:items-center", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1 relative", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Search, { className: "absolute left-2.5 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          Input,
          {
            type: "text",
            placeholder: __("Search item types...", "yatra"),
            value: searchTerm,
            onChange: (e) => setSearchTerm(e.target.value),
            className: "pl-9"
          }
        )
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Select,
        {
          value: statusFilter,
          onChange: (e) => setStatusFilter(e.target.value),
          className: "w-full md:w-40",
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "all", children: __("All", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "draft", children: __("Draft", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "publish", children: __("Published", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "trash", children: __("Trash", "yatra") })
          ]
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Select,
        {
          value: sortBy2,
          onChange: (e) => setSortBy(e.target.value),
          className: "w-full md:w-40",
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "name", children: __("Name", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "status", children: __("Status", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "created_at", children: __("Created At", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "updated_at", children: __("Updated At", "yatra") })
          ]
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Button,
        {
          variant: "outline",
          onClick: () => setSortOrder(sortOrder === "asc" ? "desc" : "asc"),
          className: "px-3 flex items-center gap-1.5",
          title: sortOrder === "asc" ? __("Ascending", "yatra") : __("Descending", "yatra"),
          children: [
            sortOrder === "asc" ? /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowUp, { className: "w-4 h-4" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowDown, { className: "w-4 h-4" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs", children: sortOrder === "asc" ? __("Asc", "yatra") : __("Desc", "yatra") })
          ]
        }
      ),
      hasFilters && /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Button,
        {
          variant: "outline",
          onClick: handleResetFilters,
          className: "flex items-center gap-2",
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(X, { className: "w-4 h-4" }),
            __("Reset", "yatra")
          ]
        }
      )
    ] }) }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_view_trips", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
      !isItemTypesError && /* @__PURE__ */ jsxRuntimeExports.jsx(
        BulkActionToolbar,
        {
          selectedIds,
          bulkAction,
          setBulkAction,
          onApply: handleBulkApply,
          onClearSelection: handleClearSelection,
          statusFilter,
          setStatusFilter,
          statusOptions,
          showColumnsDropdown,
          setShowColumnsDropdown,
          columnOptions,
          onToggleColumn: toggleColumn,
          bulkMutationPending,
          totalItems: total,
          bulkActionOptions
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-0", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        Table,
        {
          data: itemTypes,
          columns,
          actions: tableActions,
          isLoading,
          isError: isItemTypesError,
          errorText: __("Error loading item types", "yatra"),
          errorDescription: __(
            "We couldn’t connect to the item types service. Please refresh or try again shortly.",
            "We couldn’t connect to the item types service. Please refresh or try again shortly."
          ),
          errorDetails: derivedErrorDetails,
          errorRequestInfo: errorContext.requestInfo,
          onRetry: () => queryClient2.invalidateQueries({ queryKey: ["item-types"] }),
          onSort: handleSort,
          getSortIcon,
          selectedItemIds: selectedIds,
          onSelectItem: handleSelectItem,
          onSelectAll: handleSelectAll,
          isAllSelected,
          getItemId: (itemType) => itemType.id,
          getItemStatus: (itemType) => itemType.status,
          statusFilter,
          capability: "yatra_view_trips"
        }
      ) }) }),
      total > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-4", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        Pagination,
        {
          currentPage: page,
          totalPages,
          totalItems: total,
          itemsPerPage: 10,
          onPageChange: setPage,
          itemName: __("item types", "yatra")
        }
      ) })
    ] }) })
  ] });
};
const ItemTypeForm = () => {
  const queryClient2 = useQueryClient();
  const { can } = usePermissions();
  const { showToast } = useToast();
  const [formData, setFormData] = reactExports.useState({
    name: "",
    slug: "",
    description: "",
    icon: null,
    color: "blue",
    status: "publish"
  });
  const [errors, setErrors] = reactExports.useState({});
  const [isSubmitting, setIsSubmitting] = reactExports.useState(false);
  const [isSlugEditable, setIsSlugEditable] = reactExports.useState(false);
  const action = reactExports.useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get("action") || "create";
  }, []);
  const typeId = reactExports.useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get("id") ? parseInt(params.get("id") || "0") : null;
  }, []);
  const isEditMode = action === "edit" && typeId !== null;
  const { data: typeData, isLoading: isLoadingType } = useQuery({
    queryKey: ["item-type", typeId],
    queryFn: async () => {
      if (!typeId) return null;
      try {
        const response = await apiClient.get(`/item-types/${typeId}`);
        return response;
      } catch (error) {
        showToast(
          (error == null ? void 0 : error.message) || __("Failed to load item type", "yatra"),
          "error"
        );
        throw error;
      }
    },
    enabled: isEditMode && can("yatra_view_trips")
  });
  reactExports.useEffect(() => {
    if (typeData && isEditMode) {
      let iconValue = null;
      if (typeData.icon) {
        if (typeof typeData.icon === "string") {
          iconValue = { type: "icon", value: typeData.icon };
        } else if (typeof typeData.icon === "object" && typeData.icon !== null) {
          iconValue = typeData.icon;
        }
      }
      setFormData({
        name: typeData.name || "",
        slug: typeData.slug || "",
        description: typeData.description || "",
        icon: iconValue,
        color: typeData.color || "blue",
        status: typeData.status || "publish"
      });
    }
  }, [typeData, isEditMode]);
  const handleNameChange = (value) => {
    if (!isEditMode && !isSlugEditable) {
      const newSlug = generateSlug(value);
      setFormData((prev) => ({
        ...prev,
        name: value,
        slug: newSlug
      }));
    } else {
      setFormData((prev) => ({
        ...prev,
        name: value
      }));
    }
    if (errors.name) {
      setErrors((prev) => ({ ...prev, name: "" }));
    }
  };
  const handleSlugChange = (value) => {
    if (isSlugEditable) {
      setFormData((prev) => ({ ...prev, slug: value }));
      if (errors.slug) {
        setErrors((prev) => ({ ...prev, slug: "" }));
      }
    }
  };
  const handleToggleSlugEdit = () => {
    if (isSlugEditable) {
      const newSlug = generateSlug(formData.name);
      setFormData((prev) => ({ ...prev, slug: newSlug }));
    }
    setIsSlugEditable(!isSlugEditable);
  };
  const handleFieldChange = (field, value) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
    if (errors[field]) {
      setErrors((prev) => ({ ...prev, [field]: "" }));
    }
  };
  const validateForm = () => {
    const newErrors = {};
    if (!formData.name.trim()) {
      newErrors.name = __("Name is required", "yatra");
    }
    if (!formData.slug.trim()) {
      newErrors.slug = __("Slug is required", "yatra");
    } else if (!/^[\p{L}\p{N}-]+$/u.test(formData.slug)) {
      newErrors.slug = __(
        "Slug can only contain letters, numbers, and hyphens",
        "yatra"
      );
    }
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };
  const saveMutation = useMutation({
    mutationFn: async (data) => {
      const payload = {
        name: data.name.trim(),
        slug: data.slug.trim(),
        description: data.description.trim(),
        icon: data.icon,
        color: data.color,
        status: data.status
      };
      if (isEditMode && isSlugEditable) {
        payload.preserve_slug = true;
      }
      if (isEditMode && typeId) {
        return await apiClient.put(`/item-types/${typeId}`, payload);
      } else {
        return await apiClient.post("/item-types", payload);
      }
    },
    onSuccess: (response) => {
      queryClient2.invalidateQueries({ queryKey: ["item-types"] });
      queryClient2.invalidateQueries({ queryKey: ["item-type", typeId] });
      showToast(
        isEditMode ? __("Item type updated successfully", "yatra") : __("Item type created successfully", "yatra"),
        "success"
      );
      if (isEditMode) {
        setIsSubmitting(false);
      } else {
        setTimeout(() => {
          var _a;
          const newId = (response == null ? void 0 : response.id) || typeId;
          window.location.href = `${((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=itinerary&tab=item-types&action=edit&id=${newId}`;
        }, 1e3);
      }
    },
    onError: (error) => {
      const errorMessage = (error == null ? void 0 : error.message) || __("An error occurred while saving the item type", "yatra");
      showToast(errorMessage, "error");
      setIsSubmitting(false);
    }
  });
  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!validateForm()) {
      showToast(__("Please fix the form errors", "yatra"), "warning");
      return;
    }
    setIsSubmitting(true);
    setErrors({});
    saveMutation.mutate(formData);
  };
  const handleCancel = () => {
    var _a;
    window.location.href = `${((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=itinerary&tab=item-types`;
  };
  const colorOptions = [
    { value: "blue", label: __("Blue", "yatra") },
    { value: "green", label: __("Green", "yatra") },
    { value: "purple", label: __("Purple", "yatra") },
    { value: "orange", label: __("Orange", "yatra") },
    { value: "red", label: __("Red", "yatra") },
    { value: "yellow", label: __("Yellow", "yatra") },
    { value: "gray", label: __("Gray", "yatra") }
  ];
  if (isEditMode && isLoadingType) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg p-6", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-8 bg-gray-200 dark:bg-gray-700 rounded w-1/4 mb-2 animate-pulse" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-1/2 animate-pulse" })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-3 gap-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "lg:col-span-2 space-y-3", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "p-6 space-y-4", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-20 mb-2 animate-pulse" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-16 mb-2 animate-pulse" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-24 mb-2 animate-pulse" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-32 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-16 mb-2 animate-pulse" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-16 mb-2 animate-pulse" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-16 mb-2 animate-pulse" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" })
          ] })
        ] }) }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-3", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "p-6", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-6 bg-gray-200 dark:bg-gray-700 rounded w-20 mb-4 animate-pulse" }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" })
          ] })
        ] }) }) })
      ] })
    ] });
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      PageHeader,
      {
        title: isEditMode ? __("Edit Item Type", "yatra") : __("Add New Item Type", "yatra"),
        description: isEditMode ? __("Update item type information", "yatra") : __(
          "Create a new category for organizing itinerary items",
          "yatra"
        ),
        actions: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Button,
          {
            variant: "outline",
            onClick: handleCancel,
            className: "flex items-center gap-2",
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowLeft, { className: "w-4 h-4" }),
              __("Back", "yatra")
            ]
          }
        )
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_edit_trips", children: /* @__PURE__ */ jsxRuntimeExports.jsx("form", { onSubmit: handleSubmit, children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-3 gap-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "lg:col-span-2 space-y-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Basic Information", "yatra") }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "label",
              {
                htmlFor: "name",
                className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                children: [
                  __("Type Name", "yatra"),
                  " ",
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
                ]
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              Input,
              {
                id: "name",
                type: "text",
                value: formData.name,
                onChange: (e) => handleNameChange(e.target.value),
                placeholder: __("e.g., Activity", "yatra"),
                className: errors.name ? "border-red-500" : "",
                required: true
              }
            ),
            errors.name && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1.5 text-sm text-red-600 dark:text-red-400", children: errors.name })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "label",
              {
                htmlFor: "slug",
                className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                children: [
                  __("Slug", "yatra"),
                  " ",
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
                ]
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Input,
                {
                  id: "slug",
                  type: "text",
                  value: formData.slug,
                  onChange: (e) => handleSlugChange(e.target.value),
                  placeholder: __("item-type-slug", "yatra"),
                  className: `pr-10 ${errors.slug ? "border-red-500" : ""} ${!isSlugEditable ? "bg-gray-50 dark:bg-gray-800 cursor-not-allowed" : ""}`,
                  disabled: !isSlugEditable,
                  required: true
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "button",
                {
                  type: "button",
                  onClick: handleToggleSlugEdit,
                  className: "absolute right-2 top-1/2 -translate-y-1/2 p-1.5 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors rounded",
                  "aria-label": isSlugEditable ? __("Cancel editing slug", "yatra") : __("Edit slug", "yatra"),
                  children: isSlugEditable ? /* @__PURE__ */ jsxRuntimeExports.jsx(X, { className: "w-4 h-4" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(Pen, { className: "w-4 h-4" })
                }
              )
            ] }),
            errors.slug && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm text-red-500", children: errors.slug }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-xs text-gray-500 dark:text-gray-400", children: isSlugEditable ? __(
              "Manually editing slug. Click X to cancel and regenerate from name.",
              "yatra"
            ) : __(
              "Auto-generated from name. Click edit icon to customize.",
              "yatra"
            ) })
          ] }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "label",
              {
                htmlFor: "description",
                className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                children: __("Description", "yatra")
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "textarea",
              {
                id: "description",
                value: formData.description,
                onChange: (e) => handleFieldChange("description", e.target.value),
                placeholder: __(
                  "Describe what this item type is used for...",
                  "yatra"
                ),
                rows: 4,
                className: "flex w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm ring-offset-white placeholder:text-gray-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 dark:border-gray-600 dark:bg-gray-800 dark:ring-offset-gray-900 dark:placeholder:text-gray-400 dark:focus-visible:ring-blue-400 resize-none"
              }
            )
          ] })
        ] })
      ] }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Appearance", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
              IconPicker,
              {
                value: formData.icon,
                onChange: (value) => handleFieldChange("icon", value),
                label: __("Icon", "yatra"),
                helpText: __(
                  "Choose an icon to represent this item type visually. Icons help users quickly identify different types. You can also upload a custom image.",
                  "yatra"
                ),
                allowImageUpload: true,
                allowIconSelection: true,
                size: "md"
              }
            ) }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "label",
                {
                  htmlFor: "color",
                  className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                  children: __("Color", "yatra")
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Select,
                {
                  id: "color",
                  value: formData.color,
                  onChange: (e) => handleFieldChange("color", e.target.value),
                  children: colorOptions.map((color2) => /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: color2.value, children: color2.label }, color2.value))
                }
              )
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Status", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "space-y-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "label",
              {
                htmlFor: "status",
                className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                children: __("Item Type Status", "yatra")
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              Select,
              {
                id: "status",
                value: formData.status,
                onChange: (e) => handleFieldChange("status", e.target.value),
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "publish", children: __("Publish", "yatra") }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "draft", children: __("Draft", "yatra") }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "trash", children: __("Trash", "yatra") })
                ]
              }
            )
          ] }) })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-3", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-2", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Button,
            {
              type: "submit",
              disabled: isSubmitting,
              className: "flex-1 flex items-center justify-center gap-2",
              children: isSubmitting ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Loader2, { className: "w-4 h-4 animate-spin" }),
                __("Saving...", "yatra")
              ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Save, { className: "w-4 h-4" }),
                isEditMode ? __("Update Type", "yatra") : __("Create Type", "yatra")
              ] })
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Button,
            {
              type: "button",
              variant: "outline",
              onClick: handleCancel,
              disabled: isSubmitting,
              children: __("Cancel", "yatra")
            }
          )
        ] }) }) }) })
      ] })
    ] }) }) })
  ] });
};
const Items = () => {
  var _a;
  const [searchTerm, setSearchTerm] = reactExports.useState("");
  const [typeFilter, setTypeFilter] = reactExports.useState("all");
  const [statusFilter, setStatusFilter] = reactExports.useState("all");
  const [sortBy2, setSortBy] = reactExports.useState("id");
  const [sortOrder, setSortOrder] = reactExports.useState("desc");
  const [page, setPage] = reactExports.useState(1);
  const [selectedIds, setSelectedIds] = reactExports.useState([]);
  const [bulkAction, setBulkAction] = reactExports.useState("");
  const [showColumnsDropdown, setShowColumnsDropdown] = reactExports.useState(false);
  const [bulkMutationPending, setBulkMutationPending] = reactExports.useState(false);
  const [deleteConfirm, setDeleteConfirm] = reactExports.useState({
    isOpen: false,
    item: null
  });
  const [statusActionConfirm, setStatusActionConfirm] = reactExports.useState({
    isOpen: false,
    item: null,
    action: null
  });
  const updateItemStatus = async (item, status) => {
    await apiClient.put(`/items/${item.id}`, {
      // Required for validation
      name: item.name,
      type_id: item.type_id,
      // Preserve current slug and description so status change is safe
      slug: item.slug,
      description: item.description,
      status,
      preserve_slug: true
    });
  };
  const queryClient2 = useQueryClient();
  const { can } = usePermissions();
  const { showToast } = useToast();
  const baseAdminUrl = ((_a = window.yatraAdmin) == null ? void 0 : _a.adminUrl) || "";
  const queryParams = reactExports.useMemo(() => {
    const params = {
      page,
      per_page: 10,
      orderby: sortBy2,
      order: sortOrder
    };
    if (searchTerm) {
      params.search = searchTerm;
    }
    if (typeFilter !== "all") {
      params.type_id = typeFilter;
    }
    if (statusFilter !== "all") {
      params.status = statusFilter;
    }
    return params;
  }, [searchTerm, typeFilter, statusFilter, sortBy2, sortOrder, page]);
  const { data: statsData } = useQuery({
    queryKey: ["items-stats"],
    queryFn: async () => {
      try {
        const response = await apiClient.get("/items/stats");
        return response;
      } catch (error2) {
        return { all: 0, publish: 0, draft: 0, trash: 0 };
      }
    },
    enabled: can("yatra_view_trips")
  });
  const [availableTypes, setAvailableTypes] = reactExports.useState([]);
  const { data, isLoading, error } = useQuery({
    queryKey: ["items", queryParams],
    queryFn: async () => {
      try {
        const response = await apiClient.get("/items", { params: queryParams });
        return response;
      } catch (error2) {
        showToast(
          (error2 == null ? void 0 : error2.message) || __("Failed to load items", "yatra"),
          "error"
        );
        throw error2;
      }
    },
    enabled: can("yatra_view_trips")
  });
  const deleteMutation = useMutation({
    mutationFn: async (id) => {
      return await apiClient.delete(`/items/${id}`);
    },
    onSuccess: () => {
      queryClient2.invalidateQueries({ queryKey: ["items"] });
      queryClient2.invalidateQueries({ queryKey: ["items-stats"] });
      showToast(__("Item deleted successfully", "yatra"), "success");
      setDeleteConfirm({ isOpen: false, item: null });
    },
    onError: (error2) => {
      showToast(
        (error2 == null ? void 0 : error2.message) || __("Failed to delete item", "yatra"),
        "error"
      );
    }
  });
  const items = (data == null ? void 0 : data.data) || [];
  const total = (data == null ? void 0 : data.total) || 0;
  const totalPages = Math.ceil(total / 10);
  const errorContext = getErrorContext(error);
  const apiErrorMessage = (data == null ? void 0 : data.error) || (data == null ? void 0 : data.message);
  const derivedErrorDetails = errorContext.details || (apiErrorMessage ? String(apiErrorMessage) : void 0) || (error ? String((error == null ? void 0 : error.message) || error) : void 0);
  const isItemsError = !!error || !!apiErrorMessage;
  reactExports.useEffect(() => {
    var _a2;
    if ((_a2 = data == null ? void 0 : data.meta) == null ? void 0 : _a2.available_types) {
      setAvailableTypes(data.meta.available_types);
    }
  }, [data]);
  const types = availableTypes;
  const formatDate2 = (dateString) => {
    if (!dateString) return __("N/A", "yatra");
    try {
      const date2 = new Date(dateString);
      return date2.toLocaleDateString("en-US", {
        month: "short",
        day: "numeric",
        year: "numeric",
        hour: "2-digit",
        minute: "2-digit"
      });
    } catch (e) {
      return dateString;
    }
  };
  const getStatusBadge = (status) => {
    const statusMap = {
      publish: {
        className: "bg-green-100 text-green-700 dark:bg-green-900/20 dark:text-green-400",
        label: __("Publish", "yatra")
      },
      draft: {
        className: "bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-400",
        label: __("Draft", "yatra")
      },
      trash: {
        className: "bg-red-100 text-red-700 dark:bg-red-900/20 dark:text-red-400",
        label: __("Trash", "yatra")
      }
    };
    const statusInfo = statusMap[status] || {
      className: "bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-400",
      label: status
    };
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "span",
      {
        className: `inline-flex items-center px-2 py-1 rounded-md text-xs font-medium ${statusInfo.className}`,
        children: statusInfo.label
      }
    );
  };
  const formatUser = (userId, userName) => {
    if (userName) {
      return userName;
    }
    return `User #${userId}`;
  };
  const handleCreate = () => {
    window.location.href = `${baseAdminUrl}?page=yatra&subpage=itinerary&tab=items&action=create`;
  };
  const handleEdit = (item) => {
    window.location.href = `${baseAdminUrl}?page=yatra&subpage=itinerary&tab=items&action=edit&id=${item.id}`;
  };
  const handleDelete = (item) => {
    setDeleteConfirm({ isOpen: true, item });
  };
  const confirmDelete = () => {
    if (deleteConfirm.item) {
      deleteMutation.mutate(deleteConfirm.item.id);
    }
  };
  const handleResetFilters = () => {
    setSearchTerm("");
    setTypeFilter("all");
    setStatusFilter("all");
    setSortBy("name");
    setSortOrder("asc");
    setPage(1);
  };
  const handleSort = (field) => {
    if (sortBy2 === field) {
      setSortOrder(sortOrder === "asc" ? "desc" : "asc");
    } else {
      setSortBy(field);
      setSortOrder("asc");
    }
  };
  const getSortIcon = (field) => {
    if (sortBy2 !== field) {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowUpDown, { className: "w-3.5 h-3.5 ml-1 text-gray-400" });
    }
    return sortOrder === "asc" ? /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowUp, { className: "w-3.5 h-3.5 ml-1 text-gray-600 dark:text-gray-300" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowDown, { className: "w-3.5 h-3.5 ml-1 text-gray-600 dark:text-gray-300" });
  };
  const hasFilters = searchTerm || typeFilter !== "all" || statusFilter !== "all" || sortBy2 !== "name" || sortOrder !== "asc";
  const [visibleColumns, setVisibleColumns] = reactExports.useState(
    {
      item: true,
      type: true,
      description: true,
      status: true,
      usage: true,
      date: true,
      author: true
    }
  );
  const toggleColumn = (columnKey) => {
    setVisibleColumns((prev) => ({
      ...prev,
      [columnKey]: !prev[columnKey]
    }));
  };
  const columnOptions = [
    { key: "item", label: __("Item", "yatra"), visible: visibleColumns.item },
    { key: "type", label: __("Type", "yatra"), visible: visibleColumns.type },
    {
      key: "description",
      label: __("Description", "yatra"),
      visible: visibleColumns.description
    },
    {
      key: "status",
      label: __("Status", "yatra"),
      visible: visibleColumns.status
    },
    {
      key: "usage",
      label: __("Usage", "yatra"),
      visible: visibleColumns.usage
    },
    { key: "date", label: __("Date", "yatra"), visible: visibleColumns.date },
    {
      key: "author",
      label: __("Author", "yatra"),
      visible: visibleColumns.author
    }
  ];
  const isAllSelected = items.length > 0 && selectedIds.length === items.length;
  const handleSelectItem = (id, checked) => {
    setSelectedIds(
      (prev) => checked ? [...prev, id] : prev.filter((existingId) => existingId !== id)
    );
  };
  const handleSelectAll = (checked) => {
    if (checked) {
      setSelectedIds(items.map((item) => item.id));
    } else {
      setSelectedIds([]);
    }
  };
  const handleClearSelection = () => {
    setSelectedIds([]);
  };
  const statusCounts = reactExports.useMemo(() => {
    if (statsData) {
      return {
        all: statsData.all ?? 0,
        publish: statsData.publish ?? 0,
        draft: statsData.draft ?? 0,
        trash: statsData.trash ?? 0
      };
    }
    return {
      all: 0,
      publish: 0,
      draft: 0,
      trash: 0
    };
  }, [statsData]);
  const statusOptions = [
    { key: "all", label: __("All", "yatra"), count: statusCounts.all },
    { key: "draft", label: __("Draft", "yatra"), count: statusCounts.draft },
    {
      key: "publish",
      label: __("Publish", "yatra"),
      count: statusCounts.publish
    },
    { key: "trash", label: __("Trash", "yatra"), count: statusCounts.trash }
  ];
  const bulkActionOptions = reactExports.useMemo(() => {
    if (statusFilter === "trash") {
      return [
        { value: "restore", label: __("Restore to Draft", "yatra") },
        { value: "delete", label: __("Delete Permanently", "yatra") }
      ];
    }
    return [
      { value: "publish", label: __("Mark as Published", "yatra") },
      { value: "draft", label: __("Mark as Draft", "yatra") },
      { value: "trash", label: __("Move to Trash", "yatra") },
      { value: "delete", label: __("Delete Permanently", "yatra") }
    ];
  }, [statusFilter]);
  const handleBulkApply = async () => {
    if (!bulkAction || selectedIds.length === 0) {
      showToast(
        __("Please select items and a bulk action first.", "yatra"),
        "error"
      );
      return;
    }
    try {
      setBulkMutationPending(true);
      const selectedItems = items.filter(
        (item) => selectedIds.includes(item.id)
      );
      if (bulkAction === "delete") {
        await Promise.all(
          selectedIds.map((id) => apiClient.delete(`/items/${id}`))
        );
        showToast(__("Items deleted successfully", "yatra"), "success");
      } else if (bulkAction === "publish") {
        await Promise.all(
          selectedItems.map((item) => updateItemStatus(item, "publish"))
        );
        showToast(__("Items marked as published", "yatra"), "success");
      } else if (bulkAction === "draft") {
        const targetStatus = "draft";
        await Promise.all(
          selectedItems.map(
            (item) => updateItemStatus(item, targetStatus)
          )
        );
        showToast(
          statusFilter === "trash" ? __("Items restored to draft", "yatra") : __("Items marked as draft", "yatra"),
          "success"
        );
      } else if (bulkAction === "trash") {
        await Promise.all(
          selectedItems.map((item) => updateItemStatus(item, "trash"))
        );
        showToast(__("Items moved to trash", "yatra"), "success");
      } else if (bulkAction === "restore") {
        await Promise.all(
          selectedItems.map((item) => updateItemStatus(item, "draft"))
        );
        showToast(__("Items restored to draft", "yatra"), "success");
      }
      await queryClient2.invalidateQueries({ queryKey: ["items"] });
      await queryClient2.invalidateQueries({ queryKey: ["items-stats"] });
      setSelectedIds([]);
      setBulkAction("");
    } catch (error2) {
      showToast(__("Bulk action failed", "yatra"), "error");
    } finally {
      setBulkMutationPending(false);
    }
  };
  const columns = [
    {
      key: "item",
      label: __("Item", "yatra"),
      sortable: true,
      width: "w-[200px]",
      visible: visibleColumns.item,
      render: (item) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "font-medium text-gray-900 dark:text-white", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          "a",
          {
            href: `${baseAdminUrl}?page=yatra&subpage=itinerary&tab=items&action=edit&id=${item.id}`,
            className: "hover:underline underline-offset-2 text-blue-600 dark:text-blue-400",
            children: item.name
          }
        ) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-xs text-gray-500 dark:text-gray-400 mt-0.5", children: item.slug })
      ] })
    },
    {
      key: "type",
      label: __("Type", "yatra"),
      sortable: true,
      width: "w-[150px]",
      visible: visibleColumns.type,
      render: (item) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
        item.type_icon && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-8 h-8 rounded-md bg-gray-100 dark:bg-gray-800 flex items-center justify-center", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          IconSelector,
          {
            iconName: item.type_icon,
            provider: item.type_icon_provider ?? "yatra",
            className: "w-4 h-4 text-gray-700 dark:text-gray-300"
          }
        ) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm text-gray-600 dark:text-gray-400", children: item.type_name || __("Unknown", "yatra") })
      ] })
    },
    {
      key: "description",
      label: __("Description", "yatra"),
      sortable: false,
      width: "w-[200px]",
      visible: visibleColumns.description,
      render: (item) => /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-600 dark:text-gray-400 text-sm line-clamp-2", children: item.description || __("No description", "yatra") })
    },
    {
      key: "status",
      label: __("Status", "yatra"),
      sortable: true,
      width: "w-[100px]",
      visible: visibleColumns.status,
      render: (item) => getStatusBadge(item.status)
    },
    {
      key: "usage",
      label: __("Usage", "yatra"),
      sortable: false,
      width: "w-[100px]",
      visible: visibleColumns.usage,
      render: (item) => /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-center", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Badge, { variant: "outline", className: "font-medium", children: item.usage_count ?? 0 }) })
    },
    {
      key: "date",
      label: __("Date", "yatra"),
      sortable: true,
      width: "w-[150px]",
      visible: visibleColumns.date,
      render: (item) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-gray-500 dark:text-gray-400 text-sm", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: formatDate2(item.created_at) }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-xs text-gray-400 dark:text-gray-500 mt-0.5", children: [
          __("Updated", "yatra"),
          ": ",
          formatDate2(item.updated_at)
        ] })
      ] })
    },
    {
      key: "author",
      label: __("Author", "yatra"),
      sortable: false,
      width: "w-[150px]",
      visible: visibleColumns.author,
      render: (item) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-gray-600 dark:text-gray-400 text-sm", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: formatUser(item.created_by, item.created_by_name) }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-xs text-gray-400 dark:text-gray-500 mt-0.5", children: [
          __("Updated by", "yatra"),
          ":",
          " ",
          formatUser(item.updated_by, item.updated_by_name)
        ] })
      ] })
    }
  ];
  const tableActions = reactExports.useMemo(() => {
    const actions = [];
    if (can("yatra_edit_trips")) {
      actions.push({
        key: "edit",
        label: __("Edit", "yatra"),
        icon: /* @__PURE__ */ jsxRuntimeExports.jsx(PenSquare, { className: "w-4 h-4" }),
        onClick: (item) => handleEdit(item)
      });
      actions.push({
        key: "publish",
        label: __("Mark as Published", "yatra"),
        icon: /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowUp, { className: "w-4 h-4" }),
        onClick: (item) => {
          setStatusActionConfirm({ isOpen: true, item, action: "publish" });
        },
        condition: (item) => item.status !== "publish" && item.status !== "trash"
      });
      actions.push({
        key: "draft",
        label: __("Mark as Draft", "yatra"),
        icon: /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowDown, { className: "w-4 h-4" }),
        onClick: (item) => {
          setStatusActionConfirm({ isOpen: true, item, action: "draft" });
        },
        condition: (item) => item.status !== "draft" && item.status !== "trash"
      });
      actions.push({
        key: "trash",
        label: __("Move to Trash", "yatra"),
        icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "w-4 h-4" }),
        onClick: (item) => {
          setStatusActionConfirm({ isOpen: true, item, action: "trash" });
        },
        condition: (item) => item.status !== "trash"
      });
      actions.push({
        key: "restore",
        label: __("Restore to Draft", "yatra"),
        icon: /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowUp, { className: "w-4 h-4" }),
        onClick: (item) => {
          setStatusActionConfirm({ isOpen: true, item, action: "restore" });
        },
        condition: (item) => item.status === "trash"
      });
    }
    if (can("yatra_delete_trips")) {
      actions.push({
        key: "delete",
        label: __("Delete Permanently", "yatra"),
        icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "w-4 h-4" }),
        onClick: (item) => handleDelete(item),
        variant: "destructive",
        condition: (item) => item.status === "trash"
      });
    }
    return actions;
  }, [can, queryClient2, showToast]);
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      ConfirmationDialog,
      {
        isOpen: deleteConfirm.isOpen,
        onClose: () => setDeleteConfirm({ isOpen: false, item: null }),
        onConfirm: confirmDelete,
        title: __("Delete Item", "yatra"),
        message: deleteConfirm.item ? __(
          'Are you sure you want to delete "{name}"? This action cannot be undone.',
          "yatra"
        ).replace("{name}", deleteConfirm.item.name) : __(
          "Are you sure you want to delete this item? This action cannot be undone.",
          "yatra"
        ),
        confirmText: __("Delete", "yatra"),
        cancelText: __("Cancel", "yatra"),
        variant: "danger",
        isLoading: deleteMutation.isPending
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      ConfirmationDialog,
      {
        isOpen: statusActionConfirm.isOpen,
        onClose: () => setStatusActionConfirm({ isOpen: false, item: null, action: null }),
        onConfirm: async () => {
          const { item, action } = statusActionConfirm;
          if (!item || !action) {
            return;
          }
          const targetStatus = action === "restore" ? "draft" : action;
          await updateItemStatus(
            item,
            targetStatus
          );
          const successMessage = action === "publish" ? __("Item marked as published.", "yatra") : action === "draft" || action === "restore" ? __("Item marked as draft.", "yatra") : __("Item moved to trash.", "yatra");
          showToast(successMessage, "success");
          queryClient2.invalidateQueries({ queryKey: ["items"] });
          queryClient2.invalidateQueries({ queryKey: ["items-stats"] });
          setStatusActionConfirm({ isOpen: false, item: null, action: null });
        },
        title: (() => {
          switch (statusActionConfirm.action) {
            case "publish":
              return __("Publish Item", "yatra");
            case "draft":
              return __("Mark as Draft", "yatra");
            case "trash":
              return __("Move to Trash", "yatra");
            case "restore":
              return __("Restore Item", "yatra");
            default:
              return __("Confirm Action", "yatra");
          }
        })(),
        message: (() => {
          var _a2;
          const name = ((_a2 = statusActionConfirm.item) == null ? void 0 : _a2.name) || "";
          switch (statusActionConfirm.action) {
            case "publish":
              return __(
                'Are you sure you want to publish "{name}"?',
                "yatra"
              ).replace("{name}", name);
            case "draft":
              return __(
                'Are you sure you want to mark "{name}" as draft?',
                "yatra"
              ).replace("{name}", name);
            case "trash":
              return __(
                'Are you sure you want to move "{name}" to trash?',
                "yatra"
              ).replace("{name}", name);
            case "restore":
              return __(
                'Are you sure you want to restore "{name}" to draft?',
                "yatra"
              ).replace("{name}", name);
            default:
              return __(
                "Are you sure you want to perform this action?",
                "yatra"
              );
          }
        })(),
        confirmText: (() => {
          switch (statusActionConfirm.action) {
            case "publish":
              return __("Publish", "yatra");
            case "draft":
            case "restore":
              return __("Mark as Draft", "yatra");
            case "trash":
              return __("Move to Trash", "yatra");
            default:
              return __("Confirm", "yatra");
          }
        })(),
        cancelText: __("Cancel", "yatra"),
        variant: "warning",
        isLoading: false
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      PageHeader,
      {
        title: __("Items", "yatra"),
        description: __(
          "Manage specific items (subtypes) under item types. Examples: Hiking (under Activity), Lunch (under Meal), Bus (under Transportation).",
          "yatra"
        ),
        actionCapability: "yatra_edit_trips",
        actions: /* @__PURE__ */ jsxRuntimeExports.jsxs(Button, { onClick: handleCreate, className: "flex items-center gap-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Plus, { className: "w-4 h-4" }),
          __("Add New Item", "yatra")
        ] })
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col md:flex-row gap-2 items-stretch md:items-center", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1 relative", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Search, { className: "absolute left-2.5 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          Input,
          {
            type: "text",
            placeholder: __("Search items...", "yatra"),
            value: searchTerm,
            onChange: (e) => setSearchTerm(e.target.value),
            className: "pl-9"
          }
        )
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Select,
        {
          value: typeFilter,
          onChange: (e) => setTypeFilter(e.target.value),
          className: "w-full md:w-48",
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "all", children: __("All Types", "yatra") }),
            types.map((type) => /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: type.id, children: type.name }, type.id))
          ]
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Select,
        {
          value: statusFilter,
          onChange: (e) => setStatusFilter(e.target.value),
          className: "w-full md:w-40",
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "all", children: __("All Status", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "draft", children: __("Draft", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "publish", children: __("Publish", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "trash", children: __("Trash", "yatra") })
          ]
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Select,
        {
          value: sortBy2,
          onChange: (e) => setSortBy(e.target.value),
          className: "w-full md:w-40",
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "name", children: __("Name", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "type_id", children: __("Type", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "status", children: __("Status", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "created_at", children: __("Created At", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "updated_at", children: __("Updated At", "yatra") })
          ]
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Button,
        {
          variant: "outline",
          onClick: () => setSortOrder(sortOrder === "asc" ? "desc" : "asc"),
          className: "px-3 flex items-center gap-1.5",
          title: sortOrder === "asc" ? __("Ascending", "yatra") : __("Descending", "yatra"),
          children: [
            sortOrder === "asc" ? /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowUp, { className: "w-4 h-4" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowDown, { className: "w-4 h-4" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs", children: sortOrder === "asc" ? __("Asc", "yatra") : __("Desc", "yatra") })
          ]
        }
      ),
      hasFilters && /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Button,
        {
          variant: "outline",
          onClick: handleResetFilters,
          className: "flex items-center gap-2",
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(X, { className: "w-4 h-4" }),
            __("Reset", "yatra")
          ]
        }
      )
    ] }) }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_view_trips", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
      !isItemsError && /* @__PURE__ */ jsxRuntimeExports.jsx(
        BulkActionToolbar,
        {
          selectedIds,
          bulkAction,
          setBulkAction,
          onApply: handleBulkApply,
          onClearSelection: handleClearSelection,
          statusFilter,
          setStatusFilter,
          statusOptions,
          showColumnsDropdown,
          setShowColumnsDropdown,
          columnOptions,
          onToggleColumn: toggleColumn,
          bulkMutationPending,
          totalItems: total,
          bulkActionOptions
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-0", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        Table,
        {
          data: items,
          columns,
          actions: tableActions,
          isLoading,
          isError: isItemsError,
          errorText: __("Error loading items", "yatra"),
          errorDescription: __(
            "We couldn't connect to the items service. Please refresh or try again shortly.",
            "We couldn't connect to the items service. Please refresh or try again shortly."
          ),
          errorDetails: derivedErrorDetails,
          errorRequestInfo: errorContext.requestInfo,
          onRetry: () => queryClient2.invalidateQueries({ queryKey: ["items"] }),
          emptyText: __("No items found", "yatra"),
          emptyDescription: hasFilters ? __(
            "Try adjusting your filters to see more results.",
            "yatra"
          ) : __("Get started by creating your first item.", "yatra"),
          onCreateClick: can("yatra_edit_trips") ? handleCreate : void 0,
          onSort: handleSort,
          getSortIcon,
          selectedItemIds: selectedIds,
          onSelectItem: handleSelectItem,
          onSelectAll: handleSelectAll,
          isAllSelected,
          getItemId: (item) => item.id,
          getItemStatus: (item) => item.status,
          statusFilter,
          capability: "yatra_view_trips"
        }
      ) }) }),
      total > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-4", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        Pagination,
        {
          currentPage: page,
          totalPages,
          totalItems: total,
          itemsPerPage: 10,
          onPageChange: setPage,
          itemName: __("items", "yatra")
        }
      ) })
    ] }) })
  ] });
};
const SearchableSelect = ({
  value,
  onChange,
  options: options2,
  placeholder = __("Select an option...", "yatra"),
  searchPlaceholder = __("Search...", "yatra"),
  className = "",
  error = false,
  disabled = false,
  showValueId = true
}) => {
  const [isOpen, setIsOpen] = reactExports.useState(false);
  const [searchTerm, setSearchTerm] = reactExports.useState("");
  const containerRef = reactExports.useRef(null);
  const searchInputRef = reactExports.useRef(null);
  const [menuRect, setMenuRect] = reactExports.useState(null);
  const filteredOptions = options2.filter(
    (option) => option.label.toLowerCase().includes(searchTerm.toLowerCase()) || option.value.toLowerCase().includes(searchTerm.toLowerCase())
  );
  const selectedOption = options2.find((opt) => opt.value === value);
  reactExports.useEffect(() => {
    const handleClickOutside = (event) => {
      const target2 = event.target;
      if (containerRef.current && containerRef.current.contains(target2)) {
        return;
      }
      const portalRoot = document.getElementById(
        "yatra-searchable-select-portal"
      );
      if (portalRoot && portalRoot.contains(target2)) {
        return;
      }
      setIsOpen(false);
      setSearchTerm("");
    };
    if (isOpen) {
      document.addEventListener("mousedown", handleClickOutside);
      setTimeout(() => {
        var _a;
        (_a = searchInputRef.current) == null ? void 0 : _a.focus();
      }, 100);
    }
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [isOpen]);
  reactExports.useLayoutEffect(() => {
    if (!isOpen) {
      setMenuRect(null);
      return;
    }
    const measure = () => {
      const el = containerRef.current;
      if (!el) return;
      const rect = el.getBoundingClientRect();
      setMenuRect({
        top: rect.bottom + 4,
        left: rect.left,
        width: rect.width
      });
    };
    measure();
    window.addEventListener("scroll", measure, true);
    window.addEventListener("resize", measure);
    return () => {
      window.removeEventListener("scroll", measure, true);
      window.removeEventListener("resize", measure);
    };
  }, [isOpen]);
  const handleSelect = (optionValue) => {
    onChange(optionValue);
    setIsOpen(false);
    setSearchTerm("");
  };
  const handleClear = (e) => {
    e.stopPropagation();
    onChange("");
    setSearchTerm("");
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(
    "div",
    {
      ref: containerRef,
      className: `relative ${className}`,
      style: { zIndex: isOpen ? 9999 : "auto" },
      children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "div",
          {
            className: `flex h-11 w-full rounded-md border-2 ${error ? "border-red-500" : "border-gray-300 dark:border-gray-600"} bg-white dark:bg-gray-800 px-4 py-2.5 text-base ring-offset-white focus-within:outline-none focus-within:ring-2 focus-within:ring-blue-500 focus-within:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 dark:ring-offset-gray-900 dark:focus-within:ring-blue-400 transition-colors`,
            children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "div",
              {
                onClick: () => !disabled && setIsOpen(!isOpen),
                className: `flex-1 flex items-center justify-between text-left ${disabled ? "cursor-not-allowed opacity-50" : "cursor-pointer"}`,
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "span",
                    {
                      className: selectedOption ? "text-gray-900 dark:text-white" : "text-gray-500 dark:text-gray-400",
                      children: selectedOption ? /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between w-full", children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: selectedOption.label }),
                        showValueId && selectedOption.value && selectedOption.value !== "" && /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-xs text-gray-500 dark:text-gray-400 ml-2 font-medium", children: [
                          "ID: ",
                          selectedOption.value
                        ] })
                      ] }) : placeholder
                    }
                  ),
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1", children: [
                    value && !disabled && /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "button",
                      {
                        type: "button",
                        onClick: handleClear,
                        className: "p-0.5 hover:bg-gray-100 dark:hover:bg-gray-700 rounded",
                        "aria-label": __("Clear selection", "yatra"),
                        children: /* @__PURE__ */ jsxRuntimeExports.jsx(X, { className: "w-4 h-4 text-gray-400" })
                      }
                    ),
                    /* @__PURE__ */ jsxRuntimeExports.jsx(
                      ChevronDown,
                      {
                        className: `w-4 h-4 text-gray-400 transition-transform ${isOpen ? "rotate-180" : ""}`
                      }
                    )
                  ] })
                ]
              }
            )
          }
        ),
        isOpen && menuRect && reactDomExports.createPortal(
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "div",
            {
              id: "yatra-searchable-select-portal",
              style: {
                position: "fixed",
                top: menuRect.top,
                left: menuRect.left,
                width: menuRect.width,
                zIndex: 999999
              },
              className: "bg-white dark:bg-gray-800 border-2 border-gray-300 dark:border-gray-600 rounded-md shadow-lg max-h-60 overflow-visible",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-2 border-b border-gray-200 dark:border-gray-700", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(Search, { className: "absolute left-2.5 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    Input,
                    {
                      ref: searchInputRef,
                      type: "text",
                      placeholder: searchPlaceholder,
                      value: searchTerm,
                      onChange: (e) => setSearchTerm(e.target.value),
                      className: "pl-8 h-8",
                      onClick: (e) => e.stopPropagation()
                    }
                  )
                ] }) }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "max-h-48 overflow-y-auto overflow-x-visible", children: filteredOptions.length === 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "px-3 py-2 text-sm text-gray-500 dark:text-gray-400 text-center", children: __("No options found", "yatra") }) : filteredOptions.map((option) => /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "button",
                  {
                    type: "button",
                    onClick: () => handleSelect(option.value),
                    className: `w-full px-3 py-2 text-left text-sm hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors ${value === option.value ? "bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-400" : "text-gray-900 dark:text-white"}`,
                    children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: option.label }),
                      showValueId && option.value && option.value !== "" && /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-xs text-gray-500 dark:text-gray-400 ml-2 font-medium", children: [
                        "ID: ",
                        option.value
                      ] })
                    ] })
                  },
                  option.value
                )) })
              ]
            }
          ),
          document.body
        )
      ]
    }
  );
};
const ItemForm = () => {
  const queryClient2 = useQueryClient();
  const { can } = usePermissions();
  const { showToast } = useToast();
  const [formData, setFormData] = reactExports.useState({
    name: "",
    slug: "",
    description: "",
    type_id: "",
    status: "publish"
  });
  const [errors, setErrors] = reactExports.useState({});
  const [isSubmitting, setIsSubmitting] = reactExports.useState(false);
  const [isSlugEditable, setIsSlugEditable] = reactExports.useState(false);
  const action = reactExports.useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get("action") || "create";
  }, []);
  const itemId = reactExports.useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get("id") ? parseInt(params.get("id") || "0") : null;
  }, []);
  const isEditMode = action === "edit" && itemId !== null;
  const { data: typesData } = useQuery({
    queryKey: ["item-types-published"],
    queryFn: async () => {
      try {
        const response = await apiClient.get("/item-types", {
          params: {
            per_page: 100,
            status: "publish"
            // Only get published item types
          }
        });
        return response.data || [];
      } catch (error) {
        showToast(
          (error == null ? void 0 : error.message) || __("Failed to load item types", "yatra"),
          "error"
        );
        return [];
      }
    },
    enabled: can("yatra_view_trips")
  });
  const { data: itemData, isLoading: isLoadingItem } = useQuery({
    queryKey: ["item", itemId],
    queryFn: async () => {
      if (!itemId) return null;
      try {
        const response = await apiClient.get(`/items/${itemId}`);
        return response;
      } catch (error) {
        showToast(
          (error == null ? void 0 : error.message) || __("Failed to load item", "yatra"),
          "error"
        );
        throw error;
      }
    },
    enabled: isEditMode && can("yatra_view_trips")
  });
  reactExports.useEffect(() => {
    var _a;
    if (itemData && isEditMode) {
      setFormData({
        name: itemData.name || "",
        slug: itemData.slug || "",
        description: itemData.description || "",
        type_id: ((_a = itemData.type_id) == null ? void 0 : _a.toString()) || "",
        status: itemData.status || "publish"
      });
    }
  }, [itemData, isEditMode]);
  const handleNameChange = (value) => {
    if (!isEditMode && !isSlugEditable) {
      const newSlug = generateSlug(value);
      setFormData((prev) => ({
        ...prev,
        name: value,
        slug: newSlug
      }));
    } else {
      setFormData((prev) => ({
        ...prev,
        name: value
      }));
    }
    if (errors.name) {
      setErrors((prev) => ({ ...prev, name: "" }));
    }
  };
  const handleSlugChange = (value) => {
    if (isSlugEditable) {
      setFormData((prev) => ({ ...prev, slug: value }));
      if (errors.slug) {
        setErrors((prev) => ({ ...prev, slug: "" }));
      }
    }
  };
  const handleToggleSlugEdit = () => {
    if (isSlugEditable) {
      const newSlug = generateSlug(formData.name);
      setFormData((prev) => ({ ...prev, slug: newSlug }));
    }
    setIsSlugEditable(!isSlugEditable);
  };
  const handleFieldChange = (field, value) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
    if (errors[field]) {
      setErrors((prev) => ({ ...prev, [field]: "" }));
    }
  };
  const validateForm = () => {
    const newErrors = {};
    if (!formData.name.trim()) {
      newErrors.name = __("Name is required", "yatra");
    }
    if (!formData.slug.trim()) {
      newErrors.slug = __("Slug is required", "yatra");
    } else if (!/^[\p{L}\p{N}-]+$/u.test(formData.slug)) {
      newErrors.slug = __(
        "Slug can only contain letters, numbers, and hyphens",
        "yatra"
      );
    }
    if (!formData.type_id) {
      newErrors.type_id = __("Item type is required", "yatra");
    }
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };
  const saveMutation = useMutation({
    mutationFn: async (data) => {
      const payload = {
        name: data.name.trim(),
        slug: data.slug.trim(),
        description: data.description.trim(),
        type_id: parseInt(data.type_id),
        status: data.status
      };
      if (isEditMode && isSlugEditable) {
        payload.preserve_slug = true;
      }
      if (isEditMode && itemId) {
        return await apiClient.put(`/items/${itemId}`, payload);
      } else {
        return await apiClient.post("/items", payload);
      }
    },
    onSuccess: (response) => {
      queryClient2.invalidateQueries({ queryKey: ["items"] });
      queryClient2.invalidateQueries({ queryKey: ["item", itemId] });
      showToast(
        isEditMode ? __("Item updated successfully", "yatra") : __("Item created successfully", "yatra"),
        "success"
      );
      if (response == null ? void 0 : response.redirect) {
        setTimeout(() => {
          window.location.href = response.redirect_to;
        }, 1e3);
      } else if (response == null ? void 0 : response.stay_on_page) {
        setIsSubmitting(false);
      } else {
        setTimeout(() => {
          var _a;
          window.location.href = `${((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=itinerary&tab=items`;
        }, 1e3);
      }
    },
    onError: (error) => {
      const errorMessage = (error == null ? void 0 : error.message) || __("An error occurred while saving the item", "yatra");
      showToast(errorMessage, "error");
      setIsSubmitting(false);
    }
  });
  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!validateForm()) {
      showToast(__("Please fix the form errors", "yatra"), "warning");
      return;
    }
    setIsSubmitting(true);
    setErrors({});
    saveMutation.mutate(formData);
  };
  const handleCancel = () => {
    var _a;
    window.location.href = `${((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=itinerary&tab=items`;
  };
  if (isEditMode && isLoadingItem) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-center p-8", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(Loader2, { className: "w-6 h-6 animate-spin text-gray-400" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "ml-2 text-gray-600 dark:text-gray-400", children: __("Loading...", "yatra") })
    ] });
  }
  const types = typesData || [];
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      PageHeader,
      {
        title: isEditMode ? __("Edit Item", "yatra") : __("Add New Item", "yatra"),
        description: isEditMode ? __("Update item information", "yatra") : __(
          "Create a specific item under an item type. Examples: Hiking (under Activity), Lunch (under Meal).",
          "yatra"
        ),
        actions: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Button,
          {
            variant: "outline",
            onClick: handleCancel,
            className: "flex items-center gap-2",
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowLeft, { className: "w-4 h-4" }),
              __("Back", "yatra")
            ]
          }
        )
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_edit_trips", children: /* @__PURE__ */ jsxRuntimeExports.jsx("form", { onSubmit: handleSubmit, children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-3 gap-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "lg:col-span-2 space-y-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Basic Information", "yatra") }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "label",
              {
                htmlFor: "type_id",
                className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                children: [
                  __("Item Type", "yatra"),
                  " ",
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
                ]
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              SearchableSelect,
              {
                value: formData.type_id,
                onChange: (value) => handleFieldChange("type_id", value),
                options: types.map((type) => ({
                  value: type.id.toString(),
                  label: type.name,
                  icon: type.icon
                })),
                placeholder: __("Select a type...", "yatra"),
                searchPlaceholder: __("Search item types...", "yatra"),
                className: errors.type_id ? "border-red-500" : "",
                error: !!errors.type_id
              }
            ),
            errors.type_id && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm text-red-500", children: errors.type_id })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "label",
              {
                htmlFor: "name",
                className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                children: [
                  __("Item Name", "yatra"),
                  " ",
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
                ]
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              Input,
              {
                id: "name",
                type: "text",
                value: formData.name,
                onChange: (e) => handleNameChange(e.target.value),
                placeholder: __("e.g., Hiking", "yatra"),
                className: errors.name ? "border-red-500" : "",
                required: true
              }
            ),
            errors.name && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm text-red-500", children: errors.name })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "label",
              {
                htmlFor: "slug",
                className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                children: [
                  __("Slug", "yatra"),
                  " ",
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
                ]
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Input,
                {
                  id: "slug",
                  type: "text",
                  value: formData.slug,
                  onChange: (e) => handleSlugChange(e.target.value),
                  placeholder: __("item-slug", "yatra"),
                  className: `pr-10 ${errors.slug ? "border-red-500" : ""} ${!isSlugEditable ? "bg-gray-50 dark:bg-gray-800 cursor-not-allowed" : ""}`,
                  disabled: !isSlugEditable,
                  required: true
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "button",
                {
                  type: "button",
                  onClick: handleToggleSlugEdit,
                  className: "absolute right-2 top-1/2 -translate-y-1/2 p-1.5 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors rounded",
                  "aria-label": isSlugEditable ? __("Cancel editing slug", "yatra") : __("Edit slug", "yatra"),
                  children: isSlugEditable ? /* @__PURE__ */ jsxRuntimeExports.jsx(X, { className: "w-4 h-4" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(Pen, { className: "w-4 h-4" })
                }
              )
            ] }),
            errors.slug && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm text-red-500", children: errors.slug }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-xs text-gray-500 dark:text-gray-400", children: isSlugEditable ? __(
              "Manually editing slug. Click X to cancel and regenerate from name.",
              "yatra"
            ) : __(
              "Auto-generated from name. Click edit icon to customize.",
              "yatra"
            ) })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "label",
              {
                htmlFor: "description",
                className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                children: __("Description", "yatra")
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "textarea",
              {
                id: "description",
                value: formData.description,
                onChange: (e) => handleFieldChange("description", e.target.value),
                placeholder: __("Describe this item...", "yatra"),
                rows: 4,
                className: "flex w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm ring-offset-white placeholder:text-gray-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 dark:border-gray-600 dark:bg-gray-800 dark:ring-offset-gray-900 dark:placeholder:text-gray-400 dark:focus-visible:ring-blue-400 resize-none"
              }
            )
          ] })
        ] })
      ] }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Status", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "space-y-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "label",
              {
                htmlFor: "status",
                className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                children: __("Item Status", "yatra")
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              Select,
              {
                id: "status",
                value: formData.status,
                onChange: (e) => handleFieldChange("status", e.target.value),
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "publish", children: __("Publish", "yatra") }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "draft", children: __("Draft", "yatra") }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "trash", children: __("Trash", "yatra") })
                ]
              }
            )
          ] }) })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-3", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-2", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Button,
            {
              type: "submit",
              disabled: isSubmitting,
              className: "flex-1 flex items-center justify-center gap-2",
              children: isSubmitting ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Loader2, { className: "w-4 h-4 animate-spin" }),
                __("Saving...", "yatra")
              ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Save, { className: "w-4 h-4" }),
                isEditMode ? __("Update Item", "yatra") : __("Create Item", "yatra")
              ] })
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Button,
            {
              type: "button",
              variant: "outline",
              onClick: handleCancel,
              disabled: isSubmitting,
              children: __("Cancel", "yatra")
            }
          )
        ] }) }) }) })
      ] })
    ] }) }) })
  ] });
};
const Alert = ({
  variant = "info",
  title: title2,
  children,
  onClose,
  className = ""
}) => {
  const variantClasses = {
    success: "bg-green-50 text-green-800 border-green-200 dark:bg-green-900/20 dark:text-green-400 dark:border-green-800",
    error: "bg-red-50 text-red-800 border-red-200 dark:bg-red-900/20 dark:text-red-400 dark:border-red-800",
    warning: "bg-yellow-50 text-yellow-800 border-yellow-200 dark:bg-yellow-900/20 dark:text-yellow-400 dark:border-yellow-800",
    info: "bg-blue-50 text-blue-800 border-blue-200 dark:bg-blue-900/20 dark:text-blue-400 dark:border-blue-800"
  };
  const icons = {
    success: CheckCircle,
    error: XCircle,
    warning: AlertCircle,
    info: Info
  };
  const Icon = icons[variant];
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    "div",
    {
      className: `rounded-md border p-4 ${variantClasses[variant]} ${className}`,
      children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start gap-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Icon, { className: "w-5 h-5 flex-shrink-0 mt-0.5" }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1", children: [
          title2 && /* @__PURE__ */ jsxRuntimeExports.jsx("h4", { className: "font-medium mb-1", children: title2 }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm", children })
        ] }),
        onClose && /* @__PURE__ */ jsxRuntimeExports.jsx(
          "button",
          {
            onClick: onClose,
            className: "flex-shrink-0 text-current opacity-70 hover:opacity-100 transition-opacity",
            "aria-label": __("Close", "yatra"),
            children: /* @__PURE__ */ jsxRuntimeExports.jsx(X, { className: "w-4 h-4" })
          }
        )
      ] })
    }
  );
};
const TimePicker = ({
  value,
  onChange,
  placeholder = "Select time",
  disabled = false,
  className = "",
  error = false
}) => {
  const [open, setOpen] = reactExports.useState(false);
  const [hours, setHours] = reactExports.useState("");
  const [minutes, setMinutes] = reactExports.useState("");
  const [ampm, setAmpm] = reactExports.useState("AM");
  reactExports.useEffect(() => {
    if (value) {
      const [h, m] = value.split(":");
      const hour = parseInt(h);
      if (hour === 0) {
        setHours("12");
        setAmpm("AM");
      } else if (hour < 12) {
        setHours(hour.toString());
        setAmpm("AM");
      } else if (hour === 12) {
        setHours("12");
        setAmpm("PM");
      } else {
        setHours((hour - 12).toString());
        setAmpm("PM");
      }
      setMinutes(m || "00");
    }
  }, [value]);
  const handleTimeSelect = (h, m, a2) => {
    let hour24 = parseInt(h);
    if (a2 === "PM" && hour24 !== 12) {
      hour24 += 12;
    } else if (a2 === "AM" && hour24 === 12) {
      hour24 = 0;
    }
    const timeString = `${hour24.toString().padStart(2, "0")}:${m.padStart(2, "0")}`;
    onChange == null ? void 0 : onChange(timeString);
    setOpen(false);
  };
  const formatDisplayTime = () => {
    if (!value) return "";
    const [h, m] = value.split(":");
    const hour = parseInt(h);
    if (hour === 0) return `12:${m} AM`;
    if (hour < 12) return `${hour}:${m} AM`;
    if (hour === 12) return `12:${m} PM`;
    return `${hour - 12}:${m} PM`;
  };
  const hourOptions = Array.from({ length: 12 }, (_, i) => (i + 1).toString());
  const minuteOptions = Array.from(
    { length: 60 },
    (_, i) => i.toString().padStart(2, "0")
  );
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(Popover, { open, onOpenChange: setOpen, children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(PopoverTrigger, { asChild: true, children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
      Button,
      {
        type: "button",
        variant: "outline",
        disabled,
        className: `w-full justify-start text-left font-normal ${error ? "border-red-500" : ""} ${!value ? "text-gray-500" : ""} ${className}`,
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Clock, { className: "mr-2 h-4 w-4" }),
          formatDisplayTime() || /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-500", children: placeholder })
        ]
      }
    ) }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs(PopoverContent, { className: "w-auto p-4", align: "start", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-4", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col gap-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "text-xs font-medium text-gray-700 dark:text-gray-300", children: "Hour" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid grid-cols-3 gap-1 max-h-48 overflow-y-auto", children: hourOptions.map((h) => /* @__PURE__ */ jsxRuntimeExports.jsx(
            "button",
            {
              type: "button",
              onClick: () => {
                setHours(h);
                if (hours && minutes) {
                  handleTimeSelect(h, minutes, ampm);
                }
              },
              className: `px-3 py-2 text-sm rounded-md transition-colors ${hours === h ? "bg-blue-600 text-white" : "hover:bg-gray-100 dark:hover:bg-gray-700"}`,
              children: h
            },
            h
          )) })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col gap-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "text-xs font-medium text-gray-700 dark:text-gray-300", children: "Minute" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid grid-cols-3 gap-1 max-h-48 overflow-y-auto", children: minuteOptions.map((m) => /* @__PURE__ */ jsxRuntimeExports.jsx(
            "button",
            {
              type: "button",
              onClick: () => {
                setMinutes(m);
                if (hours && m) {
                  handleTimeSelect(hours, m, ampm);
                }
              },
              className: `px-3 py-2 text-sm rounded-md transition-colors ${minutes === m ? "bg-blue-600 text-white" : "hover:bg-gray-100 dark:hover:bg-gray-700"}`,
              children: m
            },
            m
          )) })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col gap-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "text-xs font-medium text-gray-700 dark:text-gray-300", children: "AM/PM" }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col gap-1", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "button",
              {
                type: "button",
                onClick: () => {
                  setAmpm("AM");
                  if (hours && minutes) {
                    handleTimeSelect(hours, minutes, "AM");
                  }
                },
                className: `px-4 py-2 text-sm rounded-md transition-colors ${ampm === "AM" ? "bg-blue-600 text-white" : "hover:bg-gray-100 dark:hover:bg-gray-700"}`,
                children: "AM"
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "button",
              {
                type: "button",
                onClick: () => {
                  setAmpm("PM");
                  if (hours && minutes) {
                    handleTimeSelect(hours, minutes, "PM");
                  }
                },
                className: `px-4 py-2 text-sm rounded-md transition-colors ${ampm === "PM" ? "bg-blue-600 text-white" : "hover:bg-gray-100 dark:hover:bg-gray-700"}`,
                children: "PM"
              }
            )
          ] })
        ] })
      ] }),
      hours && minutes && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-4 pt-4 border-t border-gray-200 dark:border-gray-700", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        Button,
        {
          onClick: () => handleTimeSelect(hours, minutes, ampm),
          className: "w-full",
          size: "sm",
          children: "Set Time"
        }
      ) })
    ] })
  ] });
};
const MediaUpload = ({
  items = [],
  onChange,
  maxItems = 10,
  acceptTypes = "both",
  title: title2 = __("Media Gallery", "yatra"),
  description = __("Add images and videos to showcase this activity", "yatra"),
  className = ""
}) => {
  const getMediaType = (acceptTypes2) => {
    switch (acceptTypes2) {
      case "images":
        return "image";
      case "videos":
        return "video";
      default:
        return "image,video";
    }
  };
  const getMediaTitle = (acceptTypes2) => {
    switch (acceptTypes2) {
      case "images":
        return __("Photo Gallery", "yatra");
      case "videos":
        return __("Video Gallery", "yatra");
      default:
        return title2;
    }
  };
  const getMediaDescription = (acceptTypes2) => {
    switch (acceptTypes2) {
      case "images":
        return __("Upload images to showcase this activity", "yatra");
      case "videos":
        return __("Add videos to showcase this activity", "yatra");
      default:
        return description;
    }
  };
  const handleMediaAdd = () => {
    if (items.length >= maxItems) {
      alert(
        sprintf(
          // translators: %d: maximum number of media items allowed.
          __("Maximum %d media items allowed", "yatra"),
          Number(maxItems) || 0
        )
      );
      return;
    }
    if (window.wp && window.wp.media) {
      const mediaUploader = window.wp.media({
        title: __("Select Media", "yatra"),
        button: { text: __("Add Media", "yatra") },
        multiple: true,
        // Allow multiple selection
        library: { type: getMediaType(acceptTypes) }
      });
      mediaUploader.on("select", () => {
        const selection = mediaUploader.state().get("selection");
        const newItems = [];
        selection.each((attachment) => {
          var _a, _b;
          const mediaType = attachment.get("type");
          const mediaItem = {
            id: attachment.get("id").toString(),
            attachment_id: attachment.get("id"),
            url: attachment.get("url"),
            type: mediaType,
            alt_text: attachment.get("alt") || "",
            caption: attachment.get("caption") || ""
          };
          if (mediaType === "image") {
            const sizes = attachment.get("sizes");
            mediaItem.thumbnail_url = ((_a = sizes == null ? void 0 : sizes.medium) == null ? void 0 : _a.url) || ((_b = sizes == null ? void 0 : sizes.thumbnail) == null ? void 0 : _b.url) || attachment.get("url");
          }
          newItems.push(mediaItem);
        });
        if (newItems.length > 0) {
          onChange([...items, ...newItems]);
        }
      });
      prepareWordPressMediaFrameOpen();
      mediaUploader.open();
    } else {
      const input = document.createElement("input");
      input.type = "file";
      input.multiple = true;
      input.accept = acceptTypes === "videos" ? "video/*" : acceptTypes === "images" ? "image/*" : "image/*,video/*";
      input.onchange = (e) => {
        const files = Array.from(e.target.files || []);
        const newItems = files.slice(0, maxItems - items.length).map((file, index) => ({
          id: `temp_${Date.now()}_${index}`,
          attachment_id: 0,
          // Temporary files don't have attachment IDs
          url: URL.createObjectURL(file),
          type: file.type.startsWith("video/") ? "video" : "image",
          alt_text: file.name,
          caption: file.name
        }));
        onChange([...items, ...newItems]);
      };
      input.click();
    }
  };
  const handleMediaRemove = (index) => {
    onChange(items.filter((_, i) => i !== index));
  };
  const isImage = (item) => item.type === "image";
  return /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { className, children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-6", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-4", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-lg font-semibold text-gray-900 dark:text-gray-100", children: getMediaTitle(acceptTypes) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-600 dark:text-gray-400", children: getMediaDescription(acceptTypes) })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-sm text-gray-500 dark:text-gray-400", children: [
        items.length,
        "/",
        maxItems
      ] })
    ] }),
    items.length > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4", children: items.map((item, index) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative group", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "aspect-video bg-gray-100 dark:bg-gray-800 rounded-lg flex items-center justify-center overflow-hidden", children: isImage(item) ? /* @__PURE__ */ jsxRuntimeExports.jsx(
        "img",
        {
          src: item.thumbnail_url || item.url,
          alt: item.alt_text || // translators: %d: media item sequence number (1-based).
          sprintf(__("Media %d", "yatra"), index + 1),
          className: "w-full h-full object-cover",
          onError: (e) => {
            console.error("Image load error:", e, "Item:", item);
            e.target.style.display = "none";
            const parent = e.target.parentElement;
            if (parent) {
              parent.innerHTML = '<div class="flex items-center justify-center w-full h-full"><div class="text-gray-400 text-center"><div class="text-4xl mb-2">🖼️</div><div class="text-sm">' + __("Image not available", "yatra") + "</div></div></div>";
            }
          },
          onLoad: () => {
          }
        }
      ) : /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative w-full h-full", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "video",
          {
            src: item.url,
            className: "w-full h-full object-cover",
            muted: true,
            playsInline: true
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "absolute inset-0 flex items-center justify-center bg-black bg-opacity-30", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Video, { className: "w-12 h-12 text-white" }) })
      ] }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        Button,
        {
          type: "button",
          size: "sm",
          variant: "destructive",
          onClick: () => handleMediaRemove(index),
          className: "h-8 w-8 p-0 bg-red-500 hover:bg-red-600 text-white",
          children: /* @__PURE__ */ jsxRuntimeExports.jsx(X, { className: "w-4 h-4" })
        }
      ) }),
      item.caption && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/70 to-transparent p-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-white truncate", children: item.caption }) })
    ] }, item.id)) }),
    items.length < maxItems && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex justify-center", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
      Button,
      {
        type: "button",
        onClick: handleMediaAdd,
        variant: "outline",
        className: "w-full md:w-auto",
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Plus, { className: "w-4 h-4 mr-2" }),
          acceptTypes === "videos" ? __("Add Video", "yatra") : acceptTypes === "images" ? __("Add Image", "yatra") : __("Add Media", "yatra")
        ]
      }
    ) }),
    items.length === 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-center py-8 border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(Upload, { className: "w-12 h-12 text-gray-400 mx-auto mb-4" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-gray-600 dark:text-gray-400", children: __(
        "No media items yet. Click 'Add Media' to get started.",
        "yatra"
      ) })
    ] })
  ] }) }) });
};
const defaultTranslate = (key2) => {
  const translations = {
    "Enter location name": "Enter location name",
    "Show Map": "Show Map",
    "Hide Map": "Hide Map",
    Clear: "Clear",
    "Coordinates:": "Coordinates:",
    "Search for a location...": "Search for a location...",
    "Click on the map to set the location, or search for a place above.": "Click on the map to set the location, or search for a place above.",
    "GPS Coordinates": "GPS Coordinates",
    "Manual override": "Manual override",
    Latitude: "Latitude",
    Longitude: "Longitude",
    "e.g. -8.3405": "e.g. -8.3405",
    "e.g. 115.0920": "e.g. 115.0920",
    "Use Current Location": "Use Current Location",
    "Geolocation is not supported by your browser": "Geolocation is not supported by your browser",
    "Unable to get your location": "Unable to get your location",
    "Location access requires HTTPS. This feature will work on your live HTTPS site.": "Location access requires HTTPS. This feature will work on your live HTTPS site.",
    "Manual coordinate entry. These will be auto-filled when you select a location from the map above.": "Manual coordinate entry. These will be auto-filled when you select a location from the map above.",
    "Click on the map to set the location, or drag the marker to adjust coordinates.": "Click on the map to set the location, or drag the marker to adjust coordinates."
  };
  return translations[key2] || key2;
};
const LocationPicker = ({
  value,
  onChange,
  label,
  helpText,
  required = false,
  showMapButton = true,
  /** Neutral world view when no coordinates (avoid implying a random region). */
  defaultMapCenter = [20, 0],
  defaultZoom = 2,
  mapHeight = "300px",
  searchLimit = 5,
  className = "",
  inputClassName = "",
  mapClassName = "",
  __: translate = defaultTranslate,
  onLocationSelect,
  onLocationClear,
  onMapToggle,
  showManualCoordinateFields = false
}) => {
  const [showMap, setShowMap] = reactExports.useState(true);
  const [searchQuery, setSearchQuery] = reactExports.useState("");
  const [searchResults, setSearchResults] = reactExports.useState([]);
  const [searchLoading, setSearchLoading] = reactExports.useState(false);
  const [mapLoading, setMapLoading] = reactExports.useState(false);
  const [mapReady, setMapReady] = reactExports.useState(false);
  const mapRef = reactExports.useRef(null);
  const mapInstanceRef = reactExports.useRef(null);
  const markerRef = reactExports.useRef(null);
  const valueRef = reactExports.useRef(value);
  const defaultMapCenterRef = reactExports.useRef(defaultMapCenter);
  const defaultZoomRef = reactExports.useRef(defaultZoom);
  const pendingSelectionRef = reactExports.useRef(null);
  reactExports.useEffect(() => {
    valueRef.current = value;
  }, [value]);
  reactExports.useEffect(() => {
    defaultMapCenterRef.current = defaultMapCenter;
  }, [defaultMapCenter]);
  reactExports.useEffect(() => {
    defaultZoomRef.current = defaultZoom;
  }, [defaultZoom]);
  reactExports.useEffect(() => {
    return () => {
      if (mapInstanceRef.current) {
        try {
          mapInstanceRef.current.remove();
        } catch {
        }
        mapInstanceRef.current = null;
        markerRef.current = null;
      }
    };
  }, []);
  reactExports.useEffect(() => {
    if (mapInstanceRef.current && value.latitude && value.longitude) {
      const lat = parseFloat(value.latitude);
      const lng = parseFloat(value.longitude);
      if (!isNaN(lat) && !isNaN(lng)) {
        setTimeout(() => {
          if (mapInstanceRef.current) {
            addMarker(mapInstanceRef.current, lat, lng);
            mapInstanceRef.current.setView([lat, lng], defaultZoom);
          }
        }, 100);
      }
    }
  }, [value.latitude, value.longitude, defaultZoom]);
  reactExports.useEffect(() => {
    if (showMap && !mapLoading && !mapInstanceRef.current) {
      loadMap();
    }
  }, [showMap]);
  reactExports.useEffect(() => {
    if (mapReady && mapInstanceRef.current && value.latitude && value.longitude) {
      const lat = parseFloat(value.latitude);
      const lng = parseFloat(value.longitude);
      if (!isNaN(lat) && !isNaN(lng)) {
        setTimeout(() => {
          if (mapInstanceRef.current) {
            addMarker(mapInstanceRef.current, lat, lng);
            mapInstanceRef.current.setView([lat, lng], defaultZoom);
          }
        }, 150);
      }
    }
  }, [mapReady, value.latitude, value.longitude, defaultZoom]);
  const loadMap = async () => {
    setMapLoading(true);
    try {
      if (!document.querySelector('link[href*="leaflet.css"]')) {
        const leafletCSS = document.createElement("link");
        leafletCSS.rel = "stylesheet";
        leafletCSS.href = "https://unpkg.com/leaflet@1.9.4/dist/leaflet.css";
        leafletCSS.integrity = "sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=";
        leafletCSS.crossOrigin = "";
        document.head.appendChild(leafletCSS);
      }
      if (!window.L) {
        const leafletJS = document.createElement("script");
        leafletJS.src = "https://unpkg.com/leaflet@1.9.4/dist/leaflet.js";
        leafletJS.integrity = "sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=";
        leafletJS.crossOrigin = "";
        document.head.appendChild(leafletJS);
        leafletJS.onload = () => initializeMap();
      } else {
        initializeMap();
      }
    } catch (error) {
      console.error("Error loading map:", error);
      setMapLoading(false);
    }
  };
  const initializeMap = () => {
    var _a, _b, _c, _d;
    if (!mapRef.current || !window.L) return;
    const L = window.L;
    const v = valueRef.current;
    const center = defaultMapCenterRef.current;
    const zoomCfg = defaultZoomRef.current;
    const lat = ((_a = v.latitude) == null ? void 0 : _a.trim()) ? parseFloat(v.latitude) : center[0];
    const lng = ((_b = v.longitude) == null ? void 0 : _b.trim()) ? parseFloat(v.longitude) : center[1];
    const map2 = L.map(mapRef.current).setView([lat, lng], zoomCfg);
    L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
      attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
      maxZoom: 19
    }).addTo(map2);
    const pending = pendingSelectionRef.current;
    if (pending) {
      pendingSelectionRef.current = null;
      map2.setView([pending.lat, pending.lng], pending.zoom);
      addMarker(
        map2,
        pending.lat,
        pending.lng,
        pending.name ? { name: pending.name } : void 0
      );
    } else if (((_c = v.latitude) == null ? void 0 : _c.trim()) && ((_d = v.longitude) == null ? void 0 : _d.trim())) {
      addMarker(map2, lat, lng);
    }
    map2.on("click", function(e) {
      const { lat: lat2, lng: lng2 } = e.latlng;
      addMarker(map2, lat2, lng2);
      reverseGeocode(lat2, lng2);
    });
    mapInstanceRef.current = map2;
    setMapLoading(false);
    setMapReady(true);
  };
  const addMarker = (map2, lat, lng, extra) => {
    const L = window.L;
    if (markerRef.current) {
      map2.removeLayer(markerRef.current);
    }
    const customIcon = L.divIcon({
      html: '<div style="background: linear-gradient(135deg, #3b82f6, #2563eb); color: white; width: 30px; height: 30px; border-radius: 50% 50% 50% 0; transform: rotate(-45deg); display: flex; align-items: center; justify-content: center; border: 2px solid white; box-shadow: 0 2px 6px rgba(0,0,0,0.3);"><svg style="transform: rotate(45deg); width: 14px; height: 14px;" fill="currentColor" viewBox="0 0 20 20"><path fillRule="evenodd" d="M5.05 4.05a7 7 0 119.9 9.9L10 18.9l-4.95-4.95a7 7 0 010-9.9zM10 11a2 2 0 100-4 2 2 0 000 4z" clipRule="evenodd" /></svg></div>',
      iconSize: [30, 30],
      iconAnchor: [15, 30],
      className: "yatra-custom-marker"
    });
    const marker = L.marker([lat, lng], {
      icon: customIcon,
      draggable: true
    }).addTo(map2);
    markerRef.current = marker;
    marker.on("dragend", function(e) {
      const position = e.target.getLatLng();
      const newLat = position.lat;
      const newLng = position.lng;
      const newLocation2 = {
        ...valueRef.current,
        latitude: newLat.toString(),
        longitude: newLng.toString()
      };
      onChange(newLocation2);
      valueRef.current = newLocation2;
      reverseGeocode(newLat, newLng);
    });
    const newLocation = {
      ...valueRef.current,
      ...extra,
      latitude: lat.toString(),
      longitude: lng.toString()
    };
    onChange(newLocation);
    valueRef.current = newLocation;
  };
  const reverseGeocode = async (lat, lng) => {
    var _a, _b;
    try {
      const formData = new FormData();
      formData.append("action", "yatra_reverse_geocode");
      formData.append("lat", lat.toString());
      formData.append("lng", lng.toString());
      formData.append(
        "nonce",
        ((_a = window.yatraAdmin) == null ? void 0 : _a.geocodingNonce) || ""
      );
      const response = await fetch(
        ((_b = window.yatraAdmin) == null ? void 0 : _b.ajaxUrl) || "/wp-admin/admin-ajax.php",
        {
          method: "POST",
          body: formData
        }
      );
      if (response.ok) {
        const result = await response.json();
        if (result.success && result.data.result) {
          const data = result.data.result;
          const locationName2 = data.display_name || `${lat.toFixed(6)}, ${lng.toFixed(6)}`;
          const newLocation2 = {
            ...valueRef.current,
            name: locationName2,
            latitude: lat.toString(),
            longitude: lng.toString()
          };
          onChange(newLocation2);
          valueRef.current = newLocation2;
          return;
        }
      }
    } catch (error) {
      console.error("Error reverse geocoding:", error);
    }
    const locationName = `${lat.toFixed(6)}, ${lng.toFixed(6)}`;
    const newLocation = {
      ...valueRef.current,
      name: locationName,
      latitude: lat.toString(),
      longitude: lng.toString()
    };
    onChange(newLocation);
    valueRef.current = newLocation;
  };
  const searchTimeoutRef = reactExports.useRef();
  const searchLocations = async (query) => {
    var _a, _b;
    if (!query.trim() || query.length < 2) {
      setSearchResults([]);
      return;
    }
    setSearchLoading(true);
    try {
      const formData = new FormData();
      formData.append("action", "yatra_search_locations");
      formData.append("query", query);
      formData.append("limit", searchLimit.toString());
      formData.append(
        "nonce",
        ((_a = window.yatraAdmin) == null ? void 0 : _a.geocodingNonce) || ""
      );
      const response = await fetch(
        ((_b = window.yatraAdmin) == null ? void 0 : _b.ajaxUrl) || "/wp-admin/admin-ajax.php",
        {
          method: "POST",
          body: formData
        }
      );
      if (response.ok) {
        const result = await response.json();
        if (result.success) {
          setSearchResults(result.data.results);
        } else {
          console.error("Search error:", result.data.message);
          setSearchResults([]);
        }
      }
    } catch (error) {
      console.error("Error searching locations:", error);
      setSearchResults([]);
    } finally {
      setSearchLoading(false);
    }
  };
  const handleSearchChange = (e) => {
    const query = e.target.value;
    setSearchQuery(query);
    if (searchTimeoutRef.current) {
      clearTimeout(searchTimeoutRef.current);
    }
    searchTimeoutRef.current = setTimeout(() => {
      searchLocations(query);
    }, 300);
  };
  const selectLocation = (location) => {
    const lat = parseFloat(location.lat);
    const lng = parseFloat(location.lon);
    const displayName = location.display_name || "";
    const newLocation = {
      name: displayName,
      latitude: lat.toString(),
      longitude: lng.toString()
    };
    onChange(newLocation);
    valueRef.current = newLocation;
    onLocationSelect == null ? void 0 : onLocationSelect(newLocation);
    const detailZoom = 14;
    if (mapInstanceRef.current) {
      mapInstanceRef.current.setView([lat, lng], detailZoom);
      addMarker(mapInstanceRef.current, lat, lng, { name: displayName });
    } else {
      pendingSelectionRef.current = {
        lat,
        lng,
        zoom: detailZoom,
        name: displayName
      };
    }
    setSearchQuery("");
    setSearchResults([]);
  };
  const clearLocation = () => {
    pendingSelectionRef.current = null;
    const emptyLocation = { name: "", latitude: "", longitude: "" };
    onChange(emptyLocation);
    valueRef.current = emptyLocation;
    onLocationClear == null ? void 0 : onLocationClear();
    if (markerRef.current && mapInstanceRef.current) {
      mapInstanceRef.current.removeLayer(markerRef.current);
      markerRef.current = null;
    }
  };
  const toggleMap = () => {
    const newState = !showMap;
    setShowMap(newState);
    onMapToggle == null ? void 0 : onMapToggle(newState);
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: `space-y-3 ${className}`, children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("label", { className: "block text-xs font-normal text-gray-500 dark:text-gray-400", children: [
        label,
        required && /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500 ml-1", children: "*" })
      ] }),
      showMapButton && /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "button",
        {
          type: "button",
          onClick: toggleMap,
          className: "flex items-center gap-1 px-2 py-1 text-xs bg-blue-50 text-blue-600 rounded hover:bg-blue-100 transition-colors",
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(MapPin, { className: "w-3 h-3" }),
            showMap ? translate("Hide Map") : translate("Show Map")
          ]
        }
      )
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(MapPin, { className: "absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "input",
          {
            type: "text",
            value: searchQuery || value.name,
            onChange: (e) => {
              const query = e.target.value;
              setSearchQuery(query);
              handleSearchChange({
                target: { value: query }
              });
              onChange({ ...value, name: query });
            },
            placeholder: "Type location here...",
            className: `w-full pl-10 pr-10 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white ${inputClassName}`
          }
        ),
        searchLoading ? /* @__PURE__ */ jsxRuntimeExports.jsx(Loader2, { className: "absolute right-3 top-1/2 transform -translate-y-1/2 w-4 h-4 animate-spin text-gray-400" }) : searchQuery || value.name ? /* @__PURE__ */ jsxRuntimeExports.jsx(
          "button",
          {
            type: "button",
            onClick: () => {
              clearLocation();
              setSearchQuery("");
            },
            className: "absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600",
            children: /* @__PURE__ */ jsxRuntimeExports.jsx(X, { className: "w-4 h-4" })
          }
        ) : null
      ] }),
      searchResults.length > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx(
        "div",
        {
          className: "absolute top-full left-0 right-0 mt-1 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-600 rounded-lg shadow-lg max-h-64 overflow-y-auto",
          style: { zIndex: 9999 },
          children: searchResults.map((result, index) => /* @__PURE__ */ jsxRuntimeExports.jsx(
            "button",
            {
              type: "button",
              onClick: () => selectLocation(result),
              className: "w-full text-left px-4 py-3 hover:bg-blue-50 dark:hover:bg-blue-900/20 transition-colors border-b border-gray-100 dark:border-gray-700 last:border-b-0 group",
              children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start gap-3", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-5 h-5 flex-shrink-0 mt-0.5", children: /* @__PURE__ */ jsxRuntimeExports.jsx(MapPin, { className: "w-4 h-4 text-blue-500 group-hover:text-blue-600" }) }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1 min-w-0", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "font-medium text-gray-900 dark:text-white text-sm truncate", children: result.display_name.split(",")[0] }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-xs text-gray-500 dark:text-gray-400 truncate mt-0.5", children: result.display_name.split(",").slice(1).join(",").trim() })
                ] })
              ] })
            },
            index
          ))
        }
      )
    ] }),
    !showManualCoordinateFields && (value.latitude || value.longitude) && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2 p-2 bg-gray-50 dark:bg-gray-800 rounded-lg", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(Globe, { className: "w-4 h-4 text-gray-500" }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-xs text-gray-600 dark:text-gray-400", children: [
        translate("Coordinates:"),
        " ",
        value.latitude || "0",
        ",",
        " ",
        value.longitude || "0"
      ] })
    ] }),
    showMap && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "border border-gray-300 rounded-lg overflow-hidden", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative", children: [
        mapLoading && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "absolute inset-0 bg-white/80 flex items-center justify-center z-10", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Loader2, { className: "w-6 h-6 animate-spin text-blue-500" }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "div",
          {
            ref: mapRef,
            style: { height: mapHeight, width: "100%" },
            className: `bg-gray-100 ${mapClassName}`
          }
        )
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-3 bg-gray-50 dark:bg-gray-800 text-xs text-gray-600 dark:text-gray-400", children: translate(
        "Click on the map to set the location, or drag the marker to adjust coordinates."
      ) })
    ] }),
    showManualCoordinateFields && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3 pt-2 border-t border-gray-200 dark:border-gray-700", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-wrap items-center justify-between gap-2", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-sm font-medium text-gray-700 dark:text-gray-300", children: [
          translate("GPS Coordinates"),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-xs font-normal text-gray-500 dark:text-gray-400 ml-1", children: [
            "(",
            translate("Manual override"),
            ")"
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "button",
          {
            type: "button",
            onClick: () => {
              if (!navigator.geolocation) {
                alert(
                  translate("Geolocation is not supported by your browser")
                );
                return;
              }
              navigator.geolocation.getCurrentPosition(
                (position) => {
                  onChange({
                    ...value,
                    latitude: position.coords.latitude.toString(),
                    longitude: position.coords.longitude.toString()
                  });
                },
                (error) => {
                  let message2 = translate("Unable to get your location");
                  if (error.code === 1 && error.message.includes("secure origins")) {
                    message2 = translate(
                      "Location access requires HTTPS. This feature will work on your live HTTPS site."
                    );
                  }
                  alert(message2);
                }
              );
            },
            className: "text-xs bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300 px-3 py-1.5 rounded-lg hover:bg-green-200 dark:hover:bg-green-900/50 transition-colors",
            children: translate("Use Current Location")
          }
        )
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 sm:grid-cols-2 gap-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-1.5", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "text-xs font-medium text-gray-600 dark:text-gray-400", children: translate("Latitude") }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "input",
            {
              type: "text",
              inputMode: "decimal",
              value: value.latitude,
              onChange: (e) => onChange({ ...value, latitude: e.target.value }),
              placeholder: translate("e.g. -8.3405"),
              className: `w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white ${inputClassName}`
            }
          )
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-1.5", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "text-xs font-medium text-gray-600 dark:text-gray-400", children: translate("Longitude") }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "input",
            {
              type: "text",
              inputMode: "decimal",
              value: value.longitude,
              onChange: (e) => onChange({ ...value, longitude: e.target.value }),
              placeholder: translate("e.g. 115.0920"),
              className: `w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white ${inputClassName}`
            }
          )
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400", children: translate(
        "Manual coordinate entry. These will be auto-filled when you select a location from the map above."
      ) })
    ] }),
    helpText && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-xs text-gray-500 dark:text-gray-400", children: helpText })
  ] });
};
const ItineraryEntryFields = ({
  entry,
  errors = {},
  itemTypes,
  items,
  newIncludedItem = "",
  newExcludedItem = "",
  onFieldChange,
  onIncludedItemChange,
  onExcludedItemChange,
  onAddIncludedItem,
  onAddExcludedItem,
  onRemoveIncludedItem,
  onRemoveExcludedItem,
  calculateDuration,
  size = "default",
  showCardWrapper = false,
  onRefreshData
}) => {
  var _a;
  const [localGallery, setLocalGallery] = React.useState([]);
  const [localVideoUrl, setLocalVideoUrl] = React.useState("");
  React.useEffect(() => {
    if (entry.gallery && Array.isArray(entry.gallery)) {
      setLocalGallery(entry.gallery);
    } else {
      setLocalGallery([]);
    }
  }, [entry.gallery]);
  React.useEffect(() => {
    if (entry.video_url !== void 0 && entry.video_url !== null) {
      setLocalVideoUrl(entry.video_url);
    } else {
      setLocalVideoUrl("");
    }
  }, [entry.video_url]);
  const [isItemTypeModalOpen, setIsItemTypeModalOpen] = reactExports.useState(false);
  const [isItemModalOpen, setIsItemModalOpen] = reactExports.useState(false);
  const isCompact = size === "compact";
  const textSize = isCompact ? "text-xs" : "text-sm";
  const labelSize = isCompact ? "text-xs" : "text-sm";
  const autoDuration = calculateDuration ? calculateDuration(
    entry.start_time || "",
    entry.end_time || "",
    entry.time_type || "exact"
  ) : "";
  const globalCurrency = ((_a = window.yatraAdmin) == null ? void 0 : _a.currency) || "USD";
  const currencySymbol = getCurrencySymbol(globalCurrency) || "";
  const renderField = (content2) => {
    if (showCardWrapper) {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "space-y-3", children: content2 }) });
    }
    return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-3", children: content2 });
  };
  const content = /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
      !isCompact && /* @__PURE__ */ jsxRuntimeExports.jsx(
        "h5",
        {
          className: `${labelSize} font-semibold text-gray-900 dark:text-white`,
          children: __("Basic Information", "yatra")
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "label",
            {
              className: `block ${labelSize} font-medium text-gray-700 dark:text-gray-300 mb-1.5`,
              children: [
                __("Item Type", "yatra"),
                " ",
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
              ]
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            HelpText,
            {
              text: __(
                "Select the type of item (Activity, Meal, Accommodation, etc.).",
                "yatra"
              ),
              className: "mb-2"
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              Select,
              {
                value: entry.item_type_id && Number(entry.item_type_id) !== 0 ? entry.item_type_id : "",
                onChange: (e) => {
                  onFieldChange("item_type_id", e.target.value);
                  onFieldChange("item_id", "");
                },
                className: `${errors.item_type_id ? "border-red-500" : ""} ${textSize} text-gray-900 dark:text-gray-100 bg-white dark:bg-gray-800 flex-1`,
                style: {
                  color: "rgb(17, 24, 39)",
                  backgroundColor: "rgb(255, 255, 255)"
                },
                required: true,
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "", children: __("Select a type...", "yatra") }),
                  itemTypes.map((type) => /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: String(type.id), children: type.name }, type.id))
                ]
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              Button,
              {
                type: "button",
                variant: "outline",
                size: "sm",
                onClick: () => setIsItemTypeModalOpen(true),
                className: "flex items-center gap-1 whitespace-nowrap",
                title: __("Add new item type", "yatra"),
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(Plus, { className: "w-4 h-4" }),
                  isCompact ? "" : __("Add Type", "yatra")
                ]
              }
            )
          ] }),
          errors.item_type_id && /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "p",
            {
              className: `mt-1.5 ${textSize} text-red-600 dark:text-red-400 flex items-center gap-1`,
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Info, { className: "w-4 h-4" }),
                errors.item_type_id
              ]
            }
          )
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "label",
            {
              className: `block ${labelSize} font-medium text-gray-700 dark:text-gray-300 mb-1.5`,
              children: [
                __("Item", "yatra"),
                " ",
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
              ]
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            HelpText,
            {
              text: __(
                "Select the specific item (Hiking, Lunch, Bus, etc.).",
                "yatra"
              ),
              className: "mb-2"
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              Select,
              {
                value: entry.item_id && Number(entry.item_id) !== 0 ? entry.item_id : "",
                onChange: (e) => onFieldChange("item_id", e.target.value),
                disabled: !entry.item_type_id || items.filter((item) => {
                  const itemTypeId = entry.item_type_id ? String(entry.item_type_id) : "";
                  const itemTypeIdNum = item.type_id || item.item_type_id;
                  return String(itemTypeIdNum) === itemTypeId;
                }).length === 0,
                className: `${errors.item_id ? "border-red-500" : ""} ${textSize} text-gray-900 dark:text-gray-100 bg-white dark:bg-gray-800 flex-1`,
                style: {
                  color: "rgb(17, 24, 39)",
                  backgroundColor: "rgb(255, 255, 255)"
                },
                required: true,
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "", children: !entry.item_type_id ? __("Select type first...", "yatra") : items.filter((item) => {
                    const itemTypeId = entry.item_type_id ? String(entry.item_type_id) : "";
                    const itemTypeIdNum = item.type_id || item.item_type_id;
                    return String(itemTypeIdNum) === itemTypeId;
                  }).length === 0 ? __("No items available", "yatra") : __("Select an item...", "yatra") }),
                  items.filter((item) => {
                    if (!entry.item_type_id) return false;
                    const itemTypeId = String(entry.item_type_id);
                    const itemTypeIdNum = item.type_id || item.item_type_id;
                    return String(itemTypeIdNum) === itemTypeId;
                  }).map((item) => /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: String(item.id), children: item.name }, item.id))
                ]
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              Button,
              {
                type: "button",
                variant: "outline",
                size: "sm",
                onClick: () => setIsItemModalOpen(true),
                disabled: !entry.item_type_id,
                className: "flex items-center gap-1 whitespace-nowrap",
                title: __("Add new item", "yatra"),
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(Plus, { className: "w-4 h-4" }),
                  isCompact ? "" : __("Add Item", "yatra")
                ]
              }
            )
          ] }),
          errors.item_id && /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "p",
            {
              className: `mt-1.5 ${textSize} text-red-600 dark:text-red-400 flex items-center gap-1`,
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Info, { className: "w-4 h-4" }),
                errors.item_id
              ]
            }
          )
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "label",
          {
            className: `block ${labelSize} font-medium text-gray-700 dark:text-gray-300 mb-1.5`,
            children: [
              __("Itinerary Activity Title", "yatra"),
              " ",
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
            ]
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          HelpText,
          {
            text: __(
              'A descriptive title for this itinerary activity. Examples: "Arrival in Kathmandu", "Trek to Base Camp".',
              "yatra"
            ),
            className: "mb-2"
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          Input,
          {
            type: "text",
            value: entry.title || "",
            onChange: (e) => onFieldChange("title", e.target.value),
            placeholder: __("e.g., Arrival in Kathmandu", "yatra"),
            className: `${errors.title ? "border-red-500" : ""} ${textSize}`,
            required: true
          }
        ),
        errors.title && /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "p",
          {
            className: `mt-1.5 ${textSize} text-red-600 dark:text-red-400 flex items-center gap-1`,
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Info, { className: "w-4 h-4" }),
              errors.title
            ]
          }
        )
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "label",
          {
            className: `block ${labelSize} font-medium text-gray-700 dark:text-gray-300 mb-1.5`,
            children: __("Description", "yatra")
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          HelpText,
          {
            text: __(
              "Detailed description of what happens during this itinerary entry.",
              "yatra"
            ),
            className: "mb-2"
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "textarea",
          {
            value: entry.description || "",
            onChange: (e) => onFieldChange("description", e.target.value),
            placeholder: __(
              "Describe what happens during this entry...",
              "yatra"
            ),
            rows: isCompact ? 2 : 4,
            className: `flex w-full rounded-md border border-gray-300 bg-white px-3 py-2 ${textSize} ring-offset-white placeholder:text-gray-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 dark:border-gray-600 dark:bg-gray-800 dark:ring-offset-gray-900 dark:placeholder:text-gray-400 dark:focus-visible:ring-blue-400 resize-none`
          }
        )
      ] })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "div",
      {
        className: `space-y-3 ${!isCompact ? "pt-3 border-t border-gray-200 dark:border-gray-700" : ""}`,
        children: [
          !isCompact && /* @__PURE__ */ jsxRuntimeExports.jsx(
            "h5",
            {
              className: `${labelSize} font-semibold text-gray-900 dark:text-white`,
              children: __("Location & Time", "yatra")
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "label",
              {
                className: `block ${labelSize} font-medium text-gray-700 dark:text-gray-300 mb-1.5`,
                children: __("Activity Location", "yatra")
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              HelpText,
              {
                text: __(
                  "Where does this activity take place? You can search for a location or enter coordinates manually.",
                  "yatra"
                ),
                className: "mb-2"
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              LocationPicker,
              {
                value: {
                  name: entry.location || "",
                  latitude: entry.location_latitude || "",
                  longitude: entry.location_longitude || ""
                },
                onChange: (locationData) => {
                  onFieldChange("location", locationData.name);
                  onFieldChange("location_latitude", locationData.latitude);
                  onFieldChange("location_longitude", locationData.longitude);
                },
                label: "",
                placeholder: __("Search for location...", "yatra"),
                helpText: "",
                required: false,
                defaultMapCenter: entry.location_latitude && entry.location_longitude ? [
                  parseFloat(entry.location_latitude),
                  parseFloat(entry.location_longitude)
                ] : [20, 0],
                defaultZoom: entry.location_latitude && entry.location_longitude ? 13 : 2,
                mapHeight: "300px",
                showMapButton: false,
                searchLimit: 8,
                __,
                className: "",
                mapClassName: "rounded-lg"
              }
            )
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs(
                "label",
                {
                  className: `block ${labelSize} font-medium text-gray-700 dark:text-gray-300 flex items-center gap-2`,
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-4 h-4 bg-blue-100 dark:bg-blue-900 rounded flex items-center justify-center", children: /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs font-bold text-blue-600 dark:text-blue-400", children: "2" }) }),
                    __("GPS Coordinates", "yatra"),
                    /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-xs text-gray-500 dark:text-gray-400", children: [
                      "(",
                      __("Manual override", "yatra"),
                      ")"
                    ] })
                  ]
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex items-center gap-2", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
                "button",
                {
                  type: "button",
                  onClick: () => {
                    if (navigator.geolocation) {
                      navigator.geolocation.getCurrentPosition(
                        (position) => {
                          onFieldChange(
                            "location_latitude",
                            position.coords.latitude.toString()
                          );
                          onFieldChange(
                            "location_longitude",
                            position.coords.longitude.toString()
                          );
                          onFieldChange(
                            "location",
                            `${position.coords.latitude.toFixed(6)}, ${position.coords.longitude.toFixed(6)}`
                          );
                        },
                        (error) => {
                          let message2 = __(
                            "Unable to get your location",
                            "yatra"
                          );
                          let showHttpsNotice = false;
                          switch (error.code) {
                            case 1:
                              if (error.message.includes("secure origins")) {
                                message2 = __(
                                  "Location access requires HTTPS. This feature will work on your live HTTPS site.",
                                  "yatra"
                                );
                                showHttpsNotice = true;
                              } else {
                                message2 = __(
                                  "Location access denied. Please allow location access in your browser.",
                                  "yatra"
                                );
                              }
                              break;
                            case 2:
                              message2 = __(
                                "Location information is unavailable. Please try again.",
                                "yatra"
                              );
                              break;
                            case 3:
                              message2 = __(
                                "Location request timed out. Please try again.",
                                "yatra"
                              );
                              break;
                          }
                          if (showHttpsNotice) {
                            alert(
                              message2 + "\n\n" + __(
                                "For local development, you can:\n1. Use a browser extension that allows geolocation on HTTP\n2. Set up a local HTTPS certificate\n3. Test on your live HTTPS site",
                                "yatra"
                              )
                            );
                          } else {
                            alert(message2);
                          }
                        }
                      );
                    } else {
                      alert(
                        __(
                          "Geolocation is not supported by your browser",
                          "yatra"
                        )
                      );
                    }
                  },
                  className: "text-xs bg-green-100 text-green-700 px-3 py-1.5 rounded-lg hover:bg-green-200 transition-colors flex items-center gap-1",
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-3 h-3", children: /* @__PURE__ */ jsxRuntimeExports.jsx("svg", { fill: "currentColor", viewBox: "0 0 20 20", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "path",
                      {
                        fillRule: "evenodd",
                        d: "M5.05 4.05a7 7 0 119.9 9.9L10 18.9l-4.95-4.95a7 7 0 010-9.9zM10 11a2 2 0 100-4 2 2 0 000 4z",
                        clipRule: "evenodd"
                      }
                    ) }) }),
                    __("Use Current Location", "yatra")
                  ]
                }
              ) })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-2 gap-3", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs(
                  "label",
                  {
                    className: `text-xs font-medium text-gray-600 dark:text-gray-400 flex items-center gap-1`,
                    children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-2 h-2 bg-blue-400 rounded-full" }),
                      __("Latitude", "yatra")
                    ]
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Input,
                  {
                    type: "text",
                    value: entry.location_latitude || "",
                    onChange: (e) => onFieldChange("location_latitude", e.target.value),
                    placeholder: __("e.g., -8.3405", "yatra"),
                    className: `w-full text-sm`
                  }
                )
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs(
                  "label",
                  {
                    className: `text-xs font-medium text-gray-600 dark:text-gray-400 flex items-center gap-1`,
                    children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-2 h-2 bg-blue-400 rounded-full" }),
                      __("Longitude", "yatra")
                    ]
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Input,
                  {
                    type: "text",
                    value: entry.location_longitude || "",
                    onChange: (e) => onFieldChange("location_longitude", e.target.value),
                    placeholder: __("e.g., 115.0920", "yatra"),
                    className: `w-full text-sm`
                  }
                )
              ] })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: `text-xs text-gray-500 dark:text-gray-400`, children: __(
              "Manual coordinate entry. These will be auto-filled when you select a location from the map above.",
              "yatra"
            ) })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "label",
              {
                className: `block ${labelSize} font-medium text-gray-700 dark:text-gray-300 mb-1.5`,
                children: __("Time Type", "yatra")
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              HelpText,
              {
                text: __("How should the time be displayed?", "yatra"),
                className: "mb-2"
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              Select,
              {
                value: entry.time_type || "exact",
                onChange: (e) => onFieldChange("time_type", e.target.value),
                className: textSize,
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "exact", children: __("Exact Time", "yatra") }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "duration", children: __("Duration Only", "yatra") }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "flexible", children: __("Flexible", "yatra") })
                ]
              }
            )
          ] }),
          entry.time_type === "exact" && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "label",
                {
                  className: `block ${labelSize} font-medium text-gray-700 dark:text-gray-300 mb-1.5`,
                  children: __("Start Time", "yatra")
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                HelpText,
                {
                  text: __("When does this activity start?", "yatra"),
                  className: "mb-2"
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                TimePicker,
                {
                  value: entry.start_time || "",
                  onChange: (value) => {
                    onFieldChange("start_time", value);
                    if (calculateDuration && entry.end_time) {
                      const newDuration = calculateDuration(
                        value,
                        entry.end_time,
                        entry.time_type || "exact"
                      );
                      if (newDuration && !entry.duration) {
                        onFieldChange("duration", newDuration);
                      }
                    }
                  },
                  placeholder: "08:00",
                  className: "w-full",
                  error: !!(errors == null ? void 0 : errors.start_time)
                }
              ),
              errors.start_time && /* @__PURE__ */ jsxRuntimeExports.jsxs(
                "p",
                {
                  className: `mt-1.5 ${textSize} text-red-600 dark:text-red-400 flex items-center gap-1`,
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(Info, { className: "w-4 h-4" }),
                    errors.start_time
                  ]
                }
              )
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "label",
                {
                  className: `block ${labelSize} font-medium text-gray-700 dark:text-gray-300 mb-1.5`,
                  children: __("End Time", "yatra")
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                HelpText,
                {
                  text: __("When does this activity end?", "yatra"),
                  className: "mb-2"
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                TimePicker,
                {
                  value: entry.end_time || "",
                  onChange: (value) => {
                    onFieldChange("end_time", value);
                    if (calculateDuration && entry.start_time) {
                      const newDuration = calculateDuration(
                        entry.start_time,
                        value,
                        entry.time_type || "exact"
                      );
                      if (newDuration && !entry.duration) {
                        onFieldChange("duration", newDuration);
                      }
                    }
                  },
                  placeholder: "17:00",
                  className: "w-full",
                  error: !!(errors == null ? void 0 : errors.end_time)
                }
              ),
              errors.end_time && /* @__PURE__ */ jsxRuntimeExports.jsxs(
                "p",
                {
                  className: `mt-1.5 ${textSize} text-red-600 dark:text-red-400 flex items-center gap-1`,
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(Info, { className: "w-4 h-4" }),
                    errors.end_time
                  ]
                }
              )
            ] })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "label",
              {
                className: `block ${labelSize} font-medium text-gray-700 dark:text-gray-300 mb-1.5`,
                children: __("Duration", "yatra")
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              HelpText,
              {
                text: __(
                  'How long does this activity take? (e.g., "3 hours", "1 hour 30 minutes"). Leave empty to auto-calculate from times.',
                  "yatra"
                ),
                className: "mb-2"
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Clock, { className: "absolute left-2.5 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Input,
                {
                  type: "text",
                  value: entry.duration || "",
                  onChange: (e) => onFieldChange("duration", e.target.value),
                  placeholder: autoDuration || __("e.g., 3 hours", "yatra"),
                  className: `pl-9 ${textSize}`
                }
              )
            ] }),
            autoDuration && entry.time_type === "exact" && !entry.duration && /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "p",
              {
                className: `mt-1.5 ${isCompact ? "text-xs" : "text-xs"} text-gray-500 dark:text-gray-400`,
                children: [
                  __("Auto-calculated:", "yatra"),
                  " ",
                  autoDuration
                ]
              }
            )
          ] })
        ]
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "div",
      {
        className: `space-y-3 ${!isCompact ? "pt-3 border-t border-gray-200 dark:border-gray-700" : ""}`,
        children: [
          !isCompact && /* @__PURE__ */ jsxRuntimeExports.jsx(
            "h5",
            {
              className: `${labelSize} font-semibold text-gray-900 dark:text-white`,
              children: __("Cost and Additional Information", "yatra")
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "label",
                {
                  className: `block ${labelSize} font-medium text-gray-700 dark:text-gray-300 mb-1.5`,
                  children: __("Cost", "yatra")
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                HelpText,
                {
                  text: __(
                    "Optional cost for this activity. Leave empty if included in trip price.",
                    "yatra"
                  ),
                  className: "mb-2"
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-500 text-sm", children: currencySymbol }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Input,
                  {
                    type: "number",
                    min: "0",
                    step: "0.01",
                    value: entry.cost || "",
                    onChange: (e) => onFieldChange("cost", e.target.value),
                    placeholder: "0.00",
                    className: `pl-8 ${textSize}`
                  }
                )
              ] })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex items-end", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("label", { className: "flex items-center gap-2 cursor-pointer", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "input",
                {
                  type: "checkbox",
                  checked: entry.cost_per_person !== false,
                  onChange: (e) => onFieldChange("cost_per_person", e.target.checked),
                  className: "rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: `${textSize} text-gray-700 dark:text-gray-300`, children: __("Cost per person", "yatra") })
            ] }) })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "label",
              {
                className: `block ${labelSize} font-medium text-gray-700 dark:text-gray-300 mb-1.5`,
                children: __("Notes / Instructions", "yatra")
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              HelpText,
              {
                text: __(
                  "Additional notes or special instructions for this activity.",
                  "yatra"
                ),
                className: "mb-2"
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "textarea",
              {
                value: entry.notes || "",
                onChange: (e) => onFieldChange("notes", e.target.value),
                placeholder: __(
                  "e.g., Please arrive 15 minutes early, Bring comfortable shoes...",
                  "yatra"
                ),
                rows: isCompact ? 2 : 3,
                className: `flex w-full rounded-md border border-gray-300 bg-white px-3 py-2 ${textSize} ring-offset-white placeholder:text-gray-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 dark:border-gray-600 dark:bg-gray-800 dark:ring-offset-gray-900 dark:placeholder:text-gray-400 dark:focus-visible:ring-blue-400 resize-none`
              }
            )
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "label",
                {
                  className: `block ${labelSize} font-medium text-gray-700 dark:text-gray-300 mb-2`,
                  children: __("Included Items", "yatra")
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                HelpText,
                {
                  text: __("Items or services included in this activity.", "yatra"),
                  className: "mb-2"
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-2", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    Input,
                    {
                      type: "text",
                      value: newIncludedItem,
                      onChange: (e) => onIncludedItemChange == null ? void 0 : onIncludedItemChange(e.target.value),
                      onKeyPress: (e) => {
                        if (e.key === "Enter") {
                          e.preventDefault();
                          onAddIncludedItem == null ? void 0 : onAddIncludedItem();
                        }
                      },
                      placeholder: __("Add included item...", "yatra"),
                      className: `flex-1 ${textSize}`
                    }
                  ),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    Button,
                    {
                      type: "button",
                      variant: "outline",
                      size: "icon",
                      onClick: (e) => {
                        e.preventDefault();
                        e.stopPropagation();
                        if (newIncludedItem.trim()) {
                          onAddIncludedItem == null ? void 0 : onAddIncludedItem();
                        }
                      },
                      disabled: !newIncludedItem.trim(),
                      className: `flex-shrink-0 ${isCompact ? "h-9 w-9" : ""}`,
                      children: /* @__PURE__ */ jsxRuntimeExports.jsx(Plus, { className: "w-4 h-4" })
                    }
                  )
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex flex-wrap gap-2", children: (entry.included_items || []).map((item, index) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
                  Badge,
                  {
                    variant: "info",
                    className: `flex items-center gap-1.5 ${textSize}`,
                    children: [
                      item,
                      /* @__PURE__ */ jsxRuntimeExports.jsx(
                        "button",
                        {
                          type: "button",
                          onClick: () => onRemoveIncludedItem == null ? void 0 : onRemoveIncludedItem(index),
                          className: "ml-1 hover:text-red-600",
                          children: /* @__PURE__ */ jsxRuntimeExports.jsx(X, { className: "w-3 h-3" })
                        }
                      )
                    ]
                  },
                  index
                )) })
              ] })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "label",
                {
                  className: `block ${labelSize} font-medium text-gray-700 dark:text-gray-300 mb-2`,
                  children: __("Excluded Items", "yatra")
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                HelpText,
                {
                  text: __(
                    "Items or services NOT included in this activity.",
                    "yatra"
                  ),
                  className: "mb-2"
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-2", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    Input,
                    {
                      type: "text",
                      value: newExcludedItem,
                      onChange: (e) => onExcludedItemChange == null ? void 0 : onExcludedItemChange(e.target.value),
                      onKeyPress: (e) => {
                        if (e.key === "Enter") {
                          e.preventDefault();
                          onAddExcludedItem == null ? void 0 : onAddExcludedItem();
                        }
                      },
                      placeholder: __("Add excluded item...", "yatra"),
                      className: `flex-1 ${textSize}`
                    }
                  ),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    Button,
                    {
                      type: "button",
                      variant: "outline",
                      size: "icon",
                      onClick: (e) => {
                        e.preventDefault();
                        e.stopPropagation();
                        if (newExcludedItem.trim()) {
                          onAddExcludedItem == null ? void 0 : onAddExcludedItem();
                        }
                      },
                      disabled: !newExcludedItem.trim(),
                      className: `flex-shrink-0 ${isCompact ? "h-9 w-9" : ""}`,
                      children: /* @__PURE__ */ jsxRuntimeExports.jsx(Plus, { className: "w-4 h-4" })
                    }
                  )
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex flex-wrap gap-2", children: (entry.excluded_items || []).map((item, index) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
                  Badge,
                  {
                    variant: "default",
                    className: `flex items-center gap-1.5 ${textSize} border border-gray-300 dark:border-gray-600`,
                    children: [
                      item,
                      /* @__PURE__ */ jsxRuntimeExports.jsx(
                        "button",
                        {
                          type: "button",
                          onClick: () => onRemoveExcludedItem == null ? void 0 : onRemoveExcludedItem(index),
                          className: "ml-1 hover:text-red-600",
                          children: /* @__PURE__ */ jsxRuntimeExports.jsx(X, { className: "w-3 h-3" })
                        }
                      )
                    ]
                  },
                  index
                )) })
              ] })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-4", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "label",
                {
                  className: `block ${labelSize} font-medium text-gray-700 dark:text-gray-300 mb-1.5`,
                  children: __("Photo Gallery", "yatra")
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                HelpText,
                {
                  text: __("Add photos to showcase this activity", "yatra"),
                  className: "mb-2"
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                MediaUpload,
                {
                  items: localGallery,
                  onChange: (mediaItems) => {
                    setLocalGallery(mediaItems);
                    onFieldChange("gallery", mediaItems);
                  },
                  maxItems: 6,
                  acceptTypes: "images",
                  title: __("Activity Photos", "yatra"),
                  description: __(
                    "Upload photos to showcase this activity",
                    "yatra"
                  ),
                  className: "w-full"
                }
              )
            ] }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-4", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "label",
                {
                  className: `block ${labelSize} font-medium text-gray-700 dark:text-gray-300 mb-1.5`,
                  children: __("Video URL", "yatra")
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                HelpText,
                {
                  text: __(
                    "Add a video URL to showcase this activity (YouTube, Vimeo, etc.)",
                    "yatra"
                  ),
                  className: "mb-2"
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "input",
                {
                  type: "text",
                  value: localVideoUrl,
                  onChange: (e) => {
                    setLocalVideoUrl(e.target.value);
                    onFieldChange("video_url", e.target.value);
                  },
                  placeholder: __("https://youtube.com/watch?v=...", "yatra"),
                  className: `flex h-11 w-full rounded-md border-2 border-gray-300 bg-white px-4 py-2.5 text-base font-normal text-gray-900 ring-offset-white file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-gray-400 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100 dark:ring-offset-gray-900 dark:placeholder:text-gray-500 dark:focus-visible:ring-blue-400 transition-colors ${textSize}`
                }
              ),
              errors.video_url && /* @__PURE__ */ jsxRuntimeExports.jsxs(
                "p",
                {
                  className: `mt-1.5 ${textSize} text-red-600 dark:text-red-400 flex items-center gap-1`,
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(Info, { className: "w-4 h-4" }),
                    errors.video_url
                  ]
                }
              )
            ] }) })
          ] })
        ]
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      Modal,
      {
        isOpen: isItemTypeModalOpen,
        onClose: () => setIsItemTypeModalOpen(false),
        title: __("Add New Item Type", "yatra"),
        description: __(
          "Create a new category for organizing itinerary items",
          "yatra"
        ),
        size: "xl",
        children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          ItemTypeFormContent,
          {
            onSuccess: (newItemType) => {
              var _a2;
              setIsItemTypeModalOpen(false);
              const itemTypeId = ((_a2 = newItemType == null ? void 0 : newItemType.data) == null ? void 0 : _a2.id) || (newItemType == null ? void 0 : newItemType.id);
              if (itemTypeId) {
                onFieldChange("item_type_id", itemTypeId.toString());
              }
              onFieldChange("item_id", "");
              onRefreshData == null ? void 0 : onRefreshData();
            },
            onCancel: () => setIsItemTypeModalOpen(false)
          }
        )
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      Modal,
      {
        isOpen: isItemModalOpen,
        onClose: () => setIsItemModalOpen(false),
        title: __("Add New Item", "yatra"),
        description: __(
          "Create a new item for the selected item type",
          "yatra"
        ),
        size: "xl",
        children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          ItemFormContent,
          {
            selectedTypeId: entry.item_type_id,
            onSuccess: (newItem) => {
              var _a2;
              setIsItemModalOpen(false);
              const itemId = ((_a2 = newItem == null ? void 0 : newItem.data) == null ? void 0 : _a2.id) || (newItem == null ? void 0 : newItem.id);
              if (itemId) {
                onFieldChange("item_id", itemId.toString());
              }
              onRefreshData == null ? void 0 : onRefreshData();
            },
            onCancel: () => setIsItemModalOpen(false)
          }
        )
      }
    )
  ] });
  return renderField(content);
};
const ItemTypeFormContent = ({
  onSuccess,
  onCancel
}) => {
  const [formData, setFormData] = reactExports.useState({
    name: "",
    slug: "",
    description: "",
    icon: null,
    color: "blue",
    status: "publish"
  });
  const [errors, setErrors] = reactExports.useState({});
  const [isSubmitting, setIsSubmitting] = reactExports.useState(false);
  const handleNameChange = (value) => {
    const slug = value.toLowerCase().replace(/[^\p{L}\p{N}-]+/gu, "-").replace(/-+/g, "-").replace(/^-+|-+$/g, "");
    setFormData((prev) => ({
      ...prev,
      name: value,
      slug
    }));
    if (errors.name) {
      setErrors((prev) => ({ ...prev, name: "" }));
    }
  };
  const handleSubmit = async (e) => {
    var _a;
    e.preventDefault();
    setIsSubmitting(true);
    try {
      const response = await fetch("/wp-json/yatra/v1/item-types", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "X-WP-Nonce": ((_a = window.wpApiSettings) == null ? void 0 : _a.nonce) || ""
        },
        body: JSON.stringify(formData)
      });
      if (response.ok) {
        const newItemType = await response.json();
        onSuccess(newItemType);
      } else {
        const errorData = await response.json();
        setErrors(
          errorData.errors || { general: "Failed to create item type" }
        );
      }
    } catch (error) {
      setErrors({ general: "An error occurred while creating the item type" });
    } finally {
      setIsSubmitting(false);
    }
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("form", { onSubmit: handleSubmit, className: "space-y-4", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5", children: [
        __("Type Name", "yatra"),
        " ",
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        Input,
        {
          type: "text",
          value: formData.name,
          onChange: (e) => handleNameChange(e.target.value),
          placeholder: __("e.g., Activity, Meal, Accommodation", "yatra"),
          className: errors.name ? "border-red-500" : "",
          required: true
        }
      ),
      errors.name && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm text-red-600 dark:text-red-400", children: errors.name }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-xs text-gray-500 dark:text-gray-400", children: __(
        "Slug will be auto-generated. You can edit icon, color, and other options later in Item Types page",
        "yatra"
      ) })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5", children: __("Description", "yatra") }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        "textarea",
        {
          value: formData.description,
          onChange: (e) => setFormData({ ...formData, description: e.target.value }),
          placeholder: __("Brief description of this item type...", "yatra"),
          rows: 3,
          className: "flex w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm ring-offset-white placeholder:text-gray-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 dark:border-gray-600 dark:bg-gray-800 dark:ring-offset-gray-900 dark:placeholder:text-gray-400 dark:text-white resize-none"
        }
      )
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-end gap-2 pt-4 border-t dark:border-gray-700", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        Button,
        {
          type: "button",
          variant: "outline",
          onClick: onCancel,
          disabled: isSubmitting,
          children: __("Cancel", "yatra")
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { type: "submit", disabled: isSubmitting, children: isSubmitting ? __("Creating...", "yatra") : __("Create Item Type", "yatra") })
    ] })
  ] });
};
const ItemFormContent = ({
  selectedTypeId,
  onSuccess,
  onCancel
}) => {
  const [formData, setFormData] = reactExports.useState({
    name: "",
    slug: "",
    description: "",
    type_id: "",
    status: "publish"
  });
  const [errors, setErrors] = reactExports.useState({});
  const [isSubmitting, setIsSubmitting] = reactExports.useState(false);
  reactExports.useEffect(() => {
    setFormData((prev) => ({
      ...prev,
      type_id: selectedTypeId || ""
    }));
  }, [selectedTypeId]);
  if (!selectedTypeId) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "p-6 text-center", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mb-4", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Info, { className: "w-12 h-12 text-yellow-500 mx-auto" }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-lg font-semibold text-gray-900 dark:text-white mb-2", children: __("Item Type Required", "yatra") }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-gray-600 dark:text-gray-400 mb-4", children: __(
        "Please select an Item Type first before creating an Item.",
        "yatra"
      ) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { type: "button", variant: "outline", onClick: onCancel, children: __("Close", "yatra") })
    ] });
  }
  const handleNameChange = (value) => {
    const slug = value.toLowerCase().replace(/[^\p{L}\p{N}-]+/gu, "-").replace(/-+/g, "-").replace(/^-+|-+$/g, "");
    setFormData((prev) => ({
      ...prev,
      name: value,
      slug
    }));
    if (errors.name) {
      setErrors((prev) => ({ ...prev, name: "" }));
    }
  };
  const handleSubmit = async (e) => {
    var _a;
    e.preventDefault();
    setIsSubmitting(true);
    try {
      const response = await fetch("/wp-json/yatra/v1/items", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "X-WP-Nonce": ((_a = window.wpApiSettings) == null ? void 0 : _a.nonce) || ""
        },
        body: JSON.stringify(formData)
      });
      if (response.ok) {
        const newItem = await response.json();
        onSuccess(newItem);
      } else {
        const errorData = await response.json();
        setErrors(errorData.errors || { general: "Failed to create item" });
      }
    } catch (error) {
      setErrors({ general: "An error occurred while creating the item" });
    } finally {
      setIsSubmitting(false);
    }
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("form", { onSubmit: handleSubmit, className: "space-y-4", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5", children: [
        __("Item Name", "yatra"),
        " ",
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        Input,
        {
          type: "text",
          value: formData.name,
          onChange: (e) => handleNameChange(e.target.value),
          placeholder: __("e.g., Hiking, Lunch, Hotel", "yatra"),
          className: errors.name ? "border-red-500" : "",
          required: true
        }
      ),
      errors.name && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm text-red-600 dark:text-red-400", children: errors.name }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-xs text-gray-500 dark:text-gray-400", children: __(
        "Slug will be auto-generated. You can edit additional details later in Items page",
        "yatra"
      ) })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5", children: __("Description", "yatra") }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        "textarea",
        {
          value: formData.description,
          onChange: (e) => setFormData({ ...formData, description: e.target.value }),
          placeholder: __("Brief description of this item...", "yatra"),
          rows: 3,
          className: "flex w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm ring-offset-white placeholder:text-gray-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 dark:border-gray-600 dark:bg-gray-800 dark:ring-offset-gray-900 dark:placeholder:text-gray-400 dark:text-white resize-none"
        }
      )
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-end gap-2 pt-4 border-t dark:border-gray-700", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        Button,
        {
          type: "button",
          variant: "outline",
          onClick: onCancel,
          disabled: isSubmitting,
          children: __("Cancel", "yatra")
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { type: "submit", disabled: isSubmitting, children: isSubmitting ? __("Creating...", "yatra") : __("Create Item", "yatra") })
    ] })
  ] });
};
const useItineraryFormData = ({
  entryId,
  isEditMode,
  isEditDayMode,
  isAddDayMode,
  tripIdParam,
  dayParam,
  formDataItemTypeId,
  formDataTripId
}) => {
  const { can } = usePermissions();
  const { data: tripsData, isLoading: isLoadingTrips } = useQuery({
    queryKey: ["trips-simple"],
    queryFn: async () => {
      var _a;
      try {
        const response = await apiClient.get("/trips", {
          params: {
            per_page: 100,
            status: "all"
          }
        });
        const trips = ((_a = response == null ? void 0 : response.data) == null ? void 0 : _a.data) || (response == null ? void 0 : response.data) || response || [];
        return Array.isArray(trips) ? trips : [];
      } catch (error) {
        console.error("Failed to load trips:", error);
        return [];
      }
    },
    enabled: can("yatra_view_trips")
  });
  const { data: typesData } = useQuery({
    queryKey: ["item-types-published"],
    queryFn: async () => {
      var _a;
      try {
        const response = await apiClient.get("/item-types", {
          params: {
            per_page: 100,
            status: "publish"
          }
        });
        const types = ((_a = response == null ? void 0 : response.data) == null ? void 0 : _a.data) || (response == null ? void 0 : response.data) || response || [];
        return Array.isArray(types) ? types : [];
      } catch (error) {
        console.error("Failed to load item types:", error);
        return [];
      }
    },
    enabled: can("yatra_view_trips"),
    staleTime: 5 * 60 * 1e3,
    gcTime: 10 * 60 * 1e3
  });
  const itemsQueryKey = reactExports.useMemo(
    () => isAddDayMode ? ["items-all-published"] : ["items-by-type", formDataItemTypeId],
    [isAddDayMode, formDataItemTypeId]
  );
  const { data: itemsData } = useQuery({
    queryKey: itemsQueryKey,
    queryFn: async () => {
      var _a, _b;
      try {
        if (isAddDayMode) {
          const response2 = await apiClient.get("/items", {
            params: {
              per_page: 1e3,
              status: "publish"
            }
          });
          const items2 = ((_a = response2 == null ? void 0 : response2.data) == null ? void 0 : _a.data) || (response2 == null ? void 0 : response2.data) || response2 || [];
          return Array.isArray(items2) ? items2 : [];
        }
        if (!formDataItemTypeId) return [];
        const response = await apiClient.get("/items", {
          params: {
            per_page: 1e3,
            type_id: formDataItemTypeId,
            status: "publish"
          }
        });
        const items = ((_b = response == null ? void 0 : response.data) == null ? void 0 : _b.data) || (response == null ? void 0 : response.data) || response || [];
        return Array.isArray(items) ? items : [];
      } catch (error) {
        console.error("Failed to load items:", error);
        return [];
      }
    },
    enabled: can("yatra_view_trips"),
    staleTime: 5 * 60 * 1e3,
    gcTime: 10 * 60 * 1e3
  });
  const { data: entryData, isLoading: isLoadingEntryData } = useQuery({
    queryKey: ["itinerary-entry", entryId, isEditDayMode ? "day" : "activity"],
    queryFn: async () => {
      var _a;
      if (!entryId) return null;
      try {
        const mode = isEditDayMode ? "day" : "activity";
        const endpoint = API_ENDPOINTS.ITINERARY_GET(entryId, mode);
        const response = await apiClient.get(endpoint);
        const result = ((_a = response == null ? void 0 : response.data) == null ? void 0 : _a.data) || (response == null ? void 0 : response.data) || response;
        return result;
      } catch (error) {
        console.error("Failed to load itinerary entry:", error);
        return null;
      }
    },
    enabled: isEditMode && !!entryId && can("yatra_view_trips")
  });
  const entryDayId = reactExports.useMemo(() => entryData == null ? void 0 : entryData.day_id, [entryData == null ? void 0 : entryData.day_id]);
  const isActivityEntry = reactExports.useMemo(() => {
    return entryData && entryData.item_type_id !== null && entryData.item_type_id !== void 0 && entryData.item_type_id !== 0 && entryData.item_id !== null && entryData.item_id !== void 0 && entryData.item_id !== 0;
  }, [entryData]);
  const { data: dayEntryData } = useQuery({
    queryKey: ["day-entry-by-day-id", entryDayId],
    queryFn: async () => {
      var _a, _b, _c;
      if (!entryDayId || !isEditDayMode) return null;
      try {
        const response = await apiClient.get(
          `/itinerary/day-entry-by-day-id/${entryDayId}`
        );
        const dayEntryId = ((_a = response == null ? void 0 : response.data) == null ? void 0 : _a.day_entry_id) || (response == null ? void 0 : response.day_entry_id) || ((_b = response == null ? void 0 : response.data) == null ? void 0 : _b.id) || (response == null ? void 0 : response.id) || null;
        if (dayEntryId) {
          const entryResponse = await apiClient.get(`/itinerary/${dayEntryId}`);
          return ((_c = entryResponse == null ? void 0 : entryResponse.data) == null ? void 0 : _c.data) || (entryResponse == null ? void 0 : entryResponse.data) || entryResponse;
        }
        return null;
      } catch (error) {
        console.error("Failed to load day entry:", error);
        return null;
      }
    },
    enabled: isEditDayMode && !!entryDayId && isActivityEntry && can("yatra_view_trips")
  });
  const effectiveEntryData = reactExports.useMemo(() => {
    if (isEditDayMode && isActivityEntry && dayEntryData) {
      return dayEntryData;
    }
    return entryData;
  }, [isEditDayMode, isActivityEntry, dayEntryData, entryData]);
  const entryTripId = reactExports.useMemo(
    () => effectiveEntryData == null ? void 0 : effectiveEntryData.trip_id,
    [effectiveEntryData == null ? void 0 : effectiveEntryData.trip_id]
  );
  const entryDay = reactExports.useMemo(
    () => effectiveEntryData == null ? void 0 : effectiveEntryData.day,
    [effectiveEntryData == null ? void 0 : effectiveEntryData.day]
  );
  const { data: dayTripData } = useQuery({
    queryKey: ["trip-for-day-edit", entryTripId, entryDay],
    queryFn: async () => {
      if (!entryTripId || !isEditDayMode) return null;
      try {
        const response = await apiClient.get(`/trips/${entryTripId}`);
        return (response == null ? void 0 : response.data) || response;
      } catch (error) {
        console.error("Failed to load trip data for day edit:", error);
        return null;
      }
    },
    enabled: isEditDayMode && !!entryTripId && !!entryDay && can("yatra_view_trips")
  });
  const effectiveTripIdForQuery = tripIdParam || formDataTripId || "";
  const tripDataQueryKey = reactExports.useMemo(
    () => ["trip-for-day", effectiveTripIdForQuery, dayParam || ""],
    [effectiveTripIdForQuery, dayParam]
  );
  const { data: tripDataForDay } = useQuery({
    queryKey: tripDataQueryKey,
    queryFn: async () => {
      if (!effectiveTripIdForQuery) return null;
      try {
        const response = await apiClient.get(
          `/trips/${effectiveTripIdForQuery}`
        );
        return (response == null ? void 0 : response.data) || response;
      } catch (error) {
        console.error("Failed to fetch trip data:", error);
        return null;
      }
    },
    enabled: !isEditDayMode && !!effectiveTripIdForQuery && can("yatra_view_trips")
  });
  const effectiveTripData = isEditDayMode ? dayTripData : tripDataForDay;
  return {
    tripsData: tripsData || [],
    isLoadingTrips,
    typesData: typesData || [],
    itemsData: itemsData || [],
    entryData: effectiveEntryData,
    isLoadingEntry: isLoadingEntryData,
    dayTripData,
    tripDataForDay,
    effectiveTripData,
    entryTripId,
    entryDay
  };
};
const useItineraryFormValidation = () => {
  const validateForm = (formData, isAddDayMode, activityForms) => {
    const newErrors = {};
    if (!formData.trip_id) {
      newErrors.trip_id = __("Trip is required", "yatra");
    }
    if (!formData.day || parseInt(formData.day) < 1) {
      newErrors.day = __("Day must be at least 1", "yatra");
    }
    if (isAddDayMode) {
      activityForms.forEach((activityForm, index) => {
        var _a;
        if (!activityForm.data.item_type_id) {
          newErrors[`activity_${activityForm.id}_item_type_id`] = __("Item type is required for Activity", "yatra") + ` ${index + 1}`;
        }
        if (!activityForm.data.item_id) {
          newErrors[`activity_${activityForm.id}_item_id`] = __("Item is required for Activity", "yatra") + ` ${index + 1}`;
        }
        if (!((_a = activityForm.data.title) == null ? void 0 : _a.trim())) {
          newErrors[`activity_${activityForm.id}_title`] = __("Title is required for Activity", "yatra") + ` ${index + 1}`;
        }
      });
      return {
        isValid: Object.keys(newErrors).length === 0,
        errors: newErrors
      };
    }
    if (!formData.item_type_id) {
      newErrors.item_type_id = __("Item type is required", "yatra");
    }
    if (!formData.item_id) {
      newErrors.item_id = __("Item is required", "yatra");
    }
    if (!formData.title.trim()) {
      newErrors.title = __("Title is required", "yatra");
    }
    if (formData.time_type === "exact" && formData.start_time && formData.end_time) {
      const [startHour, startMin] = formData.start_time.split(":").map(Number);
      const [endHour, endMin] = formData.end_time.split(":").map(Number);
      const startMinutes = startHour * 60 + startMin;
      const endMinutes = endHour * 60 + endMin;
      if (endMinutes <= startMinutes && endMinutes < startMinutes + 60) {
        newErrors.end_time = __("End time must be after start time", "yatra");
      }
    }
    return { isValid: Object.keys(newErrors).length === 0, errors: newErrors };
  };
  return { validateForm };
};
const useItineraryFormSave = ({
  isAddDayMode,
  isEditMode,
  entryId,
  activityForms,
  formData,
  calculateDuration,
  entryData,
  dayTripData,
  tripsData
}) => {
  const queryClient2 = useQueryClient();
  const { showToast } = useToast();
  const saveMutation = useMutation({
    mutationFn: async (data) => {
      var _a, _b, _c, _d;
      if (isAddDayMode) {
        const tripId = parseInt(data.trip_id);
        const day = parseInt(data.day);
        const dayTitle = ((_a = data.day_title) == null ? void 0 : _a.trim()) || null;
        if (isEditMode && entryId) {
          const dayPayload = {
            trip_id: tripId,
            day,
            day_title: dayTitle,
            day_description: ((_b = data.day_description) == null ? void 0 : _b.trim()) || null,
            title: dayTitle || `Day ${day}`,
            // Backend requires title field
            item_type_id: null,
            item_id: null,
            status: data.status || "draft"
          };
          let dayEntryId = null;
          if (entryData && (entryData.item_type_id === null || entryData.item_type_id === void 0) && (entryData.item_id === null || entryData.item_id === void 0)) {
            dayEntryId = entryData.id ? parseInt(entryData.id.toString()) : null;
          }
          if (!dayEntryId && entryData && entryData.day_id) {
            try {
              const dayEntryResponse = await apiClient.get(
                `/itinerary/day-entry-by-day-id/${entryData.day_id}`
              );
              const dayEntryData = (dayEntryResponse == null ? void 0 : dayEntryResponse.data) || dayEntryResponse;
              if (dayEntryData && dayEntryData.day_entry_id) {
                dayEntryId = parseInt(dayEntryData.day_entry_id.toString());
              }
            } catch (error) {
            }
          }
          if (!dayEntryId && entryData && entryData.day_id && dayTripData) {
            const itineraryDays = dayTripData.itinerary_days || [];
            for (const dayData of itineraryDays) {
              if (dayData.id === entryData.day_id || dayData.day_id === entryData.day_id) {
                if (dayData.entries) {
                  const dayEntry = dayData.entries.find(
                    (e) => (e.item_type_id === null || e.item_type_id === void 0) && (e.item_id === null || e.item_id === void 0)
                  );
                  if (dayEntry && dayEntry.id) {
                    dayEntryId = parseInt(dayEntry.id.toString());
                    break;
                  }
                }
              }
            }
          }
          const originalDay = (entryData == null ? void 0 : entryData.day) ? parseInt(entryData.day.toString()) : null;
          if (!dayEntryId && dayTripData && originalDay) {
            const itineraryDays = dayTripData.itinerary_days || [];
            const dayData = itineraryDays.find(
              (d) => (d.day_number || d.day) === originalDay
            );
            if (dayData && dayData.entries) {
              const dayEntry = dayData.entries.find(
                (e) => (e.item_type_id === null || e.item_type_id === void 0) && (e.item_id === null || e.item_id === void 0)
              );
              if (dayEntry && dayEntry.id) {
                dayEntryId = parseInt(dayEntry.id.toString());
              }
            }
          }
          if (!dayEntryId) {
            throw new Error(
              "Day entry not found. The day entry should exist when editing. Please refresh the page and try again, or contact support if the issue persists."
            );
          }
          const endpoint = API_ENDPOINTS.ITINERARY_GET(dayEntryId, "day");
          const dayResponse = await apiClient.put(endpoint, dayPayload);
          const orderById = new Map(
            activityForms.map((af, idx) => [af.id, idx])
          );
          const buildActivityPayload = (activityData, order) => {
            const timeType2 = activityData.time_type || "exact";
            const startTime2 = timeType2 === "exact" && activityData.start_time ? activityData.start_time : null;
            const endTime2 = timeType2 === "exact" && activityData.end_time ? activityData.end_time : null;
            return {
              trip_id: tripId,
              day,
              day_title: dayTitle,
              item_type_id: parseInt(activityData.item_type_id),
              item_id: parseInt(activityData.item_id),
              title: activityData.title.trim(),
              description: (activityData.description || "").trim(),
              location: (activityData.location || "").trim(),
              // Latitude / longitude were saved by the form but never sent in the
              // payload before — saving silently dropped them. Send as floats; let
              // the repo coerce empty strings to null.
              location_latitude: activityData.location_latitude !== void 0 && activityData.location_latitude !== "" ? parseFloat(activityData.location_latitude) : null,
              location_longitude: activityData.location_longitude !== void 0 && activityData.location_longitude !== "" ? parseFloat(activityData.location_longitude) : null,
              duration: (activityData.duration || "").trim() || (startTime2 && endTime2 ? calculateDuration(startTime2, endTime2, timeType2) : null),
              start_time: startTime2,
              end_time: endTime2,
              time_type: timeType2,
              cost: activityData.cost ? parseFloat(activityData.cost) : null,
              cost_per_person: activityData.cost_per_person === true,
              notes: (activityData.notes || "").trim(),
              included_items: Array.isArray(activityData.included_items) ? activityData.included_items : [],
              excluded_items: Array.isArray(activityData.excluded_items) ? activityData.excluded_items : [],
              gallery: activityData.gallery || [],
              video_url: activityData.video_url || "",
              status: activityData.status || "draft",
              order: Math.max(0, order)
            };
          };
          const validatedRows = activityForms.map((af, index) => {
            var _a2;
            const activityData = af.data;
            if (!activityData.item_type_id || !activityData.item_id || !((_a2 = activityData.title) == null ? void 0 : _a2.trim())) {
              throw new Error(
                `Activity ${index + 1} is missing required fields (item type, item, or title)`
              );
            }
            const order = orderById.get(af.id) ?? index;
            const payload2 = buildActivityPayload(activityData, order);
            if (af.entryId) {
              payload2.id = typeof af.entryId === "string" ? parseInt(af.entryId, 10) : af.entryId;
            }
            return payload2;
          });
          const bulkEndpoint = API_ENDPOINTS.ITINERARY_DAY_ACTIVITIES_BULK(dayEntryId);
          try {
            const bulkResponse = await apiClient.put(bulkEndpoint, {
              trip_id: tripId,
              activities: validatedRows
            });
            const bulkData = (bulkResponse == null ? void 0 : bulkResponse.data) || bulkResponse || {};
            if (bulkData.failed && bulkData.failed > 0) {
              const firstError = (bulkData.results || []).find(
                (r2) => r2 && r2.ok === false
              );
              throw new Error(
                `${bulkData.failed} activit${bulkData.failed === 1 ? "y" : "ies"} failed to save${(firstError == null ? void 0 : firstError.error) ? `: ${firstError.error}` : ""}`
              );
            }
          } catch (error) {
            throw new Error(
              `Failed to save activities: ${(error == null ? void 0 : error.message) || "Unknown error"}`
            );
          }
          return dayResponse.data || dayResponse;
        }
        const validActivities = activityForms.filter((af) => {
          var _a2;
          const activityData = af.data;
          return activityData.item_type_id && activityData.item_id && ((_a2 = activityData.title) == null ? void 0 : _a2.trim());
        });
        if (validActivities.length === 0) {
          const payload2 = {
            trip_id: tripId,
            day,
            day_title: dayTitle,
            day_description: ((_c = data.day_description) == null ? void 0 : _c.trim()) || null,
            item_type_id: null,
            item_id: null,
            title: dayTitle || `Day ${day}`,
            description: "",
            location: null,
            duration: null,
            start_time: null,
            end_time: null,
            time_type: "exact",
            cost: null,
            cost_per_person: false,
            notes: null,
            included_items: [],
            excluded_items: [],
            status: data.status || "draft"
          };
          const response = await apiClient.post("/itinerary", payload2);
          return response.data || response;
        }
        const responses = [];
        for (let index = 0; index < validActivities.length; index++) {
          const activityForm = validActivities[index];
          const activityData = activityForm.data;
          const timeType2 = activityData.time_type || "exact";
          const startTime2 = timeType2 === "exact" && activityData.start_time ? activityData.start_time : null;
          const endTime2 = timeType2 === "exact" && activityData.end_time ? activityData.end_time : null;
          const payload2 = {
            trip_id: tripId,
            day,
            day_title: dayTitle,
            item_type_id: parseInt(activityData.item_type_id),
            item_id: parseInt(activityData.item_id),
            title: activityData.title.trim(),
            description: (activityData.description || "").trim(),
            location: (activityData.location || "").trim(),
            location_latitude: activityData.location_latitude ? parseFloat(activityData.location_latitude) : null,
            location_longitude: activityData.location_longitude ? parseFloat(activityData.location_longitude) : null,
            duration: (activityData.duration || "").trim() || (startTime2 && endTime2 ? calculateDuration(startTime2, endTime2, timeType2) : null),
            start_time: startTime2,
            end_time: endTime2,
            time_type: timeType2,
            cost: activityData.cost ? parseFloat(activityData.cost) : null,
            cost_per_person: activityData.cost_per_person === true,
            notes: (activityData.notes || "").trim(),
            included_items: Array.isArray(activityData.included_items) ? activityData.included_items : [],
            excluded_items: Array.isArray(activityData.excluded_items) ? activityData.excluded_items : [],
            gallery: activityData.gallery || [],
            video_url: activityData.video_url || "",
            status: activityData.status || "draft"
          };
          try {
            const response = await apiClient.post("/itinerary", payload2);
            responses.push(response.data || response);
          } catch (error) {
            throw new Error(
              `Failed to save activity ${index + 1}: ${(error == null ? void 0 : error.message) || "Unknown error"}`
            );
          }
        }
        return responses[0] || responses;
      }
      const timeType = data.time_type || "exact";
      const startTime = timeType === "exact" && data.start_time ? data.start_time : null;
      const endTime = timeType === "exact" && data.end_time ? data.end_time : null;
      const payload = {
        trip_id: parseInt(data.trip_id),
        day: parseInt(data.day),
        day_title: ((_d = data.day_title) == null ? void 0 : _d.trim()) || null,
        item_type_id: parseInt(data.item_type_id),
        item_id: parseInt(data.item_id),
        title: data.title.trim(),
        description: data.description.trim(),
        location: data.location.trim(),
        location_latitude: data.location_latitude ? parseFloat(data.location_latitude) : null,
        location_longitude: data.location_longitude ? parseFloat(data.location_longitude) : null,
        duration: data.duration.trim() || (startTime && endTime ? calculateDuration(startTime, endTime, timeType) : null),
        start_time: startTime,
        end_time: endTime,
        time_type: timeType,
        cost: data.cost ? parseFloat(data.cost) : null,
        cost_per_person: data.cost_per_person,
        notes: data.notes.trim(),
        included_items: data.included_items,
        excluded_items: data.excluded_items,
        gallery: data.gallery || [],
        video_url: data.video_url || "",
        status: data.status || "draft"
        // Ensure status is always included
      };
      if (isEditMode && entryId) {
        const updatePayload = {
          ...payload,
          status: data.status || "draft"
          // Explicitly include status for updates
        };
        const endpoint = API_ENDPOINTS.ITINERARY_GET(entryId, "activity");
        const response = await apiClient.put(endpoint, updatePayload);
        return response.data || response;
      } else {
        const response = await apiClient.post("/itinerary", payload);
        return response.data || response;
      }
    },
    onSuccess: () => {
      if (isAddDayMode) {
        const validActivitiesCount = activityForms.filter((af) => {
          var _a;
          const activityData = af.data;
          return activityData.item_type_id && activityData.item_id && ((_a = activityData.title) == null ? void 0 : _a.trim());
        }).length;
        const selectedTrip = tripsData == null ? void 0 : tripsData.find(
          (t) => t.id.toString() === formData.trip_id
        );
        const isSingleDay = (selectedTrip == null ? void 0 : selectedTrip.trip_type) === "single_day";
        if (isEditMode) {
          if (validActivitiesCount === 0) {
            const message2 = isSingleDay ? __("Entry updated successfully!", "yatra") : __("Day updated successfully!", "yatra");
            showToast(message2, "success");
          } else {
            const message2 = isSingleDay ? __(
              "Entry and activities updated successfully!",
              "yatra"
            ).replace(
              "activities",
              `${validActivitiesCount} ${validActivitiesCount === 1 ? "activity" : "activities"}`
            ) : __("Day and activities updated successfully!", "yatra").replace(
              "activities",
              `${validActivitiesCount} ${validActivitiesCount === 1 ? "activity" : "activities"}`
            );
            showToast(message2, "success");
          }
        } else {
          if (validActivitiesCount === 0) {
            const message2 = isSingleDay ? __("Entry created successfully!", "yatra") : __("Day created successfully!", "yatra");
            showToast(message2, "success");
          } else {
            const message2 = isSingleDay ? __(
              "Entry and activities created successfully!",
              "yatra"
            ).replace(
              "activities",
              `${validActivitiesCount} ${validActivitiesCount === 1 ? "activity" : "activities"}`
            ) : __("Day and activities created successfully!", "yatra").replace(
              "activities",
              `${validActivitiesCount} ${validActivitiesCount === 1 ? "activity" : "activities"}`
            );
            showToast(message2, "success");
          }
        }
        queryClient2.invalidateQueries({ queryKey: ["itinerary"] });
        queryClient2.invalidateQueries({ queryKey: ["itinerary-entries"] });
        queryClient2.invalidateQueries({ queryKey: ["trips"] });
        queryClient2.invalidateQueries({ queryKey: ["trips-simple"] });
        if (formData.trip_id) {
          queryClient2.invalidateQueries({
            queryKey: ["trips", parseInt(formData.trip_id)]
          });
          queryClient2.invalidateQueries({
            queryKey: ["trip", parseInt(formData.trip_id)]
          });
        }
        if (!isEditMode) {
          const day = parseInt(formData.day);
          const tripId = formData.trip_id;
          setTimeout(() => {
            var _a;
            const params = new URLSearchParams({
              trip_id: tripId,
              day: day.toString()
            });
            window.location.href = `${((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=itinerary&tab=itinerary&${params.toString()}`;
          }, 1500);
        }
        return;
      }
      showToast(
        isEditMode ? __("Itinerary entry updated successfully!", "yatra") : __("Itinerary entry created successfully!", "yatra"),
        "success"
      );
      queryClient2.invalidateQueries({ queryKey: ["itinerary"] });
      queryClient2.invalidateQueries({ queryKey: ["itinerary-entries"] });
      queryClient2.invalidateQueries({ queryKey: ["trips"] });
      queryClient2.invalidateQueries({ queryKey: ["trips-simple"] });
      if (formData.trip_id) {
        queryClient2.invalidateQueries({
          queryKey: ["trips", parseInt(formData.trip_id)]
        });
        queryClient2.invalidateQueries({
          queryKey: ["trip", parseInt(formData.trip_id)]
        });
        queryClient2.refetchQueries({
          queryKey: ["trips", parseInt(formData.trip_id)]
        });
      }
      queryClient2.refetchQueries({ queryKey: ["trips"] });
      queryClient2.refetchQueries({ queryKey: ["trips-simple"] });
      if (!isEditMode) {
        setTimeout(() => {
          var _a;
          const tripIdParam = formData.trip_id ? `&trip_id=${formData.trip_id}` : "";
          window.location.href = `${((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=itinerary&tab=itinerary${tripIdParam}`;
        }, 1e3);
      }
    },
    onError: (error) => {
      const errorMessage = (error == null ? void 0 : error.message) || __("An error occurred while saving", "yatra");
      showToast(errorMessage, "error");
    },
    onSettled: () => {
    }
  });
  return { saveMutation };
};
const DayFormFields = ({
  formData,
  errors,
  tripsData,
  isLoadingTrips,
  isEditMode = false,
  isSingleDayTrip = false,
  onFieldChange
}) => {
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Day Information", "yatra") }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "label",
            {
              htmlFor: "trip_id",
              className: "flex items-center gap-2 text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
              children: [
                __("Trip", "yatra"),
                " ",
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" }),
                isEditMode && /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "span",
                  {
                    title: __(
                      "This field cannot be changed in edit mode",
                      "yatra"
                    ),
                    children: /* @__PURE__ */ jsxRuntimeExports.jsx(Lock, { className: "w-4 h-4 text-gray-400" })
                  }
                )
              ]
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            HelpText,
            {
              text: isEditMode ? __(
                "The trip cannot be changed when editing a day.",
                "yatra"
              ) : __("Select the trip this day belongs to.", "yatra"),
              className: "mb-2"
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              SearchableSelect,
              {
                value: formData.trip_id,
                onChange: (value) => onFieldChange("trip_id", value),
                options: [
                  { value: "", label: __("-- Select a Trip --", "yatra") },
                  ...(Array.isArray(tripsData) ? tripsData : []).map(
                    (trip) => ({
                      value: trip.id.toString(),
                      label: `${trip.title || trip.name || ""}${trip.trip_type === "single_day" ? " (Single Day)" : trip.trip_type === "multi_day" ? " (Multi-Day)" : ""}`
                    })
                  ) || []
                ],
                placeholder: __("Search or select a trip...", "yatra"),
                searchPlaceholder: __("Search by trip name or ID...", "yatra"),
                className: errors.trip_id ? "border-red-500" : "",
                error: !!errors.trip_id,
                required: true,
                disabled: isLoadingTrips || isEditMode
              }
            ),
            isEditMode && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Lock, { className: "w-4 h-4 text-gray-400" }) })
          ] }),
          errors.trip_id && /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "mt-1.5 text-sm text-red-600 dark:text-red-400 flex items-center gap-1", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Info, { className: "w-4 h-4" }),
            errors.trip_id
          ] })
        ] }),
        !isSingleDayTrip && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "label",
            {
              htmlFor: "day",
              className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
              children: [
                __("Day Number", "yatra"),
                " ",
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
              ]
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            HelpText,
            {
              text: __("Which day number is this in the itinerary?", "yatra"),
              className: "mb-2"
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Input,
            {
              id: "day",
              type: "number",
              min: "1",
              value: formData.day,
              onChange: (e) => onFieldChange("day", e.target.value),
              className: errors.day ? "border-red-500" : "",
              required: true
            }
          ),
          errors.day && /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "mt-1.5 text-sm text-red-600 dark:text-red-400 flex items-center gap-1", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Info, { className: "w-4 h-4" }),
            errors.day
          ] })
        ] }),
        isSingleDayTrip && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "label",
            {
              htmlFor: "day",
              className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
              children: [
                __("Entry Number", "yatra"),
                " ",
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
              ]
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            HelpText,
            {
              text: __(
                "Entry number for ordering entries in this single-day trip.",
                "yatra"
              ),
              className: "mb-2"
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Input,
            {
              id: "day",
              type: "number",
              min: "1",
              value: formData.day,
              onChange: (e) => onFieldChange("day", e.target.value),
              className: errors.day ? "border-red-500" : "",
              required: true
            }
          ),
          errors.day && /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "mt-1.5 text-sm text-red-600 dark:text-red-400 flex items-center gap-1", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Info, { className: "w-4 h-4" }),
            errors.day
          ] })
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "label",
          {
            htmlFor: "day_title",
            className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
            children: __("Day Title (Optional)", "yatra")
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          HelpText,
          {
            text: __(
              'A descriptive title for this day (e.g., "Arrival & Welcome to Paradise").',
              "yatra"
            ),
            className: "mb-2"
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          Input,
          {
            id: "day_title",
            type: "text",
            value: formData.day_title,
            onChange: (e) => onFieldChange("day_title", e.target.value),
            placeholder: __("e.g., Arrival & Welcome to Paradise", "yatra")
          }
        )
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "label",
          {
            htmlFor: "day_description",
            className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
            children: __("Day Description (Optional)", "yatra")
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          HelpText,
          {
            text: __(
              "A detailed description of what happens on this day, activities, highlights, etc.",
              "yatra"
            ),
            className: "mb-2"
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "textarea",
          {
            id: "day_description",
            value: formData.day_description,
            onChange: (e) => onFieldChange("day_description", e.target.value),
            placeholder: __(
              "Describe the activities, highlights, and details for this day...",
              "yatra"
            ),
            rows: 4,
            className: `w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent ${errors.day_description ? "border-red-500" : ""}`
          }
        ),
        errors.day_description && /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "mt-1.5 text-sm text-red-600 dark:text-red-400 flex items-center gap-1", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Info, { className: "w-4 h-4" }),
          errors.day_description
        ] })
      ] })
    ] })
  ] });
};
const ActivityAccordion = ({
  activityForms,
  errors,
  itemTypes,
  items,
  activityIncludedItems,
  activityExcludedItems,
  onToggleExpand,
  onRemoveActivity,
  onAddActivity,
  onReorderActivities,
  onFieldChange,
  onIncludedItemChange,
  onExcludedItemChange,
  onAddIncludedItem,
  onAddExcludedItem,
  onRemoveIncludedItem,
  onRemoveExcludedItem,
  calculateDuration,
  onRefreshData
}) => {
  const reorderEnabled = typeof onReorderActivities === "function";
  const [draggingIndex, setDraggingIndex] = reactExports.useState(null);
  const [dragOverIndex, setDragOverIndex] = reactExports.useState(null);
  const handleDragStart = (index) => (e) => {
    if (!reorderEnabled) return;
    setDraggingIndex(index);
    e.dataTransfer.effectAllowed = "move";
    try {
      e.dataTransfer.setData("text/plain", String(index));
    } catch {
    }
  };
  const handleDragOver = (index) => (e) => {
    if (!reorderEnabled || draggingIndex === null) return;
    e.preventDefault();
    e.dataTransfer.dropEffect = "move";
    if (dragOverIndex !== index) {
      setDragOverIndex(index);
    }
  };
  const handleDrop = (index) => (e) => {
    if (!reorderEnabled || draggingIndex === null) return;
    e.preventDefault();
    if (draggingIndex !== index) {
      onReorderActivities == null ? void 0 : onReorderActivities(draggingIndex, index);
    }
    setDraggingIndex(null);
    setDragOverIndex(null);
  };
  const handleDragEnd = () => {
    setDraggingIndex(null);
    setDragOverIndex(null);
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
    activityForms.length > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-3", children: activityForms.map((activityForm, index) => {
      const isDragging = draggingIndex === index;
      const isDropTarget = dragOverIndex === index && draggingIndex !== index;
      return /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Card,
        {
          className: `mt-3 transition-shadow ${isDragging ? "opacity-60" : ""} ${isDropTarget ? "ring-2 ring-blue-400 dark:ring-blue-500" : ""}`,
          draggable: reorderEnabled,
          onDragStart: handleDragStart(index),
          onDragOver: handleDragOver(index),
          onDrop: handleDrop(index),
          onDragEnd: handleDragEnd,
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between gap-2", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs(CardTitle, { className: "text-base flex items-center gap-2 min-w-0 flex-1", children: [
                reorderEnabled && // The drag-handle shows the row is draggable AND gives
                // keyboard / mouse users an obvious target. The whole
                // card is the drop zone; this is just the affordance.
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "span",
                  {
                    className: "cursor-grab active:cursor-grabbing text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 shrink-0",
                    title: __("Drag to reorder this activity", "yatra"),
                    "aria-label": __(
                      "Drag to reorder this activity",
                      "yatra"
                    ),
                    children: /* @__PURE__ */ jsxRuntimeExports.jsx(GripVertical, { className: "w-4 h-4" })
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "span",
                  {
                    className: "truncate",
                    title: (activityForm.data.title || "").trim(),
                    children: (activityForm.data.title || "").trim() || `${__("Activity", "yatra")} #${index + 1}`
                  }
                )
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Button,
                  {
                    type: "button",
                    variant: "ghost",
                    size: "icon",
                    onClick: () => onToggleExpand(activityForm.id),
                    className: "h-8 w-8",
                    children: activityForm.isExpanded ? /* @__PURE__ */ jsxRuntimeExports.jsx(ChevronUp, { className: "w-4 h-4" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(ChevronDown, { className: "w-4 h-4" })
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Button,
                  {
                    type: "button",
                    variant: "ghost",
                    size: "icon",
                    onClick: () => onRemoveActivity(activityForm.id),
                    className: "h-8 w-8 text-red-600 hover:text-red-700 dark:text-red-400",
                    title: __("Remove Activity", "yatra"),
                    children: /* @__PURE__ */ jsxRuntimeExports.jsx(X, { className: "w-4 h-4" })
                  }
                )
              ] })
            ] }) }),
            activityForm.isExpanded && /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
              ItineraryEntryFields,
              {
                entry: {
                  item_type_id: activityForm.data.item_type_id || "",
                  item_id: activityForm.data.item_id || "",
                  title: activityForm.data.title || "",
                  description: activityForm.data.description || "",
                  location: activityForm.data.location || "",
                  location_latitude: activityForm.data.location_latitude || "",
                  location_longitude: activityForm.data.location_longitude || "",
                  duration: activityForm.data.duration || "",
                  start_time: activityForm.data.start_time || "",
                  end_time: activityForm.data.end_time || "",
                  time_type: activityForm.data.time_type || "exact",
                  cost: activityForm.data.cost || "",
                  cost_per_person: activityForm.data.cost_per_person !== false,
                  notes: activityForm.data.notes || "",
                  included_items: activityForm.data.included_items || [],
                  excluded_items: activityForm.data.excluded_items || []
                },
                errors,
                itemTypes,
                items,
                newIncludedItem: activityIncludedItems[activityForm.id] || "",
                newExcludedItem: activityExcludedItems[activityForm.id] || "",
                onFieldChange: (field, value) => onFieldChange(activityForm.id, field, value),
                onIncludedItemChange: (value) => onIncludedItemChange(activityForm.id, value),
                onExcludedItemChange: (value) => onExcludedItemChange(activityForm.id, value),
                onAddIncludedItem: () => onAddIncludedItem(activityForm.id),
                onAddExcludedItem: () => onAddExcludedItem(activityForm.id),
                onRemoveIncludedItem: (idx) => onRemoveIncludedItem(activityForm.id, idx),
                onRemoveExcludedItem: (idx) => onRemoveExcludedItem(activityForm.id, idx),
                calculateDuration,
                size: "default",
                showCardWrapper: false,
                onRefreshData
              }
            ) })
          ]
        },
        activityForm.id
      );
    }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
      Button,
      {
        type: "button",
        variant: "outline",
        onClick: onAddActivity,
        className: "w-full flex items-center justify-center gap-2 border-dashed",
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Plus, { className: "w-4 h-4" }),
          __("Add Activity", "yatra")
        ]
      }
    ) })
  ] });
};
const DayConflictDialog = ({
  isOpen,
  conflictDayNumber,
  suggestedDayNumber,
  existingDayNumbers,
  isUpdateMode = false,
  onClose,
  onConfirm
}) => {
  let message2 = "";
  let title2 = "";
  let confirmText = "";
  if (isUpdateMode && conflictDayNumber !== null) {
    title2 = __("Replace Existing Day?", "yatra");
    message2 = __("Day", "yatra") + ` ${conflictDayNumber} ` + __(
      "already exists for this trip. Do you want to replace it with the current day's data?",
      "yatra"
    );
    confirmText = __("Yes, Replace Day", "yatra") + ` ${conflictDayNumber}`;
  } else if (!isUpdateMode && conflictDayNumber !== null && suggestedDayNumber !== null && existingDayNumbers.length > 0) {
    title2 = __("Day Number Already Exists", "yatra");
    const existingDaysList = existingDayNumbers.join(", ");
    message2 = __("Day", "yatra") + ` ${existingDaysList} ` + __("already exists for this trip. Do you want to use day", "yatra") + ` ${suggestedDayNumber} ` + __("instead?", "yatra");
    confirmText = __("Use Day", "yatra") + ` ${suggestedDayNumber}`;
  } else {
    title2 = __("Day Number Already Exists", "yatra");
    message2 = __("This day number already exists.", "yatra");
    confirmText = __("OK", "yatra");
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    ConfirmationDialog,
    {
      isOpen,
      onClose,
      onConfirm,
      title: title2,
      message: message2,
      confirmText,
      cancelText: __("Cancel", "yatra"),
      variant: "warning"
    }
  );
};
const ItineraryFormSkeleton = () => {
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "animate-pulse", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 bg-gray-200 dark:bg-gray-700 rounded w-1/3 mb-2" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-6 bg-gray-200 dark:bg-gray-700 rounded w-1/2 mb-6" })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-3 gap-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "lg:col-span-2 space-y-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-6 bg-gray-200 dark:bg-gray-700 rounded w-1/4" }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-3", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-1/4" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 bg-gray-200 dark:bg-gray-700 rounded" })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-1/4" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 bg-gray-200 dark:bg-gray-700 rounded" })
              ] })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-1/3" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 bg-gray-200 dark:bg-gray-700 rounded" })
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-6 bg-gray-200 dark:bg-gray-700 rounded w-1/4" }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-4", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-4", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-1/3" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 bg-gray-200 dark:bg-gray-700 rounded" })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-1/3" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 bg-gray-200 dark:bg-gray-700 rounded" })
              ] })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-1/4" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-24 bg-gray-200 dark:bg-gray-700 rounded" })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-3 gap-4", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-1/2" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 bg-gray-200 dark:bg-gray-700 rounded" })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-1/2" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 bg-gray-200 dark:bg-gray-700 rounded" })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-1/2" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 bg-gray-200 dark:bg-gray-700 rounded" })
              ] })
            ] })
          ] })
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-6 bg-gray-200 dark:bg-gray-700 rounded w-1/3" }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "space-y-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-1/2" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 bg-gray-200 dark:bg-gray-700 rounded" })
          ] }) })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 bg-gray-200 dark:bg-gray-700 rounded" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 bg-gray-200 dark:bg-gray-700 rounded w-1/2" })
        ] }) }) })
      ] })
    ] })
  ] });
};
const ItineraryForm = () => {
  var _a;
  const queryClient2 = useQueryClient();
  const action = reactExports.useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get("action") || "create";
  }, []);
  const entryId = reactExports.useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get("id") ? parseInt(params.get("id") || "0") : null;
  }, []);
  const tripIdParam = reactExports.useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get("trip_id");
  }, []);
  const dayParam = reactExports.useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get("day");
  }, []);
  const typeIdParam = reactExports.useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get("type_id");
  }, []);
  const itemParam = reactExports.useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get("item");
  }, []);
  const modeParam = reactExports.useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get("mode") || "activity";
  }, []);
  const isEditMode = action === "edit" && entryId !== null;
  const isAddDayMode = modeParam === "day";
  const isEditDayMode = isEditMode && modeParam === "day";
  const [formData, setFormData] = reactExports.useState({
    trip_id: "",
    day: "",
    day_title: "",
    day_description: "",
    item_type_id: "",
    item_id: "",
    title: "",
    description: "",
    location: "",
    location_latitude: "",
    location_longitude: "",
    duration: "",
    start_time: "",
    end_time: "",
    time_type: "exact",
    cost: "",
    cost_per_person: true,
    notes: "",
    included_items: [],
    excluded_items: [],
    gallery: [],
    video_url: "",
    status: "publish"
  });
  const [errors, setErrors] = reactExports.useState({});
  const [newIncludedItem, setNewIncludedItem] = reactExports.useState("");
  const [newExcludedItem, setNewExcludedItem] = reactExports.useState("");
  const [activityForms, setActivityForms] = reactExports.useState([]);
  const [activityIncludedItems, setActivityIncludedItems] = reactExports.useState({});
  const [activityExcludedItems, setActivityExcludedItems] = reactExports.useState({});
  const [showDayConflictDialog, setShowDayConflictDialog] = reactExports.useState(false);
  const [conflictDayNumber, setConflictDayNumber] = reactExports.useState(
    null
  );
  const [suggestedDayNumber, setSuggestedDayNumber] = reactExports.useState(
    null
  );
  const [originalDayNumber, setOriginalDayNumber] = reactExports.useState(
    null
  );
  const dayManuallyEditedRef = reactExports.useRef(false);
  const lastTripIdRef = reactExports.useRef(null);
  const loadedDayActivitiesRef = reactExports.useRef(null);
  const initializedEntryIdRef = reactExports.useRef(null);
  const {
    tripsData,
    isLoadingTrips,
    typesData,
    itemsData,
    entryData,
    isLoadingEntry,
    dayTripData,
    effectiveTripData,
    entryTripId,
    entryDay
  } = useItineraryFormData({
    entryId,
    isEditMode,
    isEditDayMode,
    isAddDayMode,
    tripIdParam,
    dayParam,
    formDataItemTypeId: formData.item_type_id || "",
    formDataTripId: formData.trip_id
  });
  const refreshData = () => {
    queryClient2.invalidateQueries({ queryKey: ["item-types-published"] });
    queryClient2.invalidateQueries({ queryKey: ["items-all-published"] });
    queryClient2.invalidateQueries({ queryKey: ["items-by-type"] });
  };
  reactExports.useEffect(() => {
    if (itemParam && itemsData && itemsData.length > 0) {
      const item = itemsData.find(
        (i) => i.name.toLowerCase() === itemParam.toLowerCase()
      );
      if (item) {
        setFormData((prev) => ({ ...prev, item_id: item.id.toString() }));
      }
    }
  }, [itemParam, itemsData]);
  const { validateForm } = useItineraryFormValidation();
  const calculateDuration = (startTime, endTime, timeType) => {
    const st = startTime || formData.start_time;
    const et = endTime || formData.end_time;
    const tt = timeType || formData.time_type;
    if (st && et && tt === "exact") {
      const [startHour, startMin] = st.split(":").map(Number);
      const [endHour, endMin] = et.split(":").map(Number);
      const startMinutes = startHour * 60 + startMin;
      const endMinutes = endHour * 60 + endMin;
      let diffMinutes = endMinutes - startMinutes;
      if (diffMinutes < 0) diffMinutes += 24 * 60;
      const hours = Math.floor(diffMinutes / 60);
      const minutes = diffMinutes % 60;
      if (hours > 0 && minutes > 0) {
        return `${hours} hour${hours > 1 ? "s" : ""} ${minutes} minute${minutes > 1 ? "s" : ""}`;
      } else if (hours > 0) {
        return `${hours} hour${hours > 1 ? "s" : ""}`;
      } else {
        return `${minutes} minute${minutes > 1 ? "s" : ""}`;
      }
    }
    return "";
  };
  const { saveMutation } = useItineraryFormSave({
    isAddDayMode,
    isEditMode,
    entryId,
    activityForms,
    formData,
    calculateDuration,
    entryData,
    dayTripData,
    tripsData
  });
  reactExports.useEffect(() => {
    if (entryId !== initializedEntryIdRef.current) {
      initializedEntryIdRef.current = null;
      loadedDayActivitiesRef.current = null;
      isLoadingInitialDataRef.current = false;
    }
  }, [entryId]);
  reactExports.useEffect(() => {
    if (tripIdParam) {
      setFormData((prev) => ({ ...prev, trip_id: tripIdParam }));
      lastTripIdRef.current = tripIdParam;
    }
    if (dayParam) {
      setFormData((prev) => ({ ...prev, day: dayParam }));
      dayManuallyEditedRef.current = true;
    }
    if (typeIdParam) {
      setFormData((prev) => ({ ...prev, item_type_id: typeIdParam }));
    }
  }, [tripIdParam, dayParam, typeIdParam]);
  reactExports.useEffect(() => {
    if (itemParam && itemsData && itemsData.length > 0) {
      const item = itemsData.find(
        (i) => i.name.toLowerCase() === itemParam.toLowerCase()
      );
      if (item) {
        setFormData((prev) => ({ ...prev, item_id: item.id.toString() }));
      }
    }
  }, [itemParam, itemsData]);
  reactExports.useEffect(() => {
    var _a2, _b, _c, _d;
    if (!entryData || !isEditMode || isLoadingInitialDataRef.current) return;
    if (!entryData || !entryData.id) {
      return;
    }
    if (isEditDayMode) {
      const isActivityEntry = entryData.item_type_id !== null && entryData.item_type_id !== void 0 && entryData.item_type_id !== 0 && entryData.item_id !== null && entryData.item_id !== void 0 && entryData.item_id !== 0;
      if (isActivityEntry) {
        if (initializedEntryIdRef.current === entryData.id) return;
        return;
      }
    }
    if (initializedEntryIdRef.current === entryData.id) return;
    isLoadingInitialDataRef.current = true;
    initializedEntryIdRef.current = entryData.id;
    if (!isEditDayMode) {
      setFormData({
        trip_id: ((_a2 = entryData.trip_id) == null ? void 0 : _a2.toString()) || "",
        day: ((_b = entryData.day) == null ? void 0 : _b.toString()) || "",
        day_title: entryData.day_title || "",
        day_description: entryData.day_description || "",
        item_type_id: ((_c = entryData.item_type_id) == null ? void 0 : _c.toString()) || "",
        item_id: ((_d = entryData.item_id) == null ? void 0 : _d.toString()) || "",
        title: entryData.title || "",
        description: entryData.description || "",
        location: entryData.location || "",
        location_latitude: entryData.location_latitude || "",
        location_longitude: entryData.location_longitude || "",
        duration: entryData.duration || "",
        // Don't fake an "08:00" default for entries that were saved without a
        // time — empty inputs let the user see "no time set" via the picker
        // placeholder, and prevents the next save from baking the fake default
        // back into the row.
        start_time: entryData.start_time || "",
        end_time: entryData.end_time || "",
        time_type: entryData.time_type || "exact",
        cost: entryData.cost || "",
        cost_per_person: entryData.cost_per_person !== false,
        notes: entryData.notes || "",
        included_items: entryData.included_items || [],
        excluded_items: entryData.excluded_items || [],
        gallery: entryData.gallery || [],
        video_url: entryData.video_url || "",
        status: entryData.status || "publish"
      });
    } else if (isEditDayMode) {
      const dayNumber = entryData.day ? parseInt(entryData.day.toString()) : null;
      setOriginalDayNumber(dayNumber);
      setFormData((prev) => {
        var _a3, _b2;
        return {
          ...prev,
          trip_id: ((_a3 = entryData.trip_id) == null ? void 0 : _a3.toString()) || tripIdParam || prev.trip_id,
          day: ((_b2 = entryData.day) == null ? void 0 : _b2.toString()) || dayParam || prev.day,
          day_title: entryData.day_title || prev.day_title,
          day_description: entryData.day_description || prev.day_description,
          gallery: entryData.gallery || prev.gallery,
          video_url: entryData.video_url || prev.video_url,
          status: entryData.status || prev.status
        };
      });
    }
    setTimeout(() => {
      isLoadingInitialDataRef.current = false;
    }, 100);
  }, [
    entryId,
    isEditMode,
    isEditDayMode,
    entryData,
    tripIdParam,
    dayParam,
    dayTripData
  ]);
  reactExports.useEffect(() => {
    if (!isEditDayMode) return;
    if (!entryTripId || !entryDay) return;
    if (!dayTripData) return;
    const dayKey = `${entryTripId}-${entryDay}`;
    if (loadedDayActivitiesRef.current === dayKey) return;
    loadedDayActivitiesRef.current = dayKey;
    const dayNumber = typeof entryDay === "string" ? parseInt(entryDay) : entryDay;
    if (isNaN(dayNumber)) return;
    const itineraryDays = dayTripData.itinerary_days || [];
    const dayData = itineraryDays.find(
      (d) => (d.day_number || d.day) === dayNumber
    );
    if (!dayData || !dayData.entries) return;
    const activities = dayData.entries.filter((e) => e.item_type_id && e.item_id).slice().sort((a2, b) => {
      const ao = Number(a2.order ?? 0);
      const bo = Number(b.order ?? 0);
      if (ao !== bo) return ao - bo;
      return Number(a2.id ?? 0) - Number(b.id ?? 0);
    }).map((entry, index) => {
      var _a2, _b;
      return {
        id: `activity-${entry.id || index}`,
        entryId: entry.id ? parseInt(entry.id.toString()) : null,
        // Store actual entry ID for updates
        data: {
          item_type_id: ((_a2 = entry.item_type_id) == null ? void 0 : _a2.toString()) || "",
          item_id: ((_b = entry.item_id) == null ? void 0 : _b.toString()) || "",
          title: entry.title || "",
          description: entry.description || "",
          location: entry.location || "",
          // The form has lat/lng inputs and the DB column accepts them — without
          // mapping here, opening an existing activity in edit mode would show
          // empty coordinate fields and silently overwrite saved values.
          location_latitude: entry.location_latitude != null ? entry.location_latitude.toString() : "",
          location_longitude: entry.location_longitude != null ? entry.location_longitude.toString() : "",
          duration: entry.duration || "",
          start_time: entry.start_time || "",
          end_time: entry.end_time || "",
          time_type: entry.time_type || "exact",
          cost: entry.cost || "",
          cost_per_person: entry.cost_per_person !== false,
          notes: entry.notes || "",
          included_items: entry.included_items || [],
          excluded_items: entry.excluded_items || [],
          // Gallery + video_url are saved by buildActivityPayload but were never
          // re-loaded — admin would lose them after a single re-save.
          gallery: Array.isArray(entry.gallery) ? entry.gallery : [],
          video_url: entry.video_url || "",
          status: entry.status || "publish"
        },
        isExpanded: index === 0
      };
    });
    setActivityForms(activities);
    const includedItems = {};
    const excludedItems = {};
    activities.forEach((activity2) => {
      includedItems[activity2.id] = "";
      excludedItems[activity2.id] = "";
    });
    setActivityIncludedItems(includedItems);
    setActivityExcludedItems(excludedItems);
  }, [isEditDayMode, entryTripId, entryDay, dayTripData]);
  const isLoadingInitialDataRef = reactExports.useRef(false);
  reactExports.useEffect(() => {
    if (isLoadingInitialDataRef.current) return;
    if (formData.item_type_id && formData.item_id) ;
  }, [formData.item_type_id]);
  const dayTitle = reactExports.useMemo(() => {
    if (!effectiveTripData || !dayParam) return null;
    const itineraryDays = effectiveTripData.itinerary_days || [];
    const dayNumber = parseInt(dayParam);
    const day = itineraryDays.find(
      (d) => (d.day_number || d.day) === dayNumber
    );
    return (day == null ? void 0 : day.title) || (day == null ? void 0 : day.day_title) || null;
  }, [effectiveTripData, dayParam]);
  const selectedTripType = reactExports.useMemo(() => {
    if (!formData.trip_id) return null;
    const trip = tripsData == null ? void 0 : tripsData.find(
      (t) => t.id.toString() === formData.trip_id
    );
    return (trip == null ? void 0 : trip.trip_type) || null;
  }, [formData.trip_id, tripsData]);
  const isSingleDayTrip = selectedTripType === "single_day";
  const submitButtonLabel = reactExports.useMemo(() => {
    if (isEditMode) {
      if (isAddDayMode) {
        return isSingleDayTrip ? __("Update Entry", "yatra") : __("Update Day", "yatra");
      }
      return __("Update Itinerary Activity", "yatra");
    }
    if (isAddDayMode) {
      return isSingleDayTrip ? __("Create Entry", "yatra") : __("Create Day", "yatra");
    }
    return __("Create Itinerary Activity", "yatra");
  }, [isEditMode, isAddDayMode, isSingleDayTrip]);
  const existingDayNumbers = reactExports.useMemo(() => {
    if (!effectiveTripData || !isAddDayMode) return [];
    const itineraryDays = effectiveTripData.itinerary_days || [];
    const days = itineraryDays.map((d) => d.day_number || d.day).filter(
      (day) => day !== null && day !== void 0 && !isNaN(Number(day))
    ).map((day) => Number(day)).sort((a2, b) => a2 - b);
    return days;
  }, [effectiveTripData, isAddDayMode]);
  const nextAvailableDayNumber = reactExports.useMemo(() => {
    if (existingDayNumbers.length === 0) return 1;
    return Math.max(...existingDayNumbers) + 1;
  }, [existingDayNumbers]);
  const currentTripId = formData.trip_id || "";
  const tripIdChanged = lastTripIdRef.current !== currentTripId;
  reactExports.useEffect(() => {
    if (!isAddDayMode || isEditMode) return;
    if (currentTripId) {
      if (tripIdChanged) {
        lastTripIdRef.current = currentTripId;
        dayManuallyEditedRef.current = false;
      }
      if (isSingleDayTrip) {
        if (!formData.day || formData.day === "") {
          const currentDay = parseInt(formData.day) || 0;
          const shouldUpdate = !formData.day || formData.day === "" || existingDayNumbers.includes(currentDay);
          if (shouldUpdate && nextAvailableDayNumber) {
            setFormData((prev) => ({
              ...prev,
              day: nextAvailableDayNumber.toString()
            }));
          } else if (!formData.day || formData.day === "") {
            setFormData((prev) => ({ ...prev, day: "1" }));
          }
        }
      }
      if (effectiveTripData !== void 0 && effectiveTripData !== null) {
        if (!dayManuallyEditedRef.current) {
          const currentDay = parseInt(formData.day) || 0;
          const shouldUpdate = !formData.day || formData.day === "" || existingDayNumbers.includes(currentDay);
          if (shouldUpdate && nextAvailableDayNumber) {
            setFormData((prev) => ({
              ...prev,
              day: nextAvailableDayNumber.toString()
            }));
          }
        }
      }
    } else {
      setFormData((prev) => ({ ...prev, day: "" }));
      dayManuallyEditedRef.current = false;
      lastTripIdRef.current = null;
    }
  }, [
    isAddDayMode,
    isEditMode,
    currentTripId,
    effectiveTripData,
    nextAvailableDayNumber,
    existingDayNumbers.length,
    formData.day,
    isSingleDayTrip
  ]);
  const handleFieldChange = (field, value) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
    if (errors[field]) {
      setErrors((prev) => ({ ...prev, [field]: "" }));
    }
    if (field === "day" && isAddDayMode) {
      dayManuallyEditedRef.current = true;
    }
    if (field === "trip_id" && isAddDayMode) {
      setFormData((prev) => ({ ...prev, day: "" }));
      dayManuallyEditedRef.current = false;
      lastTripIdRef.current = value;
    }
  };
  const handleAddIncludedItem = () => {
    if (newIncludedItem.trim()) {
      setFormData((prev) => ({
        ...prev,
        included_items: [...prev.included_items, newIncludedItem.trim()]
      }));
      setNewIncludedItem("");
    }
  };
  const handleRemoveIncludedItem = (index) => {
    setFormData((prev) => ({
      ...prev,
      included_items: prev.included_items.filter((_, i) => i !== index)
    }));
  };
  const handleAddExcludedItem = () => {
    if (newExcludedItem.trim()) {
      setFormData((prev) => ({
        ...prev,
        excluded_items: [...prev.excluded_items, newExcludedItem.trim()]
      }));
      setNewExcludedItem("");
    }
  };
  const handleRemoveExcludedItem = (index) => {
    setFormData((prev) => ({
      ...prev,
      excluded_items: prev.excluded_items.filter((_, i) => i !== index)
    }));
  };
  const handleSubmit = async (e) => {
    e.preventDefault();
    if (isAddDayMode && formData.trip_id && formData.day) {
      const dayNumber = parseInt(formData.day);
      if (!isNaN(dayNumber)) {
        if (isEditMode && originalDayNumber !== null) {
          if (dayNumber === originalDayNumber) ;
          else if (existingDayNumbers.includes(dayNumber)) {
            setConflictDayNumber(dayNumber);
            setSuggestedDayNumber(null);
            setShowDayConflictDialog(true);
            return;
          }
        } else if (!isEditMode && existingDayNumbers.includes(dayNumber)) {
          setConflictDayNumber(dayNumber);
          setSuggestedDayNumber(nextAvailableDayNumber);
          setShowDayConflictDialog(true);
          return;
        }
      }
    }
    const { isValid: isValid2, errors: validationErrors } = validateForm(
      formData,
      isAddDayMode,
      activityForms
    );
    if (!isValid2) {
      setErrors(validationErrors);
      return;
    }
    setErrors({});
    saveMutation.mutate(formData);
  };
  const handleCancel = () => {
    var _a2;
    window.location.href = `${((_a2 = window.yatraAdmin) == null ? void 0 : _a2.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=itinerary&tab=itinerary`;
  };
  const handleToggleExpand = (activityId) => {
    setActivityForms(
      (prev) => prev.map(
        (af) => af.id === activityId ? { ...af, isExpanded: !af.isExpanded } : af
      )
    );
  };
  const handleReorderActivities = (fromIndex, toIndex) => {
    if (fromIndex === toIndex) return;
    setActivityForms((prev) => {
      if (fromIndex < 0 || toIndex < 0 || fromIndex >= prev.length || toIndex >= prev.length) {
        return prev;
      }
      const next = prev.slice();
      const [moved] = next.splice(fromIndex, 1);
      next.splice(toIndex, 0, moved);
      return next;
    });
  };
  const handleRemoveActivity = (activityId) => {
    setActivityForms((prev) => prev.filter((af) => af.id !== activityId));
    setActivityIncludedItems((prev) => {
      const updated = { ...prev };
      delete updated[activityId];
      return updated;
    });
    setActivityExcludedItems((prev) => {
      const updated = { ...prev };
      delete updated[activityId];
      return updated;
    });
  };
  const handleAddActivity = () => {
    const newActivityId = `activity_${Date.now()}`;
    setActivityForms((prev) => [
      ...prev,
      {
        id: newActivityId,
        data: {
          item_type_id: "",
          item_id: "",
          title: "",
          description: "",
          location: "",
          duration: "",
          start_time: "",
          end_time: "",
          time_type: "exact",
          cost: "",
          cost_per_person: true,
          notes: "",
          included_items: [],
          excluded_items: []
        },
        isExpanded: true
      }
    ]);
  };
  const handleActivityFieldChange = (activityId, field, value) => {
    setActivityForms(
      (prev) => prev.map(
        (af) => af.id === activityId ? { ...af, data: { ...af.data, [field]: value } } : af
      )
    );
  };
  const handleActivityIncludedItemChange = (activityId, value) => {
    setActivityIncludedItems((prev) => ({ ...prev, [activityId]: value }));
  };
  const handleActivityExcludedItemChange = (activityId, value) => {
    setActivityExcludedItems((prev) => ({ ...prev, [activityId]: value }));
  };
  const handleActivityAddIncludedItem = (activityId) => {
    var _a2;
    const item = (_a2 = activityIncludedItems[activityId]) == null ? void 0 : _a2.trim();
    if (item) {
      setActivityForms(
        (prev) => prev.map(
          (af) => af.id === activityId ? {
            ...af,
            data: {
              ...af.data,
              included_items: [...af.data.included_items || [], item]
            }
          } : af
        )
      );
      setActivityIncludedItems((prev) => ({ ...prev, [activityId]: "" }));
    }
  };
  const handleActivityAddExcludedItem = (activityId) => {
    var _a2;
    const item = (_a2 = activityExcludedItems[activityId]) == null ? void 0 : _a2.trim();
    if (item) {
      setActivityForms(
        (prev) => prev.map(
          (af) => af.id === activityId ? {
            ...af,
            data: {
              ...af.data,
              excluded_items: [...af.data.excluded_items || [], item]
            }
          } : af
        )
      );
      setActivityExcludedItems((prev) => ({ ...prev, [activityId]: "" }));
    }
  };
  const handleActivityRemoveIncludedItem = (activityId, index) => {
    setActivityForms(
      (prev) => prev.map(
        (af) => af.id === activityId ? {
          ...af,
          data: {
            ...af.data,
            included_items: (af.data.included_items || []).filter(
              (_, i) => i !== index
            )
          }
        } : af
      )
    );
  };
  const handleActivityRemoveExcludedItem = (activityId, index) => {
    setActivityForms(
      (prev) => prev.map(
        (af) => af.id === activityId ? {
          ...af,
          data: {
            ...af.data,
            excluded_items: (af.data.excluded_items || []).filter(
              (_, i) => i !== index
            )
          }
        } : af
      )
    );
  };
  const handleDayConflictConfirm = () => {
    if (suggestedDayNumber !== null) {
      const updatedFormData = {
        ...formData,
        day: suggestedDayNumber.toString()
      };
      setShowDayConflictDialog(false);
      setConflictDayNumber(null);
      setSuggestedDayNumber(null);
      setFormData(updatedFormData);
      const { isValid: isValid2, errors: validationErrors } = validateForm(
        updatedFormData,
        isAddDayMode,
        activityForms
      );
      if (isValid2) {
        setErrors({});
        saveMutation.mutate(updatedFormData);
      } else {
        setErrors(validationErrors);
      }
    } else {
      setShowDayConflictDialog(false);
      setConflictDayNumber(null);
      setSuggestedDayNumber(null);
    }
  };
  if (isEditMode && isLoadingEntry) {
    return /* @__PURE__ */ jsxRuntimeExports.jsx(ItineraryFormSkeleton, {});
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      PageHeader,
      {
        title: isEditMode ? __("Edit Itinerary Entry", "yatra") : isAddDayMode ? isSingleDayTrip ? __("Add New Entry", "yatra") : __("Add New Day", "yatra") : __("Add New Activity", "yatra"),
        description: isEditMode ? __("Update itinerary entry information", "yatra") : isAddDayMode ? isSingleDayTrip ? __(
          "Create a new entry for your single-day trip itinerary.",
          "yatra"
        ) : __(
          "Create a new day entry for your trip itinerary. This will be the first activity of the new day.",
          "yatra"
        ) : __(
          "Add a new activity, meal, or accommodation to this day of the trip itinerary.",
          "yatra"
        ),
        actions: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Button,
          {
            variant: "outline",
            onClick: handleCancel,
            className: "flex items-center gap-2",
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowLeft, { className: "w-4 h-4" }),
              __("Back", "yatra")
            ]
          }
        )
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_edit_trips", children: /* @__PURE__ */ jsxRuntimeExports.jsx("form", { onSubmit: handleSubmit, children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-3 gap-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "lg:col-span-2 space-y-3", children: [
        isAddDayMode && /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            DayFormFields,
            {
              formData: {
                trip_id: formData.trip_id,
                day: formData.day,
                day_title: formData.day_title || "",
                day_description: formData.day_description || ""
              },
              errors,
              tripsData,
              isLoadingTrips,
              isEditMode: isEditMode && isAddDayMode,
              isSingleDayTrip,
              onFieldChange: handleFieldChange
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            ActivityAccordion,
            {
              activityForms,
              errors,
              itemTypes: typesData,
              items: itemsData,
              activityIncludedItems,
              activityExcludedItems,
              onToggleExpand: handleToggleExpand,
              onRemoveActivity: handleRemoveActivity,
              onAddActivity: handleAddActivity,
              onReorderActivities: handleReorderActivities,
              onFieldChange: handleActivityFieldChange,
              onIncludedItemChange: handleActivityIncludedItemChange,
              onExcludedItemChange: handleActivityExcludedItemChange,
              onAddIncludedItem: handleActivityAddIncludedItem,
              onAddExcludedItem: handleActivityAddExcludedItem,
              onRemoveIncludedItem: handleActivityRemoveIncludedItem,
              onRemoveExcludedItem: handleActivityRemoveExcludedItem,
              calculateDuration,
              onRefreshData: refreshData
            }
          )
        ] }),
        !isAddDayMode && /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
          tripIdParam && dayParam && /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-3 gap-3 text-sm", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-500 dark:text-gray-400", children: __("Trip:", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "ml-2 font-medium", children: ((_a = tripsData == null ? void 0 : tripsData.find(
                (t) => t.id.toString() === tripIdParam
              )) == null ? void 0 : _a.title) || tripIdParam })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-500 dark:text-gray-400", children: __("Day:", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "ml-2 font-medium", children: dayParam })
            ] }),
            dayTitle && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-500 dark:text-gray-400", children: __("Day Title:", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "ml-2 font-medium", children: dayTitle })
            ] })
          ] }) }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            ItineraryEntryFields,
            {
              entry: {
                item_type_id: formData.item_type_id,
                item_id: formData.item_id,
                title: formData.title,
                description: formData.description,
                location: formData.location,
                location_latitude: formData.location_latitude,
                location_longitude: formData.location_longitude,
                duration: formData.duration,
                start_time: formData.start_time,
                end_time: formData.end_time,
                time_type: formData.time_type,
                cost: formData.cost,
                cost_per_person: formData.cost_per_person,
                notes: formData.notes,
                included_items: formData.included_items,
                excluded_items: formData.excluded_items,
                gallery: formData.gallery,
                video_url: formData.video_url
              },
              errors,
              itemTypes: typesData,
              items: itemsData,
              newIncludedItem,
              newExcludedItem,
              onFieldChange: (field, value) => handleFieldChange(field, value),
              onIncludedItemChange: setNewIncludedItem,
              onExcludedItemChange: setNewExcludedItem,
              onAddIncludedItem: handleAddIncludedItem,
              onAddExcludedItem: handleAddExcludedItem,
              onRemoveIncludedItem: handleRemoveIncludedItem,
              onRemoveExcludedItem: handleRemoveExcludedItem,
              calculateDuration,
              size: "default",
              showCardWrapper: true,
              onRefreshData: refreshData
            }
          )
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "sticky top-6 space-y-3 z-10 h-fit", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Status", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "space-y-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "label",
              {
                htmlFor: "status",
                className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                children: __("Entry Status", "yatra")
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              HelpText,
              {
                text: __(
                  "Published entries are visible in trip schedules. Draft entries are saved but not visible. Trashed entries are deleted.",
                  "yatra"
                ),
                className: "mb-2"
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              Select,
              {
                id: "status",
                value: formData.status,
                onChange: (e) => handleFieldChange("status", e.target.value),
                className: "w-full",
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "publish", children: __("Publish", "yatra") }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "draft", children: __("Draft", "yatra") }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "trash", children: __("Trash", "yatra") })
                ]
              }
            )
          ] }) })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
          errors.submit && /* @__PURE__ */ jsxRuntimeExports.jsx(Alert, { variant: "error", title: __("Error", "yatra"), children: errors.submit }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              Button,
              {
                type: "submit",
                disabled: saveMutation.isPending,
                className: "flex-1 flex items-center justify-center gap-2",
                children: saveMutation.isPending ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(Loader2, { className: "w-4 h-4 animate-spin" }),
                  __("Saving...", "yatra")
                ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(Save, { className: "w-4 h-4" }),
                  submitButtonLabel
                ] })
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              Button,
              {
                type: "button",
                variant: "outline",
                onClick: handleCancel,
                disabled: saveMutation.isPending,
                children: __("Cancel", "yatra")
              }
            )
          ] })
        ] }) }) })
      ] })
    ] }) }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      DayConflictDialog,
      {
        isOpen: showDayConflictDialog,
        conflictDayNumber,
        suggestedDayNumber,
        existingDayNumbers,
        isUpdateMode: isEditMode && isAddDayMode,
        onClose: () => {
          setShowDayConflictDialog(false);
          setConflictDayNumber(null);
          setSuggestedDayNumber(null);
        },
        onConfirm: handleDayConflictConfirm
      }
    )
  ] });
};
const MODULE_FEATURES = {
  white_label: [
    "Rebrand the plugin: name, logo, author, support URL",
    "Replace Yatra/MantraBrain references on plugin list + PDFs",
    "Custom admin menu labels, icons, ordering",
    "Custom brand color applied across the admin UI"
  ],
  "white-label": [
    "Rebrand the plugin: name, logo, author, support URL",
    "Replace Yatra/MantraBrain references on plugin list + PDFs",
    "Custom admin menu labels, icons, ordering",
    "Custom brand color applied across the admin UI"
  ],
  ai_assistant: [
    "Inline AI generation on trip descriptions, FAQs, SEO meta",
    "Multi-step agents for full trip + itinerary creation",
    "AI public chat widget on every single-trip page",
    "Bring your own OpenAI / Anthropic key — no per-call markup"
  ],
  "ai-assistant": [
    "Inline AI generation on trip descriptions, FAQs, SEO meta",
    "Multi-step agents for full trip + itinerary creation",
    "AI public chat widget on every single-trip page",
    "Bring your own OpenAI / Anthropic key — no per-call markup"
  ]
};
const TIER_DEFAULT_FEATURES = {
  agency: [
    "Unlocks every premium module — Scale-tier and below",
    "Full white-label rebranding capability",
    "Priority support with faster response times",
    "All future Scale-tier features included"
  ],
  growth: [
    "Advanced operator-productivity features",
    "AI assistant for content + itinerary generation",
    "Priority support included",
    "All future Growth-tier features included"
  ],
  personal: [
    "Premium booking-system extensions",
    "Email automation + abandoned-recovery workflows",
    "Dynamic pricing + advanced discount tools",
    "All future Starter-tier features included"
  ]
};
const PremiumUpgradeDialog = ({
  open,
  onClose,
  moduleName,
  moduleSlug,
  purchaseUrl,
  moduleDescription,
  requiredPlan
}) => {
  if (!open) return null;
  const planLabel = requiredPlan === "agency" ? __("Scale plan", "yatra") : requiredPlan === "growth" ? __("Growth plan", "yatra") : requiredPlan === "personal" ? __("Starter plan", "yatra") : null;
  const planCtaLabel = requiredPlan === "agency" ? __("Upgrade to Scale", "yatra") : requiredPlan === "growth" ? __("Upgrade to Growth", "yatra") : requiredPlan === "personal" ? __("Upgrade to Starter", "yatra") : __("Upgrade to Pro", "yatra");
  const planFooterCopy = requiredPlan === "agency" ? __(
    "This feature is exclusive to the Scale plan. Upgrade to unlock it.",
    "yatra"
  ) : requiredPlan === "growth" ? __(
    "This feature unlocks on the Growth plan (or Scale). Upgrade to enable it.",
    "yatra"
  ) : requiredPlan === "personal" ? __(
    "This feature is included on every Pro plan. Upgrade to unlock it.",
    "yatra"
  ) : __("Upgrade to Yatra Pro and unlock this feature today", "yatra");
  const features = moduleSlug && MODULE_FEATURES[moduleSlug] || requiredPlan && TIER_DEFAULT_FEATURES[requiredPlan] || [
    __("Advanced analytics and reporting", "yatra"),
    __("Automated workflows and notifications", "yatra"),
    __("Enhanced customer management tools", "yatra"),
    __("Priority support and updates", "yatra")
  ];
  return reactDomExports.createPortal(
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      "div",
      {
        className: "fixed top-0 left-0 right-0 bottom-0 m-0 bg-black/60 backdrop-blur-sm flex items-center justify-center px-4 pb-4",
        style: {
          zIndex: 999999,
          position: "fixed",
          top: 0,
          left: 0,
          right: 0,
          bottom: 0
        },
        children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative w-full max-w-5xl", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "absolute -inset-0.5 bg-gradient-to-r from-orange-500/20 via-orange-400/20 to-orange-500/20 rounded-2xl blur-2xl" }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { className: "relative w-full shadow-2xl border border-orange-300/80 dark:border-orange-700/50 bg-white dark:bg-slate-900 overflow-hidden max-h-[90vh] flex flex-col", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "absolute top-0 left-0 right-0 h-1 bg-gradient-to-r from-orange-500 via-orange-400 to-orange-500" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "relative pb-4 pt-6 border-b border-gray-200 dark:border-gray-800 flex-shrink-0 bg-gradient-to-b from-orange-50/30 to-transparent dark:from-orange-950/20", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start justify-between", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start gap-4", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-12 h-12 rounded-full bg-gradient-to-br from-orange-500 to-orange-600 flex items-center justify-center flex-shrink-0", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Crown, { className: "w-6 h-6 text-white" }) }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-xl font-bold text-gray-900 dark:text-white", children: moduleName || __("Premium Feature", "yatra") }),
                    planLabel && /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "span",
                      {
                        className: "inline-flex items-center gap-1 rounded-full px-2.5 py-1 text-xs font-medium text-white shadow-sm " + (requiredPlan === "agency" ? "bg-gradient-to-r from-purple-600 to-indigo-500" : requiredPlan === "growth" ? "bg-gradient-to-r from-emerald-500 to-teal-500" : "bg-gradient-to-r from-blue-500 to-blue-600"),
                        children: planLabel
                      }
                    )
                  ] }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(CardDescription, { className: "text-gray-600 dark:text-gray-400 mt-1", children: moduleDescription || __(
                    "This feature requires Yatra Pro to unlock powerful premium capabilities.",
                    "yatra"
                  ) })
                ] })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Button,
                {
                  variant: "ghost",
                  size: "sm",
                  onClick: onClose,
                  className: "text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200",
                  children: /* @__PURE__ */ jsxRuntimeExports.jsx(X, { className: "w-4 h-4" })
                }
              )
            ] }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "flex-1 overflow-hidden pt-6 px-6 pb-6", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-2 gap-6 h-full", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex flex-col overflow-y-auto pr-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-4", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("h3", { className: "text-lg font-semibold text-gray-900 dark:text-white mb-3 flex items-center gap-2", children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(Zap, { className: "w-4 h-4 text-orange-500" }),
                    __("What This Module Does", "yatra")
                  ] }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-gray-600 dark:text-gray-400 leading-relaxed", children: moduleDescription || __(
                    "This premium module adds advanced functionality to your Yatra booking system, helping you grow your business and streamline operations.",
                    "yatra"
                  ) })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("h4", { className: "font-semibold text-gray-900 dark:text-white mb-3 flex items-center gap-2", children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(Sparkles, { className: "w-4 h-4 text-orange-500" }),
                    __("Key Features", "yatra")
                  ] }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("ul", { className: "space-y-2 text-sm text-gray-600 dark:text-gray-400", children: features.map((line, i) => /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { className: "flex items-start gap-2", children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(CheckCircle2, { className: "w-4 h-4 text-green-500 flex-shrink-0 mt-0.5" }),
                    /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: line })
                  ] }, i)) })
                ] })
              ] }) }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex flex-col", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("h4", { className: "font-semibold text-gray-900 dark:text-white mb-3 flex items-center gap-2", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(Play, { className: "w-4 h-4 text-orange-500" }),
                  __("See It In Action", "yatra")
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "aspect-video bg-gray-100 dark:bg-gray-800 rounded-lg flex items-center justify-center border-2 border-dashed border-gray-300 dark:border-gray-600", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-center", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(Play, { className: "w-12 h-12 text-gray-400 mx-auto mb-2" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-500 dark:text-gray-400", children: __("Click to watch demo video", "yatra") })
                ] }) })
              ] }) })
            ] }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "border-t border-gray-200 dark:border-gray-800 p-6 bg-gray-50 dark:bg-gray-900/50", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col sm:flex-row items-center justify-between gap-4", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-center sm:text-left", children: /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-600 dark:text-gray-400", children: planFooterCopy }) }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs(
                Button,
                {
                  className: "bg-gradient-to-r from-orange-600 to-orange-500 hover:from-orange-700 hover:to-orange-600 text-white px-6 py-2 font-medium shadow-lg hover:shadow-xl transition-all duration-200 group",
                  onClick: () => window.open(
                    purchaseUrl || "https://wpyatra.com/pricing",
                    "_blank"
                  ),
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(Sparkles, { className: "w-4 h-4 mr-2 group-hover:rotate-12 transition-transform" }),
                    planCtaLabel,
                    /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowRight, { className: "w-4 h-4 group-hover:translate-x-1 transition-transform" })
                  ]
                }
              )
            ] }) })
          ] })
        ] })
      }
    ),
    document.body
  );
};
const Discounts = () => {
  var _a, _b, _c;
  const [searchTerm, setSearchTerm] = reactExports.useState("");
  const [statusFilter, setStatusFilter] = reactExports.useState("all");
  const [typeFilter, setTypeFilter] = reactExports.useState("all");
  const [sortBy2, setSortBy] = reactExports.useState("created_at");
  const [sortOrder, setSortOrder] = reactExports.useState("desc");
  const [page, setPage] = reactExports.useState(1);
  const [deleteConfirm, setDeleteConfirm] = reactExports.useState({ isOpen: false, discount: null });
  const [selectedIds, setSelectedIds] = reactExports.useState([]);
  const [bulkAction, setBulkAction] = reactExports.useState("");
  const [showColumnsDropdown, setShowColumnsDropdown] = reactExports.useState(false);
  const [isBulkPending, setIsBulkPending] = reactExports.useState(false);
  const [showDiscountTypeModal, setShowDiscountTypeModal] = reactExports.useState(false);
  const [premiumDialog, setPremiumDialog] = reactExports.useState({ open: false, type: null });
  const [visibleColumns, setVisibleColumns] = reactExports.useState(() => {
    if (typeof window === "undefined") {
      return {
        code: true,
        type: true,
        discount: true,
        usage: true,
        expiry_date: true,
        status: true
      };
    }
    const saved = window.localStorage.getItem(
      "yatra-discounts-visible-columns"
    );
    return saved ? JSON.parse(saved) : {
      code: true,
      type: true,
      discount: true,
      usage: true,
      expiry_date: true,
      status: true
    };
  });
  const queryClient2 = useQueryClient();
  const { can } = usePermissions();
  const { showToast } = useToast();
  const invalidateDiscountQueries = () => {
    queryClient2.invalidateQueries({ queryKey: ["discounts"] });
    queryClient2.invalidateQueries({ queryKey: ["discounts-stats"] });
  };
  const baseAdminUrl = ((_a = window.yatraAdmin) == null ? void 0 : _a.adminUrl) || "";
  const adminCurrency = ((_b = window == null ? void 0 : window.yatraAdmin) == null ? void 0 : _b.currency) || "USD";
  const queryParams = reactExports.useMemo(() => {
    const params = {
      page,
      per_page: 10,
      orderby: sortBy2,
      order: sortOrder
    };
    if (searchTerm) {
      params.search = searchTerm;
    }
    if (statusFilter !== "all") {
      params.status = statusFilter;
    }
    if (typeFilter !== "all") {
      params.type = typeFilter;
    }
    return params;
  }, [searchTerm, statusFilter, typeFilter, sortBy2, sortOrder, page]);
  const { data, isLoading, error, refetch } = useQuery({
    queryKey: ["discounts", queryParams],
    queryFn: async () => {
      const urlParams = new URLSearchParams(window.location.search);
      if (urlParams.get("simulate_error") === "true") {
        throw new Error(
          "Simulated API error for testing error UI functionality"
        );
      }
      const response = await apiClient.get("/discounts", {
        params: queryParams
      });
      return response;
    },
    enabled: can("yatra_manage_discounts")
  });
  const { data: discountStats } = useQuery({
    queryKey: ["discounts-stats"],
    queryFn: async () => {
      try {
        return await apiClient.get("/discounts/stats");
      } catch {
        return {
          all: 0,
          publish: 0,
          draft: 0,
          trash: 0,
          expired: 0
        };
      }
    },
    enabled: can("yatra_manage_discounts")
  });
  const discountStatusCounts = reactExports.useMemo(() => {
    const d = discountStats;
    if (!d) {
      return { all: 0, publish: 0, draft: 0, trash: 0, expired: 0 };
    }
    return {
      all: Number(d.all ?? 0),
      publish: Number(d.publish ?? 0),
      draft: Number(d.draft ?? 0),
      trash: Number(d.trash ?? 0),
      expired: Number(d.expired ?? 0)
    };
  }, [discountStats]);
  const bulkToolbarStatusOptions = reactExports.useMemo(
    () => [
      {
        key: "all",
        label: __("All", "yatra"),
        count: discountStatusCounts.all
      },
      {
        key: "publish",
        label: __("Publish", "yatra"),
        count: discountStatusCounts.publish
      },
      {
        key: "draft",
        label: __("Draft", "yatra"),
        count: discountStatusCounts.draft
      },
      {
        key: "trash",
        label: __("Trash", "yatra"),
        count: discountStatusCounts.trash
      },
      {
        key: "expired",
        label: __("Expired", "yatra"),
        count: discountStatusCounts.expired
      }
    ],
    [discountStatusCounts]
  );
  const deleteMutation = useMutation({
    mutationFn: async (id) => {
      return await apiClient.delete(`/discounts/${id}`);
    },
    onSuccess: () => {
      invalidateDiscountQueries();
      showToast(__("Discount deleted successfully", "yatra"), "success");
      setDeleteConfirm({ isOpen: false, discount: null });
    },
    onError: (error2) => {
      showToast(
        (error2 == null ? void 0 : error2.message) || __("Failed to delete discount", "yatra"),
        "error"
      );
    }
  });
  const discounts = (data == null ? void 0 : data.data) || [];
  const total = (data == null ? void 0 : data.total) || 0;
  const itemsPerPage = 10;
  const totalPages = Math.ceil(total / itemsPerPage);
  const errorContext = getErrorContext(error);
  const apiErrorMessage = (data == null ? void 0 : data.error) || (data == null ? void 0 : data.message);
  const derivedErrorDetails = errorContext.details || (apiErrorMessage ? String(apiErrorMessage) : void 0) || (error ? String((error == null ? void 0 : error.message) || error) : void 0);
  const isDiscountsError = !!error || !!apiErrorMessage;
  const formatDate2 = (dateString) => {
    if (!dateString) return __("N/A", "yatra");
    try {
      const date2 = new Date(dateString);
      return date2.toLocaleDateString("en-US", {
        month: "short",
        day: "numeric",
        year: "numeric",
        hour: "2-digit",
        minute: "2-digit"
      });
    } catch (e) {
      return __("Invalid date", "yatra");
    }
  };
  const confirmDelete = () => {
    if (deleteConfirm.discount) {
      deleteMutation.mutate(deleteConfirm.discount.id);
    }
  };
  const getStatusBadge = (status) => {
    const statusMap = {
      publish: {
        className: "bg-green-100 text-green-700 dark:bg-green-900/20 dark:text-green-400",
        label: __("Publish", "yatra")
      },
      active: {
        className: "bg-green-100 text-green-700 dark:bg-green-900/20 dark:text-green-400",
        label: __("Publish", "yatra")
      },
      draft: {
        className: "bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-400",
        label: __("Draft", "yatra")
      },
      trash: {
        className: "bg-red-100 text-red-700 dark:bg-red-900/20 dark:text-red-400",
        label: __("Trash", "yatra")
      },
      expired: {
        className: "bg-orange-100 text-orange-700 dark:bg-orange-900/20 dark:text-orange-400",
        label: __("Expired", "yatra")
      }
    };
    const statusInfo = statusMap[status] || {
      className: "bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-400",
      label: status
    };
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "span",
      {
        className: `inline-flex items-center px-2 py-1 rounded-md text-xs font-medium ${statusInfo.className}`,
        children: statusInfo.label
      }
    );
  };
  const handleEdit = (discount) => {
    window.location.href = `${baseAdminUrl}?page=yatra&subpage=discounts&action=edit&id=${discount.id}`;
  };
  const handleDelete = (discount) => {
    setDeleteConfirm({ isOpen: true, discount });
  };
  const handleDuplicate = (discount) => {
    window.location.href = `${baseAdminUrl}?page=yatra&subpage=discounts&action=create&duplicate=${discount.id}`;
  };
  const handleCreateDiscount = () => {
    setShowDiscountTypeModal(true);
  };
  const isAdvancedDiscountEnabled = !!((_c = window.yatraAdmin) == null ? void 0 : _c.advancedDiscountEnabled);
  const handleSelectDiscountType = (type) => {
    if ((type === "group" || type === "both") && !isAdvancedDiscountEnabled) {
      setPremiumDialog({ open: true, type });
      return;
    }
    setShowDiscountTypeModal(false);
    window.location.href = `${baseAdminUrl}?page=yatra&subpage=discounts&action=create&discount_mode=${type}`;
  };
  const getPremiumDialogContent = () => {
    if (premiumDialog.type === "group") {
      return {
        name: __("Group Discount", "yatra"),
        description: __(
          "Create powerful group discounts that automatically apply when customers book for multiple travelers. Set tiered pricing based on group size, offer category-specific discounts, and boost your group bookings without requiring promo codes.",
          "yatra"
        ),
        purchaseUrl: "https://wpyatra.com/pricing?module=advanced-discount"
      };
    }
    return {
      name: __("Promo + Group Discount", "yatra"),
      description: __(
        "Combine the power of promo codes with automatic group discounts. Customers get a base discount with their promo code, plus additional savings when booking for groups. Perfect for maximizing conversions and encouraging larger bookings.",
        "yatra"
      ),
      purchaseUrl: "https://wpyatra.com/pricing?module=advanced-discount"
    };
  };
  const handleResetFilters = () => {
    setSearchTerm("");
    setStatusFilter("all");
    setTypeFilter("all");
    setSortBy("created_at");
    setSortOrder("desc");
    setPage(1);
  };
  const handleSort = (field) => {
    if (sortBy2 === field) {
      setSortOrder(sortOrder === "asc" ? "desc" : "asc");
    } else {
      setSortBy(field);
      setSortOrder("desc");
    }
  };
  const getSortIcon = (field) => {
    if (sortBy2 !== field) {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowUpDown, { className: "w-3.5 h-3.5 ml-1 text-gray-400" });
    }
    return sortOrder === "asc" ? /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowUp, { className: "w-3.5 h-3.5 ml-1 text-gray-600 dark:text-gray-300" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowDown, { className: "w-3.5 h-3.5 ml-1 text-gray-600 dark:text-gray-300" });
  };
  const hasFilters = searchTerm || statusFilter !== "all" || typeFilter !== "all" || sortBy2 !== "created_at" || sortOrder !== "desc";
  const toggleColumn = (columnKey) => {
    const newVisibleColumns = {
      ...visibleColumns,
      [columnKey]: !visibleColumns[columnKey]
    };
    setVisibleColumns(newVisibleColumns);
    if (typeof window !== "undefined") {
      window.localStorage.setItem(
        "yatra-discounts-visible-columns",
        JSON.stringify(newVisibleColumns)
      );
    }
  };
  const handleSelectItem = (id, checked) => {
    setSelectedIds(
      (prev) => checked ? [...prev, id] : prev.filter((selectedId) => selectedId !== id)
    );
  };
  const handleSelectAll = (checked) => {
    if (checked) {
      setSelectedIds(discounts.map((discount) => discount.id));
    } else {
      setSelectedIds([]);
    }
  };
  const isAllSelected = discounts.length > 0 && selectedIds.length === discounts.length;
  const updateStatusForIds = async (ids, newStatus) => {
    await Promise.all(
      ids.map((id) => {
        const discount = discounts.find((item) => item.id === id);
        if (!discount) {
          return Promise.resolve();
        }
        const payload = {
          ...discount,
          status: newStatus
        };
        return apiClient.put(`/discounts/${id}`, payload);
      })
    );
  };
  const handleBulkApply = async () => {
    if (!bulkAction || selectedIds.length === 0) {
      return;
    }
    try {
      setIsBulkPending(true);
      if (bulkAction === "delete") {
        await Promise.all(
          selectedIds.map((id) => apiClient.delete(`/discounts/${id}`))
        );
        showToast(
          __("Selected discounts deleted successfully", "yatra"),
          "success"
        );
      } else {
        const newStatus = bulkAction;
        await updateStatusForIds(selectedIds, newStatus);
        showToast(__("Bulk status updated successfully", "yatra"), "success");
      }
      invalidateDiscountQueries();
      setSelectedIds([]);
      setBulkAction("");
    } catch (error2) {
      showToast(
        (error2 == null ? void 0 : error2.message) || __("Failed to perform bulk action on discounts", "yatra"),
        "error"
      );
    } finally {
      setIsBulkPending(false);
    }
  };
  const allBulkActionOptions = [
    { value: "publish", label: __("Mark as Publish", "yatra") },
    { value: "draft", label: __("Mark as Draft", "yatra") },
    { value: "trash", label: __("Move to Trash", "yatra") },
    { value: "expired", label: __("Mark as Expired", "yatra") },
    { value: "delete", label: __("Delete permanently", "yatra") }
  ];
  const getBulkActionOptionsForStatus = (view) => {
    switch (view) {
      case "publish":
        return allBulkActionOptions.filter(
          (opt) => ["draft", "trash", "expired", "delete"].includes(opt.value)
        );
      case "draft":
        return allBulkActionOptions.filter(
          (opt) => ["publish", "trash", "expired", "delete"].includes(opt.value)
        );
      case "trash":
        return allBulkActionOptions.filter(
          (opt) => ["publish", "draft", "delete"].includes(opt.value)
        );
      case "expired":
        return allBulkActionOptions.filter(
          (opt) => ["publish", "draft", "trash", "delete"].includes(opt.value)
        );
      default:
        return allBulkActionOptions;
    }
  };
  const bulkActionOptions = getBulkActionOptionsForStatus(statusFilter);
  const copyPromoCodeToClipboard = async (code) => {
    const text = code.trim();
    if (!text) {
      return;
    }
    try {
      await navigator.clipboard.writeText(text);
      showToast(__("Coupon code copied to clipboard", "yatra"), "success");
    } catch {
      try {
        const ta = document.createElement("textarea");
        ta.value = text;
        ta.setAttribute("readonly", "");
        ta.style.position = "fixed";
        ta.style.left = "-9999px";
        document.body.appendChild(ta);
        ta.select();
        document.execCommand("copy");
        document.body.removeChild(ta);
        showToast(__("Coupon code copied to clipboard", "yatra"), "success");
      } catch {
        showToast(__("Could not copy to clipboard", "yatra"), "error");
      }
    }
  };
  const statusOptions = [
    { value: "all", label: __("All Status", "yatra") },
    { value: "publish", label: __("Publish", "yatra") },
    { value: "draft", label: __("Draft", "yatra") },
    { value: "trash", label: __("Trash", "yatra") },
    { value: "expired", label: __("Expired", "yatra") }
  ];
  const sortOptions = [
    { value: "created_at", label: __("Created Date", "yatra") },
    { value: "code", label: __("Code", "yatra") },
    { value: "type", label: __("Type", "yatra") },
    { value: "amount", label: __("Amount", "yatra") },
    { value: "usage_count", label: __("Usage", "yatra") },
    { value: "expiry_date", label: __("Expiry Date", "yatra") },
    { value: "status", label: __("Status", "yatra") }
  ];
  const columnOptions = [
    {
      key: "code",
      label: __("Coupon Code", "yatra"),
      visible: visibleColumns.code
    },
    {
      key: "type",
      label: __("Type", "yatra"),
      visible: visibleColumns.type
    },
    {
      key: "discount",
      label: __("Discount", "yatra"),
      visible: visibleColumns.discount
    },
    {
      key: "usage",
      label: __("Usage", "yatra"),
      visible: visibleColumns.usage
    },
    {
      key: "expiry_date",
      label: __("Expiry Date", "yatra"),
      visible: visibleColumns.expiry_date
    },
    {
      key: "status",
      label: __("Status", "yatra"),
      visible: visibleColumns.status
    }
  ];
  const columns = [
    {
      key: "code",
      label: __("Name / Code", "yatra"),
      sortable: true,
      visible: visibleColumns.code,
      width: "w-[280px]",
      render: (discount) => {
        var _a2;
        return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex items-center gap-2 mb-1 flex-wrap", children: discount.discount_mode === "group" ? /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Badge,
            {
              variant: "success",
              className: "text-xs flex items-center gap-1",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Users, { className: "w-3 h-3" }),
                __("Group Only", "yatra")
              ]
            }
          ) : discount.discount_mode === "promo" ? /* @__PURE__ */ jsxRuntimeExports.jsxs(Badge, { variant: "info", className: "text-xs flex items-center gap-1", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Tag, { className: "w-3 h-3" }),
            __("Promo Code", "yatra")
          ] }) : discount.is_group_discount ? /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Badge,
            {
              variant: "warning",
              className: "text-xs flex items-center gap-1",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Tag, { className: "w-3 h-3" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(Users, { className: "w-3 h-3" }),
                __("Promo + Group", "yatra")
              ]
            }
          ) : /* @__PURE__ */ jsxRuntimeExports.jsxs(Badge, { variant: "info", className: "text-xs flex items-center gap-1", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Tag, { className: "w-3 h-3" }),
            __("Promo Code", "yatra")
          ] }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1.5 mt-1 flex-wrap", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "a",
              {
                href: `${baseAdminUrl}?page=yatra&subpage=discounts&action=edit&id=${discount.id}`,
                className: "font-medium font-mono text-sm text-blue-600 dark:text-blue-400 hover:underline underline-offset-2",
                children: discount.code
              }
            ),
            discount.discount_mode !== "group" && ((_a2 = discount.code) == null ? void 0 : _a2.trim()) ? /* @__PURE__ */ jsxRuntimeExports.jsx(
              "button",
              {
                type: "button",
                className: "inline-flex h-8 w-8 shrink-0 cursor-pointer items-center justify-center rounded-md border border-gray-300 bg-white text-gray-800 shadow-sm transition-colors hover:border-gray-400 hover:bg-gray-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2 dark:border-gray-500 dark:bg-gray-800 dark:text-gray-100 dark:hover:border-gray-400 dark:hover:bg-gray-700",
                title: __("Copy coupon code", "yatra"),
                "aria-label": __("Copy coupon code", "yatra"),
                onClick: (e) => {
                  e.preventDefault();
                  e.stopPropagation();
                  void copyPromoCodeToClipboard(discount.code);
                },
                children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                  ClipboardCopy,
                  {
                    className: "pointer-events-none h-4 w-4",
                    strokeWidth: 2.25,
                    "aria-hidden": true
                  }
                )
              }
            ) : null
          ] }),
          discount.description && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-xs text-gray-500 dark:text-gray-400 mt-1", children: discount.description })
        ] });
      }
    },
    {
      key: "type",
      label: __("Discount", "yatra"),
      sortable: true,
      visible: visibleColumns.type,
      render: (discount) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-1.5", children: [
        discount.discount_mode !== "group" && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-medium text-gray-900 dark:text-white", children: discount.type === "percentage" ? `${discount.amount}%` : formatYatraMoney(
            Number(discount.amount) || 0,
            adminCurrency,
            {
              zeroAsUnknown: false
            }
          ) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs text-gray-500", children: __("off", "yatra") })
        ] }),
        discount.is_group_discount && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-1", children: discount.group_discount_mode === "category_based" && discount.category_discounts && discount.category_discounts.length > 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-1", children: discount.category_discounts.map((cat, idx) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-xs", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "font-medium text-gray-700 dark:text-gray-300", children: [
            cat.traveler_category_label,
            ":"
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "ml-1 text-green-600 dark:text-green-400", children: cat.ranges && cat.ranges.length > 0 ? cat.ranges.map((range3, rIdx) => /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { children: [
            rIdx > 0 && ", ",
            range3.min_group_size,
            range3.max_group_size ? `-${range3.max_group_size}` : "+",
            ":",
            range3.discount_type === "percentage" ? `${range3.discount_amount}%` : formatYatraMoney(
              Number(range3.discount_amount) || 0,
              adminCurrency,
              { zeroAsUnknown: false }
            )
          ] }, rIdx)) : "-" })
        ] }, idx)) }) : discount.group_discount_ranges && discount.group_discount_ranges.length > 0 ? (
          /* Total-based group discount ranges */
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-0.5", children: discount.group_discount_ranges.map((range3, idx) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "div",
            {
              className: "text-xs text-green-600 dark:text-green-400 flex items-center gap-1",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Users, { className: "w-3 h-3" }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { children: [
                  range3.min_group_size,
                  range3.max_group_size ? `-${range3.max_group_size}` : "+",
                  " ",
                  __("pax", "yatra"),
                  ":",
                  range3.discount_type === "percentage" ? ` ${range3.discount_amount}%` : ` ${formatYatraMoney(
                    Number(range3.discount_amount) || 0,
                    adminCurrency,
                    { zeroAsUnknown: false }
                  )}`,
                  " ",
                  __("off", "yatra")
                ] })
              ]
            },
            idx
          )) })
        ) : (
          /* Fallback for legacy data */
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-xs text-green-600 dark:text-green-400 flex items-center gap-1", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Users, { className: "w-3 h-3" }),
            discount.min_group_size ? `${discount.min_group_size}+ ${__("travelers", "yatra")}: ${discount.group_discount_type === "percentage" ? `${discount.group_discount_amount}%` : formatYatraMoney(Number(discount.group_discount_amount) || 0, adminCurrency, { zeroAsUnknown: false })}` : __("Group pricing", "yatra")
          ] })
        ) })
      ] })
    },
    {
      key: "usage",
      label: __("Usage", "yatra"),
      sortable: true,
      visible: visibleColumns.usage,
      render: (discount) => /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-center", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(Badge, { variant: "outline", className: "font-medium", children: [
        discount.usage_count,
        " /",
        " ",
        discount.usage_limit === 0 ? "∞" : discount.usage_limit
      ] }) })
    },
    {
      key: "expiry_date",
      label: __("Expiry Date", "yatra"),
      sortable: true,
      visible: visibleColumns.expiry_date,
      render: (discount) => /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-500 dark:text-gray-400 text-sm", children: discount.expiry_date ? formatDate2(discount.expiry_date) : __("No expiry", "yatra") })
    },
    {
      key: "status",
      label: __("Status", "yatra"),
      sortable: true,
      visible: visibleColumns.status,
      render: (discount) => getStatusBadge(discount.status)
    }
  ];
  const actions = [
    {
      key: "duplicate",
      label: __("Duplicate", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Copy, { className: "w-4 h-4" }),
      onClick: (discount) => handleDuplicate(discount)
    },
    {
      key: "edit",
      label: __("Edit", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(PenSquare, { className: "w-4 h-4" }),
      onClick: (discount) => handleEdit(discount)
    },
    {
      key: "mark_publish",
      label: __("Mark as Publish", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowUp, { className: "w-4 h-4" }),
      onClick: async (discount) => {
        setIsBulkPending(true);
        try {
          await updateStatusForIds([discount.id], "publish");
          invalidateDiscountQueries();
          showToast(__("Discount status updated", "yatra"), "success");
        } catch (error2) {
          showToast(
            (error2 == null ? void 0 : error2.message) || __("Failed to update discount status", "yatra"),
            "error"
          );
        } finally {
          setIsBulkPending(false);
        }
      },
      condition: (discount) => discount.status !== "publish"
    },
    {
      key: "mark_draft",
      label: __("Mark as Draft", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowDown, { className: "w-4 h-4" }),
      onClick: async (discount) => {
        setIsBulkPending(true);
        try {
          await updateStatusForIds([discount.id], "draft");
          invalidateDiscountQueries();
          showToast(__("Discount status updated", "yatra"), "success");
        } catch (error2) {
          showToast(
            (error2 == null ? void 0 : error2.message) || __("Failed to update discount status", "yatra"),
            "error"
          );
        } finally {
          setIsBulkPending(false);
        }
      },
      condition: (discount) => discount.status !== "draft"
    },
    {
      key: "move_trash",
      label: __("Move to Trash", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "w-4 h-4" }),
      onClick: async (discount) => {
        setIsBulkPending(true);
        try {
          await updateStatusForIds([discount.id], "trash");
          invalidateDiscountQueries();
          showToast(__("Discount moved to trash", "yatra"), "success");
        } catch (error2) {
          showToast(
            (error2 == null ? void 0 : error2.message) || __("Failed to move discount to trash", "yatra"),
            "error"
          );
        } finally {
          setIsBulkPending(false);
        }
      },
      condition: (discount) => discount.status !== "trash"
    },
    {
      key: "mark_expired",
      label: __("Mark as Expired", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowDown, { className: "w-4 h-4" }),
      onClick: async (discount) => {
        setIsBulkPending(true);
        try {
          await updateStatusForIds([discount.id], "expired");
          invalidateDiscountQueries();
          showToast(__("Discount status updated", "yatra"), "success");
        } catch (error2) {
          showToast(
            (error2 == null ? void 0 : error2.message) || __("Failed to update discount status", "yatra"),
            "error"
          );
        } finally {
          setIsBulkPending(false);
        }
      },
      condition: (discount) => discount.status !== "expired"
    },
    {
      key: "delete",
      label: __("Delete", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "w-4 h-4" }),
      onClick: (discount) => handleDelete(discount),
      variant: "destructive"
    }
  ];
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      Modal,
      {
        isOpen: showDiscountTypeModal,
        onClose: () => setShowDiscountTypeModal(false),
        title: __("What type of discount do you want to create?", "yatra"),
        description: __(
          "Choose the discount type that best fits your needs",
          "yatra"
        ),
        size: "lg",
        footer: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex justify-end", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          Button,
          {
            variant: "outline",
            onClick: () => setShowDiscountTypeModal(false),
            children: __("Cancel", "yatra")
          }
        ) }),
        children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-3 gap-4", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "button",
            {
              onClick: () => handleSelectDiscountType("promo"),
              className: "flex flex-col items-center p-6 border-2 border-gray-200 dark:border-gray-600 rounded-xl hover:border-blue-500 hover:bg-blue-50 dark:hover:bg-blue-900/20 transition-all group text-left",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-14 h-14 bg-blue-100 dark:bg-blue-900/50 rounded-full flex items-center justify-center mb-4 group-hover:bg-blue-200 dark:group-hover:bg-blue-800 transition-colors", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Tag, { className: "w-7 h-7 text-blue-600 dark:text-blue-400" }) }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "font-semibold text-gray-900 dark:text-white mb-2", children: __("Promo Code", "yatra") }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400 text-center", children: __(
                  "Customer enters a code to get a percentage or fixed discount",
                  "yatra"
                ) })
              ]
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "button",
            {
              onClick: () => handleSelectDiscountType("group"),
              className: "relative flex flex-col items-center p-6 border-2 border-gray-200 dark:border-gray-600 rounded-xl hover:border-green-500 hover:bg-green-50 dark:hover:bg-green-900/20 transition-all group text-left",
              children: [
                !isAdvancedDiscountEnabled && /* @__PURE__ */ jsxRuntimeExports.jsxs(
                  "div",
                  {
                    className: "absolute top-2 right-2 z-10 flex items-center gap-1 px-2 py-1 text-[10px] font-semibold rounded-full shadow-md",
                    style: {
                      background: "linear-gradient(to right, #f59e0b, #f97316)",
                      color: "#ffffff",
                      border: "1px solid #fbbf24"
                    },
                    children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx(Lock, { className: "w-3 h-3", style: { color: "#ffffff" } }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { style: { color: "#ffffff" }, children: __("Pro", "yatra") })
                    ]
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-14 h-14 bg-green-100 dark:bg-green-900/50 rounded-full flex items-center justify-center mb-4 group-hover:bg-green-200 dark:group-hover:bg-green-800 transition-colors", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Users, { className: "w-7 h-7 text-green-600 dark:text-green-400" }) }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "font-semibold text-gray-900 dark:text-white mb-2", children: __("Group Discount", "yatra") }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400 text-center", children: __(
                  "Auto-applies when booking multiple travelers. No code needed.",
                  "yatra"
                ) })
              ]
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "button",
            {
              onClick: () => handleSelectDiscountType("both"),
              className: "relative flex flex-col items-center p-6 border-2 border-gray-200 dark:border-gray-600 rounded-xl hover:border-purple-500 hover:bg-purple-50 dark:hover:bg-purple-900/20 transition-all group text-left",
              children: [
                !isAdvancedDiscountEnabled && /* @__PURE__ */ jsxRuntimeExports.jsxs(
                  "div",
                  {
                    className: "absolute top-2 right-2 z-10 flex items-center gap-1 px-2 py-1 text-[10px] font-semibold rounded-full shadow-md",
                    style: {
                      background: "linear-gradient(to right, #f59e0b, #f97316)",
                      color: "#ffffff",
                      border: "1px solid #fbbf24"
                    },
                    children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx(Lock, { className: "w-3 h-3", style: { color: "#ffffff" } }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { style: { color: "#ffffff" }, children: __("Pro", "yatra") })
                    ]
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-14 h-14 bg-purple-100 dark:bg-purple-900/50 rounded-full flex items-center justify-center mb-4 group-hover:bg-purple-200 dark:group-hover:bg-purple-800 transition-colors", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex -space-x-1", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(Tag, { className: "w-5 h-5 text-purple-600 dark:text-purple-400" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(Users, { className: "w-5 h-5 text-purple-600 dark:text-purple-400" })
                ] }) }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "font-semibold text-gray-900 dark:text-white mb-2", children: __("Promo + Group", "yatra") }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400 text-center", children: __(
                  "Promo code gives base discount + extra savings for groups",
                  "yatra"
                ) })
              ]
            }
          )
        ] })
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      ConfirmationDialog,
      {
        isOpen: deleteConfirm.isOpen,
        onClose: () => setDeleteConfirm({ isOpen: false, discount: null }),
        onConfirm: confirmDelete,
        title: __("Delete Discount", "yatra"),
        message: deleteConfirm.discount ? __(
          'Are you sure you want to delete discount code "{code}"? This action cannot be undone.',
          "yatra"
        ).replace("{code}", deleteConfirm.discount.code) : __(
          "Are you sure you want to delete this discount? This action cannot be undone.",
          "yatra"
        ),
        confirmText: __("Delete", "yatra"),
        cancelText: __("Cancel", "yatra"),
        variant: "danger",
        isLoading: deleteMutation.isPending
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      PremiumUpgradeDialog,
      {
        open: premiumDialog.open,
        onClose: () => setPremiumDialog({ open: false, type: null }),
        moduleName: getPremiumDialogContent().name,
        moduleDescription: getPremiumDialogContent().description,
        purchaseUrl: getPremiumDialogContent().purchaseUrl
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      PageHeader,
      {
        title: __("Discounts", "yatra"),
        description: __(
          "Create and manage discount coupons for your trips",
          "yatra"
        ),
        actionCapability: "yatra_manage_discounts",
        actions: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Button,
          {
            onClick: handleCreateDiscount,
            className: "flex items-center gap-2",
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Plus, { className: "w-4 h-4" }),
              __("Create Discount", "yatra")
            ]
          }
        )
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col lg:flex-row lg:items-center lg:justify-between gap-2", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex-1 min-w-0", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        SearchFilterToolbar,
        {
          searchTerm,
          onSearchChange: setSearchTerm,
          statusFilter,
          onStatusChange: (value) => {
            setStatusFilter(value);
            setPage(1);
          },
          statusOptions,
          sortBy: sortBy2,
          onSortByChange: (field) => {
            setSortBy(field);
            setPage(1);
          },
          sortOrder,
          onSortOrderChange: (order) => {
            setSortOrder(order);
            setPage(1);
          },
          sortOptions,
          onResetFilters: handleResetFilters,
          hasFilters: !!hasFilters,
          placeholder: __("Search by code...", "yatra")
        }
      ) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-full lg:w-auto flex lg:justify-end", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Select,
        {
          value: typeFilter,
          onChange: (e) => {
            setTypeFilter(e.target.value);
            setPage(1);
          },
          className: "w-full lg:w-48 max-w-xs",
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "all", children: __("All Types", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "percentage", children: __("Percentage", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "fixed", children: __("Fixed Amount", "yatra") })
          ]
        }
      ) })
    ] }) }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_manage_discounts", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        BulkActionToolbar,
        {
          selectedIds,
          bulkAction,
          setBulkAction,
          onApply: handleBulkApply,
          onClearSelection: () => setSelectedIds([]),
          statusFilter,
          setStatusFilter: (value) => {
            setStatusFilter(value);
            setPage(1);
          },
          statusOptions: bulkToolbarStatusOptions,
          showColumnsDropdown,
          setShowColumnsDropdown,
          columnOptions,
          onToggleColumn: toggleColumn,
          bulkMutationPending: isBulkPending,
          totalItems: total,
          bulkActionOptions
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-0", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        Table,
        {
          data: discounts,
          columns,
          actions,
          isLoading,
          isError: isDiscountsError,
          errorText: __("Error loading discounts", "yatra"),
          errorDescription: __(
            "We couldn't connect to the discounts service. Please refresh or try again shortly.",
            "We couldn't connect to the discounts service. Please refresh or try again shortly."
          ),
          errorDetails: derivedErrorDetails,
          errorRequestInfo: errorContext.requestInfo,
          onRetry: () => refetch(),
          emptyText: __("No discounts found", "yatra"),
          emptyDescription: hasFilters ? __(
            "Try adjusting your filters to see more results.",
            "yatra"
          ) : __(
            "Get started by creating your first discount coupon.",
            "yatra"
          ),
          onCreateClick: can("yatra_manage_discounts") ? handleCreateDiscount : void 0,
          onSort: handleSort,
          getSortIcon,
          selectedItemIds: selectedIds,
          onSelectItem: handleSelectItem,
          onSelectAll: handleSelectAll,
          isAllSelected,
          getItemId: (discount) => discount.id,
          skeletonRows: 5,
          capability: "yatra_manage_discounts"
        }
      ) }) }),
      total > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-4", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        Pagination,
        {
          currentPage: page,
          totalPages,
          totalItems: total,
          itemsPerPage,
          onPageChange: (newPage) => setPage(newPage),
          itemName: __("coupons", "yatra")
        }
      ) })
    ] }) })
  ] });
};
function getAdminRestConfig() {
  var _a, _b;
  const w = window;
  const raw = ((_a = w == null ? void 0 : w.yatraAdmin) == null ? void 0 : _a.restUrl) || "/wp-json";
  const base = raw.endsWith("/") ? raw.slice(0, -1) : raw;
  const nonce = ((_b = w == null ? void 0 : w.yatraAdmin) == null ? void 0 : _b.nonce) || "";
  return { base, nonce };
}
function buildInvoiceUrl(base, paymentId) {
  const suffix = `/yatra/v1/payment/${paymentId}/invoice`;
  const origin = typeof window !== "undefined" ? window.location.origin : "http://localhost";
  let u;
  try {
    u = new URL(base, origin);
  } catch {
    return `${base.replace(/\/$/, "")}${suffix}?download=1`;
  }
  if (u.searchParams.has("rest_route")) {
    const route2 = (u.searchParams.get("rest_route") || "").replace(/\/$/, "");
    u.searchParams.set("rest_route", `${route2}${suffix}`);
    u.searchParams.set("download", "1");
    return u.toString();
  }
  u.pathname = (u.pathname || "").replace(/\/$/, "") + suffix;
  u.searchParams.set("download", "1");
  return u.toString();
}
async function readError(res) {
  let msg = res.statusText || "Request failed";
  try {
    const j = await res.json();
    if ((j == null ? void 0 : j.message) && typeof j.message === "string") {
      msg = j.message;
    }
  } catch {
    const t = await res.text().catch(() => "");
    if (t && t.length < 300) {
      msg = t;
    }
  }
  return msg;
}
async function downloadAdminInvoice(paymentId) {
  if (!paymentId || paymentId <= 0) {
    throw new Error("Invalid payment ID");
  }
  const { base, nonce } = getAdminRestConfig();
  if (!nonce) {
    throw new Error("Missing REST nonce; please reload the page.");
  }
  const url = buildInvoiceUrl(base, paymentId);
  const res = await fetch(url, {
    method: "GET",
    credentials: "include",
    headers: {
      "X-WP-Nonce": nonce,
      Accept: "application/pdf, application/octet-stream, */*"
    }
  });
  if (!res.ok) {
    throw new Error(await readError(res));
  }
  const blob = await res.blob();
  const dispo = res.headers.get("Content-Disposition");
  let filename = `invoice-${paymentId}.pdf`;
  if (dispo) {
    const m = /filename\*?=(?:UTF-8'')?["']?([^";\n]+)/i.exec(dispo);
    if (m == null ? void 0 : m[1]) {
      try {
        filename = decodeURIComponent(m[1].replace(/['"]/g, "").trim());
      } catch {
        filename = m[1].replace(/['"]/g, "").trim();
      }
    }
  }
  const objectUrl = URL.createObjectURL(blob);
  const link2 = document.createElement("a");
  link2.href = objectUrl;
  link2.download = filename;
  document.body.appendChild(link2);
  link2.click();
  document.body.removeChild(link2);
  URL.revokeObjectURL(objectUrl);
}
const Payments = () => {
  var _a, _b;
  const [searchTerm, setSearchTerm] = reactExports.useState("");
  const [statusFilter, setStatusFilter] = reactExports.useState("all");
  const [methodFilter, setMethodFilter] = reactExports.useState("all");
  const [sortBy2, setSortBy] = reactExports.useState("payment_date");
  const [sortOrder, setSortOrder] = reactExports.useState("desc");
  const [page, setPage] = reactExports.useState(1);
  const [selectedIds, setSelectedIds] = reactExports.useState([]);
  const [bulkAction, setBulkAction] = reactExports.useState("");
  const [showColumnsDropdown, setShowColumnsDropdown] = reactExports.useState(false);
  const [isBulkPending, setIsBulkPending] = reactExports.useState(false);
  const [deleteConfirm, setDeleteConfirm] = reactExports.useState({
    isOpen: false,
    payment: null
  });
  const [visibleColumns, setVisibleColumns] = reactExports.useState(() => {
    if (typeof window === "undefined") {
      return {
        payment: true,
        customer: true,
        booking: true,
        amount: true,
        method: true,
        status: true,
        date: true
      };
    }
    const saved = window.localStorage.getItem("yatra-payments-visible-columns");
    return saved ? JSON.parse(saved) : {
      payment: true,
      customer: true,
      booking: true,
      amount: true,
      method: true,
      status: true,
      date: true
    };
  });
  const queryClient2 = useQueryClient();
  const { can } = usePermissions();
  const { showToast } = useToast();
  const defaultCurrency = ((_a = window == null ? void 0 : window.yatraAdmin) == null ? void 0 : _a.currency) || ((_b = window == null ? void 0 : window.yatraBookingData) == null ? void 0 : _b.currency) || "USD";
  const PAYMENTS_PER_PAGE = 10;
  const queryParams = reactExports.useMemo(() => {
    const params = {
      page,
      per_page: PAYMENTS_PER_PAGE,
      orderby: sortBy2,
      order: sortOrder
    };
    if (searchTerm) {
      params.search = searchTerm;
    }
    if (statusFilter !== "all") {
      params.payment_status = statusFilter;
    }
    if (methodFilter !== "all") {
      params.payment_method = methodFilter;
    }
    return params;
  }, [searchTerm, statusFilter, methodFilter, sortBy2, sortOrder, page]);
  const { data, isLoading, error } = useQuery({
    queryKey: ["payments", queryParams],
    queryFn: async () => {
      const paramsObj = {
        page: queryParams.page,
        per_page: queryParams.per_page
      };
      if (queryParams.search) {
        paramsObj.search = queryParams.search;
      }
      if (queryParams.payment_status) {
        paramsObj.status = queryParams.payment_status;
      }
      if (queryParams.payment_method) {
        paramsObj.gateway = queryParams.payment_method;
      }
      return await apiService.getPayments(paramsObj);
    },
    enabled: can("yatra_view_bookings")
  });
  const { data: paymentStatsRaw } = useQuery({
    queryKey: ["payments-stats"],
    queryFn: () => apiService.getPaymentsStats(),
    enabled: can("yatra_view_bookings")
  });
  const deleteMutation = useMutation({
    mutationFn: async (id) => {
      await apiService.deletePayment(id);
    },
    onSuccess: () => {
      queryClient2.invalidateQueries({ queryKey: ["payments"] });
      queryClient2.invalidateQueries({ queryKey: ["payments-stats"] });
      queryClient2.invalidateQueries({ queryKey: ["bookings"] });
      showToast(__("Payment deleted successfully", "yatra"), "success");
      setDeleteConfirm({ isOpen: false, payment: null });
    },
    onError: (error2) => {
      showToast(
        (error2 == null ? void 0 : error2.message) || __("Failed to delete payment", "yatra"),
        "error"
      );
    }
  });
  const payments = (data == null ? void 0 : data.data) || [];
  const listMeta = data == null ? void 0 : data.meta;
  const total = Number((listMeta == null ? void 0 : listMeta.total) ?? (data == null ? void 0 : data.total) ?? 0);
  const perPage = Number(
    (listMeta == null ? void 0 : listMeta.per_page) ?? (data == null ? void 0 : data.per_page) ?? PAYMENTS_PER_PAGE
  ) || PAYMENTS_PER_PAGE;
  const totalPages = Math.max(
    1,
    Number((listMeta == null ? void 0 : listMeta.total_pages) ?? (data == null ? void 0 : data.total_pages)) || (total > 0 ? Math.ceil(total / perPage) : 1)
  );
  const payCounts = paymentStatsRaw ?? {};
  const countFor = (key2) => Number(payCounts[key2] ?? 0);
  const errorContext = getErrorContext(error);
  const formatDate2 = (dateString) => {
    return formatDate$1(dateString);
  };
  const formatPrice = (price, currencyCode = defaultCurrency) => formatYatraMoney(Number(price) || 0, currencyCode, {
    zeroAsUnknown: false
  });
  const getStatusBadge = (status) => {
    const statusMap = {
      completed: {
        className: "bg-green-100 text-green-700 dark:bg-green-900/20 dark:text-green-400",
        label: __("Completed", "yatra")
      },
      pending: {
        className: "bg-yellow-100 text-yellow-700 dark:bg-yellow-900/20 dark:text-yellow-400",
        label: __("Pending", "yatra")
      },
      partial: {
        className: "bg-blue-100 text-blue-700 dark:bg-blue-900/20 dark:text-blue-400",
        label: __("Partial", "yatra")
      },
      failed: {
        className: "bg-red-100 text-red-700 dark:bg-red-900/20 dark:text-red-400",
        label: __("Failed", "yatra")
      },
      refunded: {
        className: "bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-400",
        label: __("Refunded", "yatra")
      },
      cancelled: {
        className: "bg-orange-100 text-orange-700 dark:bg-orange-900/20 dark:text-orange-400",
        label: __("Cancelled", "yatra")
      }
    };
    const statusInfo = statusMap[status] || {
      className: "bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-400",
      label: status
    };
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "span",
      {
        className: `inline-flex items-center px-2 py-1 rounded-md text-xs font-medium ${statusInfo.className}`,
        children: statusInfo.label
      }
    );
  };
  const handleEdit = (payment) => {
    var _a2;
    window.location.href = `${((_a2 = window.yatraAdmin) == null ? void 0 : _a2.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=payments&action=edit&id=${payment.id}`;
  };
  const handleDelete = (payment) => {
    setDeleteConfirm({ isOpen: true, payment });
  };
  const confirmDelete = () => {
    if (deleteConfirm.payment) {
      deleteMutation.mutate(deleteConfirm.payment.id);
    }
  };
  const handleView = (payment) => {
    var _a2;
    window.location.href = `${((_a2 = window.yatraAdmin) == null ? void 0 : _a2.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=payments&action=view&id=${payment.id}`;
  };
  const handleCreatePayment = () => {
    var _a2;
    window.location.href = `${((_a2 = window.yatraAdmin) == null ? void 0 : _a2.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=payments&action=create`;
  };
  const handleResetFilters = () => {
    setSearchTerm("");
    setStatusFilter("all");
    setMethodFilter("all");
    setSortBy("payment_date");
    setSortOrder("desc");
    setPage(1);
  };
  const handleSort = (field) => {
    if (sortBy2 === field) {
      setSortOrder(sortOrder === "asc" ? "desc" : "asc");
    } else {
      setSortBy(field);
      setSortOrder("desc");
    }
  };
  const getSortIcon = (field) => {
    if (sortBy2 !== field) {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowUpDown, { className: "w-3.5 h-3.5 ml-1 text-gray-400" });
    }
    return sortOrder === "asc" ? /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowUp, { className: "w-3.5 h-3.5 ml-1 text-gray-600 dark:text-gray-300" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowDown, { className: "w-3.5 h-3.5 ml-1 text-gray-600 dark:text-gray-300" });
  };
  const hasFilters = searchTerm || statusFilter !== "all" || methodFilter !== "all" || sortBy2 !== "payment_date" || sortOrder !== "desc";
  const toggleColumn = (columnKey) => {
    const newVisibleColumns = {
      ...visibleColumns,
      [columnKey]: !visibleColumns[columnKey]
    };
    setVisibleColumns(newVisibleColumns);
    if (typeof window !== "undefined") {
      window.localStorage.setItem(
        "yatra-payments-visible-columns",
        JSON.stringify(newVisibleColumns)
      );
    }
  };
  const handleSelectItem = (id, checked) => {
    setSelectedIds(
      (prev) => checked ? [...prev, id] : prev.filter((selectedId) => selectedId !== id)
    );
  };
  const handleSelectAll = (checked) => {
    if (checked) {
      setSelectedIds(payments.map((payment) => payment.id));
    } else {
      setSelectedIds([]);
    }
  };
  const isAllSelected = payments.length > 0 && selectedIds.length === payments.length;
  const updateStatusForIds = async (ids, newStatus) => {
    await Promise.all(
      ids.map(async (id) => {
        await apiService.updatePaymentStatus(id, newStatus);
      })
    );
  };
  const handleBulkApply = async () => {
    if (!bulkAction || selectedIds.length === 0) {
      return;
    }
    try {
      setIsBulkPending(true);
      if (bulkAction === "delete") {
        await apiService.bulkPaymentsAction("delete", selectedIds);
        showToast(
          __("Selected payments deleted successfully", "yatra"),
          "success"
        );
      } else {
        const newStatus = bulkAction;
        await updateStatusForIds(selectedIds, newStatus);
        showToast(__("Bulk status updated successfully", "yatra"), "success");
      }
      queryClient2.invalidateQueries({ queryKey: ["payments"] });
      queryClient2.invalidateQueries({ queryKey: ["payments-stats"] });
      queryClient2.invalidateQueries({ queryKey: ["bookings"] });
      setSelectedIds([]);
      setBulkAction("");
    } catch (error2) {
      showToast(
        (error2 == null ? void 0 : error2.message) || __("Failed to perform bulk action on payments", "yatra"),
        "error"
      );
    } finally {
      setIsBulkPending(false);
    }
  };
  const allBulkActionOptions = [
    { value: "completed", label: __("Mark as Completed", "yatra") },
    { value: "failed", label: __("Mark as Failed", "yatra") },
    { value: "refunded", label: __("Mark as Refunded", "yatra") },
    { value: "cancelled", label: __("Mark as Cancelled", "yatra") },
    { value: "delete", label: __("Delete permanently", "yatra") }
  ];
  const getBulkActionOptionsForStatus = (view) => {
    switch (view) {
      case "completed":
        return allBulkActionOptions.filter(
          (opt) => ["failed", "refunded", "cancelled", "delete"].includes(opt.value)
        );
      case "pending":
        return allBulkActionOptions.filter(
          (opt) => ["completed", "failed", "cancelled", "delete"].includes(opt.value)
        );
      case "partial":
        return allBulkActionOptions.filter(
          (opt) => ["completed", "cancelled", "delete"].includes(opt.value)
        );
      case "failed":
        return allBulkActionOptions.filter(
          (opt) => ["completed", "cancelled", "delete"].includes(opt.value)
        );
      case "refunded":
        return allBulkActionOptions.filter(
          (opt) => ["completed", "cancelled", "delete"].includes(opt.value)
        );
      case "cancelled":
        return allBulkActionOptions.filter(
          (opt) => ["completed", "delete"].includes(opt.value)
        );
      default:
        return allBulkActionOptions;
    }
  };
  const bulkActionOptions = getBulkActionOptionsForStatus(statusFilter);
  const statusOptions = [
    { value: "all", label: __("All Status", "yatra") },
    { value: "completed", label: __("Completed", "yatra") },
    { value: "pending", label: __("Pending", "yatra") },
    { value: "partial", label: __("Partial", "yatra") },
    { value: "failed", label: __("Failed", "yatra") },
    { value: "refunded", label: __("Refunded", "yatra") },
    { value: "cancelled", label: __("Cancelled", "yatra") }
  ];
  const sortOptions = [
    { value: "payment_date", label: __("Payment Date", "yatra") },
    { value: "payment_number", label: __("Payment Number", "yatra") },
    { value: "customer_name", label: __("Customer", "yatra") },
    { value: "amount", label: __("Amount", "yatra") },
    { value: "payment_method", label: __("Payment Method", "yatra") },
    { value: "payment_status", label: __("Status", "yatra") }
  ];
  const columnOptions = [
    {
      key: "payment",
      label: __("Payment", "yatra"),
      visible: visibleColumns.payment
    },
    {
      key: "customer",
      label: __("Customer", "yatra"),
      visible: visibleColumns.customer
    },
    {
      key: "booking",
      label: __("Booking", "yatra"),
      visible: visibleColumns.booking
    },
    {
      key: "amount",
      label: __("Amount", "yatra"),
      visible: visibleColumns.amount
    },
    {
      key: "method",
      label: __("Method", "yatra"),
      visible: visibleColumns.method
    },
    {
      key: "status",
      label: __("Status", "yatra"),
      visible: visibleColumns.status
    },
    { key: "date", label: __("Date", "yatra"), visible: visibleColumns.date }
  ];
  const columns = [
    {
      key: "payment",
      label: __("Payment", "yatra"),
      sortable: true,
      visible: visibleColumns.payment,
      width: "w-[220px]",
      render: (payment) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "button",
          {
            type: "button",
            onClick: () => handleView(payment),
            className: "flex items-center gap-2 mb-1 group cursor-pointer",
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(CreditCard, { className: "w-4 h-4 text-blue-500 dark:text-blue-400 group-hover:text-blue-600 dark:group-hover:text-blue-300" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-medium text-blue-600 dark:text-blue-400 font-mono text-sm group-hover:text-blue-700 dark:group-hover:text-blue-300 group-hover:underline", children: payment.payment_number })
            ]
          }
        ),
        payment.transaction_id && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-xs text-gray-500 dark:text-gray-400 mt-0.5", children: [
          __("TXN", "yatra"),
          ": ",
          payment.transaction_id
        ] })
      ] })
    },
    {
      key: "customer",
      label: __("Customer", "yatra"),
      sortable: true,
      visible: visibleColumns.customer,
      render: (payment) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm font-medium text-gray-900 dark:text-white", children: payment.customer_name }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-xs text-gray-500 dark:text-gray-400 mt-0.5", children: payment.customer_email })
      ] })
    },
    {
      key: "booking",
      label: __("Booking", "yatra"),
      sortable: false,
      visible: visibleColumns.booking,
      render: (payment) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm font-medium text-gray-900 dark:text-white", children: payment.booking_number }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-xs text-gray-500 dark:text-gray-400 mt-0.5", children: payment.trip_title })
      ] })
    },
    {
      key: "amount",
      label: __("Amount", "yatra"),
      sortable: true,
      visible: visibleColumns.amount,
      render: (payment) => /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-semibold text-gray-900 dark:text-white", children: formatPrice(payment.amount, payment.currency || defaultCurrency) })
    },
    {
      key: "method",
      label: __("Method", "yatra"),
      sortable: true,
      visible: visibleColumns.method,
      render: (payment) => /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-600 dark:text-gray-400", children: payment.payment_method })
    },
    {
      key: "status",
      label: __("Status", "yatra"),
      sortable: true,
      visible: visibleColumns.status,
      render: (payment) => getStatusBadge(payment.payment_status)
    },
    {
      key: "date",
      label: __("Date", "yatra"),
      sortable: true,
      visible: visibleColumns.date,
      render: (payment) => /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-500 dark:text-gray-400 text-sm", children: formatDate2(payment.payment_date) })
    }
  ];
  const actions = [
    {
      key: "view",
      label: __("View", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Eye, { className: "w-4 h-4" }),
      onClick: (payment) => handleView(payment)
    },
    {
      key: "edit",
      label: __("Edit", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(PenSquare, { className: "w-4 h-4" }),
      onClick: (payment) => handleEdit(payment)
    },
    {
      key: "download_invoice",
      label: __("Download Invoice", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Download, { className: "w-4 h-4" }),
      onClick: async (payment) => {
        try {
          await downloadAdminInvoice(payment.id);
        } catch (error2) {
          showToast(
            (error2 == null ? void 0 : error2.message) || __("Failed to download invoice", "yatra"),
            "error"
          );
        }
      },
      condition: (payment) => ["completed", "paid"].includes(
        String(payment.payment_status).toLowerCase()
      )
    },
    {
      key: "mark_completed",
      label: __("Mark as Completed", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowUp, { className: "w-4 h-4" }),
      onClick: async (payment) => {
        setIsBulkPending(true);
        try {
          await updateStatusForIds([payment.id], "completed");
          queryClient2.invalidateQueries({ queryKey: ["payments"] });
          queryClient2.invalidateQueries({ queryKey: ["payments-stats"] });
          queryClient2.invalidateQueries({ queryKey: ["bookings"] });
          showToast(__("Payment status updated", "yatra"), "success");
        } catch (error2) {
          showToast(
            (error2 == null ? void 0 : error2.message) || __("Failed to update payment status", "yatra"),
            "error"
          );
        } finally {
          setIsBulkPending(false);
        }
      },
      condition: (payment) => can("yatra_edit_bookings") && payment.payment_status !== "completed"
    },
    {
      key: "mark_failed",
      label: __("Mark as Failed", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowDown, { className: "w-4 h-4" }),
      onClick: async (payment) => {
        setIsBulkPending(true);
        try {
          await updateStatusForIds([payment.id], "failed");
          queryClient2.invalidateQueries({ queryKey: ["payments"] });
          queryClient2.invalidateQueries({ queryKey: ["payments-stats"] });
          queryClient2.invalidateQueries({ queryKey: ["bookings"] });
          showToast(__("Payment status updated", "yatra"), "success");
        } catch (error2) {
          showToast(
            (error2 == null ? void 0 : error2.message) || __("Failed to update payment status", "yatra"),
            "error"
          );
        } finally {
          setIsBulkPending(false);
        }
      },
      condition: (payment) => can("yatra_edit_bookings") && payment.payment_status !== "failed"
    },
    {
      key: "mark_refunded",
      label: __("Mark as Refunded", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowDown, { className: "w-4 h-4" }),
      onClick: async (payment) => {
        setIsBulkPending(true);
        try {
          await updateStatusForIds([payment.id], "refunded");
          queryClient2.invalidateQueries({ queryKey: ["payments"] });
          queryClient2.invalidateQueries({ queryKey: ["payments-stats"] });
          queryClient2.invalidateQueries({ queryKey: ["bookings"] });
          showToast(__("Payment status updated", "yatra"), "success");
        } catch (error2) {
          showToast(
            (error2 == null ? void 0 : error2.message) || __("Failed to update payment status", "yatra"),
            "error"
          );
        } finally {
          setIsBulkPending(false);
        }
      },
      // Refund cap matches the backend gate on PaymentController's
      // update + delete endpoints. Previously this checked
      // `yatra_edit_bookings`, which let Sales Agent / Front Desk
      // see the Refund button — they'd then 403 on click. Accountant
      // role holds `yatra_refund_bookings` without `yatra_edit_bookings`,
      // so this is also what makes the button visible for them.
      condition: (payment) => can("yatra_refund_bookings") && payment.payment_status !== "refunded"
    },
    {
      key: "mark_cancelled",
      label: __("Mark as Cancelled", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowDown, { className: "w-4 h-4" }),
      onClick: async (payment) => {
        setIsBulkPending(true);
        try {
          await updateStatusForIds([payment.id], "cancelled");
          queryClient2.invalidateQueries({ queryKey: ["payments"] });
          queryClient2.invalidateQueries({ queryKey: ["payments-stats"] });
          queryClient2.invalidateQueries({ queryKey: ["bookings"] });
          showToast(__("Payment status updated", "yatra"), "success");
        } catch (error2) {
          showToast(
            (error2 == null ? void 0 : error2.message) || __("Failed to update payment status", "yatra"),
            "error"
          );
        } finally {
          setIsBulkPending(false);
        }
      },
      condition: (payment) => can("yatra_edit_bookings") && payment.payment_status !== "cancelled"
    },
    {
      key: "delete",
      label: __("Delete", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "w-4 h-4" }),
      onClick: (payment) => handleDelete(payment),
      variant: "destructive"
    }
  ];
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      ConfirmationDialog,
      {
        isOpen: deleteConfirm.isOpen,
        onClose: () => setDeleteConfirm({ isOpen: false, payment: null }),
        onConfirm: confirmDelete,
        title: __("Delete Payment", "yatra"),
        message: deleteConfirm.payment ? __(
          'Are you sure you want to delete payment "{number}"? This action cannot be undone.',
          "yatra"
        ).replace("{number}", deleteConfirm.payment.payment_number) : __(
          "Are you sure you want to delete this payment? This action cannot be undone.",
          "yatra"
        ),
        confirmText: __("Delete", "yatra"),
        cancelText: __("Cancel", "yatra"),
        variant: "danger",
        isLoading: deleteMutation.isPending
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      PageHeader,
      {
        title: __("Payments", "yatra"),
        description: __("Manage payment records for bookings", "yatra"),
        actionCapability: "yatra_edit_bookings",
        actions: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Button,
          {
            onClick: handleCreatePayment,
            className: "flex items-center gap-2",
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Plus, { className: "w-4 h-4" }),
              __("Add New Payment", "yatra")
            ]
          }
        )
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col lg:flex-row lg:items-center lg:justify-between gap-2", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex-1 min-w-0", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        SearchFilterToolbar,
        {
          searchTerm,
          onSearchChange: setSearchTerm,
          statusFilter,
          onStatusChange: (value) => {
            setStatusFilter(value);
            setPage(1);
          },
          statusOptions,
          sortBy: sortBy2,
          onSortByChange: (field) => {
            setSortBy(field);
            setPage(1);
          },
          sortOrder,
          onSortOrderChange: (order) => {
            setSortOrder(order);
            setPage(1);
          },
          sortOptions,
          onResetFilters: handleResetFilters,
          hasFilters: !!hasFilters,
          placeholder: __("Search payments...", "yatra")
        }
      ) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-full lg:w-auto flex lg:justify-end", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Select,
        {
          value: methodFilter,
          onChange: (e) => {
            setMethodFilter(e.target.value);
            setPage(1);
          },
          className: "w-full lg:w-48 max-w-xs",
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "all", children: __("All Methods", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "Credit Card", children: __("Credit Card", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "PayPal", children: __("PayPal", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "Bank Transfer", children: __("Bank Transfer", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "Cash", children: __("Cash", "yatra") })
          ]
        }
      ) })
    ] }) }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_view_bookings", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
      !error && /* @__PURE__ */ jsxRuntimeExports.jsx(
        BulkActionToolbar,
        {
          selectedIds,
          bulkAction,
          setBulkAction,
          onApply: handleBulkApply,
          onClearSelection: () => setSelectedIds([]),
          statusFilter,
          setStatusFilter: (value) => {
            setStatusFilter(value);
            setPage(1);
          },
          statusOptions: [
            {
              key: "all",
              label: __("All", "yatra"),
              count: countFor("all")
            },
            {
              key: "completed",
              label: __("Completed", "yatra"),
              count: countFor("completed")
            },
            {
              key: "pending",
              label: __("Pending", "yatra"),
              count: countFor("pending")
            },
            {
              key: "partial",
              label: __("Partial", "yatra"),
              count: countFor("partial")
            },
            {
              key: "failed",
              label: __("Failed", "yatra"),
              count: countFor("failed")
            },
            {
              key: "refunded",
              label: __("Refunded", "yatra"),
              count: countFor("refunded")
            },
            {
              key: "cancelled",
              label: __("Cancelled", "yatra"),
              count: countFor("cancelled")
            }
          ],
          showColumnsDropdown,
          setShowColumnsDropdown,
          columnOptions,
          onToggleColumn: toggleColumn,
          bulkMutationPending: isBulkPending,
          totalItems: total,
          bulkActionOptions
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-0", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        Table,
        {
          data: payments,
          columns,
          actions,
          isLoading,
          isError: !!error,
          errorText: __("Error loading payments", "yatra"),
          errorDescription: __(
            "We couldn’t connect to the payments service. Please refresh or try again in a moment.",
            "We couldn’t connect to the payments service. Please refresh or try again in a moment."
          ),
          onRetry: () => {
            queryClient2.invalidateQueries({ queryKey: ["payments"] });
            queryClient2.invalidateQueries({
              queryKey: ["payments-stats"]
            });
          },
          errorDetails: errorContext.details,
          errorRequestInfo: errorContext.requestInfo,
          emptyText: __("No payments found", "yatra"),
          emptyDescription: hasFilters ? __(
            "Try adjusting your filters to see more results.",
            "yatra"
          ) : __(
            "Get started by recording your first payment.",
            "yatra"
          ),
          onCreateClick: can("yatra_edit_bookings") ? handleCreatePayment : void 0,
          onSort: handleSort,
          getSortIcon,
          selectedItemIds: selectedIds,
          onSelectItem: handleSelectItem,
          onSelectAll: handleSelectAll,
          isAllSelected,
          getItemId: (payment) => payment.id,
          skeletonRows: 5,
          capability: "yatra_view_bookings"
        }
      ) }) }),
      !error && total > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-4", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        Pagination,
        {
          currentPage: page,
          totalPages,
          totalItems: total,
          itemsPerPage: perPage,
          onPageChange: (newPage) => setPage(newPage),
          itemName: __("payments", "yatra")
        }
      ) })
    ] }) })
  ] });
};
const formatBookingLabel = (b) => {
  var _a;
  const code = b.booking_number || b.reference || `#${b.id}`;
  const customer = (_a = b.customer_name) == null ? void 0 : _a.trim();
  return customer ? `${code} — ${customer}` : code;
};
const formatBookingMeta = (b) => {
  const parts = [];
  if (b.trip_title) parts.push(b.trip_title);
  if (b.customer_email) parts.push(b.customer_email);
  return parts.join(" · ");
};
const BookingPicker = ({
  value,
  onChange,
  placeholder = __("Select a booking…", "yatra"),
  searchPlaceholder = __("Search by booking code, name, or email…", "yatra"),
  className = "",
  error = false,
  disabled = false,
  perPage = 20,
  debounceMs = 300,
  maxHeight = 320
}) => {
  const [isOpen, setIsOpen] = reactExports.useState(false);
  const [searchTerm, setSearchTerm] = reactExports.useState("");
  const [debouncedTerm, setDebouncedTerm] = reactExports.useState("");
  const [results, setResults] = reactExports.useState([]);
  const [isLoading, setIsLoading] = reactExports.useState(false);
  const [loadError, setLoadError] = reactExports.useState("");
  const [selected, setSelected] = reactExports.useState(null);
  const containerRef = reactExports.useRef(null);
  const searchInputRef = reactExports.useRef(null);
  const requestIdRef = reactExports.useRef(0);
  reactExports.useEffect(() => {
    const timer2 = setTimeout(() => {
      setDebouncedTerm(searchTerm.trim());
    }, debounceMs);
    return () => clearTimeout(timer2);
  }, [searchTerm, debounceMs]);
  reactExports.useEffect(() => {
    if (!isOpen) return;
    const reqId = ++requestIdRef.current;
    setIsLoading(true);
    setLoadError("");
    apiService.getBookings({ search: debouncedTerm, per_page: perPage, page: 1 }).then((response) => {
      var _a;
      if (reqId !== requestIdRef.current) return;
      const list = Array.isArray(response == null ? void 0 : response.data) ? response.data : Array.isArray((_a = response == null ? void 0 : response.data) == null ? void 0 : _a.data) ? response.data.data : [];
      setResults(list);
    }).catch((err) => {
      if (reqId !== requestIdRef.current) return;
      setLoadError((err == null ? void 0 : err.message) || __("Failed to load bookings.", "yatra"));
      setResults([]);
    }).finally(() => {
      if (reqId === requestIdRef.current) {
        setIsLoading(false);
      }
    });
  }, [isOpen, debouncedTerm, perPage]);
  reactExports.useEffect(() => {
    if (!value) {
      setSelected(null);
      return;
    }
    if (selected && String(selected.id) === String(value)) {
      return;
    }
    let cancelled = false;
    apiService.getBooking(value).then((response) => {
      if (cancelled) return;
      const data = (response == null ? void 0 : response.data) ?? response;
      if (data && typeof data === "object" && data.id) {
        setSelected(data);
      }
    }).catch(() => {
    });
    return () => {
      cancelled = true;
    };
  }, [value]);
  reactExports.useEffect(() => {
    if (!isOpen) return;
    const handler = (event) => {
      if (containerRef.current && !containerRef.current.contains(event.target)) {
        setIsOpen(false);
        setSearchTerm("");
      }
    };
    document.addEventListener("mousedown", handler);
    const focusTimer = setTimeout(() => {
      var _a;
      return (_a = searchInputRef.current) == null ? void 0 : _a.focus();
    }, 80);
    return () => {
      document.removeEventListener("mousedown", handler);
      clearTimeout(focusTimer);
    };
  }, [isOpen]);
  const handleToggle = () => {
    if (disabled) return;
    setIsOpen((prev) => !prev);
  };
  const handleSelect = (booking) => {
    setSelected(booking);
    setIsOpen(false);
    setSearchTerm("");
    onChange(String(booking.id), booking);
  };
  const handleClear = (e) => {
    e.stopPropagation();
    setSelected(null);
    onChange("", null);
  };
  const closedLabel = reactExports.useMemo(() => {
    if (selected) return formatBookingLabel(selected);
    if (value) return `#${value}`;
    return "";
  }, [selected, value]);
  const closedMeta = reactExports.useMemo(
    () => selected ? formatBookingMeta(selected) : "",
    [selected]
  );
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(
    "div",
    {
      ref: containerRef,
      className: `relative ${className}`,
      style: { zIndex: isOpen ? 9999 : "auto" },
      children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "div",
          {
            className: `flex min-h-[2.75rem] w-full rounded-md border-2 ${error ? "border-red-500" : "border-gray-300 dark:border-gray-600"} bg-white dark:bg-gray-800 px-4 py-2 text-base ring-offset-white focus-within:outline-none focus-within:ring-2 focus-within:ring-blue-500 focus-within:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 dark:ring-offset-gray-900 dark:focus-within:ring-blue-400 transition-colors`,
            children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "button",
              {
                type: "button",
                onClick: handleToggle,
                disabled,
                className: `flex-1 flex items-center justify-between text-left ${disabled ? "cursor-not-allowed opacity-50" : "cursor-pointer"}`,
                "aria-haspopup": "listbox",
                "aria-expanded": isOpen,
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "span",
                    {
                      className: closedLabel ? "text-gray-900 dark:text-white" : "text-gray-500 dark:text-gray-400",
                      children: closedLabel ? /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "flex flex-col", children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-medium", children: closedLabel }),
                        closedMeta && /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs text-gray-500 dark:text-gray-400", children: closedMeta })
                      ] }) : placeholder
                    }
                  ),
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "flex items-center gap-1 ml-2", children: [
                    value && !disabled && /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "span",
                      {
                        role: "button",
                        tabIndex: -1,
                        onClick: handleClear,
                        className: "p-0.5 hover:bg-gray-100 dark:hover:bg-gray-700 rounded",
                        "aria-label": __("Clear selection", "yatra"),
                        children: /* @__PURE__ */ jsxRuntimeExports.jsx(X, { className: "w-4 h-4 text-gray-400" })
                      }
                    ),
                    /* @__PURE__ */ jsxRuntimeExports.jsx(
                      ChevronDown,
                      {
                        className: `w-4 h-4 text-gray-400 transition-transform ${isOpen ? "rotate-180" : ""}`
                      }
                    )
                  ] })
                ]
              }
            )
          }
        ),
        isOpen && /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "div",
          {
            className: "absolute z-[9999] w-full mt-1 bg-white dark:bg-gray-800 border-2 border-gray-300 dark:border-gray-600 rounded-md shadow-lg overflow-hidden",
            style: { maxHeight },
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-2 border-b border-gray-200 dark:border-gray-700", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Search, { className: "absolute left-2.5 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Input,
                  {
                    ref: searchInputRef,
                    type: "text",
                    placeholder: searchPlaceholder,
                    value: searchTerm,
                    onChange: (e) => setSearchTerm(e.target.value),
                    className: "pl-8 h-8",
                    onClick: (e) => e.stopPropagation()
                  }
                ),
                isLoading && /* @__PURE__ */ jsxRuntimeExports.jsx(Loader2, { className: "absolute right-2.5 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400 animate-spin" })
              ] }) }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "div",
                {
                  className: "overflow-y-auto",
                  style: { maxHeight: maxHeight - 56 },
                  children: loadError ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "px-3 py-3 text-sm text-red-600 dark:text-red-400", children: loadError }) : isLoading && results.length === 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "px-3 py-4 text-sm text-gray-500 dark:text-gray-400 text-center", children: __("Loading bookings…", "yatra") }) : results.length === 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "px-3 py-4 text-sm text-gray-500 dark:text-gray-400 text-center", children: debouncedTerm ? __("No bookings match this search.", "yatra") : __("No bookings found.", "yatra") }) : results.map((booking) => {
                    const isActive = String(booking.id) === String(value);
                    return /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "button",
                      {
                        type: "button",
                        onClick: () => handleSelect(booking),
                        className: `w-full px-3 py-2 text-left text-sm hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors ${isActive ? "bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-400" : "text-gray-900 dark:text-white"}`,
                        children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between gap-3", children: [
                          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col min-w-0", children: [
                            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-medium truncate", children: formatBookingLabel(booking) }),
                            formatBookingMeta(booking) && /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs text-gray-500 dark:text-gray-400 truncate", children: formatBookingMeta(booking) })
                          ] }),
                          /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-xs text-gray-500 dark:text-gray-400 whitespace-nowrap", children: [
                            "ID: ",
                            booking.id
                          ] })
                        ] })
                      },
                      booking.id
                    );
                  })
                }
              )
            ]
          }
        )
      ]
    }
  );
};
const PaymentForm = () => {
  const queryClient2 = useQueryClient();
  const { can } = usePermissions();
  const [formData, setFormData] = reactExports.useState({
    booking_id: "",
    amount: "",
    payment_method: "Credit Card",
    payment_status: "pending",
    payment_date: (/* @__PURE__ */ new Date()).toISOString().split("T")[0],
    transaction_id: "",
    notes: ""
  });
  const [errors, setErrors] = reactExports.useState({});
  const [isSubmitting, setIsSubmitting] = reactExports.useState(false);
  const action = reactExports.useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get("action") || "create";
  }, []);
  const paymentId = reactExports.useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get("id") ? parseInt(params.get("id") || "0") : null;
  }, []);
  const isEditMode = action === "edit" && paymentId !== null;
  const { data: paymentData, isLoading: isLoadingPayment } = useQuery({
    queryKey: ["payment", paymentId],
    queryFn: async () => {
      if (!paymentId) return null;
      const result = await apiService.getPayment(paymentId);
      if (!result) {
        throw new Error("Failed to fetch payment");
      }
      if (!result.success) {
        throw new Error(result.message || "Payment not found");
      }
      const data = result.data;
      const processedAt = data.processed_at;
      const processedDate = typeof processedAt === "string" && processedAt.includes(" ") ? processedAt.split(" ")[0] : (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
      return {
        id: data.id,
        booking_id: data.booking_id,
        amount: data.amount,
        payment_method: data.gateway,
        payment_status: data.status,
        payment_date: processedDate,
        transaction_id: data.transaction_id ?? "",
        notes: data.notes ?? ""
      };
    },
    enabled: isEditMode && can("yatra_view_bookings")
  });
  reactExports.useEffect(() => {
    if (paymentData && isEditMode) {
      setFormData({
        booking_id: String(paymentData.booking_id ?? ""),
        amount: String(paymentData.amount ?? ""),
        payment_method: String(paymentData.payment_method || "Credit Card"),
        payment_status: String(paymentData.payment_status || "pending") || "pending",
        payment_date: String(
          paymentData.payment_date || (/* @__PURE__ */ new Date()).toISOString().split("T")[0]
        ),
        transaction_id: String(paymentData.transaction_id ?? ""),
        notes: String(paymentData.notes ?? "")
      });
    }
  }, [paymentData, isEditMode]);
  const handleFieldChange = (field, value) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
    if (errors[field]) {
      setErrors((prev) => ({ ...prev, [field]: "" }));
    }
  };
  const validateForm = () => {
    const newErrors = {};
    if (!formData.booking_id.trim()) {
      newErrors.booking_id = __("Booking is required", "yatra");
    } else {
      const bookingId = parseInt(formData.booking_id);
      if (isNaN(bookingId) || bookingId <= 0) {
        newErrors.booking_id = __("Valid booking ID is required", "yatra");
      }
    }
    if (!formData.amount.trim()) {
      newErrors.amount = __("Payment amount is required", "yatra");
    } else {
      const amount = parseFloat(formData.amount);
      if (isNaN(amount) || amount <= 0) {
        newErrors.amount = __(
          "Payment amount must be a positive number",
          "yatra"
        );
      }
    }
    if (!formData.payment_method.trim()) {
      newErrors.payment_method = __("Payment method is required", "yatra");
    }
    if (!formData.payment_date.trim()) {
      newErrors.payment_date = __("Payment date is required", "yatra");
    }
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };
  const saveMutation = useMutation({
    mutationFn: async (data) => {
      const payload = {
        booking_id: parseInt(data.booking_id),
        amount: parseFloat(data.amount),
        gateway: data.payment_method,
        status: data.payment_status,
        processed_at: data.payment_date,
        transaction_id: data.transaction_id.trim() || null,
        notes: data.notes.trim() || null
      };
      return isEditMode && paymentId ? await apiService.updatePayment(paymentId, payload) : await apiService.createPayment(payload);
    },
    onSuccess: () => {
      var _a;
      queryClient2.invalidateQueries({ queryKey: ["payments"] });
      queryClient2.invalidateQueries({ queryKey: ["bookings"] });
      window.location.href = `${((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=payments`;
    },
    onError: (error) => {
      console.error("Error saving payment:", error);
      setErrors({
        submit: error.message || __("Failed to save payment", "yatra")
      });
    }
  });
  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!validateForm()) {
      return;
    }
    setIsSubmitting(true);
    try {
      await saveMutation.mutateAsync(formData);
    } catch (error) {
    } finally {
      setIsSubmitting(false);
    }
  };
  const handleBack = () => {
    var _a;
    window.location.href = `${((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=payments`;
  };
  if (isLoadingPayment) {
    return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex items-center justify-center p-8", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Loader2, { className: "w-6 h-6 animate-spin text-gray-400" }) });
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      PageHeader,
      {
        title: isEditMode ? __("Edit Payment", "yatra") : __("Add New Payment", "yatra"),
        description: isEditMode ? __("Update payment details", "yatra") : __("Record a new payment for a booking", "yatra"),
        actions: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Button,
          {
            variant: "outline",
            onClick: handleBack,
            className: "flex items-center gap-2",
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowLeft, { className: "w-4 h-4" }),
              __("Back", "yatra")
            ]
          }
        )
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_edit_bookings", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("form", { onSubmit: handleSubmit, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-3 gap-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "lg:col-span-2 space-y-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Payment Information", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs(
                "label",
                {
                  htmlFor: "booking_id",
                  className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                  children: [
                    __("Booking", "yatra"),
                    " ",
                    /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
                  ]
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                HelpText,
                {
                  text: __(
                    "Search by booking code (e.g. YTR-123), customer name, or email. Results load from your existing bookings as you type.",
                    "yatra"
                  ),
                  className: "mb-2"
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                BookingPicker,
                {
                  value: formData.booking_id,
                  onChange: (id) => handleFieldChange("booking_id", id),
                  error: Boolean(errors.booking_id),
                  disabled: isEditMode,
                  placeholder: __("Select a booking…", "yatra"),
                  searchPlaceholder: __(
                    "Search by booking code, name, or email…",
                    "yatra"
                  )
                }
              ),
              errors.booking_id && /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "mt-1.5 text-sm text-red-600 dark:text-red-400 flex items-center gap-1", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Info, { className: "w-4 h-4" }),
                errors.booking_id
              ] }),
              isEditMode && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1.5 text-xs text-gray-500 dark:text-gray-400", children: __(
                "The booking linked to a payment cannot be changed after creation.",
                "yatra"
              ) })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-3", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs(
                  "label",
                  {
                    htmlFor: "amount",
                    className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                    children: [
                      __("Payment Amount", "yatra"),
                      " ",
                      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
                    ]
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  HelpText,
                  {
                    text: __("Enter the payment amount received.", "yatra"),
                    className: "mb-2"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-500 text-sm", children: "$" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    Input,
                    {
                      id: "amount",
                      type: "number",
                      min: "0",
                      step: "0.01",
                      value: formData.amount,
                      onChange: (e) => handleFieldChange("amount", e.target.value),
                      placeholder: __("e.g., 2500.00", "yatra"),
                      className: `pl-7 ${errors.amount ? "border-red-500" : ""}`,
                      required: true
                    }
                  )
                ] }),
                errors.amount && /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "mt-1.5 text-sm text-red-600 dark:text-red-400 flex items-center gap-1", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(Info, { className: "w-4 h-4" }),
                  errors.amount
                ] })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs(
                  "label",
                  {
                    htmlFor: "payment_method",
                    className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                    children: [
                      __("Payment Method", "yatra"),
                      " ",
                      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
                    ]
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  HelpText,
                  {
                    text: __(
                      "Select the payment method used for this transaction.",
                      "yatra"
                    ),
                    className: "mb-2"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsxs(
                  Select,
                  {
                    id: "payment_method",
                    value: formData.payment_method,
                    onChange: (e) => handleFieldChange("payment_method", e.target.value),
                    className: errors.payment_method ? "border-red-500" : "",
                    required: true,
                    children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "Credit Card", children: __("Credit Card", "yatra") }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "Debit Card", children: __("Debit Card", "yatra") }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "PayPal", children: __("PayPal", "yatra") }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "Bank Transfer", children: __("Bank Transfer", "yatra") }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "Cash", children: __("Cash", "yatra") }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "Check", children: __("Check", "yatra") }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "Other", children: __("Other", "yatra") })
                    ]
                  }
                ),
                errors.payment_method && /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "mt-1.5 text-sm text-red-600 dark:text-red-400 flex items-center gap-1", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(Info, { className: "w-4 h-4" }),
                  errors.payment_method
                ] })
              ] })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-3", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs(
                  "label",
                  {
                    htmlFor: "payment_date",
                    className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                    children: [
                      __("Payment Date", "yatra"),
                      " ",
                      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
                    ]
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  HelpText,
                  {
                    text: __(
                      "Date when the payment was received.",
                      "yatra"
                    ),
                    className: "mb-2"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  DatePicker,
                  {
                    value: formData.payment_date,
                    onChange: (value) => handleFieldChange("payment_date", value),
                    placeholder: __("Select payment date", "yatra"),
                    maxDate: /* @__PURE__ */ new Date(),
                    error: Boolean(errors.payment_date)
                  }
                ),
                errors.payment_date && /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "mt-1.5 text-sm text-red-600 dark:text-red-400 flex items-center gap-1", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(Info, { className: "w-4 h-4" }),
                  errors.payment_date
                ] })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "label",
                  {
                    htmlFor: "transaction_id",
                    className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                    children: __("Transaction ID", "yatra")
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  HelpText,
                  {
                    text: __(
                      "Optional transaction ID or reference number from the payment gateway.",
                      "yatra"
                    ),
                    className: "mb-2"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Input,
                  {
                    id: "transaction_id",
                    type: "text",
                    value: formData.transaction_id,
                    onChange: (e) => handleFieldChange("transaction_id", e.target.value),
                    placeholder: __("e.g., TXN123456789", "yatra"),
                    className: errors.transaction_id ? "border-red-500" : ""
                  }
                ),
                errors.transaction_id && /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "mt-1.5 text-sm text-red-600 dark:text-red-400 flex items-center gap-1", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(Info, { className: "w-4 h-4" }),
                  errors.transaction_id
                ] })
              ] })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "label",
                {
                  htmlFor: "notes",
                  className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                  children: __("Notes", "yatra")
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                HelpText,
                {
                  text: __(
                    "Optional notes about this payment for internal reference.",
                    "yatra"
                  ),
                  className: "mb-2"
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "textarea",
                {
                  id: "notes",
                  value: formData.notes,
                  onChange: (e) => handleFieldChange("notes", e.target.value),
                  placeholder: __(
                    "e.g., Full payment received, Partial payment - balance pending",
                    "yatra"
                  ),
                  rows: 3,
                  className: "flex w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm ring-offset-white placeholder:text-gray-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 dark:border-gray-600 dark:bg-gray-800 dark:ring-offset-gray-900 dark:placeholder:text-gray-400 dark:focus-visible:ring-blue-400 resize-none"
                }
              )
            ] })
          ] })
        ] }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Payment Status", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              Select,
              {
                value: formData.payment_status,
                onChange: (e) => handleFieldChange(
                  "payment_status",
                  e.target.value
                ),
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "pending", children: __("Pending", "yatra") }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "completed", children: __("Completed", "yatra") }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "partial", children: __("Partial", "yatra") }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "failed", children: __("Failed", "yatra") }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "refunded", children: __("Refunded", "yatra") })
                ]
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "text-xs text-gray-500 dark:text-gray-400", children: [
              formData.payment_status === "completed" && __("Payment has been successfully processed.", "yatra"),
              formData.payment_status === "pending" && __("Payment is pending confirmation.", "yatra"),
              formData.payment_status === "partial" && __(
                "Partial payment recorded. Balance may be pending.",
                "yatra"
              ),
              formData.payment_status === "failed" && __(
                "Payment processing failed. Please check the details.",
                "yatra"
              ),
              formData.payment_status === "refunded" && __("Payment has been refunded to the customer.", "yatra")
            ] })
          ] })
        ] }) })
      ] }),
      errors.submit && /* @__PURE__ */ jsxRuntimeExports.jsx(Alert, { variant: "error", className: "mt-3", children: errors.submit }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-end gap-3 mt-6", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          Button,
          {
            type: "button",
            variant: "outline",
            onClick: handleBack,
            disabled: isSubmitting,
            children: __("Cancel", "yatra")
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          Button,
          {
            type: "submit",
            disabled: isSubmitting,
            className: "flex items-center gap-2",
            children: isSubmitting ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Loader2, { className: "w-4 h-4 animate-spin" }),
              __("Saving...", "yatra")
            ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Save, { className: "w-4 h-4" }),
              isEditMode ? __("Update Payment", "yatra") : __("Record Payment", "yatra")
            ] })
          }
        )
      ] })
    ] }) })
  ] });
};
function paymentStr(v, fallback = "") {
  if (v == null || v === "") return fallback;
  return String(v);
}
function paymentNum(v) {
  if (typeof v === "number" && !Number.isNaN(v)) return v;
  const n = typeof v === "string" ? parseFloat(v) : NaN;
  return Number.isNaN(n) ? 0 : n;
}
const ViewPayment = () => {
  const { can } = usePermissions();
  const { showToast } = useToast();
  const [isDownloadingInvoice, setIsDownloadingInvoice] = React.useState(false);
  const paymentId = reactExports.useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get("id") ? parseInt(params.get("id") || "0") : null;
  }, []);
  const {
    data: payment,
    isLoading,
    error
  } = useQuery({
    queryKey: ["payment", paymentId],
    queryFn: async () => {
      if (!paymentId) return null;
      const result = await apiService.getPayment(paymentId);
      if (!result) {
        throw new Error("Failed to fetch payment");
      }
      if (!result.success) {
        throw new Error(result.message || "Payment not found");
      }
      const data = result.data;
      const idNum = paymentNum(data.id);
      const bookingId = paymentNum(data.booking_id);
      const ref = paymentStr(data.booking_reference);
      const row = {
        id: idNum,
        payment_number: `PAY-${String(idNum).padStart(6, "0")}`,
        booking_id: bookingId,
        booking_number: ref || `#${bookingId}`,
        customer_name: paymentStr(data.customer_name, "N/A"),
        customer_email: paymentStr(data.customer_email),
        customer_phone: paymentStr(data.customer_phone),
        trip_id: paymentNum(data.trip_id),
        trip_title: paymentStr(data.trip_title),
        amount: paymentNum(data.amount),
        payment_method: paymentStr(data.gateway),
        payment_status: paymentStr(data.status, "pending"),
        transaction_id: paymentStr(data.transaction_id),
        payment_date: paymentStr(data.processed_at || data.created_at),
        notes: paymentStr(data.notes),
        created_at: paymentStr(data.created_at),
        updated_at: paymentStr(data.updated_at)
      };
      return row;
    },
    enabled: !!paymentId && can("yatra_view_bookings")
  });
  const formatDate2 = (dateString) => {
    return new Date(dateString).toLocaleDateString("en-US", {
      weekday: "long",
      year: "numeric",
      month: "long",
      day: "numeric"
    });
  };
  const formatPrice = (price, currencyCode = "USD") => formatYatraMoney(Number(price) || 0, currencyCode, {
    zeroAsUnknown: false
  });
  const getPaymentStatusBadge = (status) => {
    const statusMap = {
      completed: {
        className: "bg-green-100 text-green-700 dark:bg-green-900/20 dark:text-green-400",
        label: __("Completed", "yatra")
      },
      pending: {
        className: "bg-yellow-100 text-yellow-700 dark:bg-yellow-900/20 dark:text-yellow-400",
        label: __("Pending", "yatra")
      },
      partial: {
        className: "bg-blue-100 text-blue-700 dark:bg-blue-900/20 dark:text-blue-400",
        label: __("Partial", "yatra")
      },
      failed: {
        className: "bg-red-100 text-red-700 dark:bg-red-900/20 dark:text-red-400",
        label: __("Failed", "yatra")
      },
      refunded: {
        className: "bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-400",
        label: __("Refunded", "yatra")
      }
    };
    const statusInfo = statusMap[status] || {
      className: "bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-400",
      label: status
    };
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "span",
      {
        className: `inline-flex items-center px-3 py-1 rounded-md text-sm font-medium ${statusInfo.className}`,
        children: statusInfo.label
      }
    );
  };
  const handleBack = () => {
    var _a;
    window.location.href = `${((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=payments`;
  };
  const handleEdit = () => {
    var _a;
    window.location.href = `${((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=payments&action=edit&id=${paymentId}`;
  };
  const handleViewBooking = () => {
    var _a;
    if (payment == null ? void 0 : payment.booking_id) {
      window.location.href = `${((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=bookings&action=view&id=${payment.booking_id}`;
    }
  };
  const handleDownloadInvoice = async () => {
    if (!paymentId) return;
    setIsDownloadingInvoice(true);
    try {
      await downloadAdminInvoice(paymentId);
    } catch (e) {
      showToast(
        (e == null ? void 0 : e.message) || __("Failed to download invoice", "yatra"),
        "error"
      );
    } finally {
      setIsDownloadingInvoice(false);
    }
  };
  const canDownloadInvoice = !!payment && ["completed", "paid"].includes(
    String(payment.payment_status).toLowerCase()
  );
  if (isLoading) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        PageHeader,
        {
          title: __("Payment Details", "yatra"),
          actions: /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Button,
            {
              variant: "outline",
              onClick: handleBack,
              className: "flex items-center gap-2",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowLeft, { className: "w-4 h-4" }),
                __("Back", "yatra")
              ]
            }
          )
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-3 gap-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "lg:col-span-2 space-y-3", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-6 w-40" }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "space-y-4", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-2 gap-4", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-12 w-full" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-12 w-full" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-12 w-full" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-12 w-full" })
            ] }) })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-6 w-32" }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-2 gap-4", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-12 w-full" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-12 w-full" })
            ] }) })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-6 w-24" }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-5 w-full" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-5 w-3/4" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-5 w-1/2" })
          ] })
        ] }) })
      ] })
    ] });
  }
  if (error || !payment) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        PageHeader,
        {
          title: __("Payment Not Found", "yatra"),
          actions: /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Button,
            {
              variant: "outline",
              onClick: handleBack,
              className: "flex items-center gap-2",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowLeft, { className: "w-4 h-4" }),
                __("Back to Payments", "yatra")
              ]
            }
          )
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-8 text-center text-red-500", children: __(
        "Payment not found or you do not have permission to view it.",
        "yatra"
      ) }) })
    ] });
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      PageHeader,
      {
        title: __("Payment Details", "yatra"),
        description: __("View complete payment information", "yatra"),
        actions: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Button,
            {
              variant: "outline",
              onClick: handleBack,
              className: "flex items-center gap-2",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowLeft, { className: "w-4 h-4" }),
                __("Back", "yatra")
              ]
            }
          ),
          canDownloadInvoice && /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Button,
            {
              variant: "outline",
              onClick: handleDownloadInvoice,
              disabled: isDownloadingInvoice,
              className: "flex items-center gap-2",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Download, { className: "w-4 h-4" }),
                isDownloadingInvoice ? __("Downloading…", "yatra") : __("Download Invoice", "yatra")
              ]
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_edit_bookings", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(Button, { onClick: handleEdit, className: "flex items-center gap-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(PenSquare, { className: "w-4 h-4" }),
            __("Edit Payment", "yatra")
          ] }) })
        ] })
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_view_bookings", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-3 gap-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "lg:col-span-2 space-y-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Payment Information", "yatra") }),
            getPaymentStatusBadge(payment.payment_status)
          ] }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-4", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-4", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wide", children: __("Payment Number", "yatra") }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm font-mono font-semibold text-gray-900 dark:text-white", children: payment.payment_number })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wide", children: __("Payment Amount", "yatra") }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-lg font-semibold text-gray-900 dark:text-white", children: formatPrice(payment.amount) })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wide", children: __("Payment Method", "yatra") }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-1 flex items-center gap-2", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(CreditCard, { className: "w-4 h-4 text-gray-400" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm font-medium text-gray-900 dark:text-white", children: payment.payment_method })
                ] })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wide", children: __("Payment Date", "yatra") }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-1 flex items-center gap-2", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(Calendar$1, { className: "w-4 h-4 text-gray-400" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm font-medium text-gray-900 dark:text-white", children: formatDate2(payment.payment_date) })
                ] })
              ] }),
              payment.transaction_id && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wide", children: __("Transaction ID", "yatra") }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm font-mono text-gray-900 dark:text-white", children: payment.transaction_id })
              ] })
            ] }),
            payment.notes && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "pt-4 border-t border-gray-200 dark:border-gray-700", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-2 block", children: __("Notes", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-700 dark:text-gray-300 whitespace-pre-wrap", children: payment.notes })
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Related Booking", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              Button,
              {
                variant: "ghost",
                size: "sm",
                onClick: handleViewBooking,
                className: "flex items-center gap-1.5 text-sm",
                children: [
                  __("View Booking", "yatra"),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(ExternalLink, { className: "w-3.5 h-3.5" })
                ]
              }
            )
          ] }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "space-y-4", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-4", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wide", children: __("Booking Number", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm font-mono font-semibold text-gray-900 dark:text-white", children: payment.booking_number })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wide", children: __("Trip", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm font-medium text-gray-900 dark:text-white", children: payment.trip_title })
            ] })
          ] }) })
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Customer", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm font-medium text-gray-900 dark:text-white", children: payment.customer_name }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2 text-sm text-gray-600 dark:text-gray-400", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Mail, { className: "w-4 h-4" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: payment.customer_email })
            ] }),
            payment.customer_phone && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2 text-sm text-gray-600 dark:text-gray-400", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Phone, { className: "w-4 h-4" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: payment.customer_phone })
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Timeline", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wide", children: __("Created", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm text-gray-900 dark:text-white", children: formatDate2(payment.created_at) })
            ] }),
            payment.updated_at && payment.updated_at !== payment.created_at && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wide", children: __("Last Updated", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm text-gray-900 dark:text-white", children: formatDate2(payment.updated_at) })
            ] })
          ] })
        ] })
      ] })
    ] }) })
  ] });
};
const TravelerCategories = () => {
  var _a;
  const [searchTerm, setSearchTerm] = reactExports.useState("");
  const [statusFilter, setStatusFilter] = reactExports.useState("all");
  const [sortBy2, setSortBy] = reactExports.useState("id");
  const [sortOrder, setSortOrder] = reactExports.useState("desc");
  const [page, setPage] = reactExports.useState(1);
  const [deleteConfirm, setDeleteConfirm] = reactExports.useState({
    isOpen: false,
    category: null
  });
  const queryClient2 = useQueryClient();
  const { can } = usePermissions();
  const { showToast } = useToast();
  const baseAdminUrl = ((_a = window.yatraAdmin) == null ? void 0 : _a.adminUrl) || "";
  const queryParams = reactExports.useMemo(() => {
    const params = {
      page,
      per_page: 10,
      orderby: sortBy2,
      order: sortOrder
    };
    if (searchTerm) {
      params.search = searchTerm;
    }
    if (statusFilter !== "all") {
      params.status = statusFilter;
    }
    return params;
  }, [searchTerm, statusFilter, sortBy2, sortOrder, page]);
  const { data: statsData } = useQuery({
    queryKey: ["traveler-categories-stats"],
    queryFn: async () => {
      try {
        const response = await apiClient.get("/traveler-categories/stats");
        return response;
      } catch (error2) {
        return { all: 0, publish: 0, draft: 0, trash: 0 };
      }
    },
    enabled: can("yatra_view_trips")
  });
  const { data, isLoading, error } = useQuery({
    queryKey: ["traveler-categories", queryParams],
    queryFn: async () => {
      try {
        const response = await apiClient.get("/traveler-categories", {
          params: queryParams
        });
        return response;
      } catch (error2) {
        showToast(
          (error2 == null ? void 0 : error2.message) || __("Failed to load traveler categories", "yatra"),
          "error"
        );
        throw error2;
      }
    },
    enabled: can("yatra_view_trips")
  });
  const deleteMutation = useMutation({
    mutationFn: async (id) => {
      return await apiClient.delete(`/traveler-categories/${id}`);
    },
    onSuccess: () => {
      queryClient2.invalidateQueries({ queryKey: ["traveler-categories"] });
      queryClient2.invalidateQueries({
        queryKey: ["traveler-categories-stats"]
      });
      showToast(
        __("Traveler category deleted successfully", "yatra"),
        "success"
      );
      setDeleteConfirm({ isOpen: false, category: null });
    },
    onError: (error2) => {
      showToast(
        (error2 == null ? void 0 : error2.message) || __("Failed to delete traveler category", "yatra"),
        "error"
      );
    }
  });
  const categories = (data == null ? void 0 : data.data) || [];
  const total = (data == null ? void 0 : data.total) || 0;
  const totalPages = Math.ceil(total / 10);
  const errorContext = getErrorContext(error);
  const apiErrorMessage = (data == null ? void 0 : data.error) || (data == null ? void 0 : data.message);
  const isCategoriesError = !!error || !!apiErrorMessage;
  const formatDate2 = (dateString) => {
    if (!dateString) return __("N/A", "yatra");
    try {
      const date2 = new Date(dateString);
      return date2.toLocaleDateString("en-US", {
        month: "short",
        day: "numeric",
        year: "numeric",
        hour: "2-digit",
        minute: "2-digit"
      });
    } catch (e) {
      return dateString;
    }
  };
  const getStatusBadge = (status) => {
    const statusMap = {
      publish: {
        className: "bg-green-100 text-green-700 dark:bg-green-900/20 dark:text-green-400",
        label: __("Publish", "yatra")
      },
      draft: {
        className: "bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-400",
        label: __("Draft", "yatra")
      },
      trash: {
        className: "bg-red-100 text-red-700 dark:bg-red-900/20 dark:text-red-400",
        label: __("Trash", "yatra")
      }
    };
    const statusInfo = statusMap[status] || {
      className: "bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-400",
      label: status
    };
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "span",
      {
        className: `inline-flex items-center px-2 py-1 rounded-md text-xs font-medium ${statusInfo.className}`,
        children: statusInfo.label
      }
    );
  };
  const formatUser = (userId, userName) => {
    if (userName) {
      return userName;
    }
    return `User #${userId}`;
  };
  const formatAgeRange = (ageMin, ageMax) => {
    if (ageMin !== null && ageMin !== void 0 && ageMax !== null && ageMax !== void 0) {
      return `${ageMin}-${ageMax} ${__("years old", "yatra")}`;
    } else if (ageMin !== null && ageMin !== void 0) {
      return `${ageMin}+ ${__("years old", "yatra")}`;
    } else if (ageMax !== null && ageMax !== void 0) {
      return `${__("Under", "yatra")} ${ageMax} ${__("years old", "yatra")}`;
    }
    return __("No age restriction", "yatra");
  };
  const formatPricing = (category) => {
    const mode = category.pricing_mode || "per_person";
    if (mode === "per_group") {
      const hasMin = category.min_pax !== null && category.min_pax !== void 0;
      const hasMax = category.max_pax !== null && category.max_pax !== void 0;
      if (hasMin && hasMax) {
        return `${__("Per group", "yatra")} (${category.min_pax}-${category.max_pax})`;
      }
      if (hasMin) {
        return `${__("Per group", "yatra")} (${__("From", "yatra")} ${category.min_pax})`;
      }
      if (hasMax) {
        return `${__("Per group", "yatra")} (${__("Up to", "yatra")} ${category.max_pax})`;
      }
      return __("Per group", "yatra");
    }
    return __("Per person", "yatra");
  };
  const renderIcon = (icon) => {
    if (!icon) {
      return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-8 h-8 rounded bg-gray-100 dark:bg-gray-800 flex items-center justify-center", children: /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs text-gray-400 dark:text-gray-500", children: "—" }) });
    }
    if (icon.type === "image") {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        "img",
        {
          src: icon.value,
          alt: "",
          className: "w-8 h-8 rounded object-cover",
          onError: (e) => {
            const target2 = e.target;
            target2.style.display = "none";
            if (target2.parentElement) {
              target2.parentElement.innerHTML = '<div class="w-8 h-8 rounded bg-gray-100 dark:bg-gray-800 flex items-center justify-center"><span class="text-xs text-gray-400 dark:text-gray-500">—</span></div>';
            }
          }
        }
      );
    }
    return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-8 h-8 rounded bg-gray-100 dark:bg-gray-800 flex items-center justify-center", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
      IconSelector,
      {
        iconName: icon.value,
        provider: icon.provider ?? "yatra",
        className: "w-5 h-5 text-gray-600 dark:text-gray-400"
      }
    ) });
  };
  const handleEdit = (category) => {
    window.location.href = `${baseAdminUrl}?page=yatra&subpage=traveler-categories&action=edit&id=${category.id}`;
  };
  const handleDelete = (category) => {
    setDeleteConfirm({ isOpen: true, category });
  };
  const confirmDelete = () => {
    if (deleteConfirm.category) {
      deleteMutation.mutate(deleteConfirm.category.id);
    }
  };
  const handleCreateCategory = () => {
    window.location.href = `${baseAdminUrl}?page=yatra&subpage=traveler-categories&action=create`;
  };
  const handleResetFilters = () => {
    setSearchTerm("");
    setStatusFilter("all");
    setSortBy("label");
    setSortOrder("asc");
    setPage(1);
  };
  const handleSort = (field) => {
    if (sortBy2 === field) {
      setSortOrder(sortOrder === "asc" ? "desc" : "asc");
    } else {
      setSortBy(field);
      setSortOrder("asc");
    }
  };
  const getSortIcon = (field) => {
    if (sortBy2 !== field) {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowUpDown, { className: "w-3.5 h-3.5 ml-1 text-gray-400" });
    }
    return sortOrder === "asc" ? /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowUp, { className: "w-3.5 h-3.5 ml-1 text-gray-600 dark:text-gray-300" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowDown, { className: "w-3.5 h-3.5 ml-1 text-gray-600 dark:text-gray-300" });
  };
  const hasFilters = searchTerm || statusFilter !== "all" || sortBy2 !== "id" || sortOrder !== "desc";
  const [selectedIds, setSelectedIds] = reactExports.useState([]);
  const [bulkAction, setBulkAction] = reactExports.useState("");
  const [showColumnsDropdown, setShowColumnsDropdown] = reactExports.useState(false);
  const [visibleColumns, setVisibleColumns] = reactExports.useState({
    category: true,
    description: true,
    age_range: true,
    pricing: true,
    status: true,
    dates: true,
    author: true
  });
  const toggleColumnVisibility = (key2) => {
    setVisibleColumns((prev) => ({
      ...prev,
      [key2]: !prev[key2]
    }));
  };
  const statusCounts = reactExports.useMemo(() => {
    if (statsData) {
      return {
        all: statsData.all ?? 0,
        publish: statsData.publish ?? 0,
        draft: statsData.draft ?? 0,
        trash: statsData.trash ?? 0
      };
    }
    return {
      all: 0,
      publish: 0,
      draft: 0,
      trash: 0
    };
  }, [statsData]);
  const bulkMutation = useMutation({
    mutationFn: async ({
      action,
      ids
    }) => {
      if (action === "delete") {
        await Promise.all(
          ids.map((id) => apiClient.delete(`/traveler-categories/${id}`))
        );
      } else {
        await Promise.all(
          ids.map(async (id) => {
            try {
              const response = await apiClient.get(
                `/traveler-categories/${id}`
              );
              const category = response;
              if (!category || !category.label) {
                return;
              }
              await apiClient.put(`/traveler-categories/${id}`, {
                label: category.label,
                slug: category.slug,
                description: category.description,
                age_min: category.age_min,
                age_max: category.age_max,
                icon: category.icon,
                pricing_mode: category.pricing_mode || "per_person",
                min_pax: category.min_pax ?? null,
                max_pax: category.max_pax ?? null,
                status: action
              });
            } catch {
              throw new Error("bulk_item_failed");
            }
          })
        );
      }
    },
    onSuccess: (_data, variables) => {
      queryClient2.invalidateQueries({ queryKey: ["traveler-categories"] });
      queryClient2.invalidateQueries({
        queryKey: ["traveler-categories-stats"]
      });
      const msgMap = {
        delete: __(
          "Selected traveler categories deleted successfully",
          "yatra"
        ),
        trash: __("Selected traveler categories moved to trash", "yatra"),
        draft: __("Selected traveler categories marked as draft", "yatra"),
        publish: __("Selected traveler categories published", "yatra")
      };
      showToast(
        msgMap[variables.action] || __("Bulk action completed", "yatra"),
        "success"
      );
      setSelectedIds([]);
      setBulkAction("");
    },
    onError: (error2, variables) => {
      const msgMapError = {
        delete: __("Failed to delete selected traveler categories", "yatra"),
        trash: __("Failed to move traveler categories to trash", "yatra"),
        draft: __("Failed to mark traveler categories as draft", "yatra"),
        publish: __("Failed to publish traveler categories", "yatra")
      };
      showToast(
        (error2 == null ? void 0 : error2.message) || msgMapError[variables.action] || __("Bulk action failed", "yatra"),
        "error"
      );
    }
  });
  const handleBulkApply = () => {
    if (!bulkAction) {
      showToast(__("Select a bulk action first.", "yatra"), "warning");
      return;
    }
    if (selectedIds.length === 0) {
      showToast(
        __("Select at least one traveler category.", "yatra"),
        "warning"
      );
      return;
    }
    bulkMutation.mutate({ action: bulkAction, ids: selectedIds });
  };
  const columns = [
    {
      key: "category",
      label: __("Category", "yatra"),
      sortable: true,
      visible: visibleColumns.category,
      render: (category) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3", children: [
        renderIcon(category.icon),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "a",
            {
              href: `${baseAdminUrl}?page=yatra&subpage=traveler-categories&action=edit&id=${category.id}`,
              className: "font-medium text-gray-900 dark:text-white text-blue-600 dark:text-blue-400 hover:underline underline-offset-2",
              children: category.label
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-xs text-gray-500 dark:text-gray-400 mt-0.5 flex items-center gap-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: category.slug }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-gray-400 dark:text-gray-500", children: [
              "(ID: ",
              category.id,
              ")"
            ] })
          ] })
        ] })
      ] })
    },
    {
      key: "description",
      label: __("Description", "yatra"),
      visible: visibleColumns.description,
      render: (category) => /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-gray-600 dark:text-gray-400 text-sm line-clamp-2", children: category.description || __("No description", "yatra") })
    },
    {
      key: "age_range",
      label: __("Age Range", "yatra"),
      visible: visibleColumns.age_range,
      render: (category) => /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-600 dark:text-gray-400 text-sm", children: formatAgeRange(category.age_min, category.age_max) })
    },
    {
      key: "pricing",
      label: __("Pricing", "yatra"),
      visible: visibleColumns.pricing,
      render: (category) => /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-600 dark:text-gray-400 text-sm", children: formatPricing(category) })
    },
    {
      key: "status",
      label: __("Status", "yatra"),
      sortable: true,
      visible: visibleColumns.status,
      render: (category) => getStatusBadge(category.status)
    },
    {
      key: "dates",
      label: __("Date", "yatra"),
      sortable: true,
      visible: visibleColumns.dates,
      render: (category) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-gray-500 dark:text-gray-400 text-sm", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: formatDate2(category.created_at) }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-xs text-gray-400 dark:text-gray-500 mt-0.5", children: [
          __("Updated", "yatra"),
          ": ",
          formatDate2(category.updated_at)
        ] })
      ] })
    },
    {
      key: "author",
      label: __("Author", "yatra"),
      visible: visibleColumns.author,
      render: (category) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-gray-600 dark:text-gray-400 text-sm", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: formatUser(category.created_by, category.created_by_name) }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-xs text-gray-400 dark:text-gray-500 mt-0.5", children: [
          __("Updated by", "yatra"),
          ":",
          " ",
          formatUser(category.updated_by, category.updated_by_name)
        ] })
      ] })
    }
  ];
  const actions = [
    {
      key: "edit",
      label: __("Edit", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(PenSquare, { className: "w-4 h-4" }),
      onClick: (category) => handleEdit(category),
      condition: () => can("yatra_edit_trips")
    },
    {
      key: "publish",
      label: __("Make Published", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(PenSquare, { className: "w-4 h-4" }),
      onClick: (category) => bulkMutation.mutate({ action: "publish", ids: [category.id] }),
      condition: (category) => can("yatra_edit_trips") && category.status !== "publish"
    },
    {
      key: "draft",
      label: __("Make Draft", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(PenSquare, { className: "w-4 h-4" }),
      onClick: (category) => bulkMutation.mutate({ action: "draft", ids: [category.id] }),
      condition: (category) => can("yatra_edit_trips") && category.status !== "draft"
    },
    {
      key: "trash",
      label: __("Move to Trash", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "w-4 h-4" }),
      onClick: (category) => bulkMutation.mutate({ action: "trash", ids: [category.id] }),
      variant: "destructive",
      condition: (category) => can("yatra_edit_trips") && category.status !== "trash"
    },
    {
      key: "delete",
      label: __("Delete Permanently", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "w-4 h-4" }),
      onClick: (category) => handleDelete(category),
      variant: "destructive",
      condition: (category) => can("yatra_delete_trips") && category.status === "trash"
    }
  ];
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      ConfirmationDialog,
      {
        isOpen: deleteConfirm.isOpen,
        onClose: () => setDeleteConfirm({ isOpen: false, category: null }),
        onConfirm: confirmDelete,
        title: __("Delete Traveler Category", "yatra"),
        message: deleteConfirm.category ? __(
          'Are you sure you want to delete "{label}"? This action cannot be undone.',
          "yatra"
        ).replace("{label}", deleteConfirm.category.label) : __(
          "Are you sure you want to delete this traveler category? This action cannot be undone.",
          "yatra"
        ),
        confirmText: __("Delete", "yatra"),
        cancelText: __("Cancel", "yatra"),
        variant: "danger",
        isLoading: deleteMutation.isPending
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      PageHeader,
      {
        title: __("Traveler Categories", "yatra"),
        description: __(
          "Manage pricing categories for different types of travelers",
          "yatra"
        ),
        actionCapability: "yatra_edit_trips",
        actions: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Button,
          {
            onClick: handleCreateCategory,
            className: "flex items-center gap-2",
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Plus, { className: "w-4 h-4" }),
              __("Add New Category", "yatra")
            ]
          }
        )
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-3", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
      SearchFilterToolbar,
      {
        searchTerm,
        onSearchChange: setSearchTerm,
        statusFilter,
        onStatusChange: (value) => {
          setStatusFilter(value);
          setPage(1);
        },
        statusOptions: [
          { value: "all", label: __("All Status", "yatra") },
          { value: "publish", label: __("Publish", "yatra") },
          { value: "draft", label: __("Draft", "yatra") },
          { value: "trash", label: __("Trash", "yatra") }
        ],
        sortBy: sortBy2,
        onSortByChange: (value) => {
          setSortBy(value);
          setSortOrder("asc");
          setPage(1);
        },
        sortOrder,
        onSortOrderChange: (order) => {
          setSortOrder(order);
          setPage(1);
        },
        sortOptions: [
          { value: "id", label: __("ID", "yatra") },
          { value: "label", label: __("Label", "yatra") },
          { value: "status", label: __("Status", "yatra") },
          { value: "created_at", label: __("Created At", "yatra") },
          { value: "updated_at", label: __("Updated At", "yatra") }
        ],
        onResetFilters: handleResetFilters,
        hasFilters: !!hasFilters,
        placeholder: __("Search categories...", "yatra")
      }
    ) }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs(ConditionalRender, { capability: "yatra_view_trips", children: [
      !isCategoriesError && /* @__PURE__ */ jsxRuntimeExports.jsx(
        BulkActionToolbar,
        {
          selectedIds,
          bulkAction,
          setBulkAction,
          onApply: handleBulkApply,
          onClearSelection: () => setSelectedIds([]),
          statusFilter,
          setStatusFilter: (value) => {
            setStatusFilter(value);
            setPage(1);
            setSelectedIds([]);
            setBulkAction("");
          },
          statusOptions: [
            {
              key: "all",
              label: __("All", "yatra"),
              count: statusCounts.all
            },
            {
              key: "publish",
              label: __("Published", "yatra"),
              count: statusCounts.publish
            },
            {
              key: "draft",
              label: __("Draft", "yatra"),
              count: statusCounts.draft
            },
            {
              key: "trash",
              label: __("Trash", "yatra"),
              count: statusCounts.trash
            }
          ],
          showColumnsDropdown,
          setShowColumnsDropdown,
          columnOptions: [
            {
              key: "category",
              label: __("Category", "yatra"),
              visible: visibleColumns.category
            },
            {
              key: "description",
              label: __("Description", "yatra"),
              visible: visibleColumns.description
            },
            {
              key: "age_range",
              label: __("Age Range", "yatra"),
              visible: visibleColumns.age_range
            },
            {
              key: "pricing",
              label: __("Pricing", "yatra"),
              visible: visibleColumns.pricing
            },
            {
              key: "status",
              label: __("Status", "yatra"),
              visible: visibleColumns.status
            },
            {
              key: "dates",
              label: __("Date", "yatra"),
              visible: visibleColumns.dates
            },
            {
              key: "author",
              label: __("Author", "yatra"),
              visible: visibleColumns.author
            }
          ],
          onToggleColumn: (key2) => toggleColumnVisibility(key2),
          bulkMutationPending: bulkMutation.isPending,
          totalItems: categories.length,
          bulkActionOptions: getDefaultBulkStatusOptions(statusFilter).filter(
            (opt) => opt.value !== "delete" || can("yatra_delete_trips")
          )
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-0", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        Table,
        {
          data: categories,
          columns,
          actions,
          isLoading,
          isError: isCategoriesError,
          errorText: __("Error loading traveler categories", "yatra"),
          errorDescription: __(
            "We couldn’t connect to the traveler categories service. Please refresh or try again shortly.",
            "We couldn’t connect to the traveler categories service. Please refresh or try again shortly."
          ),
          errorDetails: errorContext.details || apiErrorMessage,
          errorRequestInfo: errorContext.requestInfo,
          onRetry: () => queryClient2.invalidateQueries({
            queryKey: ["traveler-categories"]
          }),
          emptyText: __("No traveler categories found", "yatra"),
          emptyDescription: hasFilters ? __(
            "Try adjusting your filters to see more results.",
            "yatra"
          ) : __(
            "Get started by creating your first traveler category.",
            "yatra"
          ),
          onCreateClick: can("yatra_edit_trips") ? handleCreateCategory : void 0,
          onSort: handleSort,
          getSortIcon,
          capability: "yatra_view_trips",
          selectedItemIds: selectedIds,
          onSelectItem: (id, checked) => {
            if (checked) {
              setSelectedIds((prev) => Array.from(/* @__PURE__ */ new Set([...prev, id])));
            } else {
              setSelectedIds(
                (prev) => prev.filter((existingId) => existingId !== id)
              );
            }
          },
          onSelectAll: (checked) => {
            if (checked) {
              setSelectedIds(
                categories.map((cat) => cat.id)
              );
            } else {
              setSelectedIds([]);
            }
          },
          isAllSelected: categories.length > 0 && selectedIds.length === categories.length,
          getItemId: (cat) => cat.id,
          getItemStatus: (cat) => cat.status,
          statusFilter
        }
      ) }) }),
      total > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-4", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        Pagination,
        {
          currentPage: page,
          totalPages,
          totalItems: total,
          itemsPerPage: 10,
          onPageChange: (newPage) => setPage(newPage),
          itemName: __("categories", "yatra")
        }
      ) })
    ] })
  ] });
};
const TravelerCategoryForm = () => {
  const queryClient2 = useQueryClient();
  const { can } = usePermissions();
  const { showToast } = useToast();
  const [formData, setFormData] = reactExports.useState({
    label: "",
    slug: "",
    description: "",
    age_min: "",
    age_max: "",
    icon: null,
    status: "publish",
    pricing_mode: "per_person",
    min_pax: "",
    max_pax: ""
  });
  const [errors, setErrors] = reactExports.useState({});
  const [isSubmitting, setIsSubmitting] = reactExports.useState(false);
  const [isSlugEditable, setIsSlugEditable] = reactExports.useState(false);
  const action = reactExports.useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get("action") || "create";
  }, []);
  const categoryId = reactExports.useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get("id") ? parseInt(params.get("id") || "0") : null;
  }, []);
  const isEditMode = action === "edit" && categoryId !== null;
  const { data: categoryData, isLoading: isLoadingCategory } = useQuery({
    queryKey: ["traveler-category", categoryId],
    queryFn: async () => {
      if (!categoryId) return null;
      try {
        const response = await apiClient.get(
          `/traveler-categories/${categoryId}`
        );
        return response;
      } catch (error) {
        showToast(
          (error == null ? void 0 : error.message) || __("Failed to load traveler category", "yatra"),
          "error"
        );
        throw error;
      }
    },
    enabled: isEditMode && can("yatra_view_trips")
  });
  reactExports.useEffect(() => {
    var _a, _b;
    if (categoryData && isEditMode) {
      setFormData({
        label: categoryData.label || "",
        slug: categoryData.slug || "",
        description: categoryData.description || "",
        age_min: ((_a = categoryData.age_min) == null ? void 0 : _a.toString()) || "",
        age_max: ((_b = categoryData.age_max) == null ? void 0 : _b.toString()) || "",
        icon: categoryData.icon || null,
        status: categoryData.status || "draft",
        pricing_mode: categoryData.pricing_mode || "per_person",
        min_pax: categoryData.min_pax !== void 0 && categoryData.min_pax !== null ? categoryData.min_pax.toString() : "",
        max_pax: categoryData.max_pax !== void 0 && categoryData.max_pax !== null ? categoryData.max_pax.toString() : ""
      });
    }
  }, [categoryData, isEditMode]);
  const handleLabelChange = (value) => {
    if (!isEditMode && !isSlugEditable) {
      const newSlug = generateSlug(value);
      setFormData((prev) => ({
        ...prev,
        label: value,
        slug: newSlug
      }));
    } else {
      setFormData((prev) => ({
        ...prev,
        label: value
      }));
    }
    if (errors.label) {
      setErrors((prev) => ({ ...prev, label: "" }));
    }
  };
  const handleSlugChange = (value) => {
    if (isSlugEditable) {
      setFormData((prev) => ({ ...prev, slug: value }));
      if (errors.slug) {
        setErrors((prev) => ({ ...prev, slug: "" }));
      }
    }
  };
  const handleToggleSlugEdit = () => {
    if (isSlugEditable) {
      const newSlug = generateSlug(formData.label);
      setFormData((prev) => ({ ...prev, slug: newSlug }));
    }
    setIsSlugEditable(!isSlugEditable);
  };
  const handleFieldChange = (field, value) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
    if (errors[field]) {
      setErrors((prev) => ({ ...prev, [field]: "" }));
    }
  };
  const validateForm = () => {
    const newErrors = {};
    if (!formData.label.trim()) {
      newErrors.label = __("Label is required", "yatra");
    }
    if (!formData.slug.trim()) {
      newErrors.slug = __("Slug is required", "yatra");
    } else if (!/^[\p{L}\p{N}-]+$/u.test(formData.slug)) {
      newErrors.slug = __(
        "Slug can only contain letters, numbers, and hyphens",
        "yatra"
      );
    }
    if (!formData.description.trim()) {
      newErrors.description = __("Description is required", "yatra");
    }
    if (formData.age_min && isNaN(parseInt(formData.age_min))) {
      newErrors.age_min = __("Minimum age must be a valid number", "yatra");
    }
    if (formData.age_max && isNaN(parseInt(formData.age_max))) {
      newErrors.age_max = __("Maximum age must be a valid number", "yatra");
    }
    if (formData.age_min && formData.age_max && parseInt(formData.age_min) >= parseInt(formData.age_max)) {
      newErrors.age_max = __(
        "Maximum age must be greater than minimum age",
        "yatra"
      );
    }
    if (formData.pricing_mode === "per_group") {
      if (formData.min_pax && isNaN(parseInt(formData.min_pax))) {
        newErrors.min_pax = __(
          "Minimum group size must be a valid number",
          "yatra"
        );
      }
      if (formData.max_pax && isNaN(parseInt(formData.max_pax))) {
        newErrors.max_pax = __(
          "Maximum group size must be a valid number",
          "yatra"
        );
      }
      if (formData.min_pax && formData.max_pax && !isNaN(parseInt(formData.min_pax)) && !isNaN(parseInt(formData.max_pax)) && parseInt(formData.min_pax) > parseInt(formData.max_pax)) {
        newErrors.max_pax = __(
          "Maximum group size should be greater than or equal to minimum group size",
          "yatra"
        );
      }
    }
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };
  const saveMutation = useMutation({
    mutationFn: async (data) => {
      const payload = {
        label: data.label.trim(),
        slug: data.slug.trim(),
        description: data.description.trim(),
        icon: data.icon,
        status: data.status
      };
      if (data.age_min && data.age_min.trim() !== "") {
        payload.age_min = parseInt(data.age_min);
      } else {
        payload.age_min = null;
      }
      if (data.age_max && data.age_max.trim() !== "") {
        payload.age_max = parseInt(data.age_max);
      } else {
        payload.age_max = null;
      }
      payload.pricing_mode = data.pricing_mode || "per_person";
      if (data.pricing_mode === "per_group") {
        if (data.min_pax && data.min_pax.trim() !== "") {
          payload.min_pax = parseInt(data.min_pax);
        } else {
          payload.min_pax = null;
        }
        if (data.max_pax && data.max_pax.trim() !== "") {
          payload.max_pax = parseInt(data.max_pax);
        } else {
          payload.max_pax = null;
        }
      } else {
        payload.min_pax = null;
        payload.max_pax = null;
      }
      if (isEditMode && isSlugEditable) {
        payload.preserve_slug = true;
      }
      if (isEditMode && categoryId) {
        return await apiClient.put(
          `/traveler-categories/${categoryId}`,
          payload
        );
      } else {
        return await apiClient.post("/traveler-categories", payload);
      }
    },
    onSuccess: (response) => {
      var _a;
      queryClient2.invalidateQueries({ queryKey: ["traveler-categories"] });
      queryClient2.invalidateQueries({
        queryKey: ["traveler-category", categoryId]
      });
      showToast(
        isEditMode ? __("Traveler category updated successfully", "yatra") : __("Traveler category created successfully", "yatra"),
        "success"
      );
      if (!isEditMode) {
        const newId = (response == null ? void 0 : response.id) || ((_a = response == null ? void 0 : response.data) == null ? void 0 : _a.id);
        if (newId) {
          setTimeout(() => {
            var _a2;
            window.location.href = `${((_a2 = window.yatraAdmin) == null ? void 0 : _a2.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=traveler-categories&action=edit&id=${newId}`;
          }, 800);
        }
      } else {
        setIsSubmitting(false);
      }
    },
    onError: (error) => {
      const errorMessage = (error == null ? void 0 : error.message) || __("An error occurred while saving the traveler category", "yatra");
      showToast(errorMessage, "error");
      setIsSubmitting(false);
    }
  });
  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!validateForm()) {
      showToast(__("Please fix the form errors", "yatra"), "warning");
      return;
    }
    setIsSubmitting(true);
    setErrors({});
    saveMutation.mutate(formData);
  };
  const handleCancel = () => {
    var _a;
    window.location.href = `${((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=traveler-categories`;
  };
  if (isEditMode && isLoadingCategory) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        PageHeader,
        {
          title: __("Edit Category", "yatra"),
          description: __("Update traveler category information", "yatra"),
          actions: /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "w-24 h-9 rounded-md" })
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-3 gap-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "lg:col-span-2 space-y-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-5 w-48" }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-4", children: [
            [1, 2, 3].map((section) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-4 w-32" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-10 w-full" })
            ] }, section)),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-4 w-32" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-24 w-full" })
            ] })
          ] })
        ] }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-3", children: [1, 2, 3].map((card) => /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-5 w-36" }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-40 w-full" }) })
        ] }, card)) })
      ] })
    ] });
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      PageHeader,
      {
        title: isEditMode ? __("Edit Category", "yatra") : __("Add Category", "yatra"),
        description: isEditMode ? __("Update traveler category information", "yatra") : __("Create a new traveler category for pricing", "yatra"),
        actions: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Button,
          {
            variant: "outline",
            onClick: handleCancel,
            className: "flex items-center gap-2",
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowLeft, { className: "w-4 h-4" }),
              __("Back", "yatra")
            ]
          }
        )
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_edit_trips", children: /* @__PURE__ */ jsxRuntimeExports.jsx("form", { onSubmit: handleSubmit, children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-3 gap-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "lg:col-span-2 space-y-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Category Information", "yatra") }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "label",
              {
                htmlFor: "label",
                className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                children: [
                  __("Category Label", "yatra"),
                  " ",
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
                ]
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              HelpText,
              {
                text: __(
                  "The name of this traveler category (e.g., Adult, Child, Senior, Student)",
                  "yatra"
                ),
                className: "mb-2"
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              Input,
              {
                id: "label",
                type: "text",
                value: formData.label,
                onChange: (e) => handleLabelChange(e.target.value),
                placeholder: __("e.g., Adult", "yatra"),
                className: errors.label ? "border-red-500" : "",
                required: true
              }
            ),
            errors.label && /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "mt-1.5 text-sm text-red-600 dark:text-red-400 flex items-center gap-1", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(AlertCircle, { className: "w-4 h-4" }),
              errors.label
            ] })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "label",
              {
                htmlFor: "slug",
                className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                children: [
                  __("Slug", "yatra"),
                  " ",
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
                ]
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Input,
                {
                  id: "slug",
                  type: "text",
                  value: formData.slug,
                  onChange: (e) => handleSlugChange(e.target.value),
                  placeholder: __("category-slug", "yatra"),
                  className: `pr-10 ${errors.slug ? "border-red-500" : ""} ${!isSlugEditable ? "bg-gray-50 dark:bg-gray-800 cursor-not-allowed" : ""}`,
                  disabled: !isSlugEditable,
                  required: true
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "button",
                {
                  type: "button",
                  onClick: handleToggleSlugEdit,
                  className: "absolute right-2 top-1/2 -translate-y-1/2 p-1.5 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors rounded",
                  "aria-label": isSlugEditable ? __("Cancel editing slug", "yatra") : __("Edit slug", "yatra"),
                  children: isSlugEditable ? /* @__PURE__ */ jsxRuntimeExports.jsx(X, { className: "w-4 h-4" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(Pen, { className: "w-4 h-4" })
                }
              )
            ] }),
            errors.slug && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm text-red-500", children: errors.slug }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-xs text-gray-500 dark:text-gray-400", children: isSlugEditable ? __(
              "You are manually editing the slug. Click X to cancel and regenerate from label.",
              "yatra"
            ) : __(
              "This slug is auto-generated from the label. Click the edit icon to customize.",
              "yatra"
            ) })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "label",
              {
                htmlFor: "description",
                className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                children: [
                  __("Description", "yatra"),
                  " ",
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
                ]
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              HelpText,
              {
                text: __(
                  "A brief description of this category and who it applies to",
                  "yatra"
                ),
                className: "mb-2"
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "textarea",
              {
                id: "description",
                value: formData.description,
                onChange: (e) => handleFieldChange("description", e.target.value),
                placeholder: __(
                  "e.g., Standard adult pricing for travelers aged 18 and above",
                  "yatra"
                ),
                rows: 3,
                className: `flex w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm ring-offset-white file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-gray-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 dark:border-gray-600 dark:bg-gray-800 dark:ring-offset-gray-900 dark:placeholder:text-gray-400 dark:focus-visible:ring-blue-400 resize-none ${errors.description ? "border-red-500" : ""}`,
                required: true
              }
            ),
            errors.description && /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "mt-1.5 text-sm text-red-600 dark:text-red-400 flex items-center gap-1", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(AlertCircle, { className: "w-4 h-4" }),
              errors.description
            ] })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5", children: __("Age Range", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              HelpText,
              {
                text: __(
                  "Specify the age range for this category (e.g., 0-4 for Infant, 5-17 for Child, 18+ for Adult). Leave empty if no age restriction.",
                  "yatra"
                ),
                className: "mb-2"
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-3", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "label",
                  {
                    htmlFor: "age_min",
                    className: "block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1.5",
                    children: __("Minimum Age", "yatra")
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Input,
                  {
                    id: "age_min",
                    type: "number",
                    min: "0",
                    value: formData.age_min,
                    onChange: (e) => handleFieldChange("age_min", e.target.value),
                    placeholder: __("e.g., 0, 5, 18", "yatra"),
                    className: errors.age_min ? "border-red-500" : ""
                  }
                ),
                errors.age_min && /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "mt-1.5 text-sm text-red-600 dark:text-red-400 flex items-center gap-1", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(AlertCircle, { className: "w-4 h-4" }),
                  errors.age_min
                ] })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "label",
                  {
                    htmlFor: "age_max",
                    className: "block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1.5",
                    children: __("Maximum Age", "yatra")
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Input,
                  {
                    id: "age_max",
                    type: "number",
                    min: "0",
                    value: formData.age_max,
                    onChange: (e) => handleFieldChange("age_max", e.target.value),
                    placeholder: __(
                      "e.g., 4, 17, leave empty for 18+",
                      "yatra"
                    ),
                    className: errors.age_max ? "border-red-500" : ""
                  }
                ),
                errors.age_max && /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "mt-1.5 text-sm text-red-600 dark:text-red-400 flex items-center gap-1", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(AlertCircle, { className: "w-4 h-4" }),
                  errors.age_max
                ] })
              ] })
            ] }),
            formData.age_min && formData.age_max && parseInt(formData.age_min) >= parseInt(formData.age_max) && /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "mt-1.5 text-sm text-yellow-600 dark:text-yellow-400 flex items-center gap-1", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(AlertCircle, { className: "w-4 h-4" }),
              __(
                "Minimum age should be less than maximum age",
                "yatra"
              )
            ] })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5", children: __("Pricing Mode", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              HelpText,
              {
                text: __(
                  "Choose how this traveler category is priced. Per person charges per traveler, while per group uses a flat price for a group booking.",
                  "yatra"
                ),
                className: "mb-2"
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              Select,
              {
                id: "pricing_mode",
                value: formData.pricing_mode,
                onChange: (e) => handleFieldChange(
                  "pricing_mode",
                  e.target.value
                ),
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "per_person", children: __("Per person", "yatra") }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "per_group", children: __("Per group", "yatra") })
                ]
              }
            ),
            formData.pricing_mode === "per_group" && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-3 space-y-2", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                HelpText,
                {
                  text: __(
                    "Optional group size limits for this category. These are used to validate bookings when this category is priced per group.",
                    "yatra"
                  ),
                  className: "mb-1"
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-3", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "label",
                    {
                      htmlFor: "min_pax",
                      className: "block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1.5",
                      children: __("Minimum Group Size", "yatra")
                    }
                  ),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    Input,
                    {
                      id: "min_pax",
                      type: "number",
                      min: "1",
                      value: formData.min_pax,
                      onChange: (e) => handleFieldChange("min_pax", e.target.value),
                      placeholder: __("e.g., 10", "yatra"),
                      className: errors.min_pax ? "border-red-500" : ""
                    }
                  ),
                  errors.min_pax && /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "mt-1.5 text-sm text-red-600 dark:text-red-400 flex items-center gap-1", children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(AlertCircle, { className: "w-4 h-4" }),
                    errors.min_pax
                  ] })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "label",
                    {
                      htmlFor: "max_pax",
                      className: "block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1.5",
                      children: __("Maximum Group Size", "yatra")
                    }
                  ),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    Input,
                    {
                      id: "max_pax",
                      type: "number",
                      min: "1",
                      value: formData.max_pax,
                      onChange: (e) => handleFieldChange("max_pax", e.target.value),
                      placeholder: __("e.g., 6 (optional)", "yatra"),
                      className: errors.max_pax ? "border-red-500" : ""
                    }
                  ),
                  errors.max_pax && /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "mt-1.5 text-sm text-red-600 dark:text-red-400 flex items-center gap-1", children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(AlertCircle, { className: "w-4 h-4" }),
                    errors.max_pax
                  ] })
                ] })
              ] })
            ] })
          ] })
        ] })
      ] }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Category Icon or Image", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "space-y-3", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            IconPicker,
            {
              value: formData.icon,
              onChange: (value) => handleFieldChange("icon", value),
              label: void 0,
              helpText: __(
                "Select an icon from the library or upload a custom image for this category.",
                "yatra"
              ),
              allowImageUpload: true,
              allowIconSelection: true,
              size: "md"
            }
          ) })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Status", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "space-y-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "label",
              {
                htmlFor: "status",
                className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                children: __("Status", "yatra")
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              HelpText,
              {
                text: __(
                  "Draft categories will not be available when creating trips",
                  "yatra"
                ),
                className: "mb-2"
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              Select,
              {
                id: "status",
                value: formData.status,
                onChange: (e) => handleFieldChange(
                  "status",
                  e.target.value
                ),
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "draft", children: __("Draft", "yatra") }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "publish", children: __("Publish", "yatra") }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "trash", children: __("Trash", "yatra") })
                ]
              }
            )
          ] }) })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-3", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-2", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Button,
            {
              type: "submit",
              disabled: isSubmitting,
              className: "flex-1 flex items-center justify-center gap-2",
              children: isSubmitting ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Loader2, { className: "w-4 h-4 animate-spin" }),
                __("Saving...", "yatra"),
                "..."
              ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Save, { className: "w-4 h-4" }),
                isEditMode ? __("Update Category", "yatra") : __("Create Category", "yatra")
              ] })
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Button,
            {
              type: "button",
              variant: "outline",
              onClick: handleCancel,
              disabled: isSubmitting,
              children: __("Cancel", "yatra")
            }
          )
        ] }) }) }) })
      ] })
    ] }) }) })
  ] });
};
const AvailabilityCalendar = ({
  dates,
  tripType = "multi_day",
  currency = "USD",
  onDateClick
}) => {
  const { navigate } = useNavigate();
  const [currentMonth, setCurrentMonth] = reactExports.useState(/* @__PURE__ */ new Date());
  const datesByDate = reactExports.useMemo(() => {
    const grouped = {};
    dates.forEach((date2) => {
      const key2 = date2.departure_date;
      if (!grouped[key2]) {
        grouped[key2] = [];
      }
      grouped[key2].push(date2);
    });
    return grouped;
  }, [dates]);
  const getDateAvailability = (date2) => {
    const dateKey = format(date2, "yyyy-MM-dd");
    return datesByDate[dateKey] || [];
  };
  const getDateColorClass = (dateAvailabilities) => {
    if (dateAvailabilities.length === 0) {
      return "bg-gray-50 dark:bg-gray-800 border-gray-200 dark:border-gray-700";
    }
    if (dateAvailabilities.some((d) => d.is_blocked)) {
      return "bg-red-100 dark:bg-red-900/20 border-red-300 dark:border-red-800";
    }
    if (dateAvailabilities.every(
      (d) => d.available_seats === 0 || d.status === "sold_out"
    )) {
      return "bg-gray-200 dark:bg-gray-700 border-gray-300 dark:border-gray-600";
    }
    const hasLowAvailability = dateAvailabilities.some((d) => {
      const threshold2 = d.alert_threshold || 5;
      return d.available_seats > 0 && d.available_seats <= threshold2;
    });
    if (hasLowAvailability) {
      return "bg-yellow-100 dark:bg-yellow-900/20 border-yellow-300 dark:border-yellow-800";
    }
    if (dateAvailabilities.some((d) => d.status === "limited")) {
      return "bg-orange-100 dark:bg-orange-900/20 border-orange-300 dark:border-orange-800";
    }
    return "bg-green-100 dark:bg-green-900/20 border-green-300 dark:border-green-800";
  };
  const monthStart = startOfMonth(currentMonth);
  const monthEnd = endOfMonth(currentMonth);
  const calendarStart = startOfWeek(monthStart, { weekStartsOn: 0 });
  const calendarEnd = endOfWeek(monthEnd, { weekStartsOn: 0 });
  const days = eachDayOfInterval({ start: calendarStart, end: calendarEnd });
  const previousMonth = () => {
    setCurrentMonth(subMonths(currentMonth));
  };
  const nextMonth = () => {
    setCurrentMonth(addMonths(currentMonth, 1));
  };
  const weekDays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
  const formatTime = (timeString) => {
    if (!timeString) return "";
    const [hours, minutes] = timeString.split(":");
    const hour = parseInt(hours);
    const ampm = hour >= 12 ? "PM" : "AM";
    return `${hour % 12 || 12}:${minutes} ${ampm}`;
  };
  const formatTimeForDisplay = (timeString) => {
    if (!timeString) return "";
    const time2 = /* @__PURE__ */ new Date(`1970-01-01T${timeString}`);
    const timeStringFormatted = time2.toLocaleTimeString("en-US", {
      hour12: false,
      hour: "numeric",
      minute: "2-digit"
    });
    return timeStringFormatted;
  };
  const getCurrencySymbol2 = (currency2) => {
    const symbols = {
      USD: "$",
      EUR: "€",
      GBP: "£",
      INR: "₹"
    };
    return symbols[currency2] || currency2;
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-4", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        Button,
        {
          variant: "outline",
          size: "sm",
          onClick: previousMonth,
          className: "h-8 w-8 p-0",
          children: /* @__PURE__ */ jsxRuntimeExports.jsx(ChevronLeft, { className: "w-4 h-4" })
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-lg font-semibold text-gray-900 dark:text-white", children: format(currentMonth, "MMMM yyyy") }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        Button,
        {
          variant: "outline",
          size: "sm",
          onClick: nextMonth,
          className: "h-8 w-8 p-0",
          children: /* @__PURE__ */ jsxRuntimeExports.jsx(ChevronRight, { className: "w-4 h-4" })
        }
      )
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid grid-cols-7 bg-gray-50 dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700", children: weekDays.map((day) => /* @__PURE__ */ jsxRuntimeExports.jsx(
        "div",
        {
          className: "p-2 text-center text-xs font-medium text-gray-700 dark:text-gray-300 border-r border-gray-200 dark:border-gray-700 last:border-r-0",
          children: day
        },
        day
      )) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid grid-cols-7", children: days.map((day, dayIdx) => {
        const isCurrentMonth = isSameMonth(day, currentMonth);
        const isTodayDate = isToday(day);
        const dateAvailabilities = getDateAvailability(day);
        const colorClass = getDateColorClass(dateAvailabilities);
        const hasMultipleSlots = dateAvailabilities.length > 1;
        return /* @__PURE__ */ jsxRuntimeExports.jsx(
          "div",
          {
            className: `
                  min-h-[80px] p-1 border-r border-b border-gray-200 dark:border-gray-700
                  ${isCurrentMonth ? "" : "bg-gray-50 dark:bg-gray-900/50 opacity-50"}
                  ${colorClass}
                `,
            children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col h-full", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between mb-1", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "span",
                  {
                    className: `
                        text-xs font-medium
                        ${isTodayDate ? "bg-blue-600 text-white rounded-full w-5 h-5 flex items-center justify-center" : ""}
                        ${isCurrentMonth ? "text-gray-900 dark:text-white" : "text-gray-400 dark:text-gray-600"}
                      `,
                    children: isTodayDate ? format(day, "d") : format(day, "d")
                  }
                ),
                hasMultipleSlots && /* @__PURE__ */ jsxRuntimeExports.jsx(Badge, { className: "text-xs bg-blue-100 text-blue-700 dark:bg-blue-900/20 dark:text-blue-400", children: dateAvailabilities.length })
              ] }),
              isCurrentMonth && dateAvailabilities.length > 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1 space-y-1 relative", children: [
                dateAvailabilities.slice(0, 2).map((availability) => {
                  const isBlocked = availability.is_blocked;
                  const isSoldOut = availability.available_seats === 0;
                  const isLow = availability.available_seats > 0 && availability.available_seats <= (availability.alert_threshold || 5);
                  return /* @__PURE__ */ jsxRuntimeExports.jsxs(Popover, { children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(PopoverTrigger, { asChild: true, children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
                      "button",
                      {
                        type: "button",
                        className: "w-full text-left p-1 rounded text-xs hover:bg-white/50 dark:hover:bg-gray-800/50 transition-colors cursor-pointer",
                        children: [
                          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1 mb-0.5", children: [
                            tripType === "single_day" && availability.departure_time && /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs font-medium", children: formatTime(
                              availability.departure_time
                            ) }),
                            isBlocked && /* @__PURE__ */ jsxRuntimeExports.jsx(Ban, { className: "w-3 h-3 text-red-600 dark:text-red-400" }),
                            isLow && !isBlocked && /* @__PURE__ */ jsxRuntimeExports.jsx(Bell, { className: "w-3 h-3 text-yellow-600 dark:text-yellow-400" })
                          ] }),
                          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1", children: [
                            /* @__PURE__ */ jsxRuntimeExports.jsx(Users, { className: "w-3 h-3 text-gray-400" }),
                            /* @__PURE__ */ jsxRuntimeExports.jsx(
                              "span",
                              {
                                className: `text-xs font-semibold ${isSoldOut ? "text-red-600 dark:text-red-400" : isLow ? "text-yellow-600 dark:text-yellow-400" : "text-green-600 dark:text-green-400"}`,
                                children: availability.available_seats
                              }
                            ),
                            availability.waitlist_count > 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-xs text-blue-600 dark:text-blue-400", children: [
                              "+",
                              availability.waitlist_count
                            ] })
                          ] })
                        ]
                      }
                    ) }),
                    /* @__PURE__ */ jsxRuntimeExports.jsx(
                      PopoverContent,
                      {
                        className: "w-80 p-4 z-50",
                        align: "start",
                        side: "right",
                        children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
                          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
                            /* @__PURE__ */ jsxRuntimeExports.jsx("h4", { className: "font-semibold text-sm text-gray-900 dark:text-white", children: format(
                              parseISO(availability.departure_date),
                              "EEEE, MMMM d, yyyy"
                            ) }),
                            /* @__PURE__ */ jsxRuntimeExports.jsx(
                              Button,
                              {
                                variant: "ghost",
                                size: "sm",
                                onClick: () => {
                                  if (onDateClick) {
                                    onDateClick(availability);
                                  } else {
                                    navigate({
                                      subpage: "trips",
                                      tab: "availability",
                                      action: "edit",
                                      id: availability.id
                                    });
                                  }
                                },
                                className: "h-7 w-7 p-0",
                                children: /* @__PURE__ */ jsxRuntimeExports.jsx(PenSquare, { className: "w-3.5 h-3.5" })
                              }
                            )
                          ] }),
                          tripType === "single_day" && availability.departure_time && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-xs text-gray-600 dark:text-gray-400", children: [
                            __("Time", "yatra"),
                            ":",
                            " ",
                            formatTimeForDisplay(
                              availability.departure_time
                            ),
                            " ",
                            "-",
                            " ",
                            availability.arrival_time ? formatTimeForDisplay(
                              availability.arrival_time
                            ) : ""
                          ] }),
                          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-2 gap-3 text-xs", children: [
                            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-gray-500 dark:text-gray-400 mb-1", children: __("Capacity", "yatra") }),
                              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "font-semibold text-gray-900 dark:text-white", children: availability.total_seats })
                            ] }),
                            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-gray-500 dark:text-gray-400 mb-1", children: __("Booked", "yatra") }),
                              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "font-semibold text-orange-600 dark:text-orange-400", children: availability.booked_seats })
                            ] }),
                            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-gray-500 dark:text-gray-400 mb-1", children: __("Available", "yatra") }),
                              /* @__PURE__ */ jsxRuntimeExports.jsx(
                                "div",
                                {
                                  className: `font-semibold ${availability.available_seats === 0 ? "text-red-600 dark:text-red-400" : availability.available_seats <= (availability.alert_threshold || 5) ? "text-yellow-600 dark:text-yellow-400" : "text-green-600 dark:text-green-400"}`,
                                  children: availability.available_seats
                                }
                              )
                            ] }),
                            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-gray-500 dark:text-gray-400 mb-1", children: __("Price", "yatra") }),
                              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "font-semibold text-gray-900 dark:text-white", children: [
                                getCurrencySymbol2(currency),
                                parseFloat(
                                  availability.discounted_price || availability.original_price
                                ).toLocaleString()
                              ] })
                            ] })
                          ] }),
                          availability.waitlist_count > 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2 text-xs", children: [
                            /* @__PURE__ */ jsxRuntimeExports.jsx(Users, { className: "w-4 h-4 text-blue-600 dark:text-blue-400" }),
                            /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-gray-600 dark:text-gray-400", children: [
                              availability.waitlist_count,
                              " ",
                              __("people on waitlist", "yatra")
                            ] })
                          ] }),
                          availability.is_blocked && availability.block_reason && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2 text-xs text-red-600 dark:text-red-400", children: [
                            /* @__PURE__ */ jsxRuntimeExports.jsx(Ban, { className: "w-4 h-4" }),
                            /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { children: [
                              __("Blocked", "yatra"),
                              ":",
                              " ",
                              availability.block_reason
                            ] })
                          ] }),
                          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2 pt-2 border-t border-gray-200 dark:border-gray-700", children: [
                            /* @__PURE__ */ jsxRuntimeExports.jsxs(
                              Button,
                              {
                                variant: "outline",
                                size: "sm",
                                onClick: () => {
                                  if (onDateClick) {
                                    onDateClick(availability);
                                  } else {
                                    navigate({
                                      subpage: "trips",
                                      tab: "availability",
                                      action: "edit",
                                      id: availability.id
                                    });
                                  }
                                },
                                className: "flex-1 text-xs h-7",
                                children: [
                                  /* @__PURE__ */ jsxRuntimeExports.jsx(PenSquare, { className: "w-3 h-3 mr-1" }),
                                  __("Edit", "yatra")
                                ]
                              }
                            ),
                            /* @__PURE__ */ jsxRuntimeExports.jsxs(
                              Button,
                              {
                                variant: "outline",
                                size: "sm",
                                onClick: () => navigate({
                                  subpage: "trips",
                                  tab: "availability",
                                  action: "view",
                                  id: availability.id
                                }),
                                className: "flex-1 text-xs h-7",
                                children: [
                                  /* @__PURE__ */ jsxRuntimeExports.jsx(Eye, { className: "w-3 h-3 mr-1" }),
                                  __("View", "yatra")
                                ]
                              }
                            )
                          ] })
                        ] })
                      }
                    )
                  ] }, availability.id);
                }),
                dateAvailabilities.length > 2 && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-xs text-gray-500 dark:text-gray-400 text-center pt-1", children: [
                  "+",
                  dateAvailabilities.length - 2,
                  " ",
                  __("more", "yatra")
                ] })
              ] })
            ] })
          },
          dayIdx
        );
      }) })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-wrap items-center gap-4 text-xs", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-4 h-4 rounded border-2 border-green-300 dark:border-green-800 bg-green-100 dark:bg-green-900/20" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-600 dark:text-gray-400", children: __("Available", "yatra") })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-4 h-4 rounded border-2 border-yellow-300 dark:border-yellow-800 bg-yellow-100 dark:bg-yellow-900/20" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-600 dark:text-gray-400", children: __("Low Availability", "yatra") })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-4 h-4 rounded border-2 border-orange-300 dark:border-orange-800 bg-orange-100 dark:bg-orange-900/20" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-600 dark:text-gray-400", children: __("Limited", "yatra") })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-4 h-4 rounded border-2 border-gray-300 dark:border-gray-600 bg-gray-200 dark:bg-gray-700" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-600 dark:text-gray-400", children: __("Sold Out", "yatra") })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-4 h-4 rounded border-2 border-red-300 dark:border-red-800 bg-red-100 dark:bg-red-900/20" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-600 dark:text-gray-400", children: __("Blocked", "yatra") })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-4 h-4 rounded border-2 border-gray-300 dark:border-gray-600 bg-gray-200 dark:bg-gray-700" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-600 dark:text-gray-400", children: __("Not Available", "yatra") })
      ] })
    ] })
  ] });
};
const dayNames = [
  { value: 0, label: "Sunday" },
  { value: 1, label: "Monday" },
  { value: 2, label: "Tuesday" },
  { value: 3, label: "Wednesday" },
  { value: 4, label: "Thursday" },
  { value: 5, label: "Friday" },
  { value: 6, label: "Saturday" }
];
const RecurringRules = ({
  tripId,
  tripName,
  tripType = "multi_day",
  pricingType = "regular",
  onAddRule,
  onEditRule
}) => {
  var _a;
  const isSingleDayTrip = tripType === "single_day";
  const isTravelerBased = pricingType === "traveler_based";
  const queryClient2 = useQueryClient();
  const { showToast } = useToast();
  const adminCurrency = typeof window !== "undefined" && ((_a = window.yatraAdmin) == null ? void 0 : _a.currency) || "USD";
  const [searchTerm, setSearchTerm] = reactExports.useState("");
  const [statusFilter, setStatusFilter] = reactExports.useState("all");
  const [selectedIds, setSelectedIds] = reactExports.useState([]);
  const [bulkAction, setBulkAction] = reactExports.useState("");
  const [showColumnsDropdown, setShowColumnsDropdown] = reactExports.useState(false);
  const [visibleColumns, setVisibleColumns] = reactExports.useState({
    name: true,
    pattern: true,
    start_date: true,
    end_date: true,
    capacity: true,
    generated: true,
    price: true,
    status: true
  });
  const [deleteConfirm, setDeleteConfirm] = reactExports.useState({
    isOpen: false,
    rule: null
  });
  const [duplicateConfirm, setDuplicateConfirm] = reactExports.useState({
    isOpen: false,
    rule: null
  });
  const formatRulePattern = (rule) => {
    var _a2;
    switch (rule.rule_type) {
      case "weekly":
        const days = (rule.days_of_week_array || []).map((d) => {
          var _a3;
          return (_a3 = dayNames.find((dn) => dn.value === d)) == null ? void 0 : _a3.label.slice(0, 3);
        }).filter(Boolean).join(", ");
        return `Every ${days}`;
      case "monthly":
        return `${rule.week_of_month || ""} ${((_a2 = dayNames.find((d) => d.value === rule.day_of_week)) == null ? void 0 : _a2.label) || ""} of month`;
      case "interval":
        return `Every ${rule.interval_days} days`;
      default:
        return "Unknown pattern";
    }
  };
  const { data: countsData } = useQuery({
    queryKey: ["recurring-availability", "counts", tripId],
    queryFn: async () => {
      const response = await apiClient.get("/recurring-availability/counts", {
        params: {
          trip_id: tripId
        }
      });
      return response || { all: 0, active: 0, inactive: 0 };
    },
    enabled: !!tripId,
    staleTime: 0,
    gcTime: 0
  });
  const statusCounts = countsData || { all: 0, active: 0, inactive: 0 };
  const { data: rulesData, isLoading } = useQuery({
    queryKey: ["recurring-availability", tripId],
    queryFn: async () => {
      const response = await apiClient.get("/recurring-availability", {
        params: {
          trip_id: tripId
        }
      });
      return {
        rules: (response == null ? void 0 : response.data) || [],
        total: (response == null ? void 0 : response.total) || 0
      };
    },
    enabled: !!tripId,
    staleTime: 0,
    // Always fetch fresh data
    gcTime: 0
    // Don't cache the data (replaces cacheTime in newer versions)
  });
  const allRules = (rulesData == null ? void 0 : rulesData.rules) || [];
  const rules = reactExports.useMemo(() => {
    let filtered = allRules;
    if (statusFilter !== "all") {
      filtered = filtered.filter(
        (r2) => r2.status === statusFilter
      );
    }
    if (searchTerm) {
      const search2 = searchTerm.toLowerCase();
      filtered = filtered.filter(
        (r2) => r2.name && r2.name.toLowerCase().includes(search2) || formatRulePattern(r2).toLowerCase().includes(search2)
      );
    }
    return filtered;
  }, [allRules, statusFilter, searchTerm]);
  const deleteMutation = useMutation({
    mutationFn: async (id) => {
      return await apiClient.delete(`/recurring-availability/${id}`);
    },
    onSuccess: () => {
      queryClient2.invalidateQueries({ queryKey: ["recurring-availability"] });
      showToast(__("Recurring rule deleted successfully", "yatra"), "success");
      setDeleteConfirm({ isOpen: false, rule: null });
      setSelectedIds([]);
    },
    onError: (error) => {
      showToast(
        (error == null ? void 0 : error.message) || __("Failed to delete rule", "yatra"),
        "error"
      );
    }
  });
  const bulkDeleteMutation = useMutation({
    mutationFn: async (ids) => {
      await Promise.all(
        ids.map((id) => apiClient.delete(`/recurring-availability/${id}`))
      );
    },
    onSuccess: () => {
      queryClient2.invalidateQueries({ queryKey: ["recurring-availability"] });
      showToast(__("Rules deleted successfully", "yatra"), "success");
      setSelectedIds([]);
    },
    onError: (error) => {
      showToast(
        (error == null ? void 0 : error.message) || __("Failed to delete rules", "yatra"),
        "error"
      );
    }
  });
  const duplicateMutation = useMutation({
    mutationFn: async (id) => {
      const response = await apiClient.post(
        `/recurring-availability/${id}/duplicate`
      );
      return response;
    },
    onSuccess: () => {
      queryClient2.invalidateQueries({ queryKey: ["recurring-availability"] });
      showToast(__("Rule duplicated successfully", "yatra"), "success");
      setDuplicateConfirm({ isOpen: false, rule: null });
    },
    onError: (error) => {
      showToast(
        (error == null ? void 0 : error.message) || __("Failed to duplicate rule", "yatra"),
        "error"
      );
    }
  });
  const handleBulkApply = () => {
    if (!bulkAction || selectedIds.length === 0) {
      showToast(__("Please select rules and an action", "yatra"), "warning");
      return;
    }
    switch (bulkAction) {
      case "delete":
        if (confirm(
          __(
            "Are you sure you want to delete {count} rule(s)?",
            "yatra"
          ).replace("{count}", selectedIds.length.toString())
        )) {
          bulkDeleteMutation.mutate(selectedIds.map((id) => id.toString()));
        }
        break;
    }
    setBulkAction("");
  };
  const toggleColumn = (key2) => {
    setVisibleColumns((prev) => ({
      ...prev,
      [key2]: !prev[key2]
    }));
  };
  const formatDate2 = (dateString) => {
    if (!dateString) return "--";
    try {
      const date2 = new Date(dateString);
      return date2.toLocaleDateString("en-US", {
        year: "numeric",
        month: "short",
        day: "numeric"
      });
    } catch {
      return dateString;
    }
  };
  const getStatusBadge = (status) => {
    const statusConfig = {
      active: {
        label: __("Active", "yatra"),
        className: "bg-green-100 text-green-700 dark:bg-green-900/20 dark:text-green-400",
        icon: /* @__PURE__ */ jsxRuntimeExports.jsx(CheckCircle, { className: "w-3 h-3" })
      },
      inactive: {
        label: __("Inactive", "yatra"),
        className: "bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-400",
        icon: /* @__PURE__ */ jsxRuntimeExports.jsx(XCircle, { className: "w-3 h-3" })
      }
    };
    const config2 = statusConfig[status] || statusConfig.inactive;
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(Badge, { className: `${config2.className} flex items-center gap-1`, children: [
      config2.icon,
      config2.label
    ] });
  };
  const tableColumns = reactExports.useMemo(() => {
    const cols = [];
    if (visibleColumns.name) {
      cols.push({
        key: "name",
        label: __("Rule Name", "yatra"),
        visible: visibleColumns.name,
        render: (rule) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "button",
            {
              onClick: () => onEditRule(rule.id),
              className: "text-sm font-medium text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300 text-left hover:underline",
              children: rule.name || formatRulePattern(rule)
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs text-gray-500 dark:text-gray-400", children: rule.rule_type === "weekly" ? __("Weekly", "yatra") : rule.rule_type === "monthly" ? __("Monthly", "yatra") : __("Interval", "yatra") })
        ] })
      });
    }
    if (visibleColumns.pattern) {
      cols.push({
        key: "pattern",
        label: __("Pattern", "yatra"),
        visible: visibleColumns.pattern,
        render: (rule) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1 text-sm text-gray-700 dark:text-gray-300", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(RefreshCw, { className: "w-3 h-3" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: formatRulePattern(rule) })
        ] })
      });
    }
    if (visibleColumns.start_date) {
      cols.push({
        key: "start_date",
        label: __("Start Date", "yatra"),
        visible: visibleColumns.start_date,
        render: (rule) => /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-900 dark:text-white", children: formatDate2(rule.start_date) })
      });
    }
    if (visibleColumns.end_date) {
      cols.push({
        key: "end_date",
        label: __("End Date", "yatra"),
        visible: visibleColumns.end_date,
        render: (rule) => /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-500 dark:text-gray-400", children: rule.end_date ? formatDate2(rule.end_date) : __("Ongoing", "yatra") })
      });
    }
    if (visibleColumns.capacity) {
      cols.push({
        key: "capacity",
        label: __("Capacity", "yatra"),
        visible: visibleColumns.capacity,
        render: (rule) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col items-center", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm font-medium text-gray-900 dark:text-white", children: rule.seats_total || 0 }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs text-gray-500 dark:text-gray-400", children: __("total", "yatra") })
        ] })
      });
    }
    if (visibleColumns.generated) {
      cols.push({
        key: "generated",
        label: __("Generated", "yatra"),
        visible: visibleColumns.generated,
        render: (rule) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col items-center", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm font-semibold text-blue-600 dark:text-blue-400", children: rule.generated_count || 0 }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs text-gray-500 dark:text-gray-400", children: __("dates", "yatra") })
        ] })
      });
    }
    if (visibleColumns.price) {
      cols.push({
        key: "price",
        label: __("Price", "yatra"),
        visible: visibleColumns.price,
        render: (rule) => /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm font-semibold text-gray-900 dark:text-white", children: rule.sale_price ? formatYatraMoney(Number(rule.sale_price) || 0, adminCurrency, {
          zeroAsUnknown: false
        }) : rule.original_price ? formatYatraMoney(
          Number(rule.original_price) || 0,
          adminCurrency,
          { zeroAsUnknown: false }
        ) : formatYatraMoney(0, adminCurrency, { zeroAsUnknown: false }) })
      });
    }
    if (visibleColumns.status) {
      cols.push({
        key: "status",
        label: __("Status", "yatra"),
        visible: visibleColumns.status,
        render: (rule) => getStatusBadge(rule.status)
      });
    }
    return cols;
  }, [
    visibleColumns,
    formatRulePattern,
    formatDate2,
    getStatusBadge,
    adminCurrency
  ]);
  const toggleStatusMutation = useMutation({
    mutationFn: async ({
      id,
      status
    }) => {
      return await apiClient.put(`/recurring-availability/${id}`, { status });
    },
    onSuccess: () => {
      queryClient2.invalidateQueries({ queryKey: ["recurring-availability"] });
      showToast(__("Rule status updated successfully", "yatra"), "success");
    },
    onError: (error) => {
      showToast(
        (error == null ? void 0 : error.message) || __("Failed to update rule status", "yatra"),
        "error"
      );
    }
  });
  const tableActions = reactExports.useMemo(
    () => [
      {
        key: "edit",
        label: __("Edit", "yatra"),
        icon: /* @__PURE__ */ jsxRuntimeExports.jsx(PenSquare, { className: "w-4 h-4" }),
        onClick: (rule) => onEditRule(rule.id)
      },
      {
        key: "set-inactive",
        label: __("Set Inactive", "yatra"),
        icon: /* @__PURE__ */ jsxRuntimeExports.jsx(XCircle, { className: "w-4 h-4" }),
        onClick: (rule) => {
          toggleStatusMutation.mutate({ id: rule.id, status: "inactive" });
        },
        condition: (rule) => rule.status === "active"
      },
      {
        key: "set-active",
        label: __("Set Active", "yatra"),
        icon: /* @__PURE__ */ jsxRuntimeExports.jsx(CheckCircle, { className: "w-4 h-4" }),
        onClick: (rule) => {
          toggleStatusMutation.mutate({ id: rule.id, status: "active" });
        },
        condition: (rule) => rule.status === "inactive"
      },
      {
        key: "duplicate",
        label: __("Duplicate", "yatra"),
        icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Copy, { className: "w-4 h-4" }),
        onClick: (rule) => setDuplicateConfirm({ isOpen: true, rule })
      },
      {
        key: "delete",
        label: __("Delete", "yatra"),
        icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "w-4 h-4" }),
        onClick: (rule) => setDeleteConfirm({ isOpen: true, rule }),
        variant: "destructive"
      }
    ],
    [toggleStatusMutation, onEditRule]
  );
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-6", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      ConfirmationDialog,
      {
        isOpen: deleteConfirm.isOpen,
        onClose: () => setDeleteConfirm({ isOpen: false, rule: null }),
        onConfirm: () => {
          if (deleteConfirm.rule) {
            deleteMutation.mutate(deleteConfirm.rule.id);
          }
        },
        title: __("Delete Recurring Rule", "yatra"),
        message: deleteConfirm.rule ? __(
          'Are you sure you want to delete the rule "{name}"? This action cannot be undone.',
          "yatra"
        ).replace(
          "{name}",
          deleteConfirm.rule.name || formatRulePattern(deleteConfirm.rule)
        ) : __(
          "Are you sure you want to delete this rule? This action cannot be undone.",
          "yatra"
        ),
        confirmText: __("Delete", "yatra"),
        cancelText: __("Cancel", "yatra"),
        variant: "danger",
        isLoading: deleteMutation.isPending
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      ConfirmationDialog,
      {
        isOpen: duplicateConfirm.isOpen,
        onClose: () => setDuplicateConfirm({ isOpen: false, rule: null }),
        onConfirm: () => {
          if (duplicateConfirm.rule) {
            duplicateMutation.mutate(duplicateConfirm.rule.id);
          }
        },
        title: __("Duplicate Recurring Rule", "yatra"),
        message: __(
          "This will create a copy of this rule. You can edit it after creation.",
          "yatra"
        ),
        confirmText: __("Duplicate", "yatra"),
        cancelText: __("Cancel", "yatra"),
        isLoading: duplicateMutation.isPending
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-lg font-medium text-gray-900 dark:text-white", children: __("Recurring Rules", "yatra") }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          Badge,
          {
            className: isSingleDayTrip ? "bg-purple-100 text-purple-700 dark:bg-purple-900/20 dark:text-purple-400" : "bg-indigo-100 text-indigo-700 dark:bg-indigo-900/20 dark:text-indigo-400",
            children: isSingleDayTrip ? __("Single-Day Trip", "yatra") : __("Multi-Day Trip", "yatra")
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          Badge,
          {
            className: isTravelerBased ? "bg-green-100 text-green-700 dark:bg-green-900/20 dark:text-green-400" : "bg-gray-100 text-gray-700 dark:bg-gray-900/20 dark:text-gray-400",
            children: isTravelerBased ? __("Traveler-Based Pricing", "yatra") : __("Regular Pricing", "yatra")
          }
        )
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(Button, { variant: "outline", onClick: onAddRule, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Plus, { className: "w-4 h-4 mr-2" }),
        isSingleDayTrip ? __("Add Time Slots Rule", "yatra") : __("Add Recurring Rule", "yatra")
      ] })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-500 dark:text-gray-400", children: isSingleDayTrip ? __(
      "Create recurring time slots for your single-day trip (supports multiple time slots per day)",
      "yatra"
    ) : __(
      "Automatically generate availability dates based on patterns",
      "yatra"
    ) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "pt-6", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-3 gap-4", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2", children: __("Search", "yatra") }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Search, { className: "absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Input,
            {
              type: "text",
              value: searchTerm,
              onChange: (e) => setSearchTerm(e.target.value),
              placeholder: __("Search rules...", "yatra"),
              className: "pl-10"
            }
          )
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2", children: __("Status", "yatra") }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Select,
          {
            value: statusFilter,
            onChange: (e) => setStatusFilter(e.target.value),
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "all", children: __("All Status", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "active", children: __("Active", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "inactive", children: __("Inactive", "yatra") })
            ]
          }
        )
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex items-end", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Button,
        {
          variant: "outline",
          onClick: () => {
            setSearchTerm("");
            setStatusFilter("all");
          },
          className: "w-full",
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(X, { className: "w-4 h-4 mr-2" }),
            __("Clear Filters", "yatra")
          ]
        }
      ) })
    ] }) }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      BulkActionToolbar,
      {
        selectedIds,
        bulkAction,
        setBulkAction,
        onApply: handleBulkApply,
        onClearSelection: () => setSelectedIds([]),
        statusFilter,
        setStatusFilter,
        statusOptions: [
          { key: "all", label: __("All", "yatra"), count: statusCounts.all },
          {
            key: "active",
            label: __("Active", "yatra"),
            count: statusCounts.active
          },
          {
            key: "inactive",
            label: __("Inactive", "yatra"),
            count: statusCounts.inactive
          }
        ],
        showColumnsDropdown,
        setShowColumnsDropdown,
        columnOptions: [
          {
            key: "name",
            label: __("Rule Name", "yatra"),
            visible: visibleColumns.name
          },
          {
            key: "pattern",
            label: __("Pattern", "yatra"),
            visible: visibleColumns.pattern
          },
          {
            key: "start_date",
            label: __("Start Date", "yatra"),
            visible: visibleColumns.start_date
          },
          {
            key: "end_date",
            label: __("End Date", "yatra"),
            visible: visibleColumns.end_date
          },
          {
            key: "capacity",
            label: __("Capacity", "yatra"),
            visible: visibleColumns.capacity
          },
          {
            key: "generated",
            label: __("Generated", "yatra"),
            visible: visibleColumns.generated
          },
          {
            key: "price",
            label: __("Price", "yatra"),
            visible: visibleColumns.price
          },
          {
            key: "status",
            label: __("Status", "yatra"),
            visible: visibleColumns.status
          }
        ],
        onToggleColumn: (columnKey) => toggleColumn(columnKey),
        bulkMutationPending: bulkDeleteMutation.isPending,
        totalItems: rules.length,
        bulkActionOptions: [{ value: "delete", label: __("Delete", "yatra") }]
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "pt-6", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mb-6", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-lg font-semibold text-gray-900 dark:text-white", children: __("Recurring Rules", "yatra") }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-600 dark:text-gray-400 mt-1", children: tripName && /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
          __("Managing availability for", "yatra"),
          " ",
          /* @__PURE__ */ jsxRuntimeExports.jsx("strong", { children: tripName }),
          rules.length > 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "ml-2", children: [
            "(",
            rules.length,
            " ",
            rules.length === 1 ? __("rule", "yatra") : __("rules", "yatra"),
            ")"
          ] })
        ] }) })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        Table,
        {
          data: rules,
          columns: tableColumns,
          actions: tableActions,
          isLoading,
          isError: false,
          selectedItemIds: selectedIds,
          onSelectItem: (id, checked) => {
            if (checked) {
              setSelectedIds([...selectedIds, id]);
            } else {
              setSelectedIds(selectedIds.filter((sid) => sid !== id));
            }
          },
          onSelectAll: (checked) => {
            if (checked) {
              setSelectedIds(rules.map((r2) => r2.id));
            } else {
              setSelectedIds([]);
            }
          },
          isAllSelected: selectedIds.length === rules.length && rules.length > 0,
          getItemId: (rule) => rule.id,
          emptyText: __("No recurring rules found", "yatra"),
          emptyDescription: __(
            "Create your first recurring rule to get started",
            "yatra"
          ),
          onCreateClick: onAddRule,
          skeletonRows: 5,
          capability: "yatra_view_trips"
        }
      )
    ] }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { className: "bg-blue-50 dark:bg-blue-900/10 border-blue-200 dark:border-blue-800", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "py-4", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start gap-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(AlertCircle, { className: "w-5 h-5 text-blue-600 dark:text-blue-400 mt-0.5 flex-shrink-0" }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("h5", { className: "font-medium text-blue-900 dark:text-blue-200 mb-1", children: __("How Recurring Rules Work", "yatra") }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("ul", { className: "text-sm text-blue-800 dark:text-blue-300 space-y-1", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { children: [
            "•",
            " ",
            __(
              "Dates are generated automatically based on your patterns",
              "yatra"
            )
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { children: [
            "•",
            " ",
            __(
              "Specific dates (added manually) take priority over generated dates",
              "yatra"
            )
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { children: [
            "•",
            " ",
            __(
              "Use excluded dates to skip holidays or special occasions",
              "yatra"
            )
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { children: [
            "•",
            " ",
            __(
              "Bookings for generated dates create specific availability entries",
              "yatra"
            )
          ] })
        ] })
      ] })
    ] }) }) })
  ] });
};
function mapApiRowToTrip(trip) {
  return {
    id: Number(trip.id),
    title: String(trip.title ?? ""),
    slug: String(trip.slug ?? ""),
    currency: String(trip.currency || "USD"),
    starting_location: trip.starting_location,
    ending_location: trip.ending_location,
    trip_type: trip.trip_type || "multi_day"
  };
}
function tripsFromAvailabilityQueryCached(raw) {
  if (raw == null) {
    return [];
  }
  if (Array.isArray(raw)) {
    return raw;
  }
  if (typeof raw === "object") {
    const o = raw;
    if (Array.isArray(o.trips)) {
      return o.trips;
    }
    let rows = [];
    if (Array.isArray(o.data)) {
      rows = o.data;
    } else if (o.data && typeof o.data === "object" && Array.isArray(o.data.data)) {
      rows = o.data.data;
    }
    return rows.map((t) => mapApiRowToTrip(t));
  }
  return [];
}
const Availability = () => {
  const { navigate } = useNavigate();
  const queryClient2 = useQueryClient();
  const { showToast } = useToast();
  const [urlKey, setUrlKey] = reactExports.useState(0);
  reactExports.useEffect(() => {
    const handleLocationChange = () => {
      setUrlKey((prev) => prev + 1);
    };
    window.addEventListener("popstate", handleLocationChange);
    const interval = setInterval(() => {
      const currentSearch = window.location.search;
      if (currentSearch !== window.__lastAvailabilitySearch) {
        window.__lastAvailabilitySearch = currentSearch;
        handleLocationChange();
      }
    }, 100);
    return () => {
      window.removeEventListener("popstate", handleLocationChange);
      clearInterval(interval);
    };
  }, []);
  const tripIdFromUrl = reactExports.useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    const tripId = params.get("trip_id");
    return tripId ? parseInt(tripId) : null;
  }, [urlKey]);
  const [selectedTripId, setSelectedTripId] = reactExports.useState(() => {
    const storedTripId = localStorage.getItem("yatra_selected_trip_id");
    if (storedTripId) {
      const parsed = parseInt(storedTripId, 10);
      if (!Number.isNaN(parsed)) {
        return parsed;
      }
    }
    return tripIdFromUrl;
  });
  reactExports.useEffect(() => {
    if (tripIdFromUrl && tripIdFromUrl !== selectedTripId) {
      setSelectedTripId(tripIdFromUrl);
      localStorage.setItem("yatra_selected_trip_id", tripIdFromUrl.toString());
    }
  }, [tripIdFromUrl, selectedTripId]);
  reactExports.useEffect(() => {
    if (selectedTripId) {
      localStorage.setItem("yatra_selected_trip_id", selectedTripId.toString());
    } else {
      localStorage.removeItem("yatra_selected_trip_id");
    }
  }, [selectedTripId]);
  const [viewMode, setViewMode] = reactExports.useState("list");
  const [tabMode, _setTabMode] = reactExports.useState(() => {
    const params = new URLSearchParams(window.location.search);
    const tabModeParam = params.get("tab_mode");
    return tabModeParam === "recurring" ? "recurring" : "specific";
  });
  const setTabMode = (mode) => {
    _setTabMode(mode);
    const params = new URLSearchParams(window.location.search);
    params.set("tab_mode", mode);
    const newUrl = `${window.location.pathname}?${params.toString()}`;
    window.history.replaceState({}, "", newUrl);
  };
  const [searchTerm, setSearchTerm] = reactExports.useState("");
  const [statusFilter, setStatusFilter] = reactExports.useState("all");
  const [monthFilter, setMonthFilter] = reactExports.useState("all");
  const [isSyncing, setIsSyncing] = reactExports.useState(false);
  const [lastSyncTime, setLastSyncTime] = reactExports.useState(null);
  const [showAlerts, setShowAlerts] = reactExports.useState(true);
  const [page, setPage] = reactExports.useState(1);
  const [selectedIds, setSelectedIds] = reactExports.useState([]);
  const [bulkAction, setBulkAction] = reactExports.useState("");
  const [showColumnsDropdown, setShowColumnsDropdown] = reactExports.useState(false);
  const [visibleColumns, setVisibleColumns] = reactExports.useState({
    departure: true,
    arrival: true,
    locations: true,
    capacity: true,
    booked: true,
    available: true,
    waitlist: true,
    price: true,
    status: true
    // Always show status column
  });
  const toggleColumn = (key2) => {
    setVisibleColumns((prev) => ({
      ...prev,
      [key2]: !prev[key2]
    }));
  };
  const { data: tripsData } = useQuery({
    queryKey: ["trips", "availability-dropdown", "v2"],
    queryFn: async () => {
      const response = await apiClient.get("/trips", {
        params: { per_page: 100, status: "publish" }
      });
      return tripsFromAvailabilityQueryCached(response);
    }
  });
  const tripsList = reactExports.useMemo(
    () => tripsFromAvailabilityQueryCached(tripsData),
    [tripsData]
  );
  const {
    data: availabilityData,
    isLoading,
    error: availabilityError
  } = useQuery({
    queryKey: ["availability", selectedTripId, monthFilter, page, searchTerm],
    queryFn: async () => {
      if (!selectedTripId) return { dates: [], total: 0 };
      const response = await apiClient.get("/availability", {
        params: {
          trip_id: selectedTripId,
          month: monthFilter !== "all" ? monthFilter : void 0,
          search: searchTerm || void 0,
          page,
          per_page: 50
        }
      });
      return {
        dates: ((response == null ? void 0 : response.dates) || []).map((date2) => {
          var _a, _b, _c, _d;
          return {
            id: date2.id.toString(),
            trip_id: date2.trip_id,
            departure_date: date2.departure_date,
            departure_time: date2.departure_time,
            arrival_date: date2.arrival_date || date2.departure_date,
            arrival_time: date2.arrival_time,
            total_seats: date2.total_seats || date2.seats_total || 0,
            booked_seats: date2.booked_seats || (date2.total_seats || date2.seats_total) - (date2.available_seats || date2.seats_available || 0),
            available_seats: date2.available_seats || date2.seats_available || 0,
            waitlist_count: date2.waitlist_count || date2.seats_waitlist || 0,
            seats_remaining: (date2.available_seats || date2.seats_available || 0) > 10 ? "10+" : (date2.available_seats || date2.seats_available || 0).toString(),
            original_price: ((_a = date2.original_price) == null ? void 0 : _a.toString()) || "0",
            discounted_price: ((_b = date2.discounted_price) == null ? void 0 : _b.toString()) || ((_c = date2.original_price) == null ? void 0 : _c.toString()) || "0",
            discount_percentage: ((_d = date2.discount_percentage) == null ? void 0 : _d.toString()) || "0",
            status: date2.status || "available",
            is_blocked: date2.is_blocked || date2.status === "blocked",
            block_reason: date2.block_reason,
            alert_threshold: date2.alert_threshold || 5,
            last_synced_at: date2.last_synced_at || date2.updated_at,
            from_location: date2.from_location,
            to_location: date2.to_location,
            created_at: date2.created_at,
            updated_at: date2.updated_at
          };
        }),
        total: (response == null ? void 0 : response.total) || 0
      };
    },
    enabled: !!selectedTripId
  });
  const deleteMutation = useMutation({
    mutationFn: async (id) => {
      return await apiClient.delete(`/availability/${id}`);
    },
    onSuccess: () => {
      queryClient2.invalidateQueries({ queryKey: ["availability"] });
      showToast(
        __("Availability date deleted successfully", "yatra"),
        "success"
      );
      setDeleteConfirm({ isOpen: false, date: null });
    },
    onError: (error) => {
      showToast(
        (error == null ? void 0 : error.message) || __("Failed to delete availability date", "yatra"),
        "error"
      );
    }
  });
  const formatDate2 = (dateString) => {
    const date2 = new Date(dateString);
    return date2.toLocaleDateString("en-US", {
      year: "numeric",
      month: "short",
      day: "numeric"
    });
  };
  const formatTime = (timeString) => {
    if (!timeString) return "";
    const [hours, minutes] = timeString.split(":");
    const hour = parseInt(hours);
    const ampm = hour >= 12 ? "PM" : "AM";
    const displayHour = hour % 12 || 12;
    return `${displayHour}:${minutes} ${ampm}`;
  };
  const getCurrencySymbol2 = (currency) => {
    const symbols = {
      USD: "$",
      EUR: "€",
      GBP: "£",
      INR: "₹"
    };
    return symbols[currency] || currency;
  };
  const getStatusBadge = (status, isBlocked) => {
    if (isBlocked) {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(Badge, { className: "text-xs bg-red-100 text-red-700 dark:bg-red-900/20 dark:text-red-400", children: __("Blocked", "yatra") });
    }
    switch (status) {
      case "available":
        return /* @__PURE__ */ jsxRuntimeExports.jsx(
          Badge,
          {
            variant: "success",
            className: "text-xs bg-green-100 text-green-700 dark:bg-green-900/20 dark:text-green-400",
            children: __("Available", "yatra")
          }
        );
      case "limited":
        return /* @__PURE__ */ jsxRuntimeExports.jsx(
          Badge,
          {
            variant: "warning",
            className: "text-xs bg-yellow-100 text-yellow-700 dark:bg-yellow-900/20 dark:text-yellow-400",
            children: __("Limited", "yatra")
          }
        );
      case "sold_out":
        return /* @__PURE__ */ jsxRuntimeExports.jsx(
          Badge,
          {
            variant: "error",
            className: "text-xs bg-red-100 text-red-700 dark:bg-red-900/20 dark:text-red-400",
            children: __("Sold Out", "yatra")
          }
        );
      case "closed":
        return /* @__PURE__ */ jsxRuntimeExports.jsx(
          Badge,
          {
            variant: "outline",
            className: "text-xs border-gray-300 text-gray-600 dark:border-gray-600 dark:text-gray-400",
            children: __("Closed", "yatra")
          }
        );
      case "blocked":
        return /* @__PURE__ */ jsxRuntimeExports.jsx(Badge, { className: "text-xs bg-red-100 text-red-700 dark:bg-red-900/20 dark:text-red-400", children: __("Blocked", "yatra") });
      case "cancelled":
        return /* @__PURE__ */ jsxRuntimeExports.jsx(Badge, { className: "text-xs bg-gray-100 text-gray-700 dark:bg-gray-900/20 dark:text-gray-400", children: __("Cancelled", "yatra") });
      default:
        return /* @__PURE__ */ jsxRuntimeExports.jsx(
          Badge,
          {
            variant: "outline",
            className: "text-xs border-gray-300 text-gray-600 dark:border-gray-600 dark:text-gray-400",
            children: status || "Unknown"
          }
        );
    }
  };
  const handleSync = async () => {
    setIsSyncing(true);
    try {
      await queryClient2.invalidateQueries({ queryKey: ["availability"] });
      setLastSyncTime(/* @__PURE__ */ new Date());
      showToast(
        __("Availability data synced successfully", "yatra"),
        "success"
      );
    } catch (error) {
      console.error("Sync failed:", error);
      showToast(__("Failed to sync availability data", "yatra"), "error");
    } finally {
      setIsSyncing(false);
    }
  };
  const selectedTrip = tripsList.find((t) => t.id === selectedTripId);
  const availabilityErrorContext = availabilityError ? getErrorContext(availabilityError) : null;
  const filteredDates = reactExports.useMemo(() => {
    if (!(availabilityData == null ? void 0 : availabilityData.dates)) return [];
    let filtered = [...availabilityData.dates];
    if (searchTerm) {
      const searchLower = searchTerm.toLowerCase();
      filtered = filtered.filter(
        (date2) => {
          var _a, _b, _c, _d;
          return date2.departure_date.includes(searchLower) || date2.arrival_date.includes(searchLower) || ((_a = date2.departure_time) == null ? void 0 : _a.toLowerCase().includes(searchLower)) || ((_b = date2.arrival_time) == null ? void 0 : _b.toLowerCase().includes(searchLower)) || ((_c = date2.from_location) == null ? void 0 : _c.toLowerCase().includes(searchLower)) || ((_d = date2.to_location) == null ? void 0 : _d.toLowerCase().includes(searchLower));
        }
      );
    }
    if (statusFilter !== "all") {
      filtered = filtered.filter((date2) => date2.status === statusFilter);
    }
    if (monthFilter !== "all" && (selectedTrip == null ? void 0 : selectedTrip.trip_type) !== "single_day") {
      const [year, month] = monthFilter.split("-");
      filtered = filtered.filter((date2) => {
        const dateObj = new Date(date2.departure_date);
        return dateObj.getFullYear() === parseInt(year) && dateObj.getMonth() === parseInt(month) - 1;
      });
    }
    return filtered;
  }, [availabilityData, searchTerm, statusFilter, monthFilter, selectedTrip]);
  const availableMonths = reactExports.useMemo(() => {
    if (!(availabilityData == null ? void 0 : availabilityData.dates) || (selectedTrip == null ? void 0 : selectedTrip.trip_type) === "single_day")
      return [];
    const months = /* @__PURE__ */ new Set();
    availabilityData.dates.forEach((date2) => {
      const dateObj = new Date(date2.departure_date);
      const monthKey = `${dateObj.getFullYear()}-${String(dateObj.getMonth() + 1).padStart(2, "0")}`;
      months.add(monthKey);
    });
    return Array.from(months).sort();
  }, [availabilityData, selectedTrip]);
  const inventoryAlerts = reactExports.useMemo(() => {
    if (!filteredDates || filteredDates.length === 0) return [];
    return filteredDates.filter((date2) => {
      if (date2.is_blocked) return false;
      const threshold2 = date2.alert_threshold || 5;
      return date2.available_seats <= threshold2 && date2.available_seats > 0;
    });
  }, [filteredDates]);
  const waitlistEntries = reactExports.useMemo(() => {
    if (!filteredDates || filteredDates.length === 0) return [];
    return filteredDates.filter((date2) => date2.waitlist_count > 0);
  }, [filteredDates]);
  const blockedDates = reactExports.useMemo(() => {
    if (!filteredDates || filteredDates.length === 0) return [];
    return filteredDates.filter((date2) => date2.is_blocked);
  }, [filteredDates]);
  const statusCounts = reactExports.useMemo(() => {
    const counts = {
      all: 0,
      available: 0,
      limited: 0,
      sold_out: 0,
      closed: 0,
      blocked: 0
    };
    if (!(availabilityData == null ? void 0 : availabilityData.dates)) return counts;
    availabilityData.dates.forEach((date2) => {
      counts.all++;
      if (date2.status === "available") counts.available++;
      else if (date2.status === "limited") counts.limited++;
      else if (date2.status === "sold_out") counts.sold_out++;
      else if (date2.status === "closed") counts.closed++;
      else if (date2.status === "blocked") counts.blocked++;
    });
    return counts;
  }, [availabilityData]);
  const bulkDeleteMutation = useMutation({
    mutationFn: async (ids) => {
      await Promise.all(
        ids.map((id) => apiClient.delete(`/availability/${id}`))
      );
    },
    onSuccess: () => {
      queryClient2.invalidateQueries({ queryKey: ["availability"] });
      showToast(
        __("Selected availability dates deleted successfully", "yatra"),
        "success"
      );
      setSelectedIds([]);
      setBulkAction("");
    },
    onError: (error) => {
      showToast(
        (error == null ? void 0 : error.message) || __("Failed to delete selected availability dates", "yatra"),
        "error"
      );
    }
  });
  const handleBulkApply = () => {
    if (!bulkAction) {
      showToast(__("Select a bulk action first.", "yatra"), "warning");
      return;
    }
    if (selectedIds.length === 0) {
      showToast(
        __("Select at least one availability date.", "yatra"),
        "warning"
      );
      return;
    }
    if (bulkAction === "delete") {
      bulkDeleteMutation.mutate(selectedIds);
    } else {
      showToast(
        __("Unsupported bulk action for availability.", "yatra"),
        "warning"
      );
    }
  };
  const bulkStatusOptions = [
    { value: "delete", label: __("Delete Permanently", "yatra") }
  ];
  const totalFiltered = filteredDates.length;
  const [deleteConfirm, setDeleteConfirm] = reactExports.useState({
    isOpen: false,
    date: null
  });
  const [duplicateConfirm, setDuplicateConfirm] = reactExports.useState({
    isOpen: false,
    date: null
  });
  const [duplicateDepartureDate, setDuplicateDepartureDate] = reactExports.useState("");
  const [duplicateDepartureTime, setDuplicateDepartureTime] = reactExports.useState("");
  const duplicateMutation = useMutation({
    mutationFn: async (payload) => {
      return await apiClient.post(`/availability/${payload.id}/duplicate`, {
        departure_date: payload.departure_date,
        departure_time: payload.departure_time ?? null
      });
    },
    onSuccess: () => {
      queryClient2.invalidateQueries({ queryKey: ["availability"] });
      showToast(
        __("Availability date duplicated successfully", "yatra"),
        "success"
      );
      setDuplicateConfirm({ isOpen: false, date: null });
      setDuplicateDepartureDate("");
      setDuplicateDepartureTime("");
    },
    onError: (error) => {
      showToast(
        (error == null ? void 0 : error.message) || __("Failed to duplicate availability date", "yatra"),
        "error"
      );
    }
  });
  const tableColumns = reactExports.useMemo(() => {
    const cols = [];
    cols.push({
      key: "departure",
      label: (selectedTrip == null ? void 0 : selectedTrip.trip_type) === "single_day" ? __("Departure Time", "yatra") : __("Departure", "yatra"),
      visible: visibleColumns.departure,
      render: (date2) => (selectedTrip == null ? void 0 : selectedTrip.trip_type) === "single_day" ? /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(CalendarDays, { className: "w-4 h-4 text-gray-400" }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm font-medium", children: formatDate2(date2.departure_date) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-xs text-gray-500 dark:text-gray-400", children: date2.departure_time ? formatTime(date2.departure_time) : "" })
        ] })
      ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(CalendarDays, { className: "w-4 h-4 text-gray-400" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm font-medium", children: formatDate2(date2.departure_date) })
      ] })
    });
    cols.push({
      key: "arrival",
      label: (selectedTrip == null ? void 0 : selectedTrip.trip_type) === "single_day" ? __("Arrival Time", "yatra") : __("Arrival", "yatra"),
      visible: visibleColumns.arrival,
      render: (date2) => (selectedTrip == null ? void 0 : selectedTrip.trip_type) === "single_day" ? /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm font-medium", children: formatDate2(date2.arrival_date) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-xs text-gray-500 dark:text-gray-400", children: date2.arrival_time ? formatTime(date2.arrival_time) : "" })
      ] }) : /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm", children: formatDate2(date2.arrival_date) })
    });
    cols.push({
      key: "locations",
      label: __("From/To", "yatra"),
      visible: visibleColumns.locations,
      render: (date2) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1 text-sm text-gray-600 dark:text-gray-400", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(MapPin, { className: "w-3 h-3" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: date2.from_location || (selectedTrip == null ? void 0 : selectedTrip.starting_location) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: "→" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: date2.to_location || (selectedTrip == null ? void 0 : selectedTrip.ending_location) })
      ] })
    });
    cols.push({
      key: "capacity",
      label: __("Capacity", "yatra"),
      visible: visibleColumns.capacity,
      render: (date2) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col items-center", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm font-medium text-gray-900 dark:text-white", children: date2.total_seats || 0 }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs text-gray-500 dark:text-gray-400", children: __("total", "yatra") })
      ] })
    });
    cols.push({
      key: "booked",
      label: __("Booked", "yatra"),
      visible: visibleColumns.booked,
      render: (date2) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col items-center", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm font-medium text-orange-600 dark:text-orange-400", children: date2.booked_seats || 0 }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs text-gray-500 dark:text-gray-400", children: __("booked", "yatra") })
      ] })
    });
    cols.push({
      key: "available",
      label: __("Available", "yatra"),
      visible: visibleColumns.available,
      render: (date2) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col items-center", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "span",
          {
            className: `text-sm font-semibold ${date2.available_seats === 0 ? "text-red-600 dark:text-red-400" : date2.available_seats <= (date2.alert_threshold || 5) ? "text-yellow-600 dark:text-yellow-400" : "text-green-600 dark:text-green-400"}`,
            children: date2.available_seats || 0
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs text-gray-500 dark:text-gray-400", children: __("available", "yatra") }),
        date2.available_seats <= (date2.alert_threshold || 5) && date2.available_seats > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx(Bell, { className: "w-3 h-3 text-yellow-500 mt-0.5" })
      ] })
    });
    cols.push({
      key: "waitlist",
      label: __("Waitlist", "yatra"),
      visible: visibleColumns.waitlist,
      render: (date2) => date2.waitlist_count > 0 ? /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col items-center", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Badge, { className: "bg-blue-100 text-blue-700 dark:bg-blue-900/20 dark:text-blue-400 text-xs", children: date2.waitlist_count }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs text-gray-500 dark:text-gray-400 mt-1", children: __("people", "yatra") })
      ] }) : /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm text-gray-400 dark:text-gray-500", children: "-" })
    });
    cols.push({
      key: "price",
      label: __("Price", "yatra"),
      visible: visibleColumns.price,
      render: (date2) => /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex flex-col gap-1", children: date2.discounted_price && parseFloat(date2.discounted_price) < parseFloat(date2.original_price) ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-sm line-through text-gray-400", children: [
          getCurrencySymbol2((selectedTrip == null ? void 0 : selectedTrip.currency) || "USD"),
          parseFloat(date2.original_price).toLocaleString()
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-sm font-semibold text-gray-900 dark:text-white", children: [
            getCurrencySymbol2((selectedTrip == null ? void 0 : selectedTrip.currency) || "USD"),
            parseFloat(date2.discounted_price).toLocaleString()
          ] }),
          date2.discount_percentage && parseFloat(date2.discount_percentage) > 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs(Badge, { variant: "error", className: "text-xs", children: [
            date2.discount_percentage,
            "% ",
            __("OFF", "yatra")
          ] })
        ] })
      ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-sm font-semibold", children: [
        getCurrencySymbol2((selectedTrip == null ? void 0 : selectedTrip.currency) || "USD"),
        parseFloat(date2.original_price).toLocaleString()
      ] }) })
    });
    cols.push({
      key: "status",
      label: __("Status", "yatra"),
      visible: visibleColumns.status,
      render: (date2) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col gap-1", children: [
        getStatusBadge(date2.status, date2.is_blocked),
        date2.is_blocked && date2.block_reason && /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs text-gray-500 dark:text-gray-400 italic", children: date2.block_reason }),
        date2.last_synced_at && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1 text-xs text-gray-400 dark:text-gray-500", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Clock, { className: "w-3 h-3" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: new Date(date2.last_synced_at).toLocaleTimeString() })
        ] })
      ] })
    });
    return cols;
  }, [
    selectedTrip,
    visibleColumns,
    getCurrencySymbol2,
    formatDate2,
    formatTime,
    getStatusBadge
  ]);
  const tableActions = [
    {
      key: "edit",
      label: __("Edit", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(PenSquare, { className: "w-4 h-4" }),
      onClick: (date2) => navigate({
        subpage: "trips",
        tab: "availability",
        action: "edit",
        id: date2.id,
        trip_id: date2.trip_id
      })
    },
    {
      key: "duplicate",
      label: __("Duplicate", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Copy, { className: "w-4 h-4" }),
      onClick: (date2) => {
        setDuplicateConfirm({ isOpen: true, date: date2 });
        setDuplicateDepartureDate(date2.departure_date || "");
        setDuplicateDepartureTime(date2.departure_time || "");
      }
    },
    {
      key: "delete",
      label: __("Delete", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "w-4 h-4" }),
      onClick: (date2) => setDeleteConfirm({ isOpen: true, date: date2 }),
      variant: "destructive"
    }
  ];
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-6", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      ConfirmationDialog,
      {
        isOpen: deleteConfirm.isOpen,
        onClose: () => setDeleteConfirm({ isOpen: false, date: null }),
        onConfirm: () => {
          if (deleteConfirm.date) {
            deleteMutation.mutate(deleteConfirm.date.id);
          }
        },
        title: __("Delete Availability Date", "yatra"),
        message: deleteConfirm.date ? __(
          "Are you sure you want to delete this availability date on {date}? This action cannot be undone.",
          "yatra"
        ).replace("{date}", formatDate2(deleteConfirm.date.departure_date)) : __(
          "Are you sure you want to delete this availability date? This action cannot be undone.",
          "yatra"
        ),
        confirmText: __("Delete", "yatra"),
        cancelText: __("Cancel", "yatra"),
        variant: "danger",
        isLoading: deleteMutation.isPending
      }
    ),
    duplicateConfirm.isOpen && duplicateConfirm.date && /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "div",
      {
        className: "fixed inset-0 z-50 flex items-center justify-center p-4",
        style: { marginTop: "-32px" },
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "div",
            {
              className: "absolute inset-0 bg-black/50",
              onClick: () => {
                if (!duplicateMutation.isPending) {
                  setDuplicateConfirm({ isOpen: false, date: null });
                }
              }
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-full max-w-lg overflow-hidden", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "p-6 border-b border-gray-200 dark:border-gray-700", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { className: "text-lg font-semibold text-gray-900 dark:text-white", children: __("Duplicate Availability Date", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-500 dark:text-gray-400 mt-1", children: __(
                "Select the new departure date. Arrival/return will be shifted automatically.",
                "yatra"
              ) })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "p-6 space-y-4", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2", children: __("Departure Date", "yatra") }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  DatePicker,
                  {
                    value: duplicateDepartureDate,
                    onChange: (value) => setDuplicateDepartureDate(value),
                    placeholder: __("Select date", "yatra")
                  }
                )
              ] }),
              (selectedTrip == null ? void 0 : selectedTrip.trip_type) === "single_day" && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2", children: __("Departure Time", "yatra") }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  TimePicker,
                  {
                    value: duplicateDepartureTime,
                    onChange: (value) => setDuplicateDepartureTime(value),
                    placeholder: __("Select departure time", "yatra")
                  }
                )
              ] })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "p-4 bg-gray-50 dark:bg-gray-900 border-t border-gray-200 dark:border-gray-700 flex justify-end gap-2", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Button,
                {
                  variant: "outline",
                  onClick: () => setDuplicateConfirm({ isOpen: false, date: null }),
                  disabled: duplicateMutation.isPending,
                  children: __("Cancel", "yatra")
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Button,
                {
                  onClick: () => {
                    if (!duplicateConfirm.date) return;
                    if (!duplicateDepartureDate) {
                      showToast(
                        __("Please select a departure date", "yatra"),
                        "warning"
                      );
                      return;
                    }
                    duplicateMutation.mutate({
                      id: duplicateConfirm.date.id,
                      departure_date: duplicateDepartureDate,
                      departure_time: (selectedTrip == null ? void 0 : selectedTrip.trip_type) === "single_day" ? duplicateDepartureTime || null : null
                    });
                  },
                  disabled: duplicateMutation.isPending,
                  children: duplicateMutation.isPending ? __("Duplicating...", "yatra") : __("Duplicate", "yatra")
                }
              )
            ] })
          ] })
        ]
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      PageHeader,
      {
        title: __("Availability Management", "yatra"),
        description: __(
          "Manage departure dates and availability for your trips. Add dates for this month or plan ahead for the entire year.",
          "yatra"
        )
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-gradient-to-r from-blue-50 to-indigo-50 dark:from-gray-800 dark:to-gray-900 rounded-lg border border-blue-200 dark:border-gray-700 p-6", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex items-start justify-between gap-4 mb-4", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2 mb-1", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CalendarDays, { className: "w-5 h-5 text-blue-600 dark:text-blue-400" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-lg font-semibold text-gray-900 dark:text-white", children: __("Select Trip", "yatra") })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-600 dark:text-gray-400 mt-1", children: __(
          "Choose a trip to manage its availability dates and departure schedules",
          "yatra"
        ) })
      ] }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-4", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2", children: [
            __("Trip", "yatra"),
            " ",
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            SearchableSelect,
            {
              value: (selectedTripId == null ? void 0 : selectedTripId.toString()) || "",
              onChange: (value) => {
                const tripId = value ? parseInt(value) : null;
                setSelectedTripId(tripId);
                setPage(1);
              },
              options: [
                { value: "", label: __("-- Select a Trip --", "yatra") },
                ...tripsList.map((trip) => ({
                  value: trip.id.toString(),
                  label: `${trip.title}${trip.trip_type === "single_day" ? " (Single Day)" : trip.trip_type === "multi_day" ? " (Multi-Day)" : ""}`
                }))
              ],
              placeholder: __("Search or select a trip...", "yatra"),
              searchPlaceholder: __("Search by trip name or ID...", "yatra"),
              className: "w-full",
              required: true
            }
          )
        ] }),
        selectedTrip && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-4 pt-2 border-t border-blue-200 dark:border-gray-700", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(MapPin, { className: "w-4 h-4 text-blue-600 dark:text-blue-400" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-medium", children: selectedTrip.starting_location }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-400", children: "→" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-medium", children: selectedTrip.ending_location })
          ] }),
          selectedTrip.trip_type && /* @__PURE__ */ jsxRuntimeExports.jsx(
            Badge,
            {
              className: selectedTrip.trip_type === "single_day" ? "bg-purple-100 text-purple-700 dark:bg-purple-900/20 dark:text-purple-400" : "bg-indigo-100 text-indigo-700 dark:bg-indigo-900/20 dark:text-indigo-400",
              children: selectedTrip.trip_type === "single_day" ? __("Single Day", "yatra") : __("Multi-Day", "yatra")
            }
          )
        ] }),
        !selectedTripId && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-4 p-4 bg-white/60 dark:bg-gray-800/60 rounded-lg border border-blue-200/50 dark:border-gray-700/50", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start gap-3", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex-shrink-0 mt-0.5", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-8 h-8 rounded-full bg-blue-100 dark:bg-blue-900/30 flex items-center justify-center", children: /* @__PURE__ */ jsxRuntimeExports.jsx(AlertCircle, { className: "w-4 h-4 text-blue-600 dark:text-blue-400" }) }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm font-medium text-gray-900 dark:text-white mb-1", children: __("Get Started", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-600 dark:text-gray-400", children: __(
              "Select a trip from the dropdown above to view and manage its availability dates, pricing, and booking status.",
              "yatra"
            ) })
          ] })
        ] }) })
      ] })
    ] }),
    selectedTripId && /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-1", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex items-center justify-between", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "button",
          {
            onClick: () => setTabMode("specific"),
            className: `px-4 py-2 rounded-md text-sm font-medium transition-colors ${tabMode === "specific" ? "bg-blue-600 text-white" : "text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700"}`,
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(CalendarDays, { className: "w-4 h-4 inline mr-2" }),
              __("Specific Dates", "yatra")
            ]
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "button",
          {
            onClick: () => setTabMode("recurring"),
            className: `px-4 py-2 rounded-md text-sm font-medium transition-colors ${tabMode === "recurring" ? "bg-blue-600 text-white" : "text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700"}`,
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(RefreshCw, { className: "w-4 h-4 inline mr-2" }),
              __("Recurring Rules", "yatra")
            ]
          }
        )
      ] }) }) }),
      tabMode === "recurring" && /* @__PURE__ */ jsxRuntimeExports.jsx(
        RecurringRules,
        {
          tripId: selectedTripId,
          tripName: selectedTrip == null ? void 0 : selectedTrip.title,
          tripType: selectedTrip == null ? void 0 : selectedTrip.trip_type,
          onAddRule: () => navigate({
            subpage: "trips",
            tab: "availability",
            action: "create-rule",
            trip_id: selectedTripId.toString()
          }),
          onEditRule: (id) => navigate({
            subpage: "trips",
            tab: "availability",
            action: "edit-rule",
            id: id.toString()
          })
        }
      ),
      tabMode === "specific" && /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
        selectedTripId && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-end gap-2 mb-4", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center border border-gray-300 dark:border-gray-600 rounded-lg overflow-hidden", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              Button,
              {
                variant: viewMode === "list" ? "default" : "ghost",
                size: "sm",
                onClick: () => setViewMode("list"),
                className: "rounded-none border-0",
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(List, { className: "w-4 h-4 mr-1" }),
                  __("List", "yatra")
                ]
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              Button,
              {
                variant: viewMode === "calendar" ? "default" : "ghost",
                size: "sm",
                onClick: () => setViewMode("calendar"),
                className: "rounded-none border-0",
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(Calendar$1, { className: "w-4 h-4 mr-1" }),
                  __("Calendar", "yatra")
                ]
              }
            )
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Button,
            {
              variant: "outline",
              size: "sm",
              onClick: handleSync,
              disabled: isSyncing,
              title: lastSyncTime ? `Last synced: ${lastSyncTime.toLocaleTimeString()}` : __("Sync availability", "yatra"),
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  RefreshCw,
                  {
                    className: `w-4 h-4 mr-2 ${isSyncing ? "animate-spin" : ""}`
                  }
                ),
                __("Sync", "yatra")
              ]
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Button,
            {
              onClick: () => navigate({
                subpage: "trips",
                tab: "availability",
                action: "create",
                trip_id: selectedTripId.toString()
              }),
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Plus, { className: "w-4 h-4 mr-2" }),
                __("Add Availability Date", "yatra")
              ]
            }
          )
        ] }),
        showAlerts && inventoryAlerts.length > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx(
          Alert,
          {
            variant: "warning",
            className: "border-yellow-300 bg-yellow-50 dark:bg-yellow-900/10",
            children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start justify-between w-full", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start gap-3 flex-1", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Bell, { className: "w-5 h-5 text-yellow-600 dark:text-yellow-400 mt-0.5 flex-shrink-0" }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2 mb-1", children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx("h4", { className: "font-semibold text-yellow-900 dark:text-yellow-200", children: __("Inventory Alerts", "yatra") }),
                    /* @__PURE__ */ jsxRuntimeExports.jsx(Badge, { className: "bg-yellow-200 text-yellow-800 dark:bg-yellow-800 dark:text-yellow-200", children: inventoryAlerts.length })
                  ] }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-yellow-800 dark:text-yellow-300 mb-2", children: __(
                    "The following dates have low availability (below threshold).",
                    "yatra"
                  ) }),
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-wrap gap-2", children: [
                    inventoryAlerts.slice(0, 5).map((alert2) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
                      Button,
                      {
                        variant: "outline",
                        size: "sm",
                        onClick: () => navigate({
                          subpage: "trips",
                          tab: "availability",
                          action: "edit",
                          id: alert2.id,
                          trip_id: alert2.trip_id
                        }),
                        className: "text-xs border-yellow-300 text-yellow-800 hover:bg-yellow-100 dark:border-yellow-700 dark:text-yellow-300",
                        children: [
                          formatDate2(alert2.departure_date),
                          alert2.departure_time && ` ${formatTime(alert2.departure_time)}`,
                          /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "ml-1 font-semibold", children: [
                            "(",
                            alert2.available_seats,
                            " ",
                            __("seats", "yatra"),
                            ")"
                          ] })
                        ]
                      },
                      alert2.id
                    )),
                    inventoryAlerts.length > 5 && /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-xs text-yellow-700 dark:text-yellow-400 self-center", children: [
                      "+",
                      inventoryAlerts.length - 5,
                      " ",
                      __("more", "yatra")
                    ] })
                  ] })
                ] })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Button,
                {
                  variant: "ghost",
                  size: "sm",
                  onClick: () => setShowAlerts(false),
                  className: "text-yellow-600 hover:text-yellow-700 dark:text-yellow-400",
                  children: /* @__PURE__ */ jsxRuntimeExports.jsx(X, { className: "w-4 h-4" })
                }
              )
            ] })
          }
        ),
        waitlistEntries.length > 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { className: "border-blue-200 bg-blue-50 dark:bg-blue-900/10 dark:border-blue-800", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Users, { className: "w-5 h-5 text-blue-600 dark:text-blue-400" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Waitlist", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs(Badge, { className: "bg-blue-200 text-blue-800 dark:bg-blue-800 dark:text-blue-200", children: [
                waitlistEntries.reduce(
                  (sum, entry) => sum + entry.waitlist_count,
                  0
                ),
                " ",
                __("people", "yatra")
              ] })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              Button,
              {
                variant: "ghost",
                size: "sm",
                onClick: () => navigate({
                  subpage: "trips",
                  tab: "availability",
                  action: "waitlist",
                  trip_id: selectedTripId.toString()
                }),
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(Eye, { className: "w-4 h-4 mr-1" }),
                  __("View All", "yatra")
                ]
              }
            )
          ] }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-2", children: waitlistEntries.slice(0, 3).map((entry) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "div",
            {
              className: "flex items-center justify-between p-2 bg-white dark:bg-gray-800 rounded border border-blue-200 dark:border-blue-800",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(CalendarDays, { className: "w-4 h-4 text-blue-600 dark:text-blue-400" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-sm font-medium text-gray-900 dark:text-white", children: [
                      formatDate2(entry.departure_date),
                      entry.departure_time && ` ${formatTime(entry.departure_time)}`
                    ] }),
                    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-xs text-gray-500 dark:text-gray-400", children: [
                      entry.booked_seats,
                      "/",
                      entry.total_seats,
                      " ",
                      __("booked", "yatra")
                    ] })
                  ] })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs(Badge, { className: "bg-blue-100 text-blue-700 dark:bg-blue-900/20 dark:text-blue-400", children: [
                  entry.waitlist_count,
                  " ",
                  __("on waitlist", "yatra")
                ] })
              ]
            },
            entry.id
          )) }) })
        ] }),
        blockedDates.length > 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { className: "border-red-200 bg-red-50 dark:bg-red-900/10 dark:border-red-800", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-3", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex items-center justify-between", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Ban, { className: "w-5 h-5 text-red-600 dark:text-red-400" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Blocked Dates", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(Badge, { className: "bg-red-200 text-red-800 dark:bg-red-800 dark:text-red-200", children: blockedDates.length })
          ] }) }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-2", children: blockedDates.slice(0, 3).map((entry) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "div",
            {
              className: "flex items-center justify-between p-2 bg-white dark:bg-gray-800 rounded border border-red-200 dark:border-red-800",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(Ban, { className: "w-4 h-4 text-red-600 dark:text-red-400" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-sm font-medium text-gray-900 dark:text-white", children: [
                      formatDate2(entry.departure_date),
                      entry.departure_time && ` ${formatTime(entry.departure_time)}`
                    ] }),
                    entry.block_reason && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-xs text-gray-500 dark:text-gray-400", children: [
                      __("Reason", "yatra"),
                      ": ",
                      entry.block_reason
                    ] })
                  ] })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Button,
                  {
                    variant: "ghost",
                    size: "sm",
                    onClick: () => navigate({
                      subpage: "trips",
                      tab: "availability",
                      action: "edit",
                      id: entry.id,
                      trip_id: entry.trip_id
                    }),
                    children: /* @__PURE__ */ jsxRuntimeExports.jsx(Settings$1, { className: "w-4 h-4" })
                  }
                )
              ]
            },
            entry.id
          )) }) })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "pt-6", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "div",
          {
            className: `grid grid-cols-1 ${(selectedTrip == null ? void 0 : selectedTrip.trip_type) === "single_day" ? "md:grid-cols-3" : "md:grid-cols-4"} gap-4`,
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2", children: __("Search", "yatra") }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(Search, { className: "absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    Input,
                    {
                      type: "text",
                      value: searchTerm,
                      onChange: (e) => setSearchTerm(e.target.value),
                      placeholder: __(
                        "Search dates, locations...",
                        "yatra"
                      ),
                      className: "pl-10"
                    }
                  )
                ] })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2", children: __("Status", "yatra") }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs(
                  Select,
                  {
                    value: statusFilter,
                    onChange: (e) => setStatusFilter(e.target.value),
                    children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "all", children: __("All Status", "yatra") }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "available", children: __("Available", "yatra") }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "limited", children: __("Limited", "yatra") }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "sold_out", children: __("Sold Out", "yatra") }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "closed", children: __("Closed", "yatra") }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "blocked", children: __("Blocked", "yatra") })
                    ]
                  }
                )
              ] }),
              (selectedTrip == null ? void 0 : selectedTrip.trip_type) !== "single_day" && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2", children: __("Month", "yatra") }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs(
                  Select,
                  {
                    value: monthFilter,
                    onChange: (e) => setMonthFilter(e.target.value),
                    children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "all", children: __("All Months", "yatra") }),
                      availableMonths.map((month) => {
                        const [year, monthNum] = month.split("-");
                        const date2 = new Date(
                          parseInt(year),
                          parseInt(monthNum) - 1
                        );
                        return /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: month, children: date2.toLocaleDateString("en-US", {
                          year: "numeric",
                          month: "long"
                        }) }, month);
                      })
                    ]
                  }
                )
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex items-end", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
                Button,
                {
                  variant: "outline",
                  onClick: () => {
                    setSearchTerm("");
                    setStatusFilter("all");
                    setMonthFilter("all");
                  },
                  className: "w-full",
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(X, { className: "w-4 h-4 mr-2" }),
                    __("Clear Filters", "yatra")
                  ]
                }
              ) })
            ]
          }
        ) }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          BulkActionToolbar,
          {
            selectedIds,
            bulkAction,
            setBulkAction,
            onApply: handleBulkApply,
            onClearSelection: () => setSelectedIds([]),
            statusFilter,
            setStatusFilter,
            statusOptions: [
              {
                key: "all",
                label: __("All", "yatra"),
                count: statusCounts.all
              },
              {
                key: "available",
                label: __("Available", "yatra"),
                count: statusCounts.available
              },
              {
                key: "limited",
                label: __("Limited", "yatra"),
                count: statusCounts.limited
              },
              {
                key: "sold_out",
                label: __("Sold Out", "yatra"),
                count: statusCounts.sold_out
              },
              {
                key: "closed",
                label: __("Closed", "yatra"),
                count: statusCounts.closed
              },
              {
                key: "blocked",
                label: __("Blocked", "yatra"),
                count: statusCounts.blocked
              }
            ],
            showColumnsDropdown,
            setShowColumnsDropdown,
            columnOptions: [
              {
                key: "departure",
                label: __("Departure", "yatra"),
                visible: visibleColumns.departure
              },
              {
                key: "arrival",
                label: __("Arrival", "yatra"),
                visible: visibleColumns.arrival
              },
              {
                key: "locations",
                label: __("From/To", "yatra"),
                visible: visibleColumns.locations
              },
              {
                key: "capacity",
                label: __("Capacity", "yatra"),
                visible: visibleColumns.capacity
              },
              {
                key: "booked",
                label: __("Booked", "yatra"),
                visible: visibleColumns.booked
              },
              {
                key: "available",
                label: __("Available", "yatra"),
                visible: visibleColumns.available
              },
              {
                key: "waitlist",
                label: __("Waitlist", "yatra"),
                visible: visibleColumns.waitlist
              },
              {
                key: "price",
                label: __("Price", "yatra"),
                visible: visibleColumns.price
              },
              {
                key: "status",
                label: __("Status", "yatra"),
                visible: visibleColumns.status
              }
            ],
            onToggleColumn: (key2) => toggleColumn(key2),
            bulkMutationPending: bulkDeleteMutation.isPending,
            totalItems: totalFiltered,
            bulkActionOptions: bulkStatusOptions
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardHeader, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { children: __("Availability Dates", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardDescription, { children: selectedTrip && /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
              __("Managing availability for", "yatra"),
              " ",
              /* @__PURE__ */ jsxRuntimeExports.jsx("strong", { children: selectedTrip.title }),
              filteredDates.length > 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "ml-2", children: [
                "(",
                filteredDates.length,
                " ",
                (selectedTrip == null ? void 0 : selectedTrip.trip_type) === "single_day" ? __("time slots", "yatra") : __("dates", "yatra"),
                ")"
              ] })
            ] }) })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { children: viewMode === "calendar" ? filteredDates.length === 0 ? /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "py-12 text-center text-gray-500 dark:text-gray-400", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Calendar$1, { className: "w-10 h-10 mx-auto mb-3 text-gray-400 dark:text-gray-600" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm font-medium mb-1", children: __(
              "No availability dates found for this trip.",
              "yatra"
            ) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs", children: __(
              "Try adjusting your filters or add a new availability date.",
              "yatra"
            ) })
          ] }) : /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-4", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            AvailabilityCalendar,
            {
              dates: filteredDates,
              tripType: selectedTrip == null ? void 0 : selectedTrip.trip_type,
              currency: (selectedTrip == null ? void 0 : selectedTrip.currency) || "USD",
              onDateClick: (date2) => {
                navigate({
                  subpage: "trips",
                  tab: "availability",
                  action: "edit",
                  id: date2.id,
                  trip_id: date2.trip_id
                });
              }
            }
          ) }) : /* @__PURE__ */ jsxRuntimeExports.jsx(
            Table,
            {
              data: filteredDates,
              columns: tableColumns,
              actions: tableActions,
              isLoading,
              isError: !!availabilityError,
              errorText: __("Error loading availability", "yatra"),
              errorDescription: __(
                "We couldn’t connect to the availability service. Please refresh or try again shortly.",
                "We couldn’t connect to the availability service. Please refresh or try again shortly."
              ),
              errorDetails: (availabilityErrorContext == null ? void 0 : availabilityErrorContext.details) || "",
              errorRequestInfo: availabilityErrorContext == null ? void 0 : availabilityErrorContext.requestInfo,
              onRetry: () => queryClient2.invalidateQueries({
                queryKey: ["availability"]
              }),
              emptyText: __(
                "No availability dates found for this trip.",
                "yatra"
              ),
              emptyDescription: __(
                "Try adjusting your filters or add a new availability date.",
                "yatra"
              ),
              selectedItemIds: selectedIds,
              onSelectItem: (id, checked) => {
                if (checked) {
                  setSelectedIds(
                    (prev) => Array.from(/* @__PURE__ */ new Set([...prev, id]))
                  );
                } else {
                  setSelectedIds(
                    (prev) => prev.filter((existingId) => existingId !== id)
                  );
                }
              },
              onSelectAll: (checked) => {
                if (checked) {
                  setSelectedIds(filteredDates.map((d) => d.id));
                } else {
                  setSelectedIds([]);
                }
              },
              isAllSelected: filteredDates.length > 0 && selectedIds.length === filteredDates.length,
              getItemId: (date2) => date2.id,
              getItemStatus: (date2) => date2.status,
              statusFilter,
              skeletonRows: 5,
              capability: "yatra_view_trips"
            }
          ) })
        ] })
      ] })
    ] })
  ] });
};
const DateRangePicker = ({
  dateFrom,
  dateTo,
  onDateFromChange,
  onDateToChange,
  onClear,
  placeholder = "Select date range",
  disabled = false,
  className = "",
  error = false
}) => {
  const [open, setOpen] = reactExports.useState(false);
  const [currentMonth, setCurrentMonth] = reactExports.useState(/* @__PURE__ */ new Date());
  const [hoverDate, setHoverDate] = reactExports.useState();
  let fromDate = void 0;
  let toDate2 = void 0;
  if (dateFrom && dateFrom.trim()) {
    try {
      const parsed = parse(dateFrom, "yyyy-MM-dd", /* @__PURE__ */ new Date());
      if (!isNaN(parsed.getTime())) {
        fromDate = parsed;
      }
    } catch (e) {
      fromDate = void 0;
    }
  }
  if (dateTo && dateTo.trim()) {
    try {
      const parsed = parse(dateTo, "yyyy-MM-dd", /* @__PURE__ */ new Date());
      if (!isNaN(parsed.getTime())) {
        toDate2 = parsed;
      }
    } catch (e) {
      toDate2 = void 0;
    }
  }
  const handleSelect = (date2) => {
    if (!fromDate || fromDate && toDate2) {
      onDateFromChange == null ? void 0 : onDateFromChange(format(date2, "yyyy-MM-dd"));
      onDateToChange == null ? void 0 : onDateToChange("");
      setHoverDate(void 0);
    } else if (fromDate && !toDate2) {
      if (date2 < fromDate) {
        onDateToChange == null ? void 0 : onDateToChange(format(fromDate, "yyyy-MM-dd"));
        onDateFromChange == null ? void 0 : onDateFromChange(format(date2, "yyyy-MM-dd"));
      } else {
        onDateToChange == null ? void 0 : onDateToChange(format(date2, "yyyy-MM-dd"));
      }
      setHoverDate(void 0);
      setOpen(false);
    }
  };
  const handleClear = (e) => {
    e.stopPropagation();
    onClear == null ? void 0 : onClear();
    setHoverDate(void 0);
  };
  const isInRange = (date2) => {
    if (!fromDate) return false;
    const endDate = toDate2 || hoverDate;
    if (!endDate) return false;
    const start = fromDate < endDate ? fromDate : endDate;
    const end = fromDate < endDate ? endDate : fromDate;
    try {
      return isWithinInterval(date2, { start, end });
    } catch {
      return false;
    }
  };
  const isRangeStart = (date2) => {
    return fromDate && isSameDay(date2, fromDate);
  };
  const isRangeEnd = (date2) => {
    const endDate = toDate2 || hoverDate;
    return endDate && isSameDay(date2, endDate);
  };
  const getDaysForMonth = (monthDate) => {
    const monthStart = startOfMonth(monthDate);
    const monthEnd = endOfMonth(monthDate);
    const calendarStart = startOfWeek(monthStart, { weekStartsOn: 0 });
    const calendarEnd = endOfWeek(monthEnd, { weekStartsOn: 0 });
    return eachDayOfInterval({ start: calendarStart, end: calendarEnd });
  };
  const nextMonthDate = addMonths(currentMonth, 1);
  const currentMonthDays = getDaysForMonth(currentMonth);
  const nextMonthDays = getDaysForMonth(nextMonthDate);
  const weekDays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
  let displayValue = "";
  if (fromDate && !isNaN(fromDate.getTime())) {
    try {
      displayValue = format(fromDate, "MMM dd, yyyy");
      if (toDate2 && !isNaN(toDate2.getTime())) {
        displayValue += " - " + format(toDate2, "MMM dd, yyyy");
      }
    } catch (e) {
      displayValue = "";
    }
  }
  const hasValue = dateFrom || dateTo;
  const renderMonth = (monthDate, days) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "w-[280px]", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "font-semibold text-center mb-4", children: format(monthDate, "MMMM yyyy") }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid grid-cols-7 gap-1 mb-2", children: weekDays.map((day) => /* @__PURE__ */ jsxRuntimeExports.jsx(
      "div",
      {
        className: "text-center text-xs font-medium text-gray-500 dark:text-gray-400 p-2",
        children: day
      },
      day
    )) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid grid-cols-7 gap-1", children: days.map((day, idx) => {
      const isCurrentMonth = isSameMonth(day, monthDate);
      const isSelected = isRangeStart(day) || isRangeEnd(day);
      const inRange = isInRange(day);
      const isTodayDate = isToday(day);
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        "button",
        {
          type: "button",
          onClick: () => handleSelect(day),
          onMouseEnter: () => fromDate && !toDate2 && setHoverDate(day),
          onMouseLeave: () => setHoverDate(void 0),
          className: `
                p-2 text-sm rounded transition-colors relative w-9 h-9 flex items-center justify-center mx-auto
                ${!isCurrentMonth ? "text-gray-300 dark:text-gray-700 invisible" : ""}
                ${isSelected ? "bg-blue-600 text-white font-semibold hover:bg-blue-700 z-10" : ""}
                ${inRange && !isSelected ? "bg-blue-100 dark:bg-blue-900/20 text-blue-900 dark:text-blue-100 rounded-none" : ""}
                ${!isSelected && !inRange && isCurrentMonth ? "hover:bg-gray-100 dark:hover:bg-gray-700" : ""}
                ${isTodayDate && !isSelected ? "border border-blue-500" : ""}
                ${isRangeStart(day) && inRange ? "rounded-l-md" : ""}
                ${isRangeEnd(day) && inRange ? "rounded-r-md" : ""}
              `,
          disabled: !isCurrentMonth,
          children: format(day, "d")
        },
        idx
      );
    }) })
  ] });
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(Popover, { open, onOpenChange: setOpen, children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(PopoverTrigger, { asChild: true, children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
      Button,
      {
        type: "button",
        variant: "outline",
        disabled,
        className: `w-full justify-start text-left font-normal ${error ? "border-red-500" : ""} ${!displayValue ? "text-gray-500" : ""} ${className}`,
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Calendar$1, { className: "mr-2 h-4 w-4" }),
          displayValue || /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-500", children: placeholder }),
          hasValue && !disabled && /* @__PURE__ */ jsxRuntimeExports.jsx(
            X,
            {
              className: "ml-auto h-4 w-4 opacity-50 hover:opacity-100",
              onClick: handleClear
            }
          )
        ]
      }
    ) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(PopoverContent, { className: "w-auto p-0", align: "start", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "p-4", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between mb-4 px-2", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "button",
          {
            type: "button",
            onClick: () => setCurrentMonth(subMonths(currentMonth)),
            className: "p-1 hover:bg-gray-100 dark:hover:bg-gray-700 rounded",
            children: /* @__PURE__ */ jsxRuntimeExports.jsx(ChevronLeft, { className: "h-4 w-4" })
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "button",
          {
            type: "button",
            onClick: () => setCurrentMonth(addMonths(currentMonth, 1)),
            className: "p-1 hover:bg-gray-100 dark:hover:bg-gray-700 rounded",
            children: /* @__PURE__ */ jsxRuntimeExports.jsx(ChevronRight, { className: "h-4 w-4" })
          }
        )
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-8", children: [
        renderMonth(currentMonth, currentMonthDays),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "border-l border-gray-200 dark:border-gray-700 pl-8", children: renderMonth(nextMonthDate, nextMonthDays) })
      ] })
    ] }) })
  ] });
};
const formatDate = (dateString) => {
  if (!dateString) return "--";
  try {
    const date2 = new Date(dateString);
    return date2.toLocaleDateString("en-US", {
      year: "numeric",
      month: "short",
      day: "numeric"
    });
  } catch {
    return dateString;
  }
};
const formatCurrency = (value) => {
  var _a;
  if (value === void 0 || value === null) {
    return "--";
  }
  const currency = ((_a = window.yatraAdmin) == null ? void 0 : _a.currency) || "USD";
  try {
    return new Intl.NumberFormat("en-US", {
      style: "currency",
      currency
    }).format(value);
  } catch {
    return `${currency} ${value.toFixed(2)}`;
  }
};
function normalizeTripsForDropdown(raw) {
  if (Array.isArray(raw)) {
    return raw;
  }
  if (raw && typeof raw === "object") {
    const r2 = raw;
    if (Array.isArray(r2.data)) {
      return r2.data;
    }
    const inner = r2.data;
    if (inner && typeof inner === "object" && Array.isArray(inner.data)) {
      return inner.data;
    }
  }
  return [];
}
const Departures = () => {
  var _a, _b;
  const [selectedTripId, setSelectedTripId] = reactExports.useState(() => {
    try {
      const saved = localStorage.getItem("yatra_selected_trip_id");
      return saved ? parseInt(saved) : null;
    } catch {
      return null;
    }
  });
  const [statusFilter, setStatusFilter] = reactExports.useState("all");
  const [sourceFilter, setSourceFilter] = reactExports.useState("all");
  const [searchTerm, setSearchTerm] = reactExports.useState("");
  const [dateFrom, setDateFrom] = reactExports.useState("");
  const [dateTo, setDateTo] = reactExports.useState("");
  const [page, setPage] = reactExports.useState(1);
  const [showColumnMenu, setShowColumnMenu] = reactExports.useState(false);
  const [visibleColumns, setVisibleColumns] = reactExports.useState(() => {
    try {
      const saved = localStorage.getItem("yatra_departures_visible_columns");
      if (saved) {
        return JSON.parse(saved);
      }
    } catch {
    }
    return {
      trip: false,
      date: true,
      time: true,
      capacity: true,
      booked: true,
      available: true,
      revenue: true,
      travelers: true,
      bookings: true,
      status: true,
      source: false
    };
  });
  const columnMenuRef = reactExports.useRef(null);
  const [travelerModalDeparture, setTravelerModalDeparture] = reactExports.useState(null);
  const [selectedIds, setSelectedIds] = reactExports.useState([]);
  const [bulkAction, setBulkAction] = reactExports.useState("");
  const queryClient2 = useQueryClient();
  const { showToast } = useToast();
  reactExports.useEffect(() => {
    try {
      localStorage.setItem(
        "yatra_departures_visible_columns",
        JSON.stringify(visibleColumns)
      );
    } catch (error2) {
      console.error("Failed to save column visibility to localStorage:", error2);
    }
  }, [visibleColumns]);
  reactExports.useEffect(() => {
    const handleClickOutside = (event) => {
      if (columnMenuRef.current && !columnMenuRef.current.contains(event.target)) {
        setShowColumnMenu(false);
      }
    };
    if (showColumnMenu) {
      document.addEventListener("mousedown", handleClickOutside);
    }
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [showColumnMenu]);
  const toggleColumn = (column) => {
    setVisibleColumns((prev) => ({
      ...prev,
      [column]: !prev[column]
    }));
  };
  const columnOptions = Object.entries(visibleColumns).map(([key2, value]) => ({
    key: key2,
    label: key2.charAt(0).toUpperCase() + key2.slice(1),
    visible: Boolean(value)
  }));
  reactExports.useEffect(() => {
    try {
      if (selectedTripId) {
        localStorage.setItem(
          "yatra_selected_trip_id",
          selectedTripId.toString()
        );
      } else {
        localStorage.removeItem("yatra_selected_trip_id");
      }
    } catch (error2) {
      console.error("Failed to save trip selection to localStorage:", error2);
    }
  }, [selectedTripId]);
  const { data: tripsData } = useQuery({
    queryKey: ["trips", "departures-dropdown", "v1"],
    queryFn: async () => {
      const response = await apiClient.get("/trips", {
        params: { per_page: 1e3 }
      });
      return normalizeTripsForDropdown(response);
    }
  });
  const tripsList = reactExports.useMemo(
    () => normalizeTripsForDropdown(tripsData),
    [tripsData]
  );
  const {
    data: departuresData,
    isLoading,
    error,
    refetch
  } = useQuery({
    queryKey: [
      "departures",
      selectedTripId,
      statusFilter,
      sourceFilter,
      searchTerm,
      dateFrom,
      dateTo,
      page
    ],
    queryFn: async () => {
      const urlParams = new URLSearchParams(window.location.search);
      if (urlParams.get("simulate_error") === "true") {
        throw new Error(
          "Simulated API error for testing error UI functionality"
        );
      }
      const endpoint = selectedTripId ? `/trips/${selectedTripId}/departures` : "/departures";
      const response = await apiClient.get(endpoint, {
        params: {
          status: statusFilter !== "all" ? statusFilter : void 0,
          source: sourceFilter !== "all" ? sourceFilter : void 0,
          search: searchTerm || void 0,
          date_from: dateFrom && dateFrom.trim() !== "" ? dateFrom : void 0,
          date_to: dateTo && dateTo.trim() !== "" ? dateTo : void 0,
          include_past: dateFrom && dateFrom.trim() !== "" || dateTo && dateTo.trim() !== "" ? "true" : "false",
          page,
          per_page: 20
        }
      });
      const result = {
        data: (response == null ? void 0 : response.data) || [],
        meta: (response == null ? void 0 : response.meta) || { total: 0 }
      };
      if (result.data.length > 0) ;
      return result;
    },
    // Always enabled, whether trip is selected or not
    enabled: true
  });
  const departures = (departuresData == null ? void 0 : departuresData.data) || [];
  const errorContext = getErrorContext(error);
  const apiErrorMessage = (departuresData == null ? void 0 : departuresData.error) || (departuresData == null ? void 0 : departuresData.message);
  const derivedErrorDetails = errorContext.details || (apiErrorMessage ? String(apiErrorMessage) : void 0) || (error ? String((error == null ? void 0 : error.message) || error) : void 0);
  const isDeparturesError = !!error || !!apiErrorMessage;
  const totalItems = ((_a = departuresData == null ? void 0 : departuresData.meta) == null ? void 0 : _a.total) ?? 0;
  const itemsPerPage = 20;
  const totalPages = Math.max(1, Math.ceil(totalItems / itemsPerPage));
  const { data: departuresStatsData } = useQuery({
    queryKey: [
      "departures-stats",
      selectedTripId,
      sourceFilter,
      searchTerm,
      dateFrom,
      dateTo
    ],
    queryFn: async () => {
      const endpoint = selectedTripId ? `/trips/${selectedTripId}/departures` : "/departures";
      const response = await apiClient.get(endpoint, {
        params: {
          // NOTE: intentionally no status param here
          source: sourceFilter !== "all" ? sourceFilter : void 0,
          search: searchTerm || void 0,
          date_from: dateFrom && dateFrom.trim() !== "" ? dateFrom : void 0,
          date_to: dateTo && dateTo.trim() !== "" ? dateTo : void 0,
          include_past: dateFrom && dateFrom.trim() !== "" || dateTo && dateTo.trim() !== "" ? "true" : "false",
          page: 1,
          per_page: 1e3
        }
      });
      return (response == null ? void 0 : response.data) || [];
    },
    enabled: true
  });
  const statusCounts = reactExports.useMemo(() => {
    const allDepartures = Array.isArray(departuresStatsData) ? departuresStatsData : [];
    const counts = {
      all: allDepartures.length,
      upcoming: 0,
      full: 0,
      past: 0,
      cancelled: 0,
      trash: 0
    };
    allDepartures.forEach((departure) => {
      if (departure.status === "upcoming") counts.upcoming += 1;
      if (departure.status === "full") counts.full += 1;
      if (departure.status === "past") counts.past += 1;
      if (departure.status === "cancelled") counts.cancelled += 1;
      if (departure.status === "trash") counts.trash += 1;
    });
    return counts;
  }, [departuresStatsData]);
  const statusOptions = [
    { key: "all", label: __("All", "yatra"), count: statusCounts.all },
    {
      key: "upcoming",
      label: __("Upcoming", "yatra"),
      count: statusCounts.upcoming
    },
    { key: "full", label: __("Full", "yatra"), count: statusCounts.full },
    { key: "past", label: __("Past", "yatra"), count: statusCounts.past },
    {
      key: "cancelled",
      label: __("Cancelled", "yatra"),
      count: statusCounts.cancelled
    },
    { key: "trash", label: __("Trash", "yatra"), count: statusCounts.trash }
  ];
  const bulkActionOptions = reactExports.useMemo(() => {
    if (statusFilter === "trash") {
      return [
        { value: "restore", label: __("Restore", "yatra") },
        { value: "delete", label: __("Delete Permanently", "yatra") }
      ];
    }
    return [{ value: "trash", label: __("Move to Trash", "yatra") }];
  }, [statusFilter]);
  const handleBulkApply = async () => {
    const ids = selectedIds;
    if (!bulkAction || ids.length === 0) {
      showToast(
        __("Please select departures and a bulk action first.", "yatra"),
        "error"
      );
      return;
    }
    if (!selectedTripId) {
      showToast(__("Please select a trip first", "yatra"), "error");
      return;
    }
    try {
      if (bulkAction === "trash") {
        await Promise.all(
          ids.map(
            (id) => apiClient.patch(`/trips/${selectedTripId}/departures/${id}`, {
              status: "trash"
            })
          )
        );
        showToast(
          __("Selected departures moved to trash.", "yatra"),
          "success"
        );
      } else if (bulkAction === "restore") {
        await Promise.all(
          ids.map(
            (id) => apiClient.patch(`/trips/${selectedTripId}/departures/${id}`, {
              status: "upcoming"
            })
          )
        );
        showToast(__("Selected departures restored.", "yatra"), "success");
      } else if (bulkAction === "delete") {
        const eligibleIds = departures.filter(
          (d) => ids.includes(d.id) && d.status === "trash" && d.source === "booking_created" && d.booked_count === 0
        ).map((d) => d.id);
        if (eligibleIds.length === 0) {
          showToast(
            __(
              "No selected departures can be deleted (must be in trash, booking-created with zero bookings).",
              "No selected departures can be deleted (must be in trash, booking-created with zero bookings)."
            ),
            "error"
          );
          return;
        }
        await Promise.all(
          eligibleIds.map(
            (id) => apiClient.delete(`/trips/${selectedTripId}/departures/${id}`)
          )
        );
        showToast(
          __("Selected departures deleted permanently.", "yatra"),
          "success"
        );
      }
      setSelectedIds([]);
      setBulkAction("");
      queryClient2.invalidateQueries({
        queryKey: ["departures", selectedTripId]
      });
      queryClient2.invalidateQueries({
        queryKey: ["departures-stats", selectedTripId]
      });
    } catch (error2) {
      showToast(
        (error2 == null ? void 0 : error2.message) || __(
          "Failed to perform bulk action. Please try again.",
          "Failed to perform bulk action. Please try again."
        ),
        "error"
      );
    }
  };
  const tripIdForDeparture = reactExports.useCallback(
    (departure) => {
      if (departure.trip_id > 0) {
        return departure.trip_id;
      }
      if (selectedTripId != null && selectedTripId > 0) {
        return selectedTripId;
      }
      return null;
    },
    [selectedTripId]
  );
  const navigateToAdd = () => {
    if (!selectedTripId) {
      showToast(__("Please select a trip first", "yatra"), "error");
      return;
    }
    window.location.href = `?page=yatra&subpage=departures&action=create&trip_id=${selectedTripId}`;
  };
  const navigateToEdit = reactExports.useCallback(
    (departure) => {
      const tid = tripIdForDeparture(departure);
      if (!tid) {
        showToast(
          __(
            "Cannot open edit: this departure has no trip id. Select a trip filter or refresh the list.",
            "yatra"
          ),
          "error"
        );
        return;
      }
      window.location.href = `?page=yatra&subpage=departures&action=edit&id=${departure.id}&trip_id=${tid}`;
    },
    [tripIdForDeparture, showToast]
  );
  const navigateToView = reactExports.useCallback(
    (departure) => {
      const tid = tripIdForDeparture(departure);
      if (!tid) {
        showToast(
          __(
            "Cannot open departure: missing trip id. Select a trip filter or refresh the list.",
            "yatra"
          ),
          "error"
        );
        return;
      }
      window.location.href = `?page=yatra&subpage=departures&action=view&id=${departure.id}&trip_id=${tid}`;
    },
    [tripIdForDeparture, showToast]
  );
  const deleteMutation = useMutation({
    mutationFn: async ({ id, tripId: tid }) => {
      await apiClient.delete(`/trips/${tid}/departures/${id}`);
    },
    onSuccess: () => {
      queryClient2.invalidateQueries({ queryKey: ["departures"] });
      queryClient2.invalidateQueries({ queryKey: ["departures-stats"] });
      showToast(__("Departure deleted successfully", "yatra"), "success");
    },
    onError: (error2) => {
      showToast(
        (error2 == null ? void 0 : error2.message) || __("Failed to delete departure", "yatra"),
        "error"
      );
    }
  });
  const handleDelete = (departure) => {
    const tid = tripIdForDeparture(departure);
    if (!tid) {
      showToast(
        __("Cannot delete: missing trip id for this departure.", "yatra"),
        "error"
      );
      return;
    }
    if (!confirm(__("Are you sure you want to delete this departure?", "yatra"))) {
      return;
    }
    deleteMutation.mutate({ id: departure.id, tripId: tid });
  };
  const isAllSelected = departures.length > 0 && selectedIds.length === departures.length;
  const handleSelectAll = (checked) => {
    if (checked) {
      setSelectedIds(departures.map((d) => d.id));
    } else {
      setSelectedIds([]);
    }
  };
  const handleSelectRow = (id, checked) => {
    setSelectedIds(
      (prev) => checked ? [...prev, id] : prev.filter((existingId) => existingId !== id)
    );
  };
  const getStatusBadge = (status) => {
    const statusMap = {
      upcoming: {
        label: __("Upcoming", "yatra"),
        className: "bg-blue-100 text-blue-700 dark:bg-blue-900/20 dark:text-blue-400"
      },
      full: {
        label: __("Full", "yatra"),
        className: "bg-red-100 text-red-700 dark:bg-red-900/20 dark:text-red-400"
      },
      past: {
        label: __("Past", "yatra"),
        className: "bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-400"
      },
      cancelled: {
        label: __("Cancelled", "yatra"),
        className: "bg-yellow-100 text-yellow-700 dark:bg-yellow-900/20 dark:text-yellow-400"
      },
      trash: {
        label: __("Trash", "yatra"),
        className: "bg-red-100 text-red-700 dark:bg-red-900/20 dark:text-red-400"
      }
    };
    const statusInfo = statusMap[status] || statusMap.upcoming;
    return /* @__PURE__ */ jsxRuntimeExports.jsx(Badge, { className: statusInfo.className, children: statusInfo.label });
  };
  const getSourceBadge = (source) => {
    if (source === "manual") {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(Badge, { className: "bg-green-100 text-green-700 dark:bg-green-900/20 dark:text-green-400", children: __("Manual", "yatra") });
    }
    return /* @__PURE__ */ jsxRuntimeExports.jsx(Badge, { className: "bg-blue-100 text-blue-700 dark:bg-blue-900/20 dark:text-blue-400", children: __("Booking Created", "yatra") });
  };
  const clearDateFilters = () => {
    setDateFrom("");
    setDateTo("");
  };
  const openTravelerModal = (departure) => {
    if (!departure.travelers || !departure.travelers.length) {
      return;
    }
    setTravelerModalDeparture(departure);
  };
  const closeTravelerModal = () => setTravelerModalDeparture(null);
  const departureColumns = React.useMemo(
    () => [
      {
        key: "trip",
        label: __("Trip", "yatra"),
        visible: visibleColumns.trip,
        render: (departure) => {
          var _a2;
          return ((_a2 = departure.trip) == null ? void 0 : _a2.title) ? /* @__PURE__ */ jsxRuntimeExports.jsx(
            "a",
            {
              href: `?page=yatra&subpage=trips&action=edit&id=${departure.trip.id}`,
              className: "text-blue-600 hover:text-blue-800 hover:underline",
              title: __("View trip", "yatra"),
              children: departure.trip.title
            }
          ) : /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-400", children: "--" });
        }
      },
      {
        key: "date",
        label: __("Date", "yatra"),
        visible: visibleColumns.date,
        render: (departure) => formatDate(departure.start_date || departure.date)
      },
      {
        key: "time",
        label: __("Time", "yatra"),
        visible: visibleColumns.time,
        render: (departure) => departure.time ? /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-mono", children: departure.time }) : /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-400", children: "--" })
      },
      {
        key: "capacity",
        label: __("Capacity", "yatra"),
        visible: visibleColumns.capacity,
        render: (departure) => /* @__PURE__ */ jsxRuntimeExports.jsx("span", { title: __("Max Capacity", "yatra"), children: departure.max_capacity })
      },
      {
        key: "booked",
        label: __("Booked", "yatra"),
        visible: visibleColumns.booked,
        render: (departure) => /* @__PURE__ */ jsxRuntimeExports.jsx("span", { title: __("Booked Count", "yatra"), children: departure.booked_count })
      },
      {
        key: "available",
        label: __("Available", "yatra"),
        visible: visibleColumns.available,
        render: (departure) => /* @__PURE__ */ jsxRuntimeExports.jsx(
          "span",
          {
            className: departure.available_capacity === 0 ? "text-red-600 font-semibold" : "",
            title: __("Available Capacity", "yatra"),
            children: departure.available_capacity
          }
        )
      },
      {
        key: "revenue",
        label: __("Revenue", "yatra"),
        visible: visibleColumns.revenue,
        render: (departure) => departure.total_revenue !== void 0 && departure.total_revenue > 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-semibold text-green-600", children: formatCurrency(departure.total_revenue) }) : /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-400", children: "--" })
      },
      {
        key: "travelers",
        label: __("Travelers", "yatra"),
        visible: visibleColumns.travelers,
        render: (departure) => {
          var _a2;
          return /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Button,
            {
              variant: "outline",
              size: "sm",
              onClick: () => openTravelerModal(departure),
              disabled: !departure.travelers || departure.travelers.length === 0,
              className: "px-3 py-1.5",
              children: [
                departure.travelers_count || ((_a2 = departure.travelers) == null ? void 0 : _a2.length) || 0,
                " ",
                __("Traveler(s)", "yatra")
              ]
            }
          );
        }
      },
      {
        key: "bookings",
        label: __("Bookings", "yatra"),
        visible: visibleColumns.bookings,
        render: (departure) => departure.booking_ids && departure.booking_ids.length > 0 ? /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-wrap gap-1", children: [
          departure.booking_ids.slice(0, 3).map((bookingId) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "a",
            {
              href: `?page=yatra&subpage=bookings&action=view&id=${bookingId}`,
              className: "text-blue-600 hover:text-blue-800 hover:underline text-sm",
              title: __("View booking", "yatra"),
              children: [
                "#",
                bookingId
              ]
            },
            bookingId
          )),
          departure.booking_ids.length > 3 && /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-gray-500 text-sm", children: [
            "+",
            departure.booking_ids.length - 3
          ] })
        ] }) : /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-400", children: "--" })
      },
      {
        key: "status",
        label: __("Status", "yatra"),
        visible: visibleColumns.status,
        render: (departure) => getStatusBadge(departure.status)
      },
      {
        key: "source",
        label: __("Source", "yatra"),
        visible: visibleColumns.source,
        render: (departure) => getSourceBadge(departure.source)
      }
    ],
    [visibleColumns, openTravelerModal]
  );
  const handleMoveToTrash = async (departure) => {
    const tid = tripIdForDeparture(departure);
    if (!tid) {
      showToast(
        __(
          "Cannot move to trash: missing trip id for this departure.",
          "yatra"
        ),
        "error"
      );
      return;
    }
    if (!window.confirm(
      __("Are you sure you want to move this departure to trash?", "yatra")
    )) {
      return;
    }
    try {
      await apiClient.patch(`/trips/${tid}/departures/${departure.id}`, {
        status: "trash"
      });
      showToast(__("Departure moved to trash.", "yatra"), "success");
      queryClient2.invalidateQueries({ queryKey: ["departures"] });
      queryClient2.invalidateQueries({ queryKey: ["departures-stats"] });
    } catch (error2) {
      showToast(
        (error2 == null ? void 0 : error2.message) || __("Failed to move departure to trash", "yatra"),
        "error"
      );
    }
  };
  const handleRestore = async (departure) => {
    const tid = tripIdForDeparture(departure);
    if (!tid) {
      showToast(
        __("Cannot restore: missing trip id for this departure.", "yatra"),
        "error"
      );
      return;
    }
    if (!window.confirm(
      __("Are you sure you want to restore this departure?", "yatra")
    )) {
      return;
    }
    try {
      await apiClient.patch(`/trips/${tid}/departures/${departure.id}`, {
        status: "upcoming"
      });
      showToast(__("Departure restored.", "yatra"), "success");
      queryClient2.invalidateQueries({ queryKey: ["departures"] });
      queryClient2.invalidateQueries({ queryKey: ["departures-stats"] });
    } catch (error2) {
      showToast(
        (error2 == null ? void 0 : error2.message) || __("Failed to restore departure", "yatra"),
        "error"
      );
    }
  };
  const tableActions = React.useMemo(() => {
    const actions = [
      {
        key: "view",
        label: __("View", "yatra"),
        icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Eye, { className: "w-4 h-4" }),
        onClick: (departure) => navigateToView(departure)
      },
      {
        key: "edit",
        label: __("Edit", "yatra"),
        icon: /* @__PURE__ */ jsxRuntimeExports.jsx(PenSquare, { className: "w-4 h-4" }),
        onClick: (departure) => navigateToEdit(departure),
        condition: (departure) => departure.status !== "trash"
      }
    ];
    if (statusFilter === "trash") {
      actions.push({
        key: "restore",
        label: __("Restore", "yatra"),
        icon: /* @__PURE__ */ jsxRuntimeExports.jsx(RotateCcw, { className: "w-4 h-4" }),
        onClick: (departure) => handleRestore(departure)
      });
      actions.push({
        key: "delete",
        label: __("Delete Permanently", "yatra"),
        icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "w-4 h-4" }),
        onClick: (departure) => handleDelete(departure)
      });
    } else {
      actions.push({
        key: "trash",
        label: __("Move to Trash", "yatra"),
        icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "w-4 h-4" }),
        onClick: (departure) => handleMoveToTrash(departure),
        variant: "destructive"
      });
    }
    return actions;
  }, [
    statusFilter,
    navigateToEdit,
    navigateToView,
    handleDelete,
    handleRestore,
    handleMoveToTrash
  ]);
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-6", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        PageHeader,
        {
          title: __("Departures", "yatra"),
          description: __("Manage trip departure dates and capacity", "yatra"),
          actions: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex gap-2", children: selectedTripId && /* @__PURE__ */ jsxRuntimeExports.jsxs(Button, { onClick: navigateToAdd, variant: "default", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Plus, { className: "w-4 h-4 mr-2" }),
            __("Add Departure", "yatra")
          ] }) })
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-gradient-to-r from-blue-50 to-indigo-50 dark:from-gray-800 dark:to-gray-900 rounded-lg border border-blue-200 dark:border-gray-700 p-6", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex items-start justify-between gap-4 mb-4", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2 mb-1", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CalendarDays, { className: "w-5 h-5 text-blue-600 dark:text-blue-400" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-lg font-semibold text-gray-900 dark:text-white", children: __("Select Trip", "yatra") })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-600 dark:text-gray-400 mt-1", children: __(
            "Choose a trip to manage its departures and capacity",
            "yatra"
          ) })
        ] }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-4", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2", children: [
              __("Trip", "yatra"),
              " ",
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              SearchableSelect,
              {
                value: (selectedTripId == null ? void 0 : selectedTripId.toString()) || "",
                onChange: (value) => {
                  const tripId = value ? parseInt(value) : null;
                  setSelectedTripId(tripId);
                  setPage(1);
                },
                options: [
                  { value: "", label: __("-- Select a Trip --", "yatra") },
                  ...tripsList.map((trip) => ({
                    value: trip.id.toString(),
                    label: `${trip.title}${trip.trip_type === "single_day" ? " (Single Day)" : trip.trip_type === "multi_day" ? " (Multi-Day)" : ""}`
                  }))
                ],
                placeholder: __("Search or select a trip...", "yatra"),
                searchPlaceholder: __("Search by trip name or ID...", "yatra"),
                className: "w-full",
                required: true
              }
            )
          ] }),
          selectedTripId && (() => {
            const selectedTripData = tripsList.find(
              (trip) => trip.id === selectedTripId
            );
            return selectedTripData ? /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-4 pt-2 border-t border-blue-200 dark:border-gray-700", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(MapPin, { className: "w-4 h-4 text-blue-600 dark:text-blue-400" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-medium", children: selectedTripData.starting_location }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-400", children: "→" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-medium", children: selectedTripData.ending_location })
              ] }),
              selectedTripData.trip_type && /* @__PURE__ */ jsxRuntimeExports.jsx(
                Badge,
                {
                  className: selectedTripData.trip_type === "single_day" ? "bg-purple-100 text-purple-700 dark:bg-purple-900/20 dark:text-purple-400" : "bg-indigo-100 text-indigo-700 dark:bg-indigo-900/20 dark:text-indigo-400",
                  children: selectedTripData.trip_type === "single_day" ? __("Single Day", "yatra") : __("Multi-Day", "yatra")
                }
              )
            ] }) : null;
          })()
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "pt-6", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-4", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-4 items-end flex-wrap", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1 min-w-[200px]", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2", children: __("Search", "yatra") }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Search, { className: "absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              Input,
              {
                type: "text",
                placeholder: __("Search by date or notes...", "yatra"),
                value: searchTerm,
                onChange: (e) => {
                  setSearchTerm(e.target.value);
                  setPage(1);
                },
                className: "pl-10"
              }
            )
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "w-48", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2", children: __("Status", "yatra") }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Select,
            {
              value: statusFilter,
              onChange: (e) => {
                setStatusFilter(e.target.value);
                setPage(1);
              },
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "all", children: __("All Status", "yatra") }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "upcoming", children: __("Upcoming", "yatra") }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "full", children: __("Full", "yatra") }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "past", children: __("Past", "yatra") }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "cancelled", children: __("Cancelled", "yatra") })
              ]
            }
          )
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "w-48", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2", children: __("Source", "yatra") }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Select,
            {
              value: sourceFilter,
              onChange: (e) => {
                setSourceFilter(e.target.value);
                setPage(1);
              },
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "all", children: __("All Sources", "yatra") }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "manual", children: __("Manual", "yatra") }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "booking_created", children: __("Booking Created", "yatra") })
              ]
            }
          )
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "w-80", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2", children: __("Date Range", "yatra") }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            DateRangePicker,
            {
              dateFrom,
              dateTo,
              onDateFromChange: (dateStr) => {
                setDateFrom(dateStr || "");
                setPage(1);
              },
              onDateToChange: (dateStr) => {
                setDateTo(dateStr || "");
                setPage(1);
              },
              onClear: clearDateFilters,
              placeholder: __("Select date range...", "yatra")
            }
          )
        ] })
      ] }) }) }) }),
      !isDeparturesError && /* @__PURE__ */ jsxRuntimeExports.jsx(
        BulkActionToolbar,
        {
          selectedIds,
          bulkAction,
          setBulkAction,
          onApply: handleBulkApply,
          onClearSelection: () => setSelectedIds([]),
          statusFilter,
          setStatusFilter: (filter2) => {
            setStatusFilter(filter2);
            setPage(1);
          },
          statusOptions,
          showColumnsDropdown: showColumnMenu,
          setShowColumnsDropdown: setShowColumnMenu,
          columnOptions,
          onToggleColumn: (key2) => toggleColumn(key2),
          bulkMutationPending: deleteMutation.isPending,
          totalItems: departures.length,
          bulkActionOptions
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "pt-6", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        Table,
        {
          data: departures,
          columns: departureColumns,
          actions: tableActions,
          isLoading,
          isError: isDeparturesError,
          errorText: __("Error loading departures", "yatra"),
          errorDescription: __(
            "We couldn't connect to the departures service. Please refresh or try again shortly.",
            "yatra"
          ),
          errorDetails: derivedErrorDetails,
          errorRequestInfo: errorContext.requestInfo,
          onRetry: () => refetch(),
          emptyText: __("No departures found", "yatra"),
          emptyDescription: __(
            "Get started by creating your first departure.",
            "yatra"
          ),
          onCreateClick: navigateToAdd,
          selectedItemIds: selectedIds,
          onSelectItem: (id, checked) => handleSelectRow(id, checked),
          onSelectAll: handleSelectAll,
          isAllSelected,
          getItemId: (departure) => departure.id,
          getItemStatus: (departure) => departure.status,
          capability: "yatra_view_trips"
        }
      ) }) }),
      totalItems > 0 && departures.length > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-4", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        Pagination,
        {
          currentPage: page,
          totalPages,
          totalItems,
          itemsPerPage,
          onPageChange: (newPage) => setPage(newPage),
          itemName: __("departures", "yatra")
        }
      ) })
    ] }),
    travelerModalDeparture && travelerModalDeparture.travelers && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "fixed inset-0 z-50 flex items-center justify-center bg-black/50 px-4", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "w-full max-w-3xl rounded-lg bg-white p-6 shadow-xl dark:bg-gray-900", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mb-4 flex items-start justify-between gap-4", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("h3", { className: "text-lg font-semibold text-gray-800 dark:text-gray-100", children: [
            __("Travelers for", "yatra"),
            " ",
            ((_b = travelerModalDeparture.trip) == null ? void 0 : _b.title) || __("Trip", "yatra")
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-500 dark:text-gray-400", children: formatDate(
            travelerModalDeparture.start_date || travelerModalDeparture.date
          ) })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { variant: "outline", onClick: closeTravelerModal, children: __("Close", "yatra") })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "max-h-[60vh] overflow-y-auto pr-2", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(Table$1, { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(TableHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(TableRow, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(TableHead, { children: __("Traveler", "yatra") }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(TableHead, { children: __("Lead", "yatra") }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(TableHead, { children: __("Email", "yatra") }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(TableHead, { children: __("Phone", "yatra") }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(TableHead, { children: __("Booking", "yatra") })
        ] }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(TableBody, { children: travelerModalDeparture.travelers.map((traveler) => /* @__PURE__ */ jsxRuntimeExports.jsxs(TableRow, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(TableCell, { className: "font-semibold text-gray-800 dark:text-gray-100", children: [
            traveler.first_name || "—",
            " ",
            traveler.last_name || ""
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(TableCell, { children: traveler.is_lead ? /* @__PURE__ */ jsxRuntimeExports.jsx(Badge, { className: "bg-blue-100 text-blue-700 dark:bg-blue-900/20 dark:text-blue-300", children: __("Lead", "yatra") }) : /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-400", children: "—" }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(TableCell, { children: traveler.email || "—" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(TableCell, { children: traveler.phone || "—" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(TableCell, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            "a",
            {
              href: `?page=yatra&subpage=bookings&action=view&id=${traveler.booking_id}`,
              className: "text-blue-600 hover:underline",
              children: traveler.booking_reference || `#${traveler.booking_id}`
            }
          ) })
        ] }, traveler.id)) })
      ] }) })
    ] }) })
  ] });
};
const DepartureForm = () => {
  const queryClient2 = useQueryClient();
  const { showToast } = useToast();
  const urlParams = new URLSearchParams(window.location.search);
  const tripId = urlParams.get("trip_id") ? parseInt(urlParams.get("trip_id")) : null;
  const departureId = urlParams.get("id") || null;
  const isEditMode = !!departureId;
  const [formData, setFormData] = reactExports.useState({
    date: "",
    time: "",
    max_capacity: "",
    price_override: "",
    notes: ""
  });
  const [errors, setErrors] = reactExports.useState({});
  const { data: departureData, isLoading: isLoadingDeparture } = useQuery({
    queryKey: ["departure", departureId],
    queryFn: async () => {
      if (!departureId || !tripId) return null;
      const response = await apiClient.get(
        `/trips/${tripId}/departures/${departureId}`
      );
      return (response == null ? void 0 : response.data) || response;
    },
    enabled: isEditMode && !!departureId && !!tripId
  });
  reactExports.useEffect(() => {
    var _a, _b;
    if (departureData) {
      setFormData({
        date: departureData.date || departureData.start_date || "",
        time: departureData.time || "",
        max_capacity: ((_a = departureData.max_capacity) == null ? void 0 : _a.toString()) || "",
        price_override: ((_b = departureData.price_override) == null ? void 0 : _b.toString()) || "",
        notes: departureData.notes || ""
      });
    }
  }, [departureData]);
  const saveMutation = useMutation({
    mutationFn: async (data) => {
      if (!tripId) throw new Error("Trip ID is required");
      const payload = {
        trip_id: tripId,
        date: data.date,
        max_capacity: parseInt(data.max_capacity),
        source: "manual"
      };
      if (data.time) payload.time = data.time;
      if (data.price_override)
        payload.price_override = parseFloat(data.price_override);
      if (data.notes) payload.notes = data.notes;
      if (isEditMode && departureId) {
        return await apiClient.put(
          `/trips/${tripId}/departures/${departureId}`,
          payload
        );
      } else {
        return await apiClient.post(`/trips/${tripId}/departures`, payload);
      }
    },
    onSuccess: () => {
      queryClient2.invalidateQueries({ queryKey: ["departures", tripId] });
      showToast(
        isEditMode ? __("Departure updated successfully", "yatra") : __("Departure created successfully", "yatra"),
        "success"
      );
      window.location.href = `?page=yatra&subpage=departures${tripId ? `&trip_id=${tripId}` : ""}`;
    },
    onError: (error) => {
      showToast(
        (error == null ? void 0 : error.message) || __("Failed to save departure", "yatra"),
        "error"
      );
    }
  });
  const validateForm = () => {
    const newErrors = {};
    if (!formData.date) {
      newErrors.date = __("Date is required", "yatra");
    }
    if (!formData.max_capacity) {
      newErrors.max_capacity = __("Max capacity is required", "yatra");
    } else if (parseInt(formData.max_capacity) < 1) {
      newErrors.max_capacity = __("Max capacity must be at least 1", "yatra");
    }
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };
  const handleSubmit = (e) => {
    e.preventDefault();
    if (validateForm()) {
      saveMutation.mutate(formData);
    }
  };
  const handleBack = () => {
    window.location.href = `?page=yatra&subpage=departures${tripId ? `&trip_id=${tripId}` : ""}`;
  };
  if (isLoadingDeparture) {
    return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-6", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "animate-pulse", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-8 bg-gray-200 dark:bg-gray-700 rounded w-1/4 mb-4" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-64 bg-gray-200 dark:bg-gray-700 rounded" })
    ] }) });
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-6", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      PageHeader,
      {
        title: isEditMode ? __("Edit Departure", "yatra") : __("Add Departure", "yatra"),
        description: __(
          "Create or update a departure date for this trip",
          "yatra"
        ),
        actions: /* @__PURE__ */ jsxRuntimeExports.jsxs(Button, { variant: "ghost", onClick: handleBack, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowLeft, { className: "w-4 h-4 mr-2" }),
          __("Back", "yatra")
        ] })
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx("form", { onSubmit: handleSubmit, children: /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "pt-6 space-y-6", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2", children: [
          __("Departure Date", "yatra"),
          " ",
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          DatePicker,
          {
            value: formData.date,
            onChange: (value) => setFormData({ ...formData, date: value }),
            minDate: /* @__PURE__ */ new Date()
          }
        ),
        errors.date && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm text-red-600 dark:text-red-400", children: errors.date }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          HelpText,
          {
            text: __("Select the departure date for this trip", "yatra")
          }
        )
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2", children: [
          __("Departure Time", "yatra"),
          " ",
          /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-gray-400", children: [
            "(",
            __("Optional", "yatra"),
            ")"
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          TimePicker,
          {
            value: formData.time || "",
            onChange: (value) => setFormData({ ...formData, time: value })
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          HelpText,
          {
            text: __("Optional departure time (e.g., 09:00 AM)", "yatra")
          }
        )
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2", children: [
          __("Max Capacity", "yatra"),
          " ",
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          Input,
          {
            type: "number",
            min: "1",
            value: formData.max_capacity,
            onChange: (e) => setFormData({ ...formData, max_capacity: e.target.value }),
            placeholder: __("e.g., 20", "yatra")
          }
        ),
        errors.max_capacity && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm text-red-600 dark:text-red-400", children: errors.max_capacity }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          HelpText,
          {
            text: __(
              "Maximum number of travelers for this departure",
              "yatra"
            )
          }
        )
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2", children: [
          __("Price Override", "yatra"),
          " ",
          /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-gray-400", children: [
            "(",
            __("Optional", "yatra"),
            ")"
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          Input,
          {
            type: "number",
            step: "0.01",
            min: "0",
            value: formData.price_override || "",
            onChange: (e) => setFormData({ ...formData, price_override: e.target.value }),
            placeholder: __("e.g., 150.00", "yatra")
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          HelpText,
          {
            text: __(
              "Override the default trip price for this specific departure",
              "yatra"
            )
          }
        )
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2", children: [
          __("Notes", "yatra"),
          " ",
          /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-gray-400", children: [
            "(",
            __("Optional", "yatra"),
            ")"
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "textarea",
          {
            className: "w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-800 dark:text-white",
            rows: 4,
            value: formData.notes || "",
            onChange: (e) => setFormData({ ...formData, notes: e.target.value }),
            placeholder: __(
              "Additional notes about this departure...",
              "yatra"
            )
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          HelpText,
          {
            text: __(
              "Internal notes about this departure (not visible to customers)",
              "yatra"
            )
          }
        )
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-end gap-3 pt-4 border-t border-gray-200 dark:border-gray-700", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { type: "button", variant: "outline", onClick: handleBack, children: __("Cancel", "yatra") }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { type: "submit", disabled: saveMutation.isPending, children: saveMutation.isPending ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Loader2, { className: "w-4 h-4 mr-2 animate-spin" }),
          __("Saving...", "yatra")
        ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Save, { className: "w-4 h-4 mr-2" }),
          __("Save Departure", "yatra")
        ] }) })
      ] })
    ] }) }) })
  ] });
};
const SkeletonMetricCard = () => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-center p-4 bg-gray-50 dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700", children: [
  /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-8 bg-gray-200 dark:bg-gray-700 rounded animate-pulse mb-2 w-16 mx-auto" }),
  /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded animate-pulse w-20 mx-auto" })
] });
const SVGIcons = {
  Truck: () => /* @__PURE__ */ jsxRuntimeExports.jsxs(
    "svg",
    {
      className: "w-6 h-6",
      fill: "none",
      stroke: "currentColor",
      viewBox: "0 0 24 24",
      children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "path",
          {
            strokeLinecap: "round",
            strokeLinejoin: "round",
            strokeWidth: 2,
            d: "M9 17a2 2 0 11-4 0 2 2 0 014 0zM21 17a2 2 0 11-4 0 2 2 0 014 0z"
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "path",
          {
            strokeLinecap: "round",
            strokeLinejoin: "round",
            strokeWidth: 2,
            d: "M1 1h4l2.68 13.39a2 2 0 002 1.61h9.72a2 2 0 002-1.61L23 6H6"
          }
        )
      ]
    }
  ),
  Calendar: () => /* @__PURE__ */ jsxRuntimeExports.jsx(
    "svg",
    {
      className: "w-6 h-6",
      fill: "none",
      stroke: "currentColor",
      viewBox: "0 0 24 24",
      children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        "path",
        {
          strokeLinecap: "round",
          strokeLinejoin: "round",
          strokeWidth: 2,
          d: "M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"
        }
      )
    }
  ),
  Users: () => /* @__PURE__ */ jsxRuntimeExports.jsx(
    "svg",
    {
      className: "w-6 h-6",
      fill: "none",
      stroke: "currentColor",
      viewBox: "0 0 24 24",
      children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        "path",
        {
          strokeLinecap: "round",
          strokeLinejoin: "round",
          strokeWidth: 2,
          d: "M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197m13.5-9a4 4 0 11-8 0 4 4 0 018 0z"
        }
      )
    }
  ),
  DollarSign: () => /* @__PURE__ */ jsxRuntimeExports.jsx(
    "svg",
    {
      className: "w-6 h-6",
      fill: "none",
      stroke: "currentColor",
      viewBox: "0 0 24 24",
      children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        "path",
        {
          strokeLinecap: "round",
          strokeLinejoin: "round",
          strokeWidth: 2,
          d: "M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1"
        }
      )
    }
  ),
  Activity: () => /* @__PURE__ */ jsxRuntimeExports.jsx(
    "svg",
    {
      className: "w-6 h-6",
      fill: "none",
      stroke: "currentColor",
      viewBox: "0 0 24 24",
      children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        "path",
        {
          strokeLinecap: "round",
          strokeLinejoin: "round",
          strokeWidth: 2,
          d: "M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"
        }
      )
    }
  ),
  BarChart: () => /* @__PURE__ */ jsxRuntimeExports.jsx(
    "svg",
    {
      className: "w-6 h-6",
      fill: "none",
      stroke: "currentColor",
      viewBox: "0 0 24 24",
      children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        "path",
        {
          strokeLinecap: "round",
          strokeLinejoin: "round",
          strokeWidth: 2,
          d: "M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"
        }
      )
    }
  ),
  MapPin: () => /* @__PURE__ */ jsxRuntimeExports.jsxs(
    "svg",
    {
      className: "w-6 h-6",
      fill: "none",
      stroke: "currentColor",
      viewBox: "0 0 24 24",
      children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "path",
          {
            strokeLinecap: "round",
            strokeLinejoin: "round",
            strokeWidth: 2,
            d: "M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "path",
          {
            strokeLinecap: "round",
            strokeLinejoin: "round",
            strokeWidth: 2,
            d: "M15 11a3 3 0 11-6 0 3 3 0 016 0z"
          }
        )
      ]
    }
  ),
  FileText: () => /* @__PURE__ */ jsxRuntimeExports.jsx(
    "svg",
    {
      className: "w-6 h-6",
      fill: "none",
      stroke: "currentColor",
      viewBox: "0 0 24 24",
      children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        "path",
        {
          strokeLinecap: "round",
          strokeLinejoin: "round",
          strokeWidth: 2,
          d: "M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
        }
      )
    }
  ),
  Info: () => /* @__PURE__ */ jsxRuntimeExports.jsx(
    "svg",
    {
      className: "w-6 h-6",
      fill: "none",
      stroke: "currentColor",
      viewBox: "0 0 24 24",
      children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        "path",
        {
          strokeLinecap: "round",
          strokeLinejoin: "round",
          strokeWidth: 2,
          d: "M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
        }
      )
    }
  ),
  XCircle: () => /* @__PURE__ */ jsxRuntimeExports.jsx(
    "svg",
    {
      className: "w-6 h-6",
      fill: "none",
      stroke: "currentColor",
      viewBox: "0 0 24 24",
      children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        "path",
        {
          strokeLinecap: "round",
          strokeLinejoin: "round",
          strokeWidth: 2,
          d: "M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"
        }
      )
    }
  )
};
const ViewDeparture = () => {
  var _a, _b;
  const [activeTab, setActiveTab] = reactExports.useState("overview");
  const params = new URLSearchParams(window.location.search);
  const idParam = params.get("id");
  const tripIdParam = params.get("trip_id");
  const id = idParam ? parseInt(idParam, 10) : NaN;
  const tripId = tripIdParam ? parseInt(tripIdParam, 10) : NaN;
  const {
    data: departureData,
    isLoading,
    error
  } = useQuery({
    queryKey: ["departure-details", tripId, id],
    enabled: Number.isFinite(id) && Number.isFinite(tripId),
    queryFn: async () => {
      if (!Number.isFinite(id) || !Number.isFinite(tripId)) {
        throw new Error(__("Invalid departure or trip ID", "yatra"));
      }
      const response = await apiClient.get(`/trips/${tripId}/departures/${id}`);
      const payload = (response == null ? void 0 : response.data) ?? response;
      return payload && typeof payload === "object" ? payload : {};
    }
  });
  const formatCurrency2 = (amount) => {
    return new Intl.NumberFormat("en-US", {
      style: "currency",
      currency: "USD"
    }).format(amount);
  };
  const formatDate2 = (dateString) => {
    return formatDate$1(dateString);
  };
  const formatTime = (timeString) => {
    return (/* @__PURE__ */ new Date(`2000-01-01T${timeString}`)).toLocaleTimeString("en-US", {
      hour: "numeric",
      minute: "2-digit",
      hour12: true
    });
  };
  if (!Number.isFinite(id) || !Number.isFinite(tripId)) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-6", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("h2", { className: "text-xl font-bold text-red-800 dark:text-red-400 flex items-center gap-2", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(SVGIcons.XCircle, {}),
        __("Departure Not Found", "yatra")
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-red-600 dark:text-red-400 mt-2", children: __(
        "Missing or invalid departure ID or trip ID in the URL.",
        "yatra"
      ) })
    ] });
  }
  if (isLoading) {
    return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-6", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 p-6", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "animate-pulse", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-8 bg-gray-200 dark:bg-gray-700 rounded w-1/3 mb-4" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-2/3 mb-6" }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-3 gap-4", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-24 bg-gray-200 dark:bg-gray-700 rounded" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-24 bg-gray-200 dark:bg-gray-700 rounded" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-24 bg-gray-200 dark:bg-gray-700 rounded" })
      ] })
    ] }) }) });
  }
  if (error) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-6", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("h2", { className: "text-xl font-bold text-red-800 dark:text-red-400 flex items-center gap-2", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(SVGIcons.XCircle, {}),
        __("Error Loading Departure", "yatra")
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-red-600 dark:text-red-400 mt-2", children: (error == null ? void 0 : error.message) || __("Unable to load departure details.", "yatra") })
    ] });
  }
  const departure = departureData || {};
  const trip = departure.trip || {};
  const maxCapacity = departure.max_capacity || 0;
  const bookedCount = departure.booked_count || 0;
  const availableSpots = maxCapacity - bookedCount;
  const occupancyRate = maxCapacity > 0 ? bookedCount / maxCapacity * 100 : 0;
  const getStatusStyle = (status) => {
    switch (status) {
      case "confirmed":
        return "bg-green-100 dark:bg-green-900/20 text-green-800 dark:text-green-400 border-green-200 dark:border-green-800";
      case "upcoming":
        return "bg-blue-100 dark:bg-blue-900/20 text-blue-800 dark:text-blue-400 border-blue-200 dark:border-blue-800";
      case "full":
        return "bg-orange-100 dark:bg-orange-900/20 text-orange-800 dark:text-orange-400 border-orange-200 dark:border-orange-800";
      case "past":
        return "bg-gray-100 dark:bg-gray-800 text-gray-800 dark:text-gray-300 border-gray-200 dark:border-gray-700";
      case "cancelled":
        return "bg-red-100 dark:bg-red-900/20 text-red-800 dark:text-red-400 border-red-200 dark:border-red-800";
      default:
        return "bg-gray-100 dark:bg-gray-800 text-gray-800 dark:text-gray-300 border-gray-200 dark:border-gray-700";
    }
  };
  const tabs = [
    { id: "overview", label: "Overview", icon: "BarChart" },
    { id: "bookings", label: "Bookings", icon: "Calendar" },
    { id: "travelers", label: "Travelers", icon: "Users" },
    { id: "financials", label: "Financials", icon: "DollarSign" },
    { id: "operations", label: "Operations", icon: "Activity" }
  ];
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-6", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardTitle, { className: "flex items-center gap-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(SVGIcons.Truck, {}),
            trip.title || __("Departure Details", "yatra")
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardDescription, { children: [
            departure.start_date && formatDate2(departure.start_date),
            departure.time && ` ${__("at", "yatra")} ${formatTime(departure.time)}`
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Badge,
            {
              variant: departure.status === "confirmed" ? "success" : departure.status === "cancelled" ? "error" : "default",
              children: departure.status || __("upcoming", "yatra")
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "px-3 py-1 rounded-full text-sm font-medium bg-gray-100 dark:bg-gray-800 text-gray-800 dark:text-gray-200 border border-gray-200 dark:border-gray-700", children: [
            "ID: ",
            departure.id
          ] })
        ] })
      ] }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { children: isLoading ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid grid-cols-1 md:grid-cols-4 gap-6", children: [...Array(4)].map((_, i) => /* @__PURE__ */ jsxRuntimeExports.jsx(SkeletonMetricCard, {}, i)) }) : /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-4 gap-6", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-center p-4 bg-blue-50 rounded-lg border border-blue-200", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-3xl font-bold text-blue-600", children: bookedCount }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-blue-800 mt-1", children: __("Bookings", "yatra") })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-center p-4 bg-green-50 rounded-lg border border-green-200", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-3xl font-bold text-green-600", children: maxCapacity }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-green-800 mt-1", children: __("Total Capacity", "yatra") })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-center p-4 bg-purple-50 rounded-lg border border-purple-200", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-3xl font-bold text-purple-600", children: [
            occupancyRate.toFixed(1),
            "%"
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-purple-800 mt-1", children: __("Occupancy Rate", "yatra") })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-center p-4 bg-orange-50 rounded-lg border border-orange-200", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-3xl font-bold text-orange-600", children: formatCurrency2(departure.total_revenue || 0) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-orange-800 mt-1", children: __("Total Revenue", "yatra") })
        ] })
      ] }) })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "border-b border-gray-200 dark:border-gray-700", children: /* @__PURE__ */ jsxRuntimeExports.jsx("nav", { className: "flex space-x-8 px-6", children: tabs.map((tab) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "button",
        {
          onClick: () => setActiveTab(tab.id),
          className: `py-4 px-3 border-b-2 font-medium text-sm transition-colors flex items-center justify-between min-w-[120px] ${activeTab === tab.id ? "border-blue-500 text-blue-600 dark:text-blue-400" : "border-transparent text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 hover:border-gray-300 dark:hover:border-gray-600"}`,
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "flex items-center", children: React.createElement(
              SVGIcons[tab.icon]
            ) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "ml-2", children: tab.label })
          ]
        },
        tab.id
      )) }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "p-6", children: [
        activeTab === "overview" && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-6", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-2 gap-6", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-gray-50 dark:bg-gray-800 rounded-lg p-6", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("h3", { className: "text-lg font-semibold text-gray-900 dark:text-white mb-4 flex items-center gap-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(SVGIcons.Calendar, {}),
                __("Departure Information", "yatra")
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-gray-600 dark:text-gray-400", children: [
                    __("Start Date", "yatra"),
                    ":"
                  ] }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-medium text-gray-900 dark:text-white", children: departure.start_date ? formatDate2(departure.start_date) : "--" })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-gray-600 dark:text-gray-400", children: [
                    __("End Date", "yatra"),
                    ":"
                  ] }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-medium text-gray-900 dark:text-white", children: departure.end_date ? formatDate2(departure.end_date) : "--" })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-gray-600 dark:text-gray-400", children: [
                    __("Departure Time", "yatra"),
                    ":"
                  ] }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-medium text-gray-900 dark:text-white", children: departure.time ? formatTime(departure.time) : "--" })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-gray-600 dark:text-gray-400", children: [
                    __("Duration", "yatra"),
                    ":"
                  ] }),
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "font-medium text-gray-900 dark:text-white", children: [
                    trip.duration_days || "--",
                    " days"
                  ] })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-gray-600 dark:text-gray-400", children: [
                    __("Source", "yatra"),
                    ":"
                  ] }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-medium text-gray-900 dark:text-white", children: departure.source || "Manual" })
                ] })
              ] })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-gray-50 dark:bg-gray-800 rounded-lg p-6", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("h3", { className: "text-lg font-semibold text-gray-900 dark:text-white mb-4 flex items-center gap-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(SVGIcons.Users, {}),
                __("Capacity Management", "yatra")
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-4", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between mb-2", children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-600 dark:text-gray-400", children: __("Occupancy", "yatra") }),
                    /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "font-medium text-gray-900 dark:text-white", children: [
                      occupancyRate.toFixed(1),
                      "%"
                    ] })
                  ] }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-full bg-gray-200 dark:bg-gray-700 rounded-full h-3", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "div",
                    {
                      className: "bg-blue-600 h-3 rounded-full transition-all duration-300",
                      style: { width: `${Math.min(occupancyRate, 100)}%` }
                    }
                  ) })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-3 gap-4 text-center", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-2xl font-bold text-blue-600 dark:text-blue-400", children: bookedCount }),
                    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-xs text-gray-600 dark:text-gray-400", children: __("Booked", "yatra") })
                  ] }),
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-2xl font-bold text-green-600 dark:text-green-400", children: availableSpots }),
                    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-xs text-gray-600 dark:text-gray-400", children: __("Available", "yatra") })
                  ] }),
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-2xl font-bold text-gray-600 dark:text-gray-400", children: maxCapacity }),
                    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-xs text-gray-600 dark:text-gray-400", children: __("Total", "yatra") })
                  ] })
                ] })
              ] })
            ] })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-gray-50 dark:bg-gray-800 rounded-lg p-6", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("h3", { className: "text-lg font-semibold text-gray-900 dark:text-white mb-4 flex items-center gap-2", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(SVGIcons.MapPin, {}),
              __("Trip Details", "yatra")
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-gray-600 dark:text-gray-400 text-sm", children: [
                  __("Starting Location", "yatra"),
                  ":"
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "font-medium text-gray-900 dark:text-white", children: trip.starting_location || "--" })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-gray-600 dark:text-gray-400 text-sm", children: [
                  __("Ending Location", "yatra"),
                  ":"
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "font-medium text-gray-900 dark:text-white", children: trip.ending_location || "--" })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-gray-600 dark:text-gray-400 text-sm", children: [
                  __("Difficulty Level", "yatra"),
                  ":"
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "font-medium text-gray-900 dark:text-white", children: trip.difficulty_level || "--" })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-gray-600 dark:text-gray-400 text-sm", children: [
                  __("Group Type", "yatra"),
                  ":"
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "font-medium text-gray-900 dark:text-white", children: trip.group_type || "--" })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-gray-600 dark:text-gray-400 text-sm", children: [
                  __("Min Travelers", "yatra"),
                  ":"
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "font-medium text-gray-900 dark:text-white", children: trip.min_travelers || "--" })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-gray-600 dark:text-gray-400 text-sm", children: [
                  __("Max Travelers", "yatra"),
                  ":"
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "font-medium text-gray-900 dark:text-white", children: trip.max_travelers || "--" })
              ] }),
              trip.duration && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-gray-600 dark:text-gray-400 text-sm", children: [
                  __("Duration", "yatra"),
                  ":"
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "font-medium text-gray-900 dark:text-white", children: [
                  trip.duration,
                  " ",
                  __("days", "yatra")
                ] })
              ] }),
              trip.created_at && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-gray-600 dark:text-gray-400 text-sm", children: [
                  __("Trip Created", "yatra"),
                  ":"
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "font-medium text-gray-900 dark:text-white", children: formatDate2(trip.created_at) })
              ] }),
              trip.price && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-gray-600 dark:text-gray-400 text-sm", children: [
                  __("Base Price", "yatra"),
                  ":"
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "font-medium text-gray-900 dark:text-white", children: formatCurrency2(trip.price) })
              ] })
            ] })
          ] }),
          departure.notes && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg p-6", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("h3", { className: "text-lg font-semibold text-yellow-800 dark:text-yellow-300 mb-2 flex items-center gap-2", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(SVGIcons.FileText, {}),
              __("Notes", "yatra")
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-yellow-700 dark:text-yellow-400 whitespace-pre-wrap", children: departure.notes })
          ] })
        ] }),
        activeTab === "bookings" && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-4", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between items-center", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("h3", { className: "text-lg font-semibold text-gray-900 dark:text-white flex items-center gap-2", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(SVGIcons.Calendar, {}),
              __("Linked Bookings", "yatra")
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-sm text-gray-600 dark:text-gray-400", children: [
              ((_a = departure.booking_ids) == null ? void 0 : _a.length) || 0,
              " ",
              __("bookings", "yatra")
            ] })
          ] }),
          departure.booking_ids && departure.booking_ids.length > 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid gap-4", children: departure.booking_ids.map((bookingId) => /* @__PURE__ */ jsxRuntimeExports.jsx(
            "div",
            {
              className: "bg-gray-50 dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg p-4",
              children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between items-start", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("h4", { className: "font-medium text-gray-900 dark:text-white", children: [
                    __("Booking", "yatra"),
                    " #",
                    bookingId
                  ] }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-600 dark:text-gray-400 mt-1", children: __("Click to view booking details", "yatra") })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "px-2 py-1 bg-blue-100 dark:bg-blue-900/20 text-blue-800 dark:text-blue-400 text-xs rounded", children: __("Active", "yatra") }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "a",
                    {
                      href: `?page=yatra&subpage=bookings&action=view&id=${bookingId}`,
                      className: "text-blue-600 hover:text-blue-800 text-sm font-medium",
                      children: "View →"
                    }
                  )
                ] })
              ] })
            },
            bookingId
          )) }) : /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-center py-12 bg-gray-50 dark:bg-gray-800 rounded-lg", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-16 h-16 mx-auto mb-4 text-gray-400 dark:text-gray-500", children: /* @__PURE__ */ jsxRuntimeExports.jsx(SVGIcons.Calendar, {}) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-lg font-medium text-gray-900 dark:text-white mt-4", children: __("No Bookings Yet", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-gray-600 dark:text-gray-400 mt-2", children: __(
              "This departure doesn't have any linked bookings.",
              "yatra"
            ) })
          ] })
        ] }),
        activeTab === "travelers" && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-4", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between items-center", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("h3", { className: "text-lg font-semibold text-gray-900 dark:text-white flex items-center gap-2", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(SVGIcons.Users, {}),
              __("Travelers", "yatra")
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-sm text-gray-600 dark:text-gray-400", children: [
              ((_b = departure.travelers) == null ? void 0 : _b.length) || 0,
              " ",
              __("travelers", "yatra")
            ] })
          ] }),
          departure.travelers && departure.travelers.length > 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid gap-4", children: departure.travelers.map((traveler, index) => /* @__PURE__ */ jsxRuntimeExports.jsx(
            "div",
            {
              className: "bg-gray-50 dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg p-4",
              children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between items-start", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("h4", { className: "font-medium text-gray-900 dark:text-white", children: [
                    traveler.first_name,
                    " ",
                    traveler.last_name,
                    traveler.is_lead && /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "ml-2 px-2 py-1 bg-blue-100 dark:bg-blue-900/20 text-blue-800 dark:text-blue-400 text-xs rounded", children: __("Lead", "yatra") })
                  ] }),
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "text-sm text-gray-600 dark:text-gray-400 mt-1", children: [
                    traveler.email && /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "block", children: traveler.email }),
                    traveler.phone && /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "block", children: traveler.phone })
                  ] })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-right", children: traveler.booking_reference && /* @__PURE__ */ jsxRuntimeExports.jsxs(
                  "a",
                  {
                    href: `?page=yatra&subpage=bookings&action=view&id=${traveler.booking_id}`,
                    className: "text-blue-600 hover:text-blue-800 text-sm font-medium",
                    children: [
                      "Booking #",
                      traveler.booking_reference
                    ]
                  }
                ) })
              ] })
            },
            traveler.id || index
          )) }) : /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-center py-12 bg-gray-50 dark:bg-gray-800 rounded-lg", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-16 h-16 mx-auto mb-4 text-gray-400 dark:text-gray-500", children: /* @__PURE__ */ jsxRuntimeExports.jsx(SVGIcons.Users, {}) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-lg font-medium text-gray-900 dark:text-white mt-4", children: __("No Travelers Yet", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-gray-600 dark:text-gray-400 mt-2", children: __(
              "No travelers have been assigned to this departure.",
              "yatra"
            ) })
          ] })
        ] }),
        activeTab === "financials" && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-6", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("h3", { className: "text-lg font-semibold text-gray-900 dark:text-white flex items-center gap-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(SVGIcons.DollarSign, {}),
            __("Financial Overview", "yatra")
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-3 gap-6", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-lg p-6 text-center", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-3xl font-bold text-green-600 dark:text-green-400", children: formatCurrency2(departure.total_revenue || 0) }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-green-800 dark:text-green-300 mt-1", children: __("Total Revenue", "yatra") })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-6 text-center", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-3xl font-bold text-blue-600 dark:text-blue-400", children: formatCurrency2(departure.collected_amount || 0) }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-blue-800 dark:text-blue-300 mt-1", children: __("Collected", "yatra") })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-orange-50 dark:bg-orange-900/20 border border-orange-200 dark:border-orange-800 rounded-lg p-6 text-center", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-3xl font-bold text-orange-600 dark:text-orange-400", children: formatCurrency2(
                (departure.total_revenue || 0) - (departure.collected_amount || 0)
              ) }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-orange-800 dark:text-orange-300 mt-1", children: __("Pending", "yatra") })
            ] })
          ] }),
          departure.price_override && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg p-4", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("h4", { className: "font-medium text-yellow-800 dark:text-yellow-300 flex items-center gap-2", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(SVGIcons.Info, {}),
              __("Price Override Active", "yatra")
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "text-yellow-700 dark:text-yellow-400 text-sm mt-1", children: [
              __("This departure has a custom price of", "yatra"),
              " ",
              formatCurrency2(departure.price_override),
              __("instead of the standard trip price.", "yatra")
            ] })
          ] })
        ] }),
        activeTab === "operations" && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-6", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("h3", { className: "text-lg font-semibold text-gray-900 dark:text-white flex items-center gap-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(SVGIcons.Activity, {}),
            __("Operational Details", "yatra")
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-2 gap-6", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-gray-50 dark:bg-gray-800 rounded-lg p-6", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("h4", { className: "font-medium text-gray-900 dark:text-white mb-4 flex items-center gap-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(SVGIcons.BarChart, {}),
                __("Status Information", "yatra")
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-gray-600 dark:text-gray-400", children: [
                    __("Current Status", "yatra"),
                    ":"
                  ] }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "span",
                    {
                      className: `px-2 py-1 rounded text-sm font-medium ${getStatusStyle(departure.status || "upcoming")}`,
                      children: departure.status || "upcoming"
                    }
                  )
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-gray-600 dark:text-gray-400", children: [
                    __("Created", "yatra"),
                    ":"
                  ] }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-medium text-gray-900 dark:text-white", children: departure.created_at ? formatDate2(departure.created_at) : "--" })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-gray-600 dark:text-gray-400", children: [
                    __("Last Updated", "yatra"),
                    ":"
                  ] }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-medium text-gray-900 dark:text-white", children: departure.updated_at ? formatDate2(departure.updated_at) : "--" })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-gray-600 dark:text-gray-400", children: [
                    __("Source", "yatra"),
                    ":"
                  ] }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-medium text-gray-900 dark:text-white", children: departure.source || "Manual" })
                ] })
              ] })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-gray-50 dark:bg-gray-800 rounded-lg p-6", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("h4", { className: "font-medium text-gray-900 dark:text-white mb-4 flex items-center gap-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(SVGIcons.Activity, {}),
                __("Performance Metrics", "yatra")
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-gray-600 dark:text-gray-400", children: [
                    __("Booking Efficiency", "yatra"),
                    ":"
                  ] }),
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "font-medium text-gray-900 dark:text-white", children: [
                    occupancyRate.toFixed(1),
                    "%"
                  ] })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-gray-600 dark:text-gray-400", children: [
                    __("Revenue per Seat", "yatra"),
                    ":"
                  ] }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-medium text-gray-900 dark:text-white", children: formatCurrency2(
                    (departure.total_revenue || 0) / Math.max(maxCapacity, 1)
                  ) })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-gray-600 dark:text-gray-400", children: [
                    __("Utilization Rate", "yatra"),
                    ":"
                  ] }),
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "font-medium text-gray-900 dark:text-white", children: [
                    occupancyRate.toFixed(1),
                    "%"
                  ] })
                ] })
              ] })
            ] })
          ] })
        ] })
      ] })
    ] })
  ] });
};
const EnquiryReplyAffordance = ({
  enquiryId,
  value,
  onAccept,
  onDraftingChange,
  autoDraftOnMount = false,
  className = ""
}) => {
  const [menuOpen, setMenuOpen] = reactExports.useState(false);
  const [isRunning, setIsRunning] = reactExports.useState(false);
  const [error, setError] = reactExports.useState(null);
  const [preview, setPreview] = reactExports.useState(null);
  const [includeSensitive, setIncludeSensitive] = reactExports.useState(false);
  const wrapperRef = reactExports.useRef(null);
  const autoDraftedRef = reactExports.useRef(false);
  const gateBlocks = !isAiEligible() || !isAiModuleEnabled();
  const ready = isAiReady();
  reactExports.useEffect(() => {
    if (!menuOpen) return;
    const onDoc = (e) => {
      if (wrapperRef.current && !wrapperRef.current.contains(e.target)) {
        setMenuOpen(false);
      }
    };
    document.addEventListener("mousedown", onDoc);
    return () => document.removeEventListener("mousedown", onDoc);
  }, [menuOpen]);
  const runDraft = reactExports.useCallback(
    async (variant) => {
      if (!ready) {
        setError(
          __(
            "Add an API key in Yatra → AI Assistant before drafting replies.",
            "yatra"
          )
        );
        return;
      }
      setMenuOpen(false);
      setError(null);
      setIsRunning(true);
      onDraftingChange == null ? void 0 : onDraftingChange(true);
      try {
        const res = await aiApi.draftEnquiryReply(enquiryId, {
          variant,
          current_value: value,
          include_sensitive: includeSensitive
        });
        setPreview({ text: res.text, variant });
      } catch (e) {
        setError(extractError(e));
      } finally {
        setIsRunning(false);
        onDraftingChange == null ? void 0 : onDraftingChange(false);
      }
    },
    [enquiryId, value, includeSensitive, ready, onDraftingChange]
  );
  reactExports.useEffect(() => {
    if (!autoDraftOnMount || autoDraftedRef.current) return;
    if (!ready) return;
    if (value.trim() !== "") return;
    if (enquiryId <= 0) return;
    autoDraftedRef.current = true;
    runDraft("fresh");
  }, [autoDraftOnMount, ready, enquiryId]);
  const accept = () => {
    if (!preview) return;
    onAccept(preview.text);
    setPreview(null);
  };
  const tryAgain = () => {
    if (!preview) return;
    runDraft(preview.variant);
  };
  const hasValue = value.trim() !== "";
  if (gateBlocks) {
    return null;
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { ref: wrapperRef, className: `relative inline-block ${className}`, children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "button",
      {
        type: "button",
        onClick: () => {
          if (!ready) {
            setError(
              __("Add an API key in Yatra → AI Assistant first.", "yatra")
            );
            return;
          }
          if (preview) return;
          setMenuOpen((v) => !v);
          setError(null);
        },
        disabled: isRunning,
        title: __("AI: draft a reply", "yatra"),
        className: `inline-flex items-center gap-1 rounded-md border px-2 py-1 text-xs font-medium transition-colors ${isRunning ? "border-blue-200 bg-blue-50 text-blue-500 dark:border-blue-500/40 dark:bg-blue-900/20 dark:text-blue-300" : "border-blue-300 bg-blue-50 text-blue-700 hover:border-blue-400 hover:bg-blue-100 dark:border-blue-500/40 dark:bg-blue-900/20 dark:text-blue-200 dark:hover:bg-blue-900/40"}`,
        "aria-label": __("Draft reply with AI", "yatra"),
        children: [
          isRunning ? /* @__PURE__ */ jsxRuntimeExports.jsx(Loader2, { className: "h-3.5 w-3.5 animate-spin" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(Sparkles, { className: "h-3.5 w-3.5" }),
          __("Draft reply", "yatra")
        ]
      }
    ),
    menuOpen && !preview && /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "div",
      {
        className: "absolute right-0 z-30 mt-1 w-64 rounded-md border border-gray-200 bg-white p-1 text-sm shadow-lg dark:border-gray-700 dark:bg-gray-800",
        role: "menu",
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "button",
            {
              type: "button",
              onClick: () => runDraft("fresh"),
              className: "flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-gray-700 hover:bg-blue-50 dark:text-gray-200 dark:hover:bg-blue-900/30",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Wand2, { className: "h-4 w-4 text-blue-500" }),
                hasValue ? __("Regenerate from scratch", "yatra") : __("Generate reply", "yatra")
              ]
            }
          ),
          hasValue && /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "button",
              {
                type: "button",
                onClick: () => runDraft("warmer"),
                className: "flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-gray-700 hover:bg-blue-50 dark:text-gray-200 dark:hover:bg-blue-900/30",
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(Heart, { className: "h-4 w-4 text-blue-400" }),
                  __("Make warmer", "yatra")
                ]
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "button",
              {
                type: "button",
                onClick: () => runDraft("shorter"),
                className: "flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-gray-700 hover:bg-blue-50 dark:text-gray-200 dark:hover:bg-blue-900/30",
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(Scissors, { className: "h-4 w-4 text-blue-400" }),
                  __("Make shorter", "yatra")
                ]
              }
            )
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "my-1 border-t border-gray-100 dark:border-gray-700" }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("label", { className: "flex items-start gap-2 px-2 py-1.5 text-xs text-gray-600 dark:text-gray-300", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "input",
              {
                type: "checkbox",
                className: "mt-0.5",
                checked: includeSensitive,
                onChange: (e) => setIncludeSensitive(e.target.checked)
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { children: [
              includeSensitive ? /* @__PURE__ */ jsxRuntimeExports.jsx(ShieldOff, { className: "mr-1 inline h-3 w-3 text-amber-500" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(Shield, { className: "mr-1 inline h-3 w-3 text-green-500" }),
              __(
                "Include dietary / medical / special-needs in prompt",
                "yatra"
              )
            ] })
          ] })
        ]
      }
    ),
    preview && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "absolute right-0 z-30 mt-1 w-[480px] max-w-[90vw] rounded-md border border-blue-200 bg-white p-3 text-sm shadow-xl dark:border-blue-500/40 dark:bg-gray-800", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mb-2 flex items-center gap-2 text-xs font-medium text-blue-600 dark:text-blue-300", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Sparkles, { className: "h-3.5 w-3.5" }),
        preview.variant === "fresh" ? __("AI drafted this reply", "yatra") : preview.variant === "warmer" ? __("AI rewrote to be warmer", "yatra") : __("AI rewrote to be shorter", "yatra")
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("pre", { className: "max-h-72 overflow-y-auto whitespace-pre-wrap rounded border border-gray-100 bg-gray-50 p-2 text-xs text-gray-800 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-200", children: preview.text || /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-400", children: __("(empty response)", "yatra") }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-2 flex items-center justify-end gap-2", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "button",
          {
            type: "button",
            onClick: tryAgain,
            className: "rounded border border-gray-200 px-2 py-1 text-xs text-gray-600 hover:bg-gray-50 dark:border-gray-600 dark:text-gray-300 dark:hover:bg-gray-700",
            children: __("Try again", "yatra")
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "button",
          {
            type: "button",
            onClick: () => setPreview(null),
            className: "inline-flex items-center gap-1 rounded border border-gray-200 px-2 py-1 text-xs text-gray-600 hover:bg-gray-50 dark:border-gray-600 dark:text-gray-300 dark:hover:bg-gray-700",
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(X, { className: "h-3 w-3" }),
              __("Discard", "yatra")
            ]
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "button",
          {
            type: "button",
            onClick: accept,
            disabled: !preview.text,
            className: "inline-flex items-center gap-1 rounded bg-blue-600 px-3 py-1 text-xs font-medium text-white hover:bg-blue-700 disabled:opacity-50",
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Check, { className: "h-3 w-3" }),
              __("Use this reply", "yatra")
            ]
          }
        )
      ] })
    ] }),
    error && !preview && /* @__PURE__ */ jsxRuntimeExports.jsx(
      "div",
      {
        className: "absolute right-0 z-30 mt-1 w-72 rounded-md border border-red-200 bg-white p-2 text-xs text-red-700 shadow-lg dark:border-red-500/40 dark:bg-gray-800 dark:text-red-300",
        role: "alert",
        children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start gap-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(AlertTriangle, { className: "mt-0.5 h-3.5 w-3.5 shrink-0" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex-1", children: error }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "button",
            {
              type: "button",
              onClick: () => setError(null),
              className: "text-red-400 hover:text-red-600",
              "aria-label": __("Dismiss", "yatra"),
              children: /* @__PURE__ */ jsxRuntimeExports.jsx(X, { className: "h-3.5 w-3.5" })
            }
          )
        ] })
      }
    )
  ] });
};
function extractError(e) {
  var _a;
  if (!e) return "AI request failed.";
  const data = ((_a = e == null ? void 0 : e.response) == null ? void 0 : _a.data) ?? (e == null ? void 0 : e.data) ?? null;
  if (data && typeof data === "object" && typeof data.message === "string") {
    return data.message;
  }
  if (typeof (e == null ? void 0 : e.message) === "string") return e.message;
  return String(e);
}
const Enquiries = () => {
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q;
  const [searchTerm, setSearchTerm] = reactExports.useState("");
  const [statusFilter, setStatusFilter] = reactExports.useState("all");
  const [sortBy2, setSortBy] = reactExports.useState("created_at");
  const [sortOrder, setSortOrder] = reactExports.useState("desc");
  const [page, setPage] = reactExports.useState(1);
  const [respondDialogOpen, setRespondDialogOpen] = reactExports.useState(false);
  const [selectedEnquiry, setSelectedEnquiry] = reactExports.useState(null);
  const [responseMessage, setResponseMessage] = reactExports.useState("");
  const [deleteDialogOpen, setDeleteDialogOpen] = reactExports.useState(false);
  const [enquiryToDelete, setEnquiryToDelete] = reactExports.useState(null);
  const [selectedIds, setSelectedIds] = reactExports.useState([]);
  const [bulkAction, setBulkAction] = reactExports.useState("");
  const [bulkConfirmOpen, setBulkConfirmOpen] = reactExports.useState(false);
  const [bulkApplying, setBulkApplying] = reactExports.useState(false);
  const [pendingBulkAction, setPendingBulkAction] = reactExports.useState(
    null
  );
  const [showColumnsDropdown, setShowColumnsDropdown] = reactExports.useState(false);
  const [visibleColumns, setVisibleColumns] = reactExports.useState(() => {
    if (typeof window === "undefined") {
      return {
        customer: true,
        trip: true,
        message: true,
        travelers: true,
        preferred_date: true,
        status: true,
        date: true
      };
    }
    const saved = window.localStorage.getItem(
      "yatra-enquiries-visible-columns"
    );
    return saved ? JSON.parse(saved) : {
      customer: true,
      trip: true,
      message: true,
      travelers: true,
      preferred_date: true,
      status: true,
      date: true
    };
  });
  const bulkActionOptions = reactExports.useMemo(() => {
    if (statusFilter === "trash") {
      return [{ value: "delete", label: __("Delete Permanently", "yatra") }];
    }
    if (statusFilter === "spam") {
      return [
        { value: "mark_trash", label: __("Move to Trash", "yatra") },
        { value: "delete", label: __("Delete Permanently", "yatra") }
      ];
    }
    return [
      { value: "mark_spam", label: __("Mark as Spam", "yatra") },
      { value: "mark_trash", label: __("Move to Trash", "yatra") },
      { value: "delete", label: __("Delete Permanently", "yatra") }
    ];
  }, [statusFilter]);
  const queryClient2 = useQueryClient();
  const { can } = usePermissions();
  const { navigate } = useNavigate();
  const { showToast } = useToast();
  const queryParams = reactExports.useMemo(() => {
    const params = {
      page,
      per_page: 10,
      orderby: sortBy2,
      order: sortOrder
    };
    if (searchTerm) {
      params.search = searchTerm;
    }
    if (statusFilter !== "all") {
      params.status = statusFilter;
    }
    return params;
  }, [searchTerm, statusFilter, sortBy2, sortOrder, page]);
  const { data: statsData } = useQuery({
    queryKey: ["enquiries-stats"],
    queryFn: async () => {
      return await apiService.getEnquiriesStats();
    },
    enabled: can("yatra_view_enquiries")
  });
  const statusCounts = {
    all: (statsData == null ? void 0 : statsData.total) || 0,
    new: ((_b = (_a = statsData == null ? void 0 : statsData.by_status) == null ? void 0 : _a.new) == null ? void 0 : _b.count) || 0,
    pending: ((_d = (_c = statsData == null ? void 0 : statsData.by_status) == null ? void 0 : _c.pending) == null ? void 0 : _d.count) || 0,
    responded: ((_f = (_e = statsData == null ? void 0 : statsData.by_status) == null ? void 0 : _e.responded) == null ? void 0 : _f.count) || 0,
    converted: ((_h = (_g = statsData == null ? void 0 : statsData.by_status) == null ? void 0 : _g.converted) == null ? void 0 : _h.count) || 0,
    closed: ((_j = (_i = statsData == null ? void 0 : statsData.by_status) == null ? void 0 : _i.closed) == null ? void 0 : _j.count) || 0,
    spam: ((_l = (_k = statsData == null ? void 0 : statsData.by_status) == null ? void 0 : _k.spam) == null ? void 0 : _l.count) || 0,
    trash: ((_n = (_m = statsData == null ? void 0 : statsData.by_status) == null ? void 0 : _m.trash) == null ? void 0 : _n.count) || 0
  };
  const handleBulkApply = () => {
    if (!bulkAction || selectedIds.length === 0) {
      return;
    }
    setPendingBulkAction(bulkAction);
    setBulkConfirmOpen(true);
  };
  const confirmBulkApply = async () => {
    if (!pendingBulkAction || selectedIds.length === 0) {
      setBulkConfirmOpen(false);
      return;
    }
    setBulkApplying(true);
    try {
      if (["delete", "mark_spam", "mark_trash"].includes(pendingBulkAction)) {
        await apiService.bulkEnquiriesAction(pendingBulkAction, selectedIds);
        queryClient2.invalidateQueries({ queryKey: ["enquiries"] });
      }
    } catch (error2) {
      console.error("Bulk enquiry action error", error2);
    } finally {
      setBulkApplying(false);
      setBulkConfirmOpen(false);
      setPendingBulkAction(null);
      setSelectedIds([]);
      setBulkAction("");
    }
  };
  const toggleColumn = (columnKey) => {
    const newVisible = {
      ...visibleColumns,
      [columnKey]: !visibleColumns[columnKey]
    };
    setVisibleColumns(newVisible);
    if (typeof window !== "undefined") {
      window.localStorage.setItem(
        "yatra-enquiries-visible-columns",
        JSON.stringify(newVisible)
      );
    }
  };
  const columnOptions = [
    {
      key: "customer",
      label: __("Customer", "yatra"),
      visible: visibleColumns.customer
    },
    { key: "trip", label: __("Trip", "yatra"), visible: visibleColumns.trip },
    {
      key: "message",
      label: __("Message", "yatra"),
      visible: visibleColumns.message
    },
    {
      key: "travelers",
      label: __("Travelers", "yatra"),
      visible: visibleColumns.travelers
    },
    {
      key: "preferred_date",
      label: __("Preferred Date", "yatra"),
      visible: visibleColumns.preferred_date
    },
    {
      key: "status",
      label: __("Status", "yatra"),
      visible: visibleColumns.status
    },
    { key: "date", label: __("Date", "yatra"), visible: visibleColumns.date }
  ];
  const actions = [
    {
      key: "view",
      label: __("View", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Eye, { className: "w-4 h-4" }),
      onClick: (enquiry) => handleView(enquiry),
      condition: () => can("yatra_view_enquiries")
    },
    {
      key: "respond",
      label: __("Respond", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Send, { className: "w-4 h-4" }),
      onClick: (enquiry) => handleRespond(enquiry),
      // Respond cap matches the backend gate on EnquiryController's
      // PUT /enquiries/{id} + POST /enquiries/{id}/respond endpoints.
      // Front Desk role holds this cap without holding edit-bookings,
      // so checking the wrong cap would have hidden the action from
      // them while still showing 403-failing buttons to bookings-only
      // roles.
      condition: (enquiry) => can("yatra_respond_to_enquiries") && !["closed", "spam", "trash", "archived"].includes(enquiry.status)
    },
    {
      key: "edit",
      label: __("Edit", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(PenSquare, { className: "w-4 h-4" }),
      onClick: (enquiry) => handleEdit(enquiry),
      // Editing an enquiry status / notes goes through the same
      // PUT endpoint that respond does, gated on respond cap.
      condition: () => can("yatra_respond_to_enquiries")
    },
    {
      key: "delete",
      label: __("Delete", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "w-4 h-4" }),
      onClick: (enquiry) => handleDelete(enquiry),
      variant: "destructive",
      // High-sensitivity cap, distinct from respond. Only Owner /
      // Manager hold it by default.
      condition: () => can("yatra_delete_enquiries")
    }
  ];
  const { data, isLoading, error, refetch } = useQuery({
    queryKey: ["enquiries", queryParams],
    queryFn: async () => {
      var _a2, _b2, _c2;
      const urlParams = new URLSearchParams(window.location.search);
      if (urlParams.get("simulate_error") === "true") {
        throw new Error(
          "Simulated API error for testing error UI functionality"
        );
      }
      const paramsObj = {};
      Object.entries(queryParams).forEach(([key2, value]) => {
        if (value !== void 0 && value !== null) {
          paramsObj[key2] = value;
        }
      });
      const response = await apiService.getEnquiries(paramsObj);
      return {
        data: response.data || [],
        total: ((_a2 = response.meta) == null ? void 0 : _a2.total) || response.total || 0,
        page: ((_b2 = response.meta) == null ? void 0 : _b2.page) || response.page || 1,
        per_page: ((_c2 = response.meta) == null ? void 0 : _c2.per_page) || response.per_page || 10
      };
    },
    enabled: can("yatra_view_enquiries")
  });
  const deleteMutation = useMutation({
    mutationFn: async (id) => {
      await apiService.deleteEnquiry(id);
    },
    onSuccess: () => {
      queryClient2.invalidateQueries({ queryKey: ["enquiries"] });
      setDeleteDialogOpen(false);
      setEnquiryToDelete(null);
    }
  });
  const respondMutation = useMutation({
    mutationFn: async ({ id, message: message2 }) => {
      return await apiService.respondToEnquiry(id, { response: message2 });
    },
    onSuccess: () => {
      queryClient2.invalidateQueries({ queryKey: ["enquiries"] });
      setRespondDialogOpen(false);
      setSelectedEnquiry(null);
      setResponseMessage("");
      showToast(__("Response sent successfully.", "yatra"), "success");
    }
  });
  const enquiriesResponse = data;
  const enquiries = (enquiriesResponse == null ? void 0 : enquiriesResponse.data) || (enquiriesResponse == null ? void 0 : enquiriesResponse.enquiries) || [];
  const total = ((_o = enquiriesResponse == null ? void 0 : enquiriesResponse.meta) == null ? void 0 : _o.total) ?? (enquiriesResponse == null ? void 0 : enquiriesResponse.total) ?? enquiries.length ?? 0;
  const perPage = ((_p = enquiriesResponse == null ? void 0 : enquiriesResponse.meta) == null ? void 0 : _p.per_page) ?? 10;
  const totalPages = Math.max(1, Math.ceil(total / perPage));
  const errorContext = getErrorContext(error);
  const apiErrorMessage = (data == null ? void 0 : data.error) || (data == null ? void 0 : data.message);
  const derivedErrorDetails = errorContext.details || (apiErrorMessage ? String(apiErrorMessage) : void 0) || (error ? String((error == null ? void 0 : error.message) || error) : void 0);
  const isEnquiriesError = !!error || !!apiErrorMessage;
  const formatDate2 = (dateString) => {
    return formatDate$1(dateString);
  };
  const getStatusBadge = (status) => {
    const statusMap = {
      new: {
        className: "bg-blue-100 text-blue-700 dark:bg-blue-900/20 dark:text-blue-400",
        label: __("New", "yatra")
      },
      pending: {
        className: "bg-orange-100 text-orange-700 dark:bg-orange-900/20 dark:text-orange-400",
        label: __("Pending", "yatra")
      },
      responded: {
        className: "bg-yellow-100 text-yellow-700 dark:bg-yellow-900/20 dark:text-yellow-400",
        label: __("Responded", "yatra")
      },
      converted: {
        className: "bg-green-100 text-green-700 dark:bg-green-900/20 dark:text-green-400",
        label: __("Converted", "yatra")
      },
      closed: {
        className: "bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-400",
        label: __("Closed", "yatra")
      },
      spam: {
        className: "bg-red-100 text-red-700 dark:bg-red-900/20 dark:text-red-400",
        label: __("Spam", "yatra")
      },
      trash: {
        className: "bg-gray-100 text-gray-700 dark:bg-gray-900/40 dark:text-gray-300 line-through",
        label: __("Trash", "yatra")
      }
    };
    const statusInfo = statusMap[status] || {
      className: "bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-400",
      label: status
    };
    return /* @__PURE__ */ jsxRuntimeExports.jsx(Badge, { className: `text-xs ${statusInfo.className}`, children: statusInfo.label });
  };
  const handleView = (enquiry) => {
    navigate({ subpage: "enquiries", action: "view", id: enquiry.id });
  };
  const handleEdit = (enquiry) => {
    navigate({ subpage: "enquiries", action: "edit", id: enquiry.id });
  };
  const handleDelete = (enquiry) => {
    setEnquiryToDelete(enquiry);
    setDeleteDialogOpen(true);
  };
  const confirmDelete = () => {
    if (enquiryToDelete) {
      deleteMutation.mutate(enquiryToDelete.id);
    }
  };
  const handleRespond = (enquiry) => {
    setSelectedEnquiry(enquiry);
    setResponseMessage("");
    setRespondDialogOpen(true);
  };
  const sendResponse = () => {
    if (selectedEnquiry && responseMessage.trim()) {
      respondMutation.mutate({
        id: selectedEnquiry.id,
        message: responseMessage
      });
    }
  };
  const handleSort = (field) => {
    if (sortBy2 === field) {
      setSortOrder(sortOrder === "asc" ? "desc" : "asc");
    } else {
      setSortBy(field);
      setSortOrder("desc");
    }
  };
  const getSortIcon = (field) => {
    if (sortBy2 !== field) {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowUpDown, { className: "w-3.5 h-3.5 ml-1 text-gray-400" });
    }
    return sortOrder === "asc" ? /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowUp, { className: "w-3.5 h-3.5 ml-1 text-gray-600 dark:text-gray-300" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowDown, { className: "w-3.5 h-3.5 ml-1 text-gray-600 dark:text-gray-300" });
  };
  const hasFilters = searchTerm || statusFilter !== "all" || sortBy2 !== "created_at" || sortOrder !== "desc";
  const handleResetFilters = () => {
    setSearchTerm("");
    setStatusFilter("all");
    setSortBy("created_at");
    setSortOrder("desc");
    setPage(1);
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      PageHeader,
      {
        title: __("Enquiries", "yatra"),
        description: __("Manage customer enquiries and inquiries", "yatra")
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col md:flex-row gap-2 items-stretch md:items-center", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1 relative", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Search, { className: "absolute left-2.5 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          Input,
          {
            type: "text",
            placeholder: __("Search enquiries...", "yatra"),
            value: searchTerm,
            onChange: (e) => setSearchTerm(e.target.value),
            className: "pl-9"
          }
        )
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Select,
        {
          value: statusFilter,
          onChange: (e) => setStatusFilter(e.target.value),
          className: "w-full md:w-40",
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "all", children: __("All Status", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "new", children: __("New", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "pending", children: __("Pending", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "responded", children: __("Responded", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "converted", children: __("Converted", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "closed", children: __("Closed", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "spam", children: __("Spam", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "trash", children: __("Trash", "yatra") })
          ]
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Select,
        {
          value: sortBy2,
          onChange: (e) => setSortBy(e.target.value),
          className: "w-full md:w-40",
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "created_at", children: __("Date", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "name", children: __("Name", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "email", children: __("Email", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "trip_title", children: __("Trip", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "status", children: __("Status", "yatra") })
          ]
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Button,
        {
          variant: "outline",
          onClick: () => setSortOrder(sortOrder === "asc" ? "desc" : "asc"),
          className: "px-3 flex items-center gap-1.5",
          title: sortOrder === "asc" ? __("Ascending", "yatra") : __("Descending", "yatra"),
          children: [
            sortOrder === "asc" ? /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowUp, { className: "w-4 h-4" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowDown, { className: "w-4 h-4" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs", children: sortOrder === "asc" ? __("Asc", "yatra") : __("Desc", "yatra") })
          ]
        }
      ),
      hasFilters && /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Button,
        {
          variant: "outline",
          onClick: handleResetFilters,
          className: "flex items-center gap-2",
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(X, { className: "w-4 h-4" }),
            __("Reset", "yatra")
          ]
        }
      )
    ] }) }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      BulkActionToolbar,
      {
        selectedIds,
        bulkAction,
        setBulkAction,
        onApply: handleBulkApply,
        onClearSelection: () => setSelectedIds([]),
        statusFilter,
        setStatusFilter: (value) => {
          setStatusFilter(value);
          setPage(1);
          setSelectedIds([]);
          setBulkAction("");
        },
        statusOptions: [
          { key: "all", label: __("All", "yatra"), count: statusCounts.all },
          { key: "new", label: __("New", "yatra"), count: statusCounts.new },
          {
            key: "pending",
            label: __("Pending", "yatra"),
            count: statusCounts.pending
          },
          {
            key: "responded",
            label: __("Responded", "yatra"),
            count: statusCounts.responded
          },
          {
            key: "converted",
            label: __("Converted", "yatra"),
            count: statusCounts.converted
          },
          {
            key: "closed",
            label: __("Closed", "yatra"),
            count: statusCounts.closed
          },
          { key: "spam", label: __("Spam", "yatra"), count: statusCounts.spam },
          {
            key: "trash",
            label: __("Trash", "yatra"),
            count: statusCounts.trash
          }
        ],
        showColumnsDropdown,
        setShowColumnsDropdown,
        columnOptions,
        onToggleColumn: toggleColumn,
        bulkMutationPending: deleteMutation.isPending,
        totalItems: enquiries.length,
        bulkActionOptions
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-0 overflow-x-auto", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
      Table,
      {
        data: enquiries,
        columns: [
          visibleColumns.customer && {
            key: "customer",
            label: __("Customer", "yatra"),
            render: (enquiry) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "font-medium text-gray-900 dark:text-white text-sm", children: enquiry.name }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-xs text-gray-500 dark:text-gray-400 mt-1 space-y-0.5", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(Mail, { className: "w-3 h-3" }),
                  enquiry.email
                ] }),
                enquiry.phone && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(Phone, { className: "w-3 h-3" }),
                  enquiry.phone
                ] })
              ] })
            ] })
          },
          visibleColumns.trip && {
            key: "trip",
            label: __("Trip", "yatra"),
            render: (enquiry) => enquiry.trip_title ? /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1 text-sm text-gray-600 dark:text-gray-400", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(MapPin, { className: "w-3.5 h-3.5" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: enquiry.trip_title })
            ] }) : /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm text-gray-400 dark:text-gray-500 italic", children: __("General enquiry", "yatra") })
          },
          visibleColumns.message && {
            key: "message",
            label: __("Message", "yatra"),
            render: (enquiry) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start gap-2", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(MessageSquare, { className: "w-4 h-4 text-gray-400 mt-0.5 flex-shrink-0" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-600 dark:text-gray-400 line-clamp-2", children: enquiry.message })
            ] })
          },
          visibleColumns.travelers && {
            key: "travelers",
            label: __("Travelers", "yatra"),
            render: (enquiry) => /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-600 dark:text-gray-400 text-sm", children: enquiry.travelers_count || "-" })
          },
          visibleColumns.preferred_date && {
            key: "preferred_date",
            label: __("Preferred Date", "yatra"),
            render: (enquiry) => /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-500 dark:text-gray-400 text-sm", children: enquiry.travel_date ? formatDate2(enquiry.travel_date) : "-" })
          },
          visibleColumns.status && {
            key: "status",
            label: __("Status", "yatra"),
            render: (enquiry) => getStatusBadge(enquiry.status)
          },
          visibleColumns.date && {
            key: "date",
            label: __("Date", "yatra"),
            render: (enquiry) => /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-500 dark:text-gray-400 text-sm", children: formatDate2(enquiry.created_at) })
          }
        ].filter(Boolean),
        actions,
        isLoading,
        isError: isEnquiriesError,
        errorText: __("Error loading enquiries"),
        errorDescription: __(
          "We couldn't connect to the enquiries service. Please refresh or try again shortly."
        ),
        errorDetails: derivedErrorDetails,
        errorRequestInfo: errorContext.requestInfo,
        onRetry: () => refetch(),
        emptyText: __("No enquiries found"),
        emptyDescription: hasFilters ? __(
          "Try adjusting your search or filter criteria to find what you're looking for.",
          "Try adjusting your search or filter criteria to find what you're looking for."
        ) : __(
          "When customers submit enquiries, they will appear here.",
          "yatra"
        ),
        onSort: handleSort,
        getSortIcon,
        selectedItemIds: selectedIds,
        onSelectItem: (id, checked) => {
          if (checked) {
            setSelectedIds(
              (prev) => prev.includes(id) ? prev : [...prev, id]
            );
          } else {
            setSelectedIds(
              (prev) => prev.filter((existingId) => existingId !== id)
            );
          }
        },
        onSelectAll: (checked) => {
          if (checked) {
            setSelectedIds(enquiries.map((e) => e.id));
          } else {
            setSelectedIds([]);
          }
        },
        isAllSelected: enquiries.length > 0 && selectedIds.length === enquiries.length,
        getItemId: (enquiry) => enquiry.id,
        capability: "yatra_view_enquiries",
        skeletonRows: 5
      }
    ) }) }),
    total > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx(
      Pagination,
      {
        currentPage: page,
        totalPages,
        totalItems: total,
        itemsPerPage: perPage,
        onPageChange: setPage,
        itemName: __("enquiries", "yatra")
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      Modal,
      {
        isOpen: bulkConfirmOpen,
        onClose: () => {
          if (!bulkApplying) {
            setBulkConfirmOpen(false);
            setPendingBulkAction(null);
          }
        },
        title: __("Apply Bulk Action", "yatra"),
        description: pendingBulkAction ? __(
          `Are you sure you want to apply "${pendingBulkAction}" to the selected enquiries?`,
          `Are you sure you want to apply "${pendingBulkAction}" to the selected enquiries?`
        ) : void 0,
        size: "sm",
        panelClassName: "yatra-model-ui",
        bodyClassName: "p-0",
        footer: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-2 justify-end", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Button,
            {
              variant: "outline",
              onClick: () => {
                setBulkConfirmOpen(false);
                setPendingBulkAction(null);
              },
              disabled: bulkApplying,
              children: __("Cancel", "yatra")
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { onClick: confirmBulkApply, disabled: bulkApplying, children: bulkApplying ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Loader2, { className: "w-4 h-4 mr-2 animate-spin" }),
            __("Applying...", "yatra")
          ] }) : __("Apply", "yatra") })
        ] }),
        children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { "aria-hidden": "true" })
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      Modal,
      {
        isOpen: deleteDialogOpen,
        onClose: () => {
          if (!deleteMutation.isPending) {
            setDeleteDialogOpen(false);
            setEnquiryToDelete(null);
          }
        },
        title: __("Delete Enquiry", "yatra"),
        description: enquiryToDelete ? __(
          `Are you sure you want to delete the enquiry from "${enquiryToDelete.name}"? This action cannot be undone.`,
          `Are you sure you want to delete the enquiry from "${enquiryToDelete.name}"? This action cannot be undone.`
        ) : __("Are you sure you want to delete this enquiry?", "yatra"),
        size: "sm",
        panelClassName: "yatra-model-ui",
        bodyClassName: "p-0",
        footer: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-2 justify-end", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Button,
            {
              variant: "outline",
              onClick: () => {
                setDeleteDialogOpen(false);
                setEnquiryToDelete(null);
              },
              disabled: deleteMutation.isPending,
              children: __("Cancel", "yatra")
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Button,
            {
              variant: "destructive",
              onClick: confirmDelete,
              disabled: deleteMutation.isPending,
              children: deleteMutation.isPending ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Loader2, { className: "w-4 h-4 mr-2 animate-spin" }),
                __("Deleting...", "yatra")
              ] }) : __("Delete", "yatra")
            }
          )
        ] }),
        children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", {})
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      Modal,
      {
        isOpen: respondDialogOpen && !!selectedEnquiry,
        onClose: () => {
          if (!respondMutation.isPending) setRespondDialogOpen(false);
        },
        title: __("Respond to Enquiry", "yatra"),
        description: selectedEnquiry ? /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { children: [
          __("Send a response to", "yatra"),
          " ",
          /* @__PURE__ */ jsxRuntimeExports.jsx("strong", { children: selectedEnquiry.name })
        ] }) : null,
        size: "md",
        panelClassName: "yatra-model-ui",
        footer: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-2 justify-end", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Button,
            {
              variant: "outline",
              onClick: () => setRespondDialogOpen(false),
              disabled: respondMutation.isPending,
              children: __("Cancel", "yatra")
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Button,
            {
              onClick: sendResponse,
              disabled: respondMutation.isPending || !responseMessage.trim(),
              children: respondMutation.isPending ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Loader2, { className: "w-4 h-4 mr-2 animate-spin" }),
                __("Sending...", "yatra")
              ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Send, { className: "w-4 h-4 mr-2" }),
                __("Send Response", "yatra")
              ] })
            }
          )
        ] }),
        children: selectedEnquiry && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-4", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-gray-50 dark:bg-gray-800 rounded-lg p-3 space-y-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2 text-sm", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Mail, { className: "w-4 h-4 text-gray-400" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-600 dark:text-gray-400", children: selectedEnquiry.email })
            ] }),
            selectedEnquiry.trip_title && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2 text-sm", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(MapPin, { className: "w-4 h-4 text-gray-400" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-600 dark:text-gray-400", children: selectedEnquiry.trip_title })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-sm text-gray-500 dark:text-gray-400 border-t border-gray-200 dark:border-gray-700 pt-2 mt-2", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("strong", { children: [
                __("Original Message", "yatra"),
                ":"
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-gray-600 dark:text-gray-400", children: selectedEnquiry.message })
            ] })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mb-1.5 flex items-center justify-between gap-2", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300", children: [
                __("Your Response", "yatra"),
                " ",
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
              ] }),
              (selectedEnquiry == null ? void 0 : selectedEnquiry.id) && /* @__PURE__ */ jsxRuntimeExports.jsx(
                EnquiryReplyAffordance,
                {
                  enquiryId: Number(selectedEnquiry.id),
                  value: responseMessage,
                  onAccept: (text) => setResponseMessage(text)
                }
              )
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "textarea",
              {
                value: responseMessage,
                onChange: (e) => setResponseMessage(e.target.value),
                placeholder: __("Type your response here...", "yatra"),
                className: "w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none",
                rows: 5,
                disabled: respondMutation.isPending
              }
            )
          ] }),
          respondMutation.isError && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg text-sm text-red-600 dark:text-red-400", children: ((_q = respondMutation.error) == null ? void 0 : _q.message) || __("Failed to send response. Please try again.", "yatra") })
        ] })
      }
    )
  ] });
};
const ViewEnquiry = () => {
  var _a;
  const { can } = usePermissions();
  const { navigate } = useNavigate();
  const queryClient2 = useQueryClient();
  const { showToast } = useToast();
  const [respondDialogOpen, setRespondDialogOpen] = reactExports.useState(false);
  const [responseMessage, setResponseMessage] = reactExports.useState("");
  const enquiryId = reactExports.useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get("id") ? parseInt(params.get("id") || "0") : null;
  }, []);
  const {
    data: enquiry,
    isLoading,
    error
  } = useQuery({
    queryKey: ["enquiry", enquiryId],
    queryFn: async () => {
      if (!enquiryId) return null;
      const response = await apiService.getEnquiry(enquiryId);
      return (response == null ? void 0 : response.data) ?? response;
    },
    enabled: !!enquiryId && can("yatra_view_enquiries")
  });
  const respondMutation = useMutation({
    mutationFn: async ({ id, message: message2 }) => {
      return await apiService.respondToEnquiry(id, { response: message2 });
    },
    onSuccess: () => {
      queryClient2.invalidateQueries({ queryKey: ["enquiry", enquiryId] });
      setRespondDialogOpen(false);
      setResponseMessage("");
      showToast(__("Response sent successfully.", "yatra"), "success");
    }
  });
  const formatDate2 = (dateString) => {
    return new Date(dateString).toLocaleDateString("en-US", {
      weekday: "long",
      year: "numeric",
      month: "long",
      day: "numeric"
    });
  };
  const getStatusBadge = (status) => {
    const statusMap = {
      new: {
        className: "bg-blue-100 text-blue-700 dark:bg-blue-900/20 dark:text-blue-400",
        label: __("New", "yatra")
      },
      pending: {
        className: "bg-orange-100 text-orange-700 dark:bg-orange-900/20 dark:text-orange-400",
        label: __("Pending", "yatra")
      },
      responded: {
        className: "bg-yellow-100 text-yellow-700 dark:bg-yellow-900/20 dark:text-yellow-400",
        label: __("Responded", "yatra")
      },
      converted: {
        className: "bg-green-100 text-green-700 dark:bg-green-900/20 dark:text-green-400",
        label: __("Converted", "yatra")
      },
      closed: {
        className: "bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-400",
        label: __("Closed", "yatra")
      }
    };
    const statusInfo = statusMap[status] || {
      className: "bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-400",
      label: status
    };
    return /* @__PURE__ */ jsxRuntimeExports.jsx(Badge, { className: `text-sm ${statusInfo.className}`, children: statusInfo.label });
  };
  const handleBack = () => {
    navigate({ subpage: "enquiries" });
  };
  const handleEdit = () => {
    if (enquiryId) {
      navigate({ subpage: "enquiries", action: "edit", id: enquiryId });
    }
  };
  const handleViewTrip = () => {
    if (enquiry == null ? void 0 : enquiry.trip_id) {
      navigate({
        subpage: "trips",
        tab: "all",
        action: "edit",
        id: enquiry.trip_id
      });
    }
  };
  const handleRespond = () => {
    setResponseMessage("");
    setRespondDialogOpen(true);
  };
  const sendResponse = () => {
    if (enquiryId && responseMessage.trim()) {
      respondMutation.mutate({
        id: enquiryId,
        message: responseMessage
      });
    }
  };
  if (isLoading) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        PageHeader,
        {
          title: __("Enquiry Details", "yatra"),
          actions: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-10 w-24" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-10 w-32" })
          ] })
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-3 gap-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "lg:col-span-2 space-y-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-5 w-40" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-6 w-20 rounded-full" })
          ] }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-4", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-3 w-16 mb-2" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-24 w-full rounded-lg" })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-4 pt-4 border-t border-gray-200 dark:border-gray-700", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-3 w-32 mb-2" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-5 w-16" })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-3 w-36 mb-2" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-5 w-40" })
              ] })
            ] })
          ] })
        ] }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-5 w-24" }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-5 w-32" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-4 w-48" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-4 w-36" })
            ] })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-5 w-20" }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "space-y-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-3 w-20 mb-2" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-5 w-40" })
            ] }) })
          ] })
        ] })
      ] })
    ] });
  }
  if (error || !enquiry) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        PageHeader,
        {
          title: __("Enquiry Not Found", "yatra"),
          actions: /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Button,
            {
              variant: "outline",
              onClick: handleBack,
              className: "flex items-center gap-2",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowLeft, { className: "w-4 h-4" }),
                __("Back to Enquiries", "yatra")
              ]
            }
          )
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-8 text-center text-red-500", children: __(
        "Enquiry not found or you do not have permission to view it.",
        "yatra"
      ) }) })
    ] });
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      PageHeader,
      {
        title: __("Enquiry Details", "yatra"),
        description: __("View complete enquiry information", "yatra"),
        actions: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Button,
            {
              variant: "outline",
              onClick: handleBack,
              className: "flex items-center gap-2",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowLeft, { className: "w-4 h-4" }),
                __("Back", "yatra")
              ]
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_respond_to_enquiries", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
            enquiry.status !== "responded" && enquiry.status !== "closed" && /* @__PURE__ */ jsxRuntimeExports.jsxs(
              Button,
              {
                variant: "outline",
                onClick: handleRespond,
                className: "flex items-center gap-2 text-blue-600 border-blue-300 hover:bg-blue-50 dark:text-blue-400 dark:border-blue-700 dark:hover:bg-blue-900/20",
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(Send, { className: "w-4 h-4" }),
                  __("Send Response", "yatra")
                ]
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              Button,
              {
                onClick: handleEdit,
                className: "flex items-center gap-2",
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(PenSquare, { className: "w-4 h-4" }),
                  __("Edit Enquiry", "yatra")
                ]
              }
            )
          ] }) })
        ] })
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_view_enquiries", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-3 gap-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "lg:col-span-2 space-y-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Enquiry Information", "yatra") }),
            getStatusBadge(enquiry.status)
          ] }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-4", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-2 block", children: __("Message", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start gap-2 p-3 bg-gray-50 dark:bg-gray-800 rounded-lg", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(MessageSquare, { className: "w-4 h-4 text-gray-400 mt-0.5 flex-shrink-0" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-700 dark:text-gray-300 whitespace-pre-wrap flex-1", children: enquiry.message })
              ] })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-4 pt-4 border-t border-gray-200 dark:border-gray-700", children: [
              enquiry.travelers_count && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wide", children: __("Number of Travelers", "yatra") }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-1 flex items-center gap-2", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(Users, { className: "w-4 h-4 text-gray-400" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm font-medium text-gray-900 dark:text-white", children: enquiry.travelers_count })
                ] })
              ] }),
              enquiry.travel_date && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wide", children: __("Preferred Travel Date", "yatra") }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-1 flex items-center gap-2", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(Calendar$1, { className: "w-4 h-4 text-gray-400" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm font-medium text-gray-900 dark:text-white", children: formatDate2(enquiry.travel_date) })
                ] })
              ] })
            ] }),
            enquiry.response && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "pt-4 border-t border-gray-200 dark:border-gray-700", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-2 block", children: __("Response", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-700 dark:text-gray-300 whitespace-pre-wrap", children: enquiry.response })
            ] })
          ] })
        ] }),
        enquiry.trip_title && /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Related Trip", "yatra") }),
            enquiry.trip_id && /* @__PURE__ */ jsxRuntimeExports.jsxs(
              Button,
              {
                variant: "ghost",
                size: "sm",
                onClick: handleViewTrip,
                className: "flex items-center gap-1.5 text-sm",
                children: [
                  __("View Trip", "yatra"),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(ExternalLink, { className: "w-3.5 h-3.5" })
                ]
              }
            )
          ] }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "space-y-4", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wide", children: __("Trip", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-1 flex items-center gap-2", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(MapPin, { className: "w-4 h-4 text-gray-400" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm font-medium text-gray-900 dark:text-white", children: enquiry.trip_title })
            ] })
          ] }) })
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Customer", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm font-medium text-gray-900 dark:text-white", children: enquiry.name }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2 text-sm text-gray-600 dark:text-gray-400", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Mail, { className: "w-4 h-4" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: enquiry.email })
            ] }),
            enquiry.phone && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2 text-sm text-gray-600 dark:text-gray-400", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Phone, { className: "w-4 h-4" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: enquiry.phone })
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Timeline", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wide", children: __("Submitted", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm text-gray-900 dark:text-white", children: formatDate2(enquiry.created_at) })
            ] }),
            enquiry.responded_at && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wide", children: __("Responded", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm text-gray-900 dark:text-white", children: formatDate2(enquiry.responded_at) })
            ] })
          ] })
        ] })
      ] })
    ] }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      Modal,
      {
        isOpen: respondDialogOpen && !!enquiry,
        onClose: () => {
          if (!respondMutation.isPending) setRespondDialogOpen(false);
        },
        title: __("Respond to Enquiry", "yatra"),
        description: enquiry ? /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { children: [
          __("Send a response to", "yatra"),
          " ",
          /* @__PURE__ */ jsxRuntimeExports.jsx("strong", { children: enquiry.name })
        ] }) : null,
        size: "md",
        footer: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-2 justify-end", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Button,
            {
              variant: "outline",
              onClick: () => setRespondDialogOpen(false),
              disabled: respondMutation.isPending,
              children: __("Cancel", "yatra")
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Button,
            {
              onClick: sendResponse,
              disabled: respondMutation.isPending || !responseMessage.trim(),
              children: respondMutation.isPending ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Loader2, { className: "w-4 h-4 mr-2 animate-spin" }),
                __("Sending...", "yatra")
              ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Send, { className: "w-4 h-4 mr-2" }),
                __("Send Response", "yatra")
              ] })
            }
          )
        ] }),
        children: enquiry && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-4", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-gray-50 dark:bg-gray-800 rounded-lg p-3 space-y-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2 text-sm", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Mail, { className: "w-4 h-4 text-gray-400" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-600 dark:text-gray-400", children: enquiry.email })
            ] }),
            enquiry.trip_title && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2 text-sm", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(MapPin, { className: "w-4 h-4 text-gray-400" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-600 dark:text-gray-400", children: enquiry.trip_title })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-sm text-gray-500 dark:text-gray-400 border-t border-gray-200 dark:border-gray-700 pt-2 mt-2", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("strong", { children: __("Original Message:", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-gray-600 dark:text-gray-400", children: enquiry.message })
            ] })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mb-1.5 flex items-center justify-between gap-2", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300", children: [
                __("Your Response", "yatra"),
                " ",
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
              ] }),
              enquiryId && /* @__PURE__ */ jsxRuntimeExports.jsx(
                EnquiryReplyAffordance,
                {
                  enquiryId: Number(enquiryId),
                  value: responseMessage,
                  onAccept: (text) => setResponseMessage(text)
                }
              )
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "textarea",
              {
                value: responseMessage,
                onChange: (e) => setResponseMessage(e.target.value),
                placeholder: __("Type your response here...", "yatra"),
                className: "w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none",
                rows: 5,
                disabled: respondMutation.isPending
              }
            )
          ] }),
          respondMutation.isError && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg text-sm text-red-600 dark:text-red-400", children: ((_a = respondMutation.error) == null ? void 0 : _a.message) || __("Failed to send response. Please try again.", "yatra") })
        ] })
      }
    )
  ] });
};
const EnquiryForm = () => {
  var _a, _b;
  const { can } = usePermissions();
  const { navigate } = useNavigate();
  const queryClient2 = useQueryClient();
  const { showToast } = useToast();
  const [formData, setFormData] = reactExports.useState({
    name: "",
    email: "",
    phone: "",
    trip_id: void 0,
    message: "",
    travelers_count: 1,
    travel_date: "",
    status: "new",
    response_notes: ""
  });
  const [aiDrafting, setAiDrafting] = reactExports.useState(false);
  const enquiryId = reactExports.useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    const id = params.get("id");
    return id ? parseInt(id) : null;
  }, []);
  const isEdit = !!enquiryId;
  const { data: enquiry, isLoading: isLoadingEnquiry } = useQuery({
    queryKey: ["enquiry", enquiryId],
    queryFn: async () => {
      if (!enquiryId) return null;
      const response = await apiService.getEnquiry(enquiryId);
      return (response == null ? void 0 : response.data) ?? response;
    },
    enabled: !!enquiryId && can("yatra_respond_to_enquiries")
  });
  const { data: tripsData } = useQuery({
    queryKey: ["trips-select"],
    queryFn: async () => {
      return await apiService.getTrips({ per_page: 100 });
    },
    enabled: can("yatra_respond_to_enquiries")
  });
  const trips = Array.isArray(tripsData == null ? void 0 : tripsData.data) ? tripsData.data : Array.isArray(tripsData) ? tripsData : [];
  reactExports.useEffect(() => {
    if (enquiry) {
      setFormData({
        name: enquiry.name || "",
        email: enquiry.email || "",
        phone: enquiry.phone || "",
        trip_id: enquiry.trip_id,
        message: enquiry.message || "",
        travelers_count: enquiry.travelers_count || 1,
        travel_date: enquiry.travel_date || "",
        status: enquiry.status || "new",
        response_notes: enquiry.response_notes || ""
      });
    }
  }, [enquiry]);
  const saveMutation = useMutation({
    mutationFn: async (data) => {
      return isEdit ? await apiService.updateEnquiry(enquiryId, data) : await apiService.createEnquiry(data);
    },
    onSuccess: () => {
      queryClient2.invalidateQueries({ queryKey: ["enquiries"] });
      queryClient2.invalidateQueries({ queryKey: ["enquiry", enquiryId] });
      showToast(__("Enquiry saved successfully.", "yatra"), "success");
      navigate({ subpage: "enquiries" });
    }
  });
  const handleBack = () => {
    navigate({ subpage: "enquiries" });
  };
  const handleSubmit = (e) => {
    e.preventDefault();
    saveMutation.mutate(formData);
  };
  const handleChange = (field, value) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
  };
  if (isEdit && isLoadingEnquiry) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        PageHeader,
        {
          title: __("Edit Enquiry", "yatra"),
          actions: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-10 w-24" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-10 w-32" })
          ] })
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-3 gap-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "lg:col-span-2 space-y-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-5 w-40" }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-4", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-4", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-3 w-16 mb-2" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-11 w-full" })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-3 w-16 mb-2" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-11 w-full" })
              ] })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-3 w-20 mb-2" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-32 w-full" })
            ] })
          ] })
        ] }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-5 w-24" }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-4", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-11 w-full" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-11 w-full" })
          ] })
        ] }) })
      ] })
    ] });
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      PageHeader,
      {
        title: isEdit ? __("Edit Enquiry", "yatra") : __("Create Enquiry", "yatra"),
        description: isEdit ? __("Update enquiry details", "yatra") : __("Add a new enquiry", "yatra"),
        actions: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Button,
            {
              variant: "outline",
              onClick: handleBack,
              className: "flex items-center gap-2",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowLeft, { className: "w-4 h-4" }),
                __("Back", "yatra")
              ]
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Button,
            {
              onClick: handleSubmit,
              disabled: saveMutation.isPending,
              className: "flex items-center gap-2",
              children: [
                saveMutation.isPending ? /* @__PURE__ */ jsxRuntimeExports.jsx(Loader2, { className: "w-4 h-4 animate-spin" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(Save, { className: "w-4 h-4" }),
                saveMutation.isPending ? __("Saving...", "yatra") : __("Save", "yatra")
              ]
            }
          )
        ] })
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_respond_to_enquiries", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("form", { onSubmit: handleSubmit, children: [
      saveMutation.isError && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mb-3 p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg text-sm text-red-600 dark:text-red-400", children: ((_a = saveMutation.error) == null ? void 0 : _a.message) || __("Failed to save enquiry. Please try again.", "yatra") }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-3 gap-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "lg:col-span-2 space-y-3", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Customer Information", "yatra") }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-4", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-4", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5", children: [
                    __("Name", "yatra"),
                    " ",
                    /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
                  ] }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    Input,
                    {
                      value: formData.name || "",
                      onChange: (e) => handleChange("name", e.target.value),
                      placeholder: __("Customer name", "yatra"),
                      required: true
                    }
                  )
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5", children: [
                    __("Email", "yatra"),
                    " ",
                    /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
                  ] }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    Input,
                    {
                      type: "email",
                      value: formData.email || "",
                      onChange: (e) => handleChange("email", e.target.value),
                      placeholder: __("customer@example.com", "yatra"),
                      required: true
                    }
                  )
                ] })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5", children: __("Phone", "yatra") }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Input,
                  {
                    type: "tel",
                    value: formData.phone || "",
                    onChange: (e) => handleChange("phone", e.target.value),
                    placeholder: __("Phone number", "yatra")
                  }
                )
              ] })
            ] })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Enquiry Details", "yatra") }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-4", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5", children: [
                  __("Message", "yatra"),
                  " ",
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "textarea",
                  {
                    value: formData.message || "",
                    onChange: (e) => handleChange("message", e.target.value),
                    placeholder: __("Enquiry message...", "yatra"),
                    className: "w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none",
                    rows: 5,
                    required: true
                  }
                )
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-4", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5", children: __("Number of Travelers", "yatra") }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    Input,
                    {
                      type: "number",
                      min: "1",
                      value: formData.travelers_count || "",
                      onChange: (e) => handleChange(
                        "travelers_count",
                        parseInt(e.target.value, 10) || 1
                      ),
                      placeholder: "1"
                    }
                  )
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1", children: __("Preferred Travel Date", "yatra") }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    DatePicker,
                    {
                      value: formData.travel_date || "",
                      onChange: (val) => handleChange("travel_date", val),
                      placeholder: __("Select date", "yatra")
                    }
                  )
                ] })
              ] })
            ] })
          ] }),
          isEdit && /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Response Notes", "yatra") }),
              enquiryId && /* @__PURE__ */ jsxRuntimeExports.jsx(
                EnquiryReplyAffordance,
                {
                  enquiryId: Number(enquiryId),
                  value: formData.response_notes || "",
                  onAccept: (text) => handleChange("response_notes", text),
                  autoDraftOnMount: !(formData.response_notes || "").trim() && (formData.status === "new" || !formData.responded_at),
                  onDraftingChange: setAiDrafting
                }
              )
            ] }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { children: [
              aiDrafting && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mb-2 flex items-center gap-2 rounded-md border border-purple-200 bg-purple-50/60 px-2 py-1 text-xs text-purple-700 dark:border-purple-500/40 dark:bg-purple-900/20 dark:text-purple-200", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Sparkles, { className: "h-3.5 w-3.5 animate-pulse" }),
                __(
                  "AI is drafting a reply based on this enquiry, the trip details, and the customer's history…",
                  "yatra"
                )
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "textarea",
                {
                  value: formData.response_notes || "",
                  onChange: (e) => handleChange("response_notes", e.target.value),
                  placeholder: __(
                    "Internal notes about responses to this enquiry...",
                    "yatra"
                  ),
                  className: "w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none",
                  rows: 6
                }
              )
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Status", "yatra") }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
              Select,
              {
                value: formData.status || "new",
                onChange: (e) => handleChange("status", e.target.value),
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "new", children: __("New", "yatra") }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "pending", children: __("Pending", "yatra") }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "responded", children: __("Responded", "yatra") }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "converted", children: __("Converted", "yatra") }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "closed", children: __("Closed", "yatra") }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "spam", children: __("Spam", "yatra") }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "trash", children: __("Trash", "yatra") })
                ]
              }
            ) })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Related Trip", "yatra") }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
              Select,
              {
                value: ((_b = formData.trip_id) == null ? void 0 : _b.toString()) || "",
                onChange: (e) => handleChange(
                  "trip_id",
                  e.target.value ? parseInt(e.target.value) : void 0
                ),
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "", children: __("No trip selected", "yatra") }),
                  trips.map((trip) => /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: trip.id.toString(), children: trip.title }, trip.id))
                ]
              }
            ) })
          ] }),
          isEdit && enquiry && /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Information", "yatra") }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3 text-sm", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-500 dark:text-gray-400", children: __("Created:", "yatra") }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-gray-900 dark:text-white mt-0.5", children: new Date(enquiry.created_at).toLocaleDateString(
                  "en-US",
                  {
                    year: "numeric",
                    month: "long",
                    day: "numeric",
                    hour: "2-digit",
                    minute: "2-digit"
                  }
                ) })
              ] }),
              enquiry.responded_at && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-500 dark:text-gray-400", children: __("Responded:", "yatra") }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-gray-900 dark:text-white mt-0.5", children: new Date(enquiry.responded_at).toLocaleDateString(
                  "en-US",
                  {
                    year: "numeric",
                    month: "long",
                    day: "numeric",
                    hour: "2-digit",
                    minute: "2-digit"
                  }
                ) })
              ] })
            ] })
          ] })
        ] })
      ] })
    ] }) })
  ] });
};
const Modules = () => {
  var _a, _b, _c, _d, _e, _f, _g;
  const { can } = usePermissions();
  const canManageModules = can("yatra_edit_trips");
  const { data: modules = [], isLoading, error } = useModulesQuery();
  const toggleMutation = useToggleModule();
  const bulkToggleMutation = useBulkToggleModules();
  const [searchTerm, setSearchTerm] = reactExports.useState("");
  const [categoryFilter, setCategoryFilter] = reactExports.useState("all");
  const [planFilter, setPlanFilter] = reactExports.useState("all");
  const [sortOption, setSortOption] = reactExports.useState("name_asc");
  const [selected, setSelected] = reactExports.useState(/* @__PURE__ */ new Set());
  const categories = reactExports.useMemo(() => {
    const set = /* @__PURE__ */ new Set();
    modules.forEach((module) => {
      if (module.category) {
        set.add(module.category);
      }
    });
    return Array.from(set).sort((a2, b) => a2.localeCompare(b));
  }, [modules]);
  const availablePlans = reactExports.useMemo(() => {
    const set = /* @__PURE__ */ new Set();
    modules.forEach((module) => {
      set.add(module.plan ?? "free");
    });
    const order = ["free", "personal", "growth", "agency"];
    return order.filter((tier) => set.has(tier));
  }, [modules]);
  const planLabels = {
    free: __("Free", "yatra"),
    personal: __("Starter", "yatra"),
    growth: __("Growth", "yatra"),
    agency: __("Scale", "yatra")
  };
  const filteredModules = reactExports.useMemo(() => {
    let list = modules;
    if (searchTerm.trim()) {
      const term = searchTerm.toLowerCase();
      list = list.filter(
        (module) => {
          var _a2, _b2;
          return module.name.toLowerCase().includes(term) || (((_a2 = module.description) == null ? void 0 : _a2.toLowerCase().includes(term)) ?? false) || (((_b2 = module.tags) == null ? void 0 : _b2.some((tag2) => tag2.toLowerCase().includes(term))) ?? false);
        }
      );
    }
    if (categoryFilter !== "all") {
      list = list.filter(
        (module) => (module.category || __("General", "yatra")) === categoryFilter
      );
    }
    if (planFilter !== "all") {
      list = list.filter((module) => (module.plan ?? "free") === planFilter);
    }
    const sorted = [...list];
    sorted.sort((a2, b) => {
      switch (sortOption) {
        case "name_desc":
          return b.name.localeCompare(a2.name);
        case "status_enabled":
          return Number(b.enabled) - Number(a2.enabled);
        case "status_disabled":
          return Number(a2.enabled) - Number(b.enabled);
        case "name_asc":
        default:
          return a2.name.localeCompare(b.name);
      }
    });
    return sorted;
  }, [modules, searchTerm, categoryFilter, planFilter, sortOption]);
  const moduleMap = reactExports.useMemo(() => {
    const map2 = /* @__PURE__ */ new Map();
    modules.forEach((module) => {
      map2.set(module.slug, module);
    });
    return map2;
  }, [modules]);
  const [premiumDialog, setPremiumDialog] = reactExports.useState({ open: false });
  const handleToggle = (module) => {
    if (module.is_core || !canManageModules) return;
    if (module.is_premium && !module.enabled && !module.is_available) {
      setPremiumDialog({ open: true, module });
      return;
    }
    toggleMutation.mutate({
      slug: module.slug,
      enabled: !module.enabled,
      name: module.name
    });
  };
  const renderToggle = (module) => {
    const isLockedPremium = module.is_premium && !module.enabled && !module.is_available;
    const disabled = module.is_core || toggleMutation.isPending || !canManageModules;
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "button",
      {
        onClick: (event) => {
          event.stopPropagation();
          if (isLockedPremium) {
            setPremiumDialog({ open: true, module });
            return;
          }
          handleToggle(module);
        },
        disabled,
        className: `relative inline-flex h-7 w-12 items-center rounded-full transition ${module.enabled ? "bg-blue-600" : "bg-gray-300 dark:bg-gray-600"} ${isLockedPremium ? "ring-2 ring-amber-300 dark:ring-amber-500 cursor-pointer" : ""} ${disabled && !isLockedPremium ? "opacity-60 cursor-not-allowed" : "cursor-pointer"}`,
        "aria-pressed": module.enabled,
        "aria-label": module.enabled ? __("Disable module", "yatra") : __("Enable module", "yatra"),
        children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          "span",
          {
            className: `inline-block h-5 w-5 transform rounded-full bg-white transition ${module.enabled ? "translate-x-5" : "translate-x-1"}`
          }
        )
      }
    );
  };
  const handleSelect = (slug) => {
    const module = moduleMap.get(slug);
    if ((module == null ? void 0 : module.is_premium) && !module.enabled && !module.is_available) {
      setPremiumDialog({ open: true, module });
      return;
    }
    setSelected((prev) => {
      const next = new Set(prev);
      if (next.has(slug)) {
        next.delete(slug);
      } else {
        next.add(slug);
      }
      return next;
    });
  };
  const handleSelectAllVisible = () => {
    setSelected((prev) => {
      const next = new Set(prev);
      const allSelected = filteredModules.every(
        (module) => next.has(module.slug)
      );
      if (allSelected) {
        filteredModules.forEach((module) => next.delete(module.slug));
      } else {
        filteredModules.forEach((module) => next.add(module.slug));
      }
      return next;
    });
  };
  const bulkUpdate = (enabled) => {
    const items = Array.from(selected).map((slug) => moduleMap.get(slug)).filter((module) => !!module).filter(
      (module) => !(module.is_premium && enabled && !module.is_available)
    );
    if (items.length === 0) {
      if (selected.size > 0 && enabled) {
        const premiumModules = Array.from(selected).map((slug) => moduleMap.get(slug)).filter((module) => (module == null ? void 0 : module.is_premium) && !(module == null ? void 0 : module.is_available));
        if (premiumModules.length > 0) {
          setPremiumDialog({ open: true, module: premiumModules[0] });
        }
      }
      return;
    }
    const payload = items.map((module) => ({
      slug: module.slug,
      enabled,
      name: module.name
    }));
    bulkToggleMutation.mutate(payload, {
      onSuccess: () => setSelected(/* @__PURE__ */ new Set())
    });
  };
  const isAllVisibleSelected = filteredModules.length > 0 && filteredModules.every((module) => selected.has(module.slug));
  const selectedCount = selected.size;
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-4", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      PageHeader,
      {
        title: __("Modules", "yatra"),
        description: __(
          "Manage feature modules and control which capabilities are active.",
          "yatra"
        ),
        actionCapability: "yatra_edit_trips",
        actions: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Button,
          {
            variant: "outline",
            onClick: () => window.location.reload(),
            className: "flex items-center gap-2",
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Puzzle, { className: "w-4 h-4" }),
              __("Refresh Modules", "yatra")
            ]
          }
        )
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-4", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Button,
          {
            variant: isAllVisibleSelected ? "default" : "outline",
            onClick: handleSelectAllVisible,
            disabled: filteredModules.length === 0,
            className: "flex items-center gap-2",
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowUpDown, { className: "w-4 h-4" }),
              isAllVisibleSelected ? __("Clear visible selection", "yatra") : __("Select visible", "yatra")
            ]
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          Button,
          {
            variant: "outline",
            onClick: () => bulkUpdate(true),
            disabled: !canManageModules || selectedCount === 0 || bulkToggleMutation.isPending,
            children: __("Enable Selected", "yatra")
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          Button,
          {
            variant: "outline",
            onClick: () => bulkUpdate(false),
            disabled: !canManageModules || selectedCount === 0 || bulkToggleMutation.isPending,
            children: __("Disable Selected", "yatra")
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2 text-sm text-gray-600 dark:text-gray-300 pl-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Filter, { className: "w-4 h-4" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: __("Showing {count} modules", "yatra").replace(
            "{count}",
            String(filteredModules.length)
          ) })
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-1 flex-col gap-2 lg:flex-row lg:items-center lg:justify-end lg:gap-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative w-full lg:max-w-sm", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Search, { className: "absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Input,
            {
              value: searchTerm,
              onChange: (e) => setSearchTerm(e.target.value),
              placeholder: __("Search modules...", "yatra"),
              className: "pl-9"
            }
          )
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Select,
          {
            value: categoryFilter,
            onChange: (e) => setCategoryFilter(e.target.value),
            className: "w-full lg:w-44",
            "aria-label": __("Filter by category", "yatra"),
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "all", children: __("All Categories", "yatra") }),
              categories.map((category) => /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: category, children: category }, category))
            ]
          }
        ),
        availablePlans.length > 1 && /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Select,
          {
            value: planFilter,
            onChange: (e) => setPlanFilter(e.target.value),
            className: "w-full lg:w-44",
            "aria-label": __("Filter by plan", "yatra"),
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "all", children: __("All Plans", "yatra") }),
              availablePlans.map((tier) => /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: tier, children: planLabels[tier] }, tier))
            ]
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Select,
          {
            value: sortOption,
            onChange: (e) => setSortOption(e.target.value),
            className: "w-full lg:w-44",
            "aria-label": __("Sort modules", "yatra"),
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "name_asc", children: __("Name A → Z", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "name_desc", children: __("Name Z → A", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "status_enabled", children: __("Enabled first", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "status_disabled", children: __("Disabled first", "yatra") })
            ]
          }
        ),
        (searchTerm || categoryFilter !== "all" || planFilter !== "all" || sortOption !== "name_asc") && /* @__PURE__ */ jsxRuntimeExports.jsx(
          Button,
          {
            variant: "outline",
            onClick: () => {
              setSearchTerm("");
              setCategoryFilter("all");
              setPlanFilter("all");
              setSortOption("name_asc");
            },
            children: __("Reset", "yatra")
          }
        )
      ] })
    ] }) }) }),
    isLoading && /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-4", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "animate-pulse space-y-4", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col gap-3 lg:flex-row lg:items-center", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex-1 h-10 rounded-md bg-gray-100 dark:bg-gray-800" }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-3 w-full lg:w-auto", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 w-40 rounded-md bg-gray-100 dark:bg-gray-800" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 w-40 rounded-md bg-gray-100 dark:bg-gray-800" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 w-24 rounded-md bg-gray-100 dark:bg-gray-800" })
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid gap-3 md:grid-cols-3", children: Array.from({ length: 3 }).map((_, idx) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "div",
        {
          className: "border border-gray-200 dark:border-gray-800 rounded-xl p-4 space-y-3",
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-3", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-5 w-5 rounded bg-gray-200 dark:bg-gray-700" }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1 space-y-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 w-32 rounded bg-gray-200 dark:bg-gray-700" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-3 w-full rounded bg-gray-100 dark:bg-gray-800" })
              ] })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-24 rounded bg-gray-50 dark:bg-gray-900" })
          ]
        },
        `module-skeleton-${idx}`
      )) })
    ] }) }) }),
    error && /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-6 text-red-600 dark:text-red-400", children: __("Failed to load modules", "yatra") }) }),
    !isLoading && !error && modules.length === 0 && /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-6 text-gray-500 dark:text-gray-400", children: __("No modules available yet.", "yatra") }) }),
    !isLoading && !error && filteredModules.length > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid gap-3 md:grid-cols-3", children: filteredModules.map((module) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
      Card,
      {
        className: `border ${// Only show premium styling if module is premium AND not available (Pro not active)
        module.is_premium && !module.is_available ? "border-amber-300 dark:border-amber-500/60 bg-amber-50/80 dark:bg-amber-500/10 relative overflow-hidden" : "border-gray-200 dark:border-gray-700"}`,
        ...module.is_premium && !module.is_available && canManageModules && !module.enabled ? {
          role: "button",
          tabIndex: 0,
          onClick: () => setPremiumDialog({ open: true, module }),
          onKeyDown: (event) => {
            if (event.key === "Enter" || event.key === " ") {
              event.preventDefault();
              setPremiumDialog({ open: true, module });
            }
          }
        } : {},
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start justify-between gap-3 flex-wrap", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start gap-3 flex-1", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col items-center gap-1", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "input",
                  {
                    id: `module-select-${module.slug}`,
                    type: "checkbox",
                    className: "mt-1 h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500 cursor-pointer",
                    checked: selected.has(module.slug),
                    onChange: () => handleSelect(module.slug)
                  }
                ),
                module.enabled && /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-[11px] font-semibold text-green-700 uppercase tracking-wide [writing-mode:vertical-rl] [text-orientation:mixed] transform rotate-180 bg-green-100 dark:bg-green-900/40 px-1 py-1 rounded", children: __("Enabled", "yatra") })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs(
                "div",
                {
                  className: "cursor-pointer select-none",
                  onClick: (event) => {
                    event.stopPropagation();
                    handleSelect(module.slug);
                  },
                  role: "button",
                  tabIndex: 0,
                  onKeyDown: (e) => {
                    if (e.key === "Enter" || e.key === " ") {
                      e.preventDefault();
                      handleSelect(module.slug);
                    }
                  },
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsxs(CardTitle, { className: "text-lg flex items-center gap-2 flex-wrap", children: [
                      module.name,
                      module.is_core && /* @__PURE__ */ jsxRuntimeExports.jsx(Badge, { variant: "outline", children: __("Core", "yatra") }),
                      module.plan === "agency" && /* @__PURE__ */ jsxRuntimeExports.jsx(
                        Badge,
                        {
                          variant: "outline",
                          className: "px-2 py-0.5 rounded-full bg-gradient-to-r from-purple-600 to-indigo-500 border-purple-700 text-white shadow-sm dark:from-purple-500 dark:to-indigo-400 dark:border-purple-400 dark:text-white",
                          children: __("Scale", "yatra")
                        }
                      ),
                      module.plan === "growth" && /* @__PURE__ */ jsxRuntimeExports.jsx(
                        Badge,
                        {
                          variant: "outline",
                          className: "px-2 py-0.5 rounded-full bg-gradient-to-r from-emerald-500 to-teal-500 border-emerald-600 text-white shadow-sm dark:from-emerald-500 dark:to-teal-400 dark:border-emerald-400 dark:text-white",
                          children: __("Growth", "yatra")
                        }
                      ),
                      module.plan === "personal" && /* @__PURE__ */ jsxRuntimeExports.jsx(
                        Badge,
                        {
                          variant: "outline",
                          className: "flex items-center gap-1 px-2 py-0.5 rounded-full bg-blue-50 border-blue-200 text-blue-700 dark:bg-blue-900/30 dark:border-blue-500/40 dark:text-blue-200",
                          children: __("Starter", "yatra")
                        }
                      )
                    ] }),
                    /* @__PURE__ */ jsxRuntimeExports.jsx(CardDescription, { className: "mt-1 text-sm line-clamp-3", children: module.description }),
                    /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "inline-flex items-center px-2 py-0.5 mt-1 text-[11px] font-medium rounded-full bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-300", children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "w-1.5 h-1.5 rounded-full bg-blue-500 mr-1" }),
                      module.category || __("General", "yatra")
                    ] })
                  ]
                }
              )
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex items-center", children: renderToggle(module) })
          ] }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "flex items-center justify-between text-xs text-gray-500 dark:text-gray-400", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex items-center gap-2", children: module.video_url && /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "a",
              {
                href: module.video_url,
                target: "_blank",
                rel: "noreferrer",
                className: "flex items-center gap-1 text-red-600 hover:text-red-500 dark:text-red-400 text-xs font-medium",
                title: __("Watch video tutorial", "yatra"),
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "svg",
                    {
                      className: "w-3 h-3",
                      fill: "none",
                      stroke: "currentColor",
                      strokeWidth: "2",
                      strokeLinecap: "round",
                      strokeLinejoin: "round",
                      viewBox: "0 0 24 24",
                      children: /* @__PURE__ */ jsxRuntimeExports.jsx("polygon", { points: "5 3 19 12 5 21 5 3" })
                    }
                  ),
                  __("Video", "yatra")
                ]
              }
            ) }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
              module.slug === "dynamic_form_field" && module.enabled && /* @__PURE__ */ jsxRuntimeExports.jsxs(
                "a",
                {
                  href: `${window.location.origin}/wp-admin/admin.php?page=yatra&subpage=settings`,
                  className: "flex items-center gap-1 text-gray-600 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-200 text-xs font-medium",
                  title: __("Settings", "yatra"),
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsxs(
                      "svg",
                      {
                        className: "w-3 h-3",
                        fill: "none",
                        stroke: "currentColor",
                        strokeWidth: "2",
                        strokeLinecap: "round",
                        strokeLinejoin: "round",
                        viewBox: "0 0 24 24",
                        children: [
                          /* @__PURE__ */ jsxRuntimeExports.jsx("circle", { cx: "12", cy: "12", r: "3" }),
                          /* @__PURE__ */ jsxRuntimeExports.jsx("path", { d: "M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z" })
                        ]
                      }
                    ),
                    __("Settings", "yatra")
                  ]
                }
              ),
              module.docs_url && /* @__PURE__ */ jsxRuntimeExports.jsxs(
                "a",
                {
                  href: module.docs_url,
                  target: "_blank",
                  rel: "noreferrer",
                  className: "flex items-center gap-1 text-blue-600 hover:text-blue-500 dark:text-blue-400 text-xs font-medium",
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(ExternalLink, { className: "w-3 h-3" }),
                    __("Docs", "yatra")
                  ]
                }
              )
            ] })
          ] })
        ]
      },
      module.slug
    )) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      PremiumUpgradeDialog,
      {
        open: premiumDialog.open,
        moduleName: (_a = premiumDialog.module) == null ? void 0 : _a.name,
        moduleSlug: (_b = premiumDialog.module) == null ? void 0 : _b.slug,
        purchaseUrl: (_c = premiumDialog.module) == null ? void 0 : _c.purchase_url,
        moduleDescription: (_d = premiumDialog.module) == null ? void 0 : _d.description,
        requiredPlan: ((_e = premiumDialog.module) == null ? void 0 : _e.plan) === "agency" ? "agency" : ((_f = premiumDialog.module) == null ? void 0 : _f.plan) === "growth" ? "growth" : ((_g = premiumDialog.module) == null ? void 0 : _g.plan) === "personal" ? "personal" : void 0,
        onClose: () => setPremiumDialog({ open: false })
      }
    )
  ] });
};
const FALLBACK_COUNTRIES = {
  US: "United States",
  GB: "United Kingdom",
  CA: "Canada",
  AU: "Australia",
  IN: "India",
  NP: "Nepal"
};
function getCountryMap() {
  var _a;
  const raw = (_a = window == null ? void 0 : window.yatraAdmin) == null ? void 0 : _a.countries;
  if (raw && typeof raw === "object" && !Array.isArray(raw)) {
    const map2 = raw;
    if (Object.keys(map2).length > 0) return map2;
  }
  return FALLBACK_COUNTRIES;
}
function getCountryOptions() {
  const map2 = getCountryMap();
  return Object.entries(map2).map(([code, name]) => ({ code, name }));
}
function getCountryName(code) {
  if (!code) return "";
  const map2 = getCountryMap();
  return map2[code.toUpperCase()] ?? code;
}
const EXCLUDED_DYNAMIC_FIELDS = [
  "first_name",
  "last_name",
  "gender",
  "nationality",
  "phone",
  "_traveller_id",
  "_is_lead",
  "_traveller_index",
  "booking_id",
  "booking_reference",
  "trip_id",
  "trip_title",
  "travel_date",
  "traveler_index",
  "is_lead",
  "id"
];
const Travelers = () => {
  var _a, _b;
  const queryClient2 = useQueryClient();
  const { can } = usePermissions();
  const { showToast } = useToast();
  const [deleteDialogOpen, setDeleteDialogOpen] = reactExports.useState(false);
  const [travelerToDelete, setTravelerToDelete] = reactExports.useState(
    null
  );
  const [searchTerm, setSearchTerm] = reactExports.useState("");
  const [tripFilter, setTripFilter] = reactExports.useState("");
  const [page, setPage] = reactExports.useState(1);
  const perPage = 20;
  const [selectedIds, setSelectedIds] = reactExports.useState([]);
  const [bulkAction, setBulkAction] = reactExports.useState("");
  const [showColumnsDropdown, setShowColumnsDropdown] = reactExports.useState(false);
  const [visibleColumns, setVisibleColumns] = reactExports.useState(() => {
    if (typeof window === "undefined") {
      return {
        traveler_info: true,
        trip: true,
        travel_date: true,
        booking_reference: true
      };
    }
    const saved = window.localStorage.getItem(
      "yatra-travelers-visible-columns"
    );
    return saved ? JSON.parse(saved) : {
      traveler_info: true,
      trip: true,
      travel_date: true,
      booking_reference: true
    };
  });
  const { data: formConfigData } = useQuery({
    queryKey: ["booking-form-config"],
    queryFn: async () => {
      var _a2;
      const result = await apiService.getSettings("booking_form");
      return result.success ? (_a2 = result.data) == null ? void 0 : _a2.booking_form_config : null;
    }
  });
  const [availableTrips, setAvailableTrips] = reactExports.useState([]);
  const { data, isLoading, error, refetch } = useQuery({
    queryKey: ["travelers", searchTerm, tripFilter, page],
    queryFn: async () => {
      var _a2, _b2;
      const urlParams = new URLSearchParams(window.location.search);
      if (urlParams.get("simulate_error") === "true") {
        throw new Error(
          "Simulated API error for testing error UI functionality"
        );
      }
      const paramsObj = {
        page,
        per_page: perPage
      };
      if (searchTerm) paramsObj.search = searchTerm;
      if (tripFilter) paramsObj.trip_id = tripFilter;
      const response = await apiService.getTravelers(paramsObj);
      if (((_b2 = (_a2 = response.meta) == null ? void 0 : _a2.available_trips) == null ? void 0 : _b2.length) > 0) {
        setAvailableTrips(response.meta.available_trips);
      }
      return response;
    },
    enabled: can("yatra_view_bookings")
  });
  const tripsData = reactExports.useMemo(() => ({ data: availableTrips }), [availableTrips]);
  const dynamicColumns = reactExports.useMemo(() => {
    var _a2;
    const formConfig = formConfigData;
    if (!((_a2 = formConfig == null ? void 0 : formConfig.traveler_form) == null ? void 0 : _a2.fields)) {
      return [];
    }
    const enabledFields = formConfig.traveler_form.fields.filter(
      (field) => field.enabled && !EXCLUDED_DYNAMIC_FIELDS.includes(field.id)
    ).sort((a2, b) => (a2.order || 0) - (b.order || 0));
    return enabledFields.map((field) => ({
      id: field.id,
      label: field.label,
      type: field.type
    }));
  }, [formConfigData]);
  const travelers = (data == null ? void 0 : data.data) || [];
  const totalTravelers = ((_a = data == null ? void 0 : data.meta) == null ? void 0 : _a.total) || 0;
  const totalPages = Math.ceil(totalTravelers / perPage);
  const errorContext = getErrorContext(error);
  const apiErrorMessage = (data == null ? void 0 : data.error) || (data == null ? void 0 : data.message);
  const derivedErrorDetails = errorContext.details || (apiErrorMessage ? String(apiErrorMessage) : void 0) || (error ? String((error == null ? void 0 : error.message) || error) : void 0);
  const isTravelersError = !!error || !!apiErrorMessage;
  const handleViewBooking = (bookingId) => {
    var _a2;
    window.location.href = `${((_a2 = window.yatraAdmin) == null ? void 0 : _a2.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=bookings&action=view&id=${bookingId}`;
  };
  const formatDate2 = (dateString) => {
    if (!dateString) return "-";
    try {
      return new Date(dateString).toLocaleDateString();
    } catch {
      return dateString;
    }
  };
  const bulkMutation = useMutation({
    mutationFn: async ({
      action,
      ids
    }) => {
      return await apiService.bulkTravelersAction(action, ids);
    },
    onSuccess: () => {
      queryClient2.invalidateQueries({ queryKey: ["travelers"] });
      setSelectedIds([]);
      setBulkAction("");
    }
  });
  const handleBulkApply = () => {
    if (!bulkAction || selectedIds.length === 0) {
      return;
    }
    bulkMutation.mutate({ action: bulkAction, ids: selectedIds });
  };
  const handleDelete = (traveler) => {
    setTravelerToDelete(traveler);
    setDeleteDialogOpen(true);
  };
  const confirmDelete = async () => {
    if (!travelerToDelete) return;
    try {
      await bulkMutation.mutateAsync({
        action: "delete",
        ids: [travelerToDelete.id]
      });
      showToast(__("Traveler deleted successfully", "yatra"), "success");
      setDeleteDialogOpen(false);
      setTravelerToDelete(null);
    } catch (error2) {
      showToast(
        (error2 == null ? void 0 : error2.message) || __("Failed to delete traveler", "yatra"),
        "error"
      );
    }
  };
  const toggleColumn = (columnKey) => {
    const newVisibleColumns = {
      ...visibleColumns,
      [columnKey]: !visibleColumns[columnKey]
    };
    setVisibleColumns(newVisibleColumns);
    if (typeof window !== "undefined") {
      window.localStorage.setItem(
        "yatra-travelers-visible-columns",
        JSON.stringify(newVisibleColumns)
      );
    }
  };
  const columnOptions = [
    {
      key: "traveler_info",
      label: __("Traveler", "yatra"),
      visible: visibleColumns.traveler_info
    },
    { key: "trip", label: __("Trip", "yatra"), visible: visibleColumns.trip },
    {
      key: "travel_date",
      label: __("Travel Date", "yatra"),
      visible: visibleColumns.travel_date
    },
    {
      key: "booking_reference",
      label: __("Booking", "yatra"),
      visible: visibleColumns.booking_reference
    }
  ];
  const actions = [
    {
      key: "view",
      label: __("View Booking", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Eye, { className: "w-4 h-4" }),
      onClick: (traveler) => handleViewBooking(traveler.booking_id)
    },
    {
      key: "delete",
      label: __("Delete", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "w-4 h-4" }),
      onClick: (traveler) => handleDelete(traveler),
      variant: "destructive",
      condition: () => can("yatra_delete_bookings")
    }
  ];
  const formatCellValue = (value, fieldType) => {
    if (value === void 0 || value === null || value === "") {
      return /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-400", children: "-" });
    }
    switch (fieldType) {
      case "date":
        return formatDate2(value);
      case "email":
        return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1 text-sm", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Mail, { className: "w-3 h-3 text-gray-400" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "truncate max-w-[150px]", children: value })
        ] });
      case "tel":
        return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1 text-sm", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Phone, { className: "w-3 h-3 text-gray-400" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: value })
        ] });
      case "country":
        return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1 text-sm", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(MapPin, { className: "w-3 h-3 text-gray-400" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: getCountryName(value) })
        ] });
      default:
        return /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm", children: String(value) });
    }
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      PageHeader,
      {
        title: __("Travelers", "yatra"),
        description: __("View all travelers from bookings", "yatra")
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-4", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-12 gap-4 items-center", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "lg:col-span-8", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Search, { className: "absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          Input,
          {
            type: "text",
            placeholder: __("Search by name, email, phone...", "yatra"),
            value: searchTerm,
            onChange: (e) => {
              setSearchTerm(e.target.value);
              setPage(1);
            },
            className: "pl-10 w-full"
          }
        )
      ] }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "lg:col-span-4", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Select,
        {
          value: tripFilter,
          onChange: (e) => {
            setTripFilter(e.target.value);
            setPage(1);
          },
          className: "w-full",
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "all", children: __("All Trips", "yatra") }),
            (_b = tripsData == null ? void 0 : tripsData.data) == null ? void 0 : _b.map((trip) => /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: trip.id, children: trip.title }, trip.id))
          ]
        }
      ) })
    ] }) }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid grid-cols-1 sm:grid-cols-3 gap-3", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "p-4 flex items-center gap-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-10 h-10 rounded-lg bg-blue-100 dark:bg-blue-900/30 flex items-center justify-center", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Users, { className: "w-5 h-5 text-blue-600 dark:text-blue-400" }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-500 dark:text-gray-400", children: __("Total Travelers", "yatra") }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xl font-semibold text-gray-900 dark:text-white", children: isLoading ? /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-6 w-16" }) : totalTravelers })
      ] })
    ] }) }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      BulkActionToolbar,
      {
        selectedIds,
        bulkAction,
        setBulkAction,
        onApply: handleBulkApply,
        onClearSelection: () => setSelectedIds([]),
        statusFilter: "all",
        setStatusFilter: () => {
        },
        statusOptions: [
          { key: "all", label: __("All", "yatra"), count: totalTravelers }
        ],
        showColumnsDropdown,
        setShowColumnsDropdown,
        columnOptions,
        onToggleColumn: toggleColumn,
        bulkMutationPending: bulkMutation.isPending,
        totalItems: travelers.length,
        bulkActionOptions: [{ value: "delete", label: __("Delete", "yatra") }]
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-0 overflow-x-auto", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
      Table,
      {
        data: travelers,
        isLoading,
        isError: isTravelersError,
        errorText: __("Error loading travelers", "yatra"),
        errorDescription: __(
          "We couldn't connect to the travelers service. Please refresh or try again shortly.",
          "yatra"
        ),
        errorDetails: derivedErrorDetails,
        errorRequestInfo: errorContext.requestInfo,
        onRetry: () => refetch(),
        skeletonRows: 5,
        emptyText: searchTerm || tripFilter ? __("No travelers found matching your criteria", "yatra") : __("No travelers found", "yatra"),
        emptyDescription: __(
          "View and manage travelers collected from your bookings.",
          "yatra"
        ),
        capability: "yatra_view_bookings",
        selectedItemIds: selectedIds,
        onSelectItem: (id, checked) => {
          if (checked) {
            setSelectedIds(
              (prev) => prev.includes(id) ? prev : [...prev, id]
            );
          } else {
            setSelectedIds(
              (prev) => prev.filter((existingId) => existingId !== id)
            );
          }
        },
        onSelectAll: (checked) => {
          if (checked) {
            setSelectedIds(travelers.map((t) => t.id));
          } else {
            setSelectedIds([]);
          }
        },
        isAllSelected: travelers.length > 0 && selectedIds.length === travelers.length,
        getItemId: (traveler) => traveler.id,
        actions,
        columns: [
          visibleColumns.traveler_info && {
            key: "traveler_info",
            label: __("Traveler", "yatra"),
            render: (traveler) => {
              var _a2, _b2;
              return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "w-9 h-9 rounded-full bg-gray-100 dark:bg-gray-700 flex items-center justify-center text-sm font-medium text-gray-600 dark:text-gray-300", children: [
                  (((_a2 = traveler.first_name) == null ? void 0 : _a2[0]) || "?").toUpperCase(),
                  (((_b2 = traveler.last_name) == null ? void 0 : _b2[0]) || "").toUpperCase()
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "font-medium text-gray-900 dark:text-white flex items-center gap-2", children: [
                    [traveler.first_name, traveler.last_name].filter(Boolean).join(" ") || "N/A",
                    traveler.is_lead && /* @__PURE__ */ jsxRuntimeExports.jsx(Badge, { variant: "info", className: "text-xs", children: __("Lead", "yatra") })
                  ] }),
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-xs text-gray-500 dark:text-gray-400 mt-0.5 space-y-0.5", children: [
                    traveler.phone && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1", children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx(Phone, { className: "w-3 h-3" }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: traveler.phone })
                    ] }),
                    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
                      traveler.gender && /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "capitalize", children: traveler.gender }),
                      traveler.nationality && /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                        traveler.gender && /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: "•" }),
                        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: getCountryName(traveler.nationality) })
                      ] })
                    ] })
                  ] })
                ] })
              ] });
            }
          },
          ...dynamicColumns.map((col) => ({
            key: `dynamic_${col.id}`,
            label: col.label,
            render: (traveler) => formatCellValue(traveler[col.id], col.type)
          })),
          visibleColumns.trip && {
            key: "trip",
            label: __("Trip", "yatra"),
            render: (traveler) => /* @__PURE__ */ jsxRuntimeExports.jsx(
              "div",
              {
                className: "max-w-[200px] truncate",
                title: traveler.trip_title,
                children: traveler.trip_title || `Trip #${traveler.trip_id}`
              }
            )
          },
          visibleColumns.travel_date && {
            key: "travel_date",
            label: __("Travel Date", "yatra"),
            render: (traveler) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1 text-sm", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Calendar$1, { className: "w-3 h-3 text-gray-400" }),
              formatDate2(traveler.travel_date)
            ] })
          },
          visibleColumns.booking_reference && {
            key: "booking_reference",
            label: __("Booking", "yatra"),
            render: (traveler) => {
              var _a2;
              return /* @__PURE__ */ jsxRuntimeExports.jsx(
                "a",
                {
                  href: `${((_a2 = window.yatraAdmin) == null ? void 0 : _a2.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=bookings&action=view&id=${traveler.booking_id}`,
                  className: "text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300 font-mono text-sm",
                  children: traveler.booking_reference
                }
              );
            }
          }
        ].filter(Boolean)
      }
    ) }) }),
    totalTravelers > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx(
      Pagination,
      {
        currentPage: page,
        totalPages,
        totalItems: totalTravelers,
        itemsPerPage: perPage,
        onPageChange: setPage,
        itemName: __("travelers", "yatra")
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      ConfirmationDialog,
      {
        isOpen: deleteDialogOpen,
        onClose: () => {
          setDeleteDialogOpen(false);
          setTravelerToDelete(null);
        },
        onConfirm: confirmDelete,
        title: __("Delete Traveler", "yatra"),
        message: travelerToDelete ? __(
          `Are you sure you want to delete ${[travelerToDelete.first_name, travelerToDelete.last_name].filter(Boolean).join(" ")}? This action cannot be undone.`,
          "yatra"
        ) : __("Are you sure you want to delete this traveler?", "yatra"),
        confirmText: __("Delete", "yatra"),
        cancelText: __("Cancel", "yatra"),
        variant: "danger",
        isLoading: bulkMutation.isPending
      }
    )
  ] });
};
const Switch = ({
  checked,
  onCheckedChange,
  disabled = false,
  className = ""
}) => {
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    "button",
    {
      type: "button",
      role: "switch",
      "aria-checked": checked,
      disabled,
      onClick: () => !disabled && onCheckedChange(!checked),
      className: `relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 ${checked ? "bg-blue-600 dark:bg-blue-500" : "bg-gray-200 dark:bg-gray-700"} ${className}`,
      children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        "span",
        {
          className: `inline-block h-5 w-5 transform rounded-full bg-white shadow-lg transition-transform ${checked ? "translate-x-5" : "translate-x-0.5"}`
        }
      )
    }
  );
};
const GoogleCalendar = () => {
  const [settings2, setSettings] = reactExports.useState(null);
  const [loading, setLoading] = reactExports.useState(true);
  const [connecting, setConnecting] = reactExports.useState(false);
  const [syncing, setSyncing] = reactExports.useState(false);
  const { showToast } = useToast();
  const __2 = (text) => text;
  reactExports.useEffect(() => {
    fetchSettings2();
  }, []);
  const fetchSettings2 = async () => {
    try {
      const response = await apiService.getGoogleCalendarSettings();
      setSettings(response.data);
    } catch (error) {
      console.error("Failed to fetch settings:", error);
    } finally {
      setLoading(false);
    }
  };
  const handleConnect = async () => {
    setConnecting(true);
    try {
      const data = await apiService.connectGoogleCalendar();
      if (data.success && data.data.auth_url) {
        window.location.href = data.data.auth_url;
      } else {
        showToast(data.message || __2("Failed to connect"), "error");
      }
    } catch (error) {
      showToast(__2("Failed to connect to Google Calendar"), "error");
    } finally {
      setConnecting(false);
    }
  };
  const handleDisconnect = async () => {
    if (!confirm(__2("Are you sure you want to disconnect Google Calendar?"))) {
      return;
    }
    try {
      await apiService.disconnectGoogleCalendar();
      showToast(__2("Disconnected successfully"), "success");
      fetchSettings2();
    } catch (error) {
      showToast(__2("Failed to disconnect"), "error");
    }
  };
  const handleSyncAll = async () => {
    setSyncing(true);
    try {
      const data = await apiService.syncAllGoogleCalendar();
      if (data.success) {
        showToast(__2("Sync completed successfully"), "success");
        fetchSettings2();
      } else {
        showToast(data.message || __2("Sync failed"), "error");
      }
    } catch (error) {
      showToast(__2("Failed to sync bookings"), "error");
    } finally {
      setSyncing(false);
    }
  };
  const handleSettingChange = async (key2, value) => {
    try {
      await apiService.updateGoogleCalendarSettings({ [key2]: value });
      setSettings((prev) => prev ? { ...prev, [key2]: value } : null);
      showToast(__2("Settings updated"), "success");
    } catch (error) {
      showToast(__2("Failed to update settings"), "error");
    }
  };
  if (loading) {
    return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex items-center justify-center h-64", children: /* @__PURE__ */ jsxRuntimeExports.jsx(RefreshCw, { className: "w-8 h-8 animate-spin text-blue-600" }) });
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-6 p-6", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex items-center justify-between", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("h1", { className: "text-3xl font-bold text-gray-900 dark:text-white flex items-center gap-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Calendar$1, { className: "w-8 h-8 text-blue-600" }),
        __2("Google Calendar Integration")
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-gray-600 dark:text-gray-400 mt-2", children: __2(
        "Automatically sync your bookings and departures to Google Calendar"
      ) })
    ] }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs(CardHeader, { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(CardTitle, { className: "flex items-center justify-between", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: __2("Connection Status") }),
          (settings2 == null ? void 0 : settings2.connected) ? /* @__PURE__ */ jsxRuntimeExports.jsxs(Badge, { className: "bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CheckCircle, { className: "w-4 h-4 mr-1" }),
            __2("Connected")
          ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(Badge, { className: "bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-300", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(XCircle, { className: "w-4 h-4 mr-1" }),
            __2("Not Connected")
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(CardDescription, { children: (settings2 == null ? void 0 : settings2.connected) ? __2("Your Google Calendar is connected and ready to sync") : __2("Connect your Google account to start syncing bookings") })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "space-y-4", children: (settings2 == null ? void 0 : settings2.connected) ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "bg-blue-50 dark:bg-blue-900/10 border border-blue-200 dark:border-blue-800 rounded-lg p-4", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start gap-3", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Calendar$1, { className: "w-5 h-5 text-blue-600 dark:text-blue-400 mt-0.5" }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "font-medium text-gray-900 dark:text-white", children: settings2.calendar_name || __2("Primary Calendar") }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "text-sm text-gray-600 dark:text-gray-400 mt-1", children: [
              __2("Calendar ID"),
              ": ",
              settings2.calendar_id
            ] }),
            settings2.last_sync && /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "text-xs text-gray-500 dark:text-gray-500 mt-2", children: [
              __2("Last synced"),
              ":",
              " ",
              new Date(settings2.last_sync).toLocaleString()
            ] })
          ] })
        ] }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-3", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Button,
            {
              onClick: handleSyncAll,
              disabled: syncing,
              className: "flex-1",
              children: syncing ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(RefreshCw, { className: "w-4 h-4 mr-2 animate-spin" }),
                __2("Syncing...")
              ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(RefreshCw, { className: "w-4 h-4 mr-2" }),
                __2("Sync All Bookings")
              ] })
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Button,
            {
              variant: "outline",
              onClick: handleDisconnect,
              className: "text-red-600 hover:text-red-700 hover:bg-red-50 dark:hover:bg-red-900/10",
              children: __2("Disconnect")
            }
          )
        ] })
      ] }) : /* @__PURE__ */ jsxRuntimeExports.jsx(
        Button,
        {
          onClick: handleConnect,
          disabled: connecting,
          className: "w-full",
          size: "lg",
          children: connecting ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(RefreshCw, { className: "w-5 h-5 mr-2 animate-spin" }),
            __2("Connecting...")
          ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Calendar$1, { className: "w-5 h-5 mr-2" }),
            __2("Connect Google Calendar")
          ] })
        }
      ) })
    ] }),
    (settings2 == null ? void 0 : settings2.connected) && /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs(CardHeader, { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(CardTitle, { className: "flex items-center gap-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Settings$1, { className: "w-5 h-5" }),
          __2("Sync Settings")
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(CardDescription, { children: __2("Configure what gets synced to your Google Calendar") })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "space-y-6", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-4", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "font-medium text-gray-900 dark:text-white", children: __2("Auto Sync") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-600 dark:text-gray-400", children: __2("Automatically sync new bookings and changes") })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Switch,
            {
              checked: settings2.auto_sync,
              onCheckedChange: (checked) => handleSettingChange("auto_sync", checked)
            }
          )
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "font-medium text-gray-900 dark:text-white", children: __2("Sync Bookings") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-600 dark:text-gray-400", children: __2("Create calendar events for new bookings") })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Switch,
            {
              checked: settings2.sync_bookings,
              onCheckedChange: (checked) => handleSettingChange("sync_bookings", checked)
            }
          )
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "font-medium text-gray-900 dark:text-white", children: __2("Sync Departures") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-600 dark:text-gray-400", children: __2("Create calendar events for departures") })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Switch,
            {
              checked: settings2.sync_departures,
              onCheckedChange: (checked) => handleSettingChange("sync_departures", checked)
            }
          )
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "font-medium text-gray-900 dark:text-white", children: __2("Send Invitations") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-600 dark:text-gray-400", children: __2("Send calendar invitations to customers") })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Switch,
            {
              checked: settings2.send_invitations,
              onCheckedChange: (checked) => handleSettingChange("send_invitations", checked)
            }
          )
        ] })
      ] }) })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs(CardHeader, { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { children: __2("Documentation") }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(CardDescription, { children: __2("Learn more about Google Calendar integration") })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "a",
        {
          href: "https://docs.yatra.com/modules/google-calendar",
          target: "_blank",
          rel: "noopener noreferrer",
          className: "inline-flex items-center gap-2 text-blue-600 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300",
          children: [
            __2("View Documentation"),
            /* @__PURE__ */ jsxRuntimeExports.jsx(ExternalLink, { className: "w-4 h-4" })
          ]
        }
      ) })
    ] })
  ] });
};
const AdditionalServicesPremium = () => {
  const features = [
    {
      icon: Package,
      title: __("Service Management"),
      description: __(
        "Create and manage unlimited add-on services for your trips."
      )
    },
    {
      icon: DollarSign,
      title: __("Flexible Pricing"),
      description: __(
        "Set pricing per person, per booking, or per day with multiple options."
      )
    },
    {
      icon: Users,
      title: __("Trip Assignment"),
      description: __(
        "Assign services to specific trips or apply globally to all trips."
      )
    },
    {
      icon: Shield,
      title: __("Booking Integration"),
      description: __(
        "Seamless integration with booking process and payment collection."
      )
    }
  ];
  const stats = [
    {
      icon: TrendingUp,
      value: "25%",
      label: __("Revenue Increase")
    },
    {
      icon: Users,
      value: "89%",
      label: __("Customer Satisfaction")
    },
    {
      icon: Package,
      value: "Unlimited",
      label: __("Services")
    },
    {
      icon: DollarSign,
      value: "Flexible",
      label: __("Pricing Options")
    }
  ];
  const popularServices = [
    {
      icon: FileText,
      title: __("Travel Insurance"),
      description: __("Comprehensive travel coverage for peace of mind."),
      price: __("From $29/person")
    },
    {
      icon: RotateCcw,
      title: __("Airport Transfers"),
      description: __("Hassle-free airport pickup and drop-off services."),
      price: __("From $45/transfer")
    },
    {
      icon: Package,
      title: __("Equipment Rental"),
      description: __("Quality gear and equipment for outdoor activities."),
      price: __("From $15/day")
    },
    {
      icon: Users,
      title: __("Meal Packages"),
      description: __(
        "Delicious meal options for different dietary requirements."
      ),
      price: __("From $25/day")
    }
  ];
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-8", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "bg-gradient-to-r from-amber-50 to-orange-50 dark:from-amber-900/20 dark:to-orange-900/20 border border-amber-200 dark:border-amber-800 rounded-xl p-6", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Sparkles, { className: "w-6 h-6 text-amber-600 dark:text-amber-400" }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-lg font-semibold text-amber-900 dark:text-amber-100", children: __("Premium Feature") }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-amber-700 dark:text-amber-300 text-sm", children: __(
            "Additional Services is a premium module. Upgrade to Yatra Pro to unlock all features."
          ) })
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Button,
        {
          className: "bg-amber-600 text-white hover:bg-amber-700 px-6 py-2 text-sm font-medium",
          onClick: () => window.open(
            "https://wpyatra.com/pricing?module=additional-services",
            "_blank"
          ),
          children: [
            __("Upgrade to Pro"),
            /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowRight, { className: "w-4 h-4 ml-2" })
          ]
        }
      )
    ] }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-center mb-12", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "inline-flex items-center justify-center w-16 h-16 rounded-full bg-purple-100 dark:bg-purple-900 mb-6", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Package, { className: "w-8 h-8 text-purple-600 dark:text-purple-400" }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-center space-x-2 mb-4", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("h1", { className: "text-4xl font-bold text-gray-900 dark:text-white", children: __("Additional Services") }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "inline-flex items-center px-2 py-1 rounded-full bg-gradient-to-r from-amber-500 to-orange-500 text-white text-xs font-semibold shadow-md", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Sparkles, { className: "w-3 h-3 mr-1" }),
          __("PRO")
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xl text-gray-600 dark:text-gray-400 max-w-2xl mx-auto", children: __(
        "Boost your revenue by offering optional add-ons like airport transfers, travel insurance, equipment rental, and meals during trip booking."
      ) })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid grid-cols-1 md:grid-cols-4 gap-6 mb-12", children: stats.map((stat, index) => {
      const Icon = stat.icon;
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        Card,
        {
          className: "border border-gray-200 dark:border-gray-700",
          children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "pt-6", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3 mb-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-10 h-10 rounded-full bg-purple-100 dark:bg-purple-900 flex items-center justify-center", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Icon, { className: "w-5 h-5 text-purple-600 dark:text-purple-400" }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-2xl font-bold text-gray-900 dark:text-white", children: stat.value }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-600 dark:text-gray-400", children: stat.label })
            ] })
          ] }) })
        },
        index
      );
    }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mb-12", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { className: "text-2xl font-bold text-gray-900 dark:text-white mb-6 text-center", children: __("Powerful Features") }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-6", children: features.map((feature, index) => {
        const Icon = feature.icon;
        return /* @__PURE__ */ jsxRuntimeExports.jsx(
          Card,
          {
            className: "border border-gray-200 dark:border-gray-700",
            children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "pt-6", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start gap-4", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-12 h-12 rounded-full bg-purple-100 dark:bg-purple-900 flex items-center justify-center flex-shrink-0", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Icon, { className: "w-6 h-6 text-purple-600 dark:text-purple-400" }) }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-lg font-semibold text-gray-900 dark:text-white mb-2", children: feature.title }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-gray-600 dark:text-gray-400 text-sm", children: feature.description })
              ] })
            ] }) })
          },
          index
        );
      }) })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mb-12", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { className: "text-2xl font-bold text-gray-900 dark:text-white mb-6 text-center", children: __("Popular Service Types") }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6", children: popularServices.map((service, index) => {
        const Icon = service.icon;
        return /* @__PURE__ */ jsxRuntimeExports.jsx(
          Card,
          {
            className: "border border-gray-200 dark:border-gray-700",
            children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "pt-6", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-center", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-12 h-12 rounded-full bg-purple-100 dark:bg-purple-900 flex items-center justify-center mx-auto mb-4", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Icon, { className: "w-6 h-6 text-purple-600 dark:text-purple-400" }) }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("h4", { className: "font-semibold mb-2", children: service.title }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-600 dark:text-gray-400 mb-3", children: service.description }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-purple-600 dark:text-purple-400 font-semibold text-sm", children: service.price })
            ] }) })
          },
          index
        );
      }) })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "bg-gradient-to-r from-purple-50 to-indigo-50 dark:from-purple-900/20 dark:to-indigo-900/20 border border-purple-200 dark:border-purple-800 rounded-xl p-8", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col md:flex-row items-center justify-between", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mb-6 md:mb-0 md:pr-8", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3 mb-4", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-12 h-12 rounded-full bg-purple-100 dark:bg-purple-900 flex items-center justify-center", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Sparkles, { className: "w-6 h-6 text-purple-600 dark:text-purple-400" }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-2xl font-bold text-gray-900 dark:text-white", children: __("Unlock Additional Services") })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-gray-600 dark:text-gray-400 mb-4", children: __(
          "Offer premium add-ons and boost your revenue with Yatra Pro."
        ) }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CheckCircle, { className: "w-4 h-4 text-green-500" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm text-gray-600 dark:text-gray-400", children: __("Airport transfers") })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CheckCircle, { className: "w-4 h-4 text-green-500" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm text-gray-600 dark:text-gray-400", children: __("Travel insurance") })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CheckCircle, { className: "w-4 h-4 text-green-500" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm text-gray-600 dark:text-gray-400", children: __("Equipment rental") })
          ] })
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col items-center", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Button,
          {
            className: "bg-purple-600 text-white hover:bg-purple-700 px-8 py-3 text-sm font-medium mb-3",
            onClick: () => window.open(
              "https://wpyatra.com/pricing?module=additional-services",
              "_blank"
            ),
            children: [
              __("Upgrade to Pro"),
              /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowRight, { className: "w-4 h-4 ml-2" })
            ]
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400", children: __("14-day money-back guarantee") })
      ] })
    ] }) })
  ] });
};
const isModuleAvailable$2 = () => {
  const yatraAdmin = window == null ? void 0 : window.yatraAdmin;
  return Boolean(yatraAdmin == null ? void 0 : yatraAdmin.isPro);
};
const AdditionalServices = () => {
  const moduleAvailable = isModuleAvailable$2();
  const [searchTerm, setSearchTerm] = reactExports.useState("");
  const [statusFilter, setStatusFilter] = reactExports.useState("all");
  const [sortBy2, setSortBy] = reactExports.useState("name");
  const [sortOrder, setSortOrder] = reactExports.useState("asc");
  const [page, setPage] = reactExports.useState(1);
  const [selectedIds, setSelectedIds] = reactExports.useState([]);
  const [bulkAction, setBulkAction] = reactExports.useState("");
  const [showColumnsDropdown, setShowColumnsDropdown] = reactExports.useState(false);
  const [permanentDeleteConfirm, setPermanentDeleteConfirm] = reactExports.useState({
    isOpen: false,
    service: null
  });
  const [visibleColumns, setVisibleColumns] = reactExports.useState(() => {
    const saved = localStorage.getItem("yatra-additional-services-columns");
    return saved ? JSON.parse(saved) : {
      name: true,
      price: true,
      price_type: true,
      price_per: true,
      trips: true,
      status: true,
      created_at: false,
      updated_at: false
    };
  });
  const { showToast } = useToast();
  const queryClient2 = useQueryClient();
  const { can } = usePermissions();
  const toggleColumn = (columnKey) => {
    const newVisibleColumns = {
      ...visibleColumns,
      [columnKey]: !visibleColumns[columnKey]
    };
    setVisibleColumns(newVisibleColumns);
    localStorage.setItem(
      "yatra-additional-services-columns",
      JSON.stringify(newVisibleColumns)
    );
  };
  const queryParams = reactExports.useMemo(() => {
    const params = {
      page,
      per_page: 10,
      orderby: sortBy2,
      order: sortOrder
    };
    if (searchTerm) params.search = searchTerm;
    if (statusFilter !== "all") params.status = statusFilter;
    return params;
  }, [searchTerm, statusFilter, sortBy2, sortOrder, page]);
  const { data: statsData } = useQuery({
    queryKey: ["additional-services-stats"],
    queryFn: async () => {
      try {
        const response = await apiClient.get("/additional-services/stats");
        return response;
      } catch {
        return { all: 0, publish: 0, draft: 0, trash: 0 };
      }
    },
    enabled: isModuleAvailable$2()
  });
  const { data, isLoading, error } = useQuery({
    queryKey: ["additional-services", queryParams],
    queryFn: async () => {
      const response = await apiClient.get("/additional-services", {
        params: queryParams
      });
      return response;
    },
    enabled: isModuleAvailable$2()
  });
  const services = (data == null ? void 0 : data.data) || [];
  const total = (data == null ? void 0 : data.total) || 0;
  const totalPages = Math.ceil(total / 10);
  const statusCounts = reactExports.useMemo(() => {
    if (statsData) {
      return {
        all: statsData.all ?? 0,
        publish: statsData.publish ?? 0,
        draft: statsData.draft ?? 0,
        trash: statsData.trash ?? 0
      };
    }
    return { all: 0, publish: 0, draft: 0, trash: 0 };
  }, [statsData]);
  const bulkMutation = useMutation({
    mutationFn: async ({
      action,
      ids
    }) => {
      return await apiClient.post("/additional-services/bulk", { action, ids });
    },
    onSuccess: () => {
      queryClient2.invalidateQueries({ queryKey: ["additional-services"] });
      queryClient2.invalidateQueries({
        queryKey: ["additional-services-stats"]
      });
      showToast(__("Action completed successfully"), "success");
      setSelectedIds([]);
      setBulkAction("");
    },
    onError: () => {
      showToast(__("Failed to perform action"), "error");
    }
  });
  const navigateToForm = (action, id) => {
    const params = new URLSearchParams(window.location.search);
    params.set("subpage", "trips");
    params.set("tab", "additional-services");
    params.set("action", action);
    if (id) params.set("id", id.toString());
    window.history.pushState({}, "", `${window.location.pathname}?${params}`);
    window.dispatchEvent(new PopStateEvent("popstate"));
  };
  const formatPrice = (price, priceType, pricePer) => {
    var _a;
    const currency = ((_a = window == null ? void 0 : window.yatraAdmin) == null ? void 0 : _a.currency) || "USD";
    const numPrice = Number(price) || 0;
    if (priceType === "percentage") return `${numPrice}%`;
    const perLabel = { person: __("/person"), booking: __("/booking"), day: __("/day") }[pricePer] || "";
    return `${formatYatraMoney(numPrice, currency, { zeroAsUnknown: false })}${perLabel}`;
  };
  const handleEdit = (service) => {
    navigateToForm("edit", service.id);
  };
  const handlePermanentDelete = (service) => {
    setPermanentDeleteConfirm({ isOpen: true, service });
  };
  const confirmPermanentDelete = () => {
    if (permanentDeleteConfirm.service) {
      bulkMutation.mutate({
        action: "delete",
        ids: [permanentDeleteConfirm.service.id]
      });
      setPermanentDeleteConfirm({ isOpen: false, service: null });
    }
  };
  const handleSort = (field) => {
    if (sortBy2 === field) {
      setSortOrder(sortOrder === "asc" ? "desc" : "asc");
    } else {
      setSortBy(field);
      setSortOrder("asc");
    }
  };
  const getSortIcon = (field) => {
    if (sortBy2 !== field) {
      return null;
    }
    return sortOrder === "asc" ? "↑" : "↓";
  };
  const handleBulkApply = () => {
    if (!bulkAction) {
      showToast(__("Select a bulk action first."), "warning");
      return;
    }
    if (selectedIds.length === 0) {
      showToast(__("Select at least one service."), "warning");
      return;
    }
    bulkMutation.mutate({ action: bulkAction, ids: selectedIds });
  };
  const handleResetFilters = () => {
    setSearchTerm("");
    setStatusFilter("all");
    setSortBy("name");
    setSortOrder("asc");
    setPage(1);
    setSelectedIds([]);
    setBulkAction("");
  };
  const hasFilters = searchTerm || statusFilter !== "all" || sortBy2 !== "name" || sortOrder !== "asc";
  reactExports.useEffect(() => {
    setSelectedIds(
      (prev) => prev.filter((id) => services.some((s2) => s2.id === id))
    );
  }, [services]);
  const viewFilters = [
    { key: "all", label: __("All"), count: statusCounts.all ?? 0 },
    {
      key: "publish",
      label: __("Published"),
      count: statusCounts.publish ?? 0
    },
    { key: "draft", label: __("Draft"), count: statusCounts.draft ?? 0 },
    { key: "trash", label: __("Trash"), count: statusCounts.trash ?? 0 }
  ];
  if (!moduleAvailable) {
    return /* @__PURE__ */ jsxRuntimeExports.jsx(AdditionalServicesPremium, {});
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      PageHeader,
      {
        title: __("Additional Services", "yatra"),
        description: __(
          "Manage add-ons and extras that customers can select when booking",
          "yatra"
        ),
        actionCapability: "yatra_edit_trips",
        actions: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Button,
          {
            onClick: () => navigateToForm("create"),
            className: "flex items-center gap-2",
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Plus, { className: "w-4 h-4" }),
              __("Add New Service", "yatra")
            ]
          }
        )
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      ConfirmationDialog,
      {
        isOpen: permanentDeleteConfirm.isOpen,
        onClose: () => setPermanentDeleteConfirm({ isOpen: false, service: null }),
        onConfirm: confirmPermanentDelete,
        title: __("Delete Service Permanently"),
        message: permanentDeleteConfirm.service ? __(
          'Are you sure you want to permanently delete "{name}"? This action cannot be undone.'
        ).replace("{name}", permanentDeleteConfirm.service.name) : __("Are you sure you want to permanently delete this service?"),
        confirmText: __("Delete Permanently"),
        cancelText: __("Cancel"),
        variant: "danger",
        isLoading: bulkMutation.isPending
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-3", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
      SearchFilterToolbar,
      {
        searchTerm,
        onSearchChange: setSearchTerm,
        statusFilter,
        onStatusChange: (value) => {
          setStatusFilter(value);
          setPage(1);
          setSelectedIds([]);
          setBulkAction("");
        },
        statusOptions: [
          { value: "all", label: __("All Status") },
          { value: "publish", label: __("Published") },
          { value: "draft", label: __("Draft") },
          { value: "trash", label: __("Trash") }
        ],
        sortBy: sortBy2,
        onSortByChange: setSortBy,
        sortOrder,
        onSortOrderChange: setSortOrder,
        sortOptions: [
          { value: "name", label: __("Name") },
          { value: "price", label: __("Price") },
          { value: "price_type", label: __("Price Type") },
          { value: "price_per", label: __("Price Per") },
          { value: "status", label: __("Status") },
          { value: "created_at", label: __("Created At") },
          { value: "updated_at", label: __("Updated At") }
        ],
        onResetFilters: handleResetFilters,
        hasFilters: !!hasFilters,
        placeholder: __("Search services...")
      }
    ) }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_view_trips", children: error ? /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-8 text-center text-red-500", children: __("Error loading services") }) }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        BulkActionToolbar,
        {
          selectedIds,
          bulkAction,
          setBulkAction,
          onApply: handleBulkApply,
          onClearSelection: () => setSelectedIds([]),
          statusFilter,
          setStatusFilter: (value) => {
            setStatusFilter(value);
            setPage(1);
            setSelectedIds([]);
            setBulkAction("");
          },
          statusOptions: viewFilters,
          showColumnsDropdown,
          setShowColumnsDropdown,
          columnOptions: [
            {
              key: "name",
              label: __("Service"),
              visible: visibleColumns.name
            },
            {
              key: "price",
              label: __("Price"),
              visible: visibleColumns.price
            },
            {
              key: "price_type",
              label: __("Price Type"),
              visible: visibleColumns.price_type
            },
            {
              key: "price_per",
              label: __("Price Per"),
              visible: visibleColumns.price_per
            },
            {
              key: "trips",
              label: __("Trips"),
              visible: visibleColumns.trips
            },
            {
              key: "status",
              label: __("Status"),
              visible: visibleColumns.status
            },
            {
              key: "created_at",
              label: __("Created Date"),
              visible: visibleColumns.created_at
            },
            {
              key: "updated_at",
              label: __("Updated Date"),
              visible: visibleColumns.updated_at
            }
          ],
          onToggleColumn: toggleColumn,
          bulkMutationPending: bulkMutation.isPending,
          totalItems: services.length,
          bulkActionOptions: getDefaultBulkStatusOptions(statusFilter)
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { className: "overflow-visible", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-0 overflow-visible", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        Table,
        {
          data: services,
          columns: [
            {
              key: "name",
              label: __("Service"),
              sortable: true,
              visible: visibleColumns.name,
              render: (service) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-10 h-10 rounded-lg bg-purple-100 dark:bg-purple-900/30 flex items-center justify-center flex-shrink-0", children: service.icon ? service.icon.type === "image" ? /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "img",
                  {
                    src: service.icon.value,
                    alt: service.name,
                    className: "w-full h-full object-cover rounded-lg"
                  }
                ) : /* @__PURE__ */ jsxRuntimeExports.jsx(
                  IconSelector,
                  {
                    iconName: service.icon.value,
                    provider: service.icon.provider ?? "yatra",
                    className: "w-5 h-5 text-purple-600 dark:text-purple-400"
                  }
                ) : /* @__PURE__ */ jsxRuntimeExports.jsx(Package, { className: "w-5 h-5 text-purple-600 dark:text-purple-400" }) }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "a",
                      {
                        href: "#",
                        onClick: (e) => {
                          e.preventDefault();
                          handleEdit(service);
                        },
                        className: "font-medium text-purple-600 dark:text-purple-400 hover:text-purple-700 dark:hover:text-purple-300 hover:underline transition-colors cursor-pointer",
                        children: service.name
                      }
                    ),
                    (service.is_required === true || service.is_required === 1 || service.is_required === "1") && /* @__PURE__ */ jsxRuntimeExports.jsx(
                      Badge,
                      {
                        variant: "outline",
                        className: "text-xs bg-amber-100 text-amber-700 border-amber-300 dark:bg-amber-900/30 dark:text-amber-400 dark:border-amber-700",
                        children: __("Required")
                      }
                    )
                  ] }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-500 dark:text-gray-400 flex items-center gap-2", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-[11px] text-gray-400 dark:text-gray-500", children: [
                    "(",
                    __("ID:", "yatra"),
                    " ",
                    service.id,
                    ")"
                  ] }) })
                ] })
              ] })
            },
            {
              key: "price",
              label: __("Price"),
              sortable: true,
              visible: visibleColumns.price,
              render: (service) => /* @__PURE__ */ jsxRuntimeExports.jsx(
                "span",
                {
                  className: service.status === "trash" ? "text-gray-400 dark:text-gray-600" : "font-medium text-gray-900 dark:text-white",
                  children: formatPrice(
                    service.price,
                    service.price_type,
                    service.price_per
                  )
                }
              )
            },
            {
              key: "price_type",
              label: __("Price Type"),
              sortable: true,
              visible: visibleColumns.price_type,
              render: (service) => /* @__PURE__ */ jsxRuntimeExports.jsx(
                "span",
                {
                  className: service.status === "trash" ? "text-gray-400 dark:text-gray-600" : "inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800 dark:bg-gray-900/30 dark:text-gray-300",
                  children: service.price_type === "fixed" ? __("Fixed") : __("Percentage")
                }
              )
            },
            {
              key: "price_per",
              label: __("Price Per"),
              sortable: true,
              visible: visibleColumns.price_per,
              render: (service) => /* @__PURE__ */ jsxRuntimeExports.jsx(
                "span",
                {
                  className: service.status === "trash" ? "text-gray-400 dark:text-gray-600" : "inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300",
                  children: {
                    person: __("Person"),
                    booking: __("Booking"),
                    day: __("Day")
                  }[service.price_per] || service.price_per
                }
              )
            },
            {
              key: "trips",
              label: __("Trips"),
              sortable: false,
              visible: visibleColumns.trips,
              render: (service) => /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex flex-col gap-1", children: service.applicable_to === "all" ? /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300", children: __("All Trips") }) : service.trips && service.trips.length > 0 ? /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-wrap gap-1", children: [
                service.trips.slice(0, 2).map((trip) => /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "span",
                  {
                    className: "inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-300 max-w-[120px] truncate",
                    title: trip.title,
                    children: trip.title
                  },
                  trip.id
                )),
                service.trips.length > 2 && /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-300", children: [
                  "+",
                  service.trips.length - 2,
                  " ",
                  __("more")
                ] })
              ] }) : /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-400 dark:text-gray-600 text-xs", children: __("No trips assigned") }) })
            },
            {
              key: "status",
              label: __("Status"),
              sortable: true,
              visible: visibleColumns.status,
              render: (service) => /* @__PURE__ */ jsxRuntimeExports.jsx(
                "span",
                {
                  className: `inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${service.status === "trash" ? "bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400" : service.status === "publish" ? "bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400" : "bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400"}`,
                  children: service.status === "trash" ? __("Trash") : service.status === "publish" ? __("Published") : __("Draft")
                }
              )
            },
            {
              key: "created_at",
              label: __("Created Date"),
              sortable: true,
              visible: visibleColumns.created_at,
              render: (service) => /* @__PURE__ */ jsxRuntimeExports.jsx(
                "span",
                {
                  className: service.status === "trash" ? "text-gray-400 dark:text-gray-600" : "text-gray-600 dark:text-gray-400",
                  children: new Date(service.created_at).toLocaleDateString(
                    "en-US",
                    {
                      year: "numeric",
                      month: "short",
                      day: "numeric"
                    }
                  )
                }
              )
            },
            {
              key: "updated_at",
              label: __("Updated Date"),
              sortable: true,
              visible: visibleColumns.updated_at,
              render: (service) => /* @__PURE__ */ jsxRuntimeExports.jsx(
                "span",
                {
                  className: service.status === "trash" ? "text-gray-400 dark:text-gray-600" : "text-gray-600 dark:text-gray-400",
                  children: new Date(service.updated_at).toLocaleDateString(
                    "en-US",
                    {
                      year: "numeric",
                      month: "short",
                      day: "numeric"
                    }
                  )
                }
              )
            }
          ],
          actions: [
            {
              key: "edit",
              label: __("Edit"),
              icon: /* @__PURE__ */ jsxRuntimeExports.jsx(PenSquare, { className: "w-4 h-4" }),
              onClick: handleEdit,
              condition: () => can("yatra_edit_trips")
            },
            {
              key: "publish",
              label: __("Publish"),
              icon: /* @__PURE__ */ jsxRuntimeExports.jsx(CheckCircle, { className: "w-4 h-4" }),
              onClick: (service) => {
                bulkMutation.mutate({
                  action: "publish",
                  ids: [service.id]
                });
              },
              condition: (service) => service.status !== "publish" && service.status !== "trash" && can("yatra_edit_trips")
            },
            {
              key: "draft",
              label: __("Set as Draft"),
              icon: /* @__PURE__ */ jsxRuntimeExports.jsx(FileText, { className: "w-4 h-4" }),
              onClick: (service) => {
                bulkMutation.mutate({
                  action: "draft",
                  ids: [service.id]
                });
              },
              condition: (service) => service.status !== "draft" && service.status !== "trash" && can("yatra_edit_trips")
            },
            {
              key: "restore",
              label: __("Restore"),
              icon: /* @__PURE__ */ jsxRuntimeExports.jsx(RotateCcw, { className: "w-4 h-4" }),
              onClick: (service) => {
                bulkMutation.mutate({
                  action: "restore",
                  ids: [service.id]
                });
              },
              condition: (service) => (service.status === "trash" || statusFilter === "trash") && can("yatra_edit_trips")
            },
            {
              key: "trash",
              label: __("Move to Trash"),
              icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "w-4 h-4" }),
              onClick: (service) => {
                bulkMutation.mutate({
                  action: "trash",
                  ids: [service.id]
                });
              },
              condition: (service) => service.status !== "trash" && statusFilter !== "trash" && can("yatra_edit_trips")
            },
            {
              key: "delete",
              label: __("Delete Permanently"),
              icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "w-4 h-4" }),
              onClick: handlePermanentDelete,
              condition: (service) => (service.status === "trash" || statusFilter === "trash") && can("yatra_delete_trips"),
              variant: "destructive"
            }
          ],
          isLoading,
          isError: !!error,
          errorText: __("Error loading services"),
          emptyText: __("No services found"),
          emptyDescription: hasFilters ? __("Try adjusting your filters to see more results.") : __("Get started by creating your first service."),
          onCreateClick: can("yatra_edit_trips") ? () => navigateToForm("create") : void 0,
          onSort: handleSort,
          getSortIcon,
          selectedItemIds: selectedIds,
          onSelectItem: (id, checked) => {
            if (checked) {
              setSelectedIds([...selectedIds, id]);
            } else {
              setSelectedIds(
                selectedIds.filter((selectedId) => selectedId !== id)
              );
            }
          },
          onSelectAll: (checked) => {
            if (checked) {
              setSelectedIds(
                services.map((s2) => s2.id)
              );
            } else {
              setSelectedIds([]);
            }
          },
          isAllSelected: services.length > 0 && selectedIds.length === services.length,
          getItemId: (service) => service.id,
          getItemStatus: (service) => service.status,
          statusFilter,
          skeletonRows: 5
        }
      ) }) }),
      total > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-4", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        Pagination,
        {
          currentPage: page,
          totalPages,
          totalItems: total,
          itemsPerPage: 10,
          onPageChange: (newPage) => setPage(newPage),
          itemName: __("services")
        }
      ) })
    ] }) })
  ] });
};
const defaultService = {
  name: "",
  description: "",
  price: 0,
  price_type: "fixed",
  price_per: "person",
  icon: null,
  status: "publish",
  sort_order: 0,
  applicable_to: "all",
  trip_ids: [],
  is_required: false
};
const isModuleAvailable$1 = () => {
  const yatraAdmin = window == null ? void 0 : window.yatraAdmin;
  return Boolean((yatraAdmin == null ? void 0 : yatraAdmin.isPro) && (yatraAdmin == null ? void 0 : yatraAdmin.additionalServicesEnabled));
};
const AdditionalServicesForm = () => {
  const [formData, setFormData] = reactExports.useState(defaultService);
  const [errors, setErrors] = reactExports.useState({});
  const [showTripDropdown, setShowTripDropdown] = reactExports.useState(false);
  const [tripSearchQuery, setTripSearchQuery] = reactExports.useState("");
  const [debouncedTripSearch, setDebouncedTripSearch] = reactExports.useState("");
  const { showToast } = useToast();
  const queryClient2 = useQueryClient();
  const { can } = usePermissions();
  const params = new URLSearchParams(window.location.search);
  const serviceId = params.get("id");
  const isEditMode = !!serviceId;
  reactExports.useEffect(() => {
    const timer2 = setTimeout(() => {
      setDebouncedTripSearch(tripSearchQuery);
    }, 300);
    return () => clearTimeout(timer2);
  }, [tripSearchQuery]);
  const tripsQuery = useQuery({
    queryKey: ["trips-for-service", debouncedTripSearch],
    queryFn: async () => {
      var _a;
      try {
        const params2 = {
          per_page: 100
        };
        if (debouncedTripSearch.trim()) {
          params2.search = debouncedTripSearch.trim();
        }
        const response = await apiClient.get("/trips", { params: params2 });
        const trips = ((_a = response == null ? void 0 : response.data) == null ? void 0 : _a.data) || (response == null ? void 0 : response.data) || response || [];
        return Array.isArray(trips) ? trips : [];
      } catch (error) {
        console.error("Failed to load trips:", error);
        return [];
      }
    },
    enabled: formData.applicable_to === "specific_trips",
    staleTime: 5 * 60 * 1e3
  });
  const tripOptions = (tripsQuery.data || []).filter(
    (t) => !!t && (typeof t.id === "number" || typeof t.id === "string")
  ).map((trip) => ({
    value: Number(trip.id),
    label: trip.title || trip.name || `Trip #${trip.id}`
  }));
  const { data: serviceData, isLoading: isLoadingService } = useQuery({
    queryKey: ["additional-service", serviceId],
    queryFn: async () => {
      var _a;
      const response = await apiClient.get(`/additional-services/${serviceId}`);
      return ((_a = response.data) == null ? void 0 : _a.data) || response.data;
    },
    enabled: isEditMode && isModuleAvailable$1()
  });
  reactExports.useEffect(() => {
    if (serviceData) {
      let iconValue = null;
      if (serviceData.icon) {
        iconValue = serviceData.icon;
      } else if (serviceData.image_url) {
        iconValue = { type: "image", value: serviceData.image_url };
      }
      setFormData({
        id: serviceData.id,
        name: serviceData.name || "",
        description: serviceData.description || "",
        price: parseFloat(serviceData.price) || 0,
        price_type: serviceData.price_type || "fixed",
        price_per: serviceData.price_per || "person",
        icon: iconValue,
        status: serviceData.status || "draft",
        sort_order: serviceData.sort_order || 0,
        applicable_to: serviceData.applicable_to || "all",
        trip_ids: serviceData.trip_ids || [],
        is_required: serviceData.is_required === true || serviceData.is_required === 1 || serviceData.is_required === "1"
      });
    }
  }, [serviceData]);
  const saveMutation = useMutation({
    mutationFn: async (data) => {
      if (isEditMode) {
        return apiClient.put(`/additional-services/${serviceId}`, data);
      }
      return apiClient.post("/additional-services", data);
    },
    onSuccess: () => {
      showToast(
        isEditMode ? __("Service updated successfully") : __("Service created successfully"),
        "success"
      );
      queryClient2.invalidateQueries({ queryKey: ["additional-services"] });
      if (!isEditMode) {
        navigateBack();
      }
    },
    onError: (error) => {
      var _a, _b;
      const message2 = ((_b = (_a = error == null ? void 0 : error.response) == null ? void 0 : _a.data) == null ? void 0 : _b.message) || __("Failed to save service");
      showToast(message2, "error");
    }
  });
  const navigateBack = () => {
    const params2 = new URLSearchParams(window.location.search);
    params2.delete("action");
    params2.delete("id");
    params2.set("subpage", "trips");
    params2.set("tab", "additional-services");
    window.history.pushState({}, "", `${window.location.pathname}?${params2}`);
    window.dispatchEvent(new PopStateEvent("popstate"));
  };
  const handleFieldChange = (field, value) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
    if (errors[field]) {
      setErrors((prev) => {
        const newErrors = { ...prev };
        delete newErrors[field];
        return newErrors;
      });
    }
  };
  const validateForm = () => {
    const newErrors = {};
    if (!formData.name.trim()) {
      newErrors.name = __("Service name is required");
    }
    if (formData.price < 0) {
      newErrors.price = __("Price cannot be negative");
    }
    if (formData.price_type === "percentage" && formData.price > 100) {
      newErrors.price = __("Percentage cannot exceed 100%");
    }
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };
  const handleSubmit = (e) => {
    e.preventDefault();
    if (!validateForm()) {
      showToast(__("Please fix the errors before saving"), "error");
      return;
    }
    saveMutation.mutate(formData);
  };
  const hasPermission = can("manage_options") || can("yatra_manage_settings") || can("yatra_edit_trips");
  if (!hasPermission) {
    return /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-12 text-center", children: /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-gray-500 dark:text-gray-400", children: __("You do not have permission to manage services.") }) }) });
  }
  if (!isModuleAvailable$1()) {
    return /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "p-12 text-center", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(Package, { className: "w-12 h-12 mx-auto text-gray-400 mb-4" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-lg font-medium text-gray-900 dark:text-white mb-2", children: __("Premium Feature") }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-gray-500 dark:text-gray-400 mb-6", children: __(
        "Additional Services is a premium feature. Upgrade to Yatra Pro to unlock."
      ) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        Button,
        {
          onClick: () => window.open(
            "https://wpyatra.com/pricing?module=additional-services",
            "_blank"
          ),
          children: __("Upgrade to Pro")
        }
      )
    ] }) });
  }
  if (isEditMode && isLoadingService) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-6", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg p-6", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-8 bg-gray-200 dark:bg-gray-700 rounded w-1/4 mb-2 animate-pulse" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-1/2 animate-pulse" })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-3 gap-6", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "lg:col-span-2 space-y-6", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-6 bg-gray-200 dark:bg-gray-700 rounded w-32 animate-pulse" }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-4", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-24 mb-2 animate-pulse" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-24 mb-2 animate-pulse" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-24 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" })
              ] })
            ] })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-6 bg-gray-200 dark:bg-gray-700 rounded w-20 animate-pulse" }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-4", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-3 gap-4", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-16 mb-2 animate-pulse" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-20 mb-2 animate-pulse" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-20 mb-2 animate-pulse" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" })
                ] })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-3/4 animate-pulse" })
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-6", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-6 bg-gray-200 dark:bg-gray-700 rounded w-20 animate-pulse" }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-4", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-16 mb-2 animate-pulse" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-20 mb-2 animate-pulse" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "pt-4 border-t border-gray-200 dark:border-gray-700", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" }) })
            ] })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-6 bg-gray-200 dark:bg-gray-700 rounded w-36 animate-pulse" }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-40 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" }) })
          ] })
        ] })
      ] })
    ] });
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-6", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      PageHeader,
      {
        description: isEditMode ? __("Update the details of this additional service.") : __(
          "Create a new additional service that customers can add to their bookings."
        ),
        actions: /* @__PURE__ */ jsxRuntimeExports.jsxs(Button, { variant: "outline", onClick: navigateBack, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowLeft, { className: "w-4 h-4 mr-2" }),
          __("Back to Services")
        ] })
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx("form", { onSubmit: handleSubmit, children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-3 gap-6", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "lg:col-span-2 space-y-6", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { children: __("Service Details") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-4", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1", children: [
                __("Service Name"),
                " ",
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Input,
                {
                  value: formData.name,
                  onChange: (e) => handleFieldChange("name", e.target.value),
                  placeholder: __("e.g., Airport Transfer, Travel Insurance"),
                  className: errors.name ? "border-red-500" : ""
                }
              ),
              errors.name && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm text-red-500", children: errors.name })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1", children: __("Description") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "textarea",
                {
                  value: formData.description,
                  onChange: (e) => handleFieldChange("description", e.target.value),
                  placeholder: __("Describe what this service includes..."),
                  rows: 4,
                  className: "w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-800 dark:text-white"
                }
              )
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start gap-3 p-3 bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "input",
                {
                  type: "checkbox",
                  id: "is_required",
                  checked: formData.is_required,
                  onChange: (e) => handleFieldChange("is_required", e.target.checked),
                  className: "mt-0.5 h-4 w-4 text-amber-600 focus:ring-amber-500 border-gray-300 rounded"
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "label",
                  {
                    htmlFor: "is_required",
                    className: "text-sm font-medium text-gray-900 dark:text-white cursor-pointer",
                    children: __("Required Service")
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400 mt-0.5", children: __(
                  "If enabled, customers must select this service when booking."
                ) })
              ] })
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { children: __("Pricing") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-4", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-3 gap-4", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1", children: __("Price") }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Input,
                  {
                    type: "number",
                    min: "0",
                    step: "0.01",
                    value: formData.price,
                    onChange: (e) => handleFieldChange(
                      "price",
                      parseFloat(e.target.value) || 0
                    ),
                    className: errors.price ? "border-red-500" : ""
                  }
                ),
                errors.price && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm text-red-500", children: errors.price })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1", children: __("Price Type") }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs(
                  Select,
                  {
                    value: formData.price_type,
                    onChange: (e) => handleFieldChange("price_type", e.target.value),
                    children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "fixed", children: __("Fixed Amount") }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "percentage", children: __("Percentage of Trip Price") })
                    ]
                  }
                )
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1", children: __("Price Per") }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs(
                  Select,
                  {
                    value: formData.price_per,
                    onChange: (e) => handleFieldChange("price_per", e.target.value),
                    children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "person", children: __("Per Person") }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "booking", children: __("Per Booking") }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "day", children: __("Per Day") })
                    ]
                  }
                )
              ] })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-500 dark:text-gray-400", children: formData.price_type === "percentage" ? __(
              "The price will be calculated as a percentage of the trip base price."
            ) : formData.price_per === "person" ? __(
              "This price will be multiplied by the number of travelers."
            ) : formData.price_per === "day" ? __(
              "This price will be multiplied by the trip duration in days."
            ) : __("This is a flat fee charged once per booking.") })
          ] })
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-6", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { children: __("Publish") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-4", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1", children: __("Status") }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs(
                Select,
                {
                  value: formData.status,
                  onChange: (e) => handleFieldChange("status", e.target.value),
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "draft", children: __("Draft") }),
                    /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "publish", children: __("Published") }),
                    /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "trash", children: __("Trash") })
                  ]
                }
              )
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1", children: __("Sort Order") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Input,
                {
                  type: "number",
                  min: "0",
                  value: formData.sort_order,
                  onChange: (e) => handleFieldChange(
                    "sort_order",
                    parseInt(e.target.value) || 0
                  )
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-xs text-gray-500 dark:text-gray-400", children: __("Lower numbers appear first") })
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { children: __("Applicable To") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              Select,
              {
                value: formData.applicable_to,
                onChange: (e) => handleFieldChange(
                  "applicable_to",
                  e.target.value
                ),
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "all", children: __("All Trips") }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "specific_trips", children: __("Specific Trips") })
                ]
              }
            ),
            formData.applicable_to === "specific_trips" && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-3 space-y-2 relative", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "div",
                {
                  className: "border border-gray-300 dark:border-gray-600 rounded-lg p-2 cursor-pointer hover:border-gray-400 dark:hover:border-gray-500 bg-white dark:bg-gray-800",
                  onClick: () => setShowTripDropdown(!showTripDropdown),
                  children: formData.trip_ids.length > 0 ? /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-wrap gap-1.5", children: [
                    formData.trip_ids.slice(0, 3).map((tripId) => {
                      const trip = tripOptions.find(
                        (t) => t.value === tripId
                      );
                      return /* @__PURE__ */ jsxRuntimeExports.jsxs(
                        "span",
                        {
                          className: "inline-flex items-center gap-1 px-2 py-0.5 text-xs font-medium bg-blue-100 dark:bg-blue-900/30 text-blue-800 dark:text-blue-300 rounded",
                          children: [
                            (trip == null ? void 0 : trip.label) || `Trip #${tripId}`,
                            /* @__PURE__ */ jsxRuntimeExports.jsx(
                              "button",
                              {
                                type: "button",
                                onClick: (e) => {
                                  e.stopPropagation();
                                  handleFieldChange(
                                    "trip_ids",
                                    formData.trip_ids.filter(
                                      (id) => id !== tripId
                                    )
                                  );
                                },
                                className: "hover:text-blue-600 dark:hover:text-blue-200",
                                children: /* @__PURE__ */ jsxRuntimeExports.jsx(X, { className: "w-3 h-3" })
                              }
                            )
                          ]
                        },
                        tripId
                      );
                    }),
                    formData.trip_ids.length > 3 && /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "inline-flex items-center px-2 py-0.5 text-xs font-medium bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300 rounded", children: [
                      "+",
                      formData.trip_ids.length - 3,
                      " ",
                      __("more")
                    ] })
                  ] }) : /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm text-gray-500 dark:text-gray-400", children: __("Click to select trips...") })
                }
              ),
              showTripDropdown && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "absolute z-50 w-full mt-1 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg shadow-lg", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-2 border-b border-gray-200 dark:border-gray-700", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    Input,
                    {
                      type: "text",
                      placeholder: __("Search trips..."),
                      value: tripSearchQuery,
                      onChange: (e) => setTripSearchQuery(e.target.value),
                      className: "w-full text-sm",
                      onClick: (e) => e.stopPropagation()
                    }
                  ),
                  tripsQuery.isFetching && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "absolute right-3 top-1/2 transform -translate-y-1/2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Loader2, { className: "w-4 h-4 animate-spin text-gray-400" }) })
                ] }) }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "max-h-[200px] overflow-y-auto", children: tripsQuery.isLoading ? /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "p-4 text-center text-sm text-gray-500 dark:text-gray-400", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(Loader2, { className: "w-5 h-5 animate-spin mx-auto mb-2" }),
                  __("Loading trips...")
                ] }) : tripOptions.length > 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "divide-y divide-gray-100 dark:divide-gray-700", children: tripOptions.map((trip) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
                  "label",
                  {
                    className: "flex items-center justify-between gap-3 px-3 py-2 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700/50",
                    onClick: (e) => e.stopPropagation(),
                    children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3", children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsx(
                          "input",
                          {
                            type: "checkbox",
                            checked: formData.trip_ids.includes(
                              trip.value
                            ),
                            onChange: (e) => {
                              if (e.target.checked) {
                                handleFieldChange("trip_ids", [
                                  ...formData.trip_ids,
                                  trip.value
                                ]);
                              } else {
                                handleFieldChange(
                                  "trip_ids",
                                  formData.trip_ids.filter(
                                    (id) => id !== trip.value
                                  )
                                );
                              }
                            },
                            className: "rounded border-gray-300 dark:border-gray-600 text-blue-600 focus:ring-blue-500"
                          }
                        ),
                        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm text-gray-700 dark:text-gray-300", children: trip.label })
                      ] }),
                      /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-xs text-gray-400 dark:text-gray-500", children: [
                        "#",
                        trip.value
                      ] })
                    ]
                  },
                  trip.value
                )) }) : /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-4 text-center text-sm text-gray-500 dark:text-gray-400", children: __("No trips found") }) }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-2 border-t border-gray-200 dark:border-gray-700", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Button,
                  {
                    type: "button",
                    variant: "outline",
                    size: "sm",
                    className: "w-full",
                    onClick: () => setShowTripDropdown(false),
                    children: __("Done")
                  }
                ) })
              ] })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400", children: formData.applicable_to === "all" ? __("This service will be available for all trips.") : __(
              "This service will only be available for the selected trips."
            ) })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { children: __("Service Icon or Image") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            IconPicker,
            {
              value: formData.icon,
              onChange: (value) => handleFieldChange("icon", value),
              label: __("Service Icon or Image"),
              helpText: __(
                "Select an icon from the library or upload a custom image for this service."
              ),
              allowImageUpload: true,
              allowIconSelection: true,
              size: "md"
            }
          ) })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "pt-6", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          Button,
          {
            type: "submit",
            className: "w-full",
            disabled: saveMutation.isPending,
            children: saveMutation.isPending ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Loader2, { className: "w-4 h-4 mr-2 animate-spin" }),
              __("Saving...")
            ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Save, { className: "w-4 h-4 mr-2" }),
              isEditMode ? __("Update Service") : __("Create Service")
            ] })
          }
        ) }) })
      ] })
    ] }) })
  ] });
};
const TripConsentPremium = () => {
  const features = [
    {
      icon: FileSignature,
      title: __("Digital Signatures"),
      description: __(
        "Create legally binding consent forms with digital signature capabilities."
      )
    },
    {
      icon: Shield,
      title: __("Legal Compliance"),
      description: __(
        "Ensure GDPR and privacy regulation compliance with proper consent management."
      )
    },
    {
      icon: ClipboardCheck,
      title: __("Custom Forms"),
      description: __(
        "Build custom consent forms with conditional logic and required fields."
      )
    },
    {
      icon: Send,
      title: __("Email Delivery"),
      description: __(
        "Automatically send consent forms to customers via email for electronic signing."
      )
    }
  ];
  const stats = [
    {
      icon: CheckCircle,
      value: "100%",
      label: __("Legal Compliance")
    },
    {
      icon: Users,
      value: "15k",
      label: __("Forms Signed")
    },
    {
      icon: Clock,
      value: "60s",
      label: __("Average Sign Time")
    },
    {
      icon: Shield,
      value: "AES256",
      label: __("Encryption")
    }
  ];
  const consentTypes = [
    {
      icon: FileSignature,
      title: __("Liability Waivers"),
      description: __(
        "Protect your business with comprehensive liability waiver forms."
      ),
      required: true
    },
    {
      icon: PenTool,
      title: __("Medical Declarations"),
      description: __(
        "Collect medical information and emergency contact details."
      ),
      required: false
    },
    {
      icon: Camera,
      title: __("Photo Releases"),
      description: __(
        "Get permission to use customer photos for marketing purposes."
      ),
      required: false
    },
    {
      icon: Shield,
      title: __("Privacy Policies"),
      description: __(
        "Ensure customers agree to your privacy and data handling policies."
      ),
      required: true
    }
  ];
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-8", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "bg-gradient-to-r from-amber-50 to-orange-50 dark:from-amber-900/20 dark:to-orange-900/20 border border-amber-200 dark:border-amber-800 rounded-xl p-6", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Sparkles, { className: "w-6 h-6 text-amber-600 dark:text-amber-400" }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-lg font-semibold text-amber-900 dark:text-amber-100", children: __("Premium Feature") }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-amber-700 dark:text-amber-300 text-sm", children: __(
            "Trip Consent is a premium module. Upgrade to Yatra Pro to manage digital consent forms."
          ) })
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Button,
        {
          className: "bg-amber-600 text-white hover:bg-amber-700 px-6 py-2 text-sm font-medium",
          onClick: () => window.open(
            "https://wpyatra.com/pricing?module=trip-consent",
            "_blank"
          ),
          children: [
            __("Upgrade to Pro"),
            /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowRight, { className: "w-4 h-4 ml-2" })
          ]
        }
      )
    ] }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-center mb-12", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "inline-flex items-center justify-center w-16 h-16 rounded-full bg-blue-100 dark:bg-blue-900 mb-6", children: /* @__PURE__ */ jsxRuntimeExports.jsx(FileSignature, { className: "w-8 h-8 text-blue-600 dark:text-blue-400" }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-center space-x-2 mb-4", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("h1", { className: "text-4xl font-bold text-gray-900 dark:text-white", children: __("Trip Consent Forms") }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "inline-flex items-center px-2 py-1 rounded-full bg-gradient-to-r from-amber-500 to-orange-500 text-white text-xs font-semibold shadow-md", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Sparkles, { className: "w-3 h-3 mr-1" }),
          __("PRO")
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xl text-gray-600 dark:text-gray-400 max-w-2xl mx-auto", children: __(
        "Create legally compliant consent forms with digital signatures and automate the collection process with Yatra Pro."
      ) })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid grid-cols-1 md:grid-cols-4 gap-6 mb-12", children: stats.map((stat, index) => {
      const Icon = stat.icon;
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        Card,
        {
          className: "border border-gray-200 dark:border-gray-700",
          children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "pt-6", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3 mb-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-10 h-10 rounded-full bg-blue-100 dark:bg-blue-900 flex items-center justify-center", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Icon, { className: "w-5 h-5 text-blue-600 dark:text-blue-400" }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-2xl font-bold text-gray-900 dark:text-white", children: stat.value }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-600 dark:text-gray-400", children: stat.label })
            ] })
          ] }) })
        },
        index
      );
    }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mb-12", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { className: "text-2xl font-bold text-gray-900 dark:text-white mb-6 text-center", children: __("Powerful Features") }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-6", children: features.map((feature, index) => {
        const Icon = feature.icon;
        return /* @__PURE__ */ jsxRuntimeExports.jsx(
          Card,
          {
            className: "border border-gray-200 dark:border-gray-700",
            children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "pt-6", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start gap-4", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-12 h-12 rounded-full bg-blue-100 dark:bg-blue-900 flex items-center justify-center flex-shrink-0", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Icon, { className: "w-6 h-6 text-blue-600 dark:text-blue-400" }) }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-lg font-semibold text-gray-900 dark:text-white mb-2", children: feature.title }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-gray-600 dark:text-gray-400 text-sm", children: feature.description })
              ] })
            ] }) })
          },
          index
        );
      }) })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mb-12", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { className: "text-2xl font-bold text-gray-900 dark:text-white mb-6 text-center", children: __("Consent Form Types") }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-6", children: consentTypes.map((consentType, index) => {
        const Icon = consentType.icon;
        return /* @__PURE__ */ jsxRuntimeExports.jsx(
          Card,
          {
            className: "border border-gray-200 dark:border-gray-700",
            children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-6", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start gap-4", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-10 h-10 rounded-full bg-blue-100 dark:bg-blue-900 flex items-center justify-center flex-shrink-0", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Icon, { className: "w-5 h-5 text-blue-600 dark:text-blue-400" }) }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("h4", { className: "font-semibold text-gray-900 dark:text-white mb-2", children: consentType.title }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-600 dark:text-gray-400 mb-3", children: consentType.description }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300", children: consentType.required ? __("Required") : __("Optional") })
              ] })
            ] }) })
          },
          index
        );
      }) })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "bg-gradient-to-r from-blue-50 to-blue-100 dark:from-blue-900/20 dark:to-blue-900/30 border border-blue-200 dark:border-blue-800 rounded-xl p-8", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col md:flex-row items-center justify-between", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mb-6 md:mb-0 md:pr-8", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3 mb-4", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-12 h-12 rounded-full bg-blue-100 dark:bg-blue-900 flex items-center justify-center", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Sparkles, { className: "w-6 h-6 text-blue-600 dark:text-blue-400" }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-2xl font-bold text-gray-900 dark:text-white", children: __("Ensure Legal Compliance") })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-gray-600 dark:text-gray-400 mb-4", children: __(
          "Protect your business and customers with professional consent forms and digital signatures powered by Yatra Pro."
        ) }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CheckCircle, { className: "w-4 h-4 text-blue-500" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm text-gray-600 dark:text-gray-400", children: __("Digital signatures") })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CheckCircle, { className: "w-4 h-4 text-blue-500" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm text-gray-600 dark:text-gray-400", children: __("Legal compliance") })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CheckCircle, { className: "w-4 h-4 text-blue-500" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm text-gray-600 dark:text-gray-400", children: __("Automated delivery") })
          ] })
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col items-center", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Button,
          {
            className: "bg-blue-600 text-white hover:bg-blue-700 px-8 py-3 text-sm font-medium mb-3",
            onClick: () => window.open(
              "https://wpyatra.com/pricing?module=trip-consent",
              "_blank"
            ),
            children: [
              __("Upgrade to Pro"),
              /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowRight, { className: "w-4 h-4 ml-2" })
            ]
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400", children: __("14-day money-back guarantee") })
      ] })
    ] }) })
  ] });
};
const isModuleAvailable = () => {
  const yatraAdmin = window == null ? void 0 : window.yatraAdmin;
  return Boolean(yatraAdmin == null ? void 0 : yatraAdmin.isPro);
};
const ConsentFormsList = () => {
  var _a;
  const queryClient2 = useQueryClient();
  const { showToast } = useToast();
  const [searchTerm, setSearchTerm] = reactExports.useState("");
  const [statusFilter, setStatusFilter] = reactExports.useState("all");
  const [sortBy2, setSortBy] = reactExports.useState("name");
  const [sortOrder, setSortOrder] = reactExports.useState("asc");
  const [page, setPage] = reactExports.useState(1);
  const [selectedIds, setSelectedIds] = reactExports.useState([]);
  const [bulkAction, setBulkAction] = reactExports.useState("");
  const [deleteConfirm, setDeleteConfirm] = reactExports.useState({
    isOpen: false,
    form: null
  });
  const [showColumnsDropdown, setShowColumnsDropdown] = reactExports.useState(false);
  const [visibleColumns, setVisibleColumns] = reactExports.useState(() => {
    const saved = localStorage.getItem("yatra-consent-forms-columns");
    return saved ? JSON.parse(saved) : {
      id: true,
      name: true,
      status: true,
      applicable_to: true,
      signatures: true,
      version: true
    };
  });
  const toggleColumn = (columnKey) => {
    const newVisibleColumns = {
      ...visibleColumns,
      [columnKey]: !visibleColumns[columnKey]
    };
    setVisibleColumns(newVisibleColumns);
    localStorage.setItem(
      "yatra-consent-forms-columns",
      JSON.stringify(newVisibleColumns)
    );
  };
  const queryParams = reactExports.useMemo(() => {
    const params = {
      page,
      per_page: 10,
      orderby: sortBy2,
      order: sortOrder
    };
    if (searchTerm) params.search = searchTerm;
    if (statusFilter !== "all") params.status = statusFilter;
    return params;
  }, [searchTerm, statusFilter, sortBy2, sortOrder, page]);
  const {
    data: formsData,
    isLoading,
    error
  } = useQuery({
    queryKey: ["consent-forms", queryParams],
    queryFn: async () => {
      const response = await apiClient.get("/consent-forms", {
        params: queryParams
      });
      return response.data || response;
    },
    enabled: isModuleAvailable()
  });
  const forms = Array.isArray(formsData) ? formsData : (formsData == null ? void 0 : formsData.data) || [];
  const total = Array.isArray(formsData) ? formsData.length : ((_a = formsData == null ? void 0 : formsData.meta) == null ? void 0 : _a.total) || 0;
  const totalPages = Math.ceil(total / 10);
  const deleteMutation = useMutation({
    mutationFn: async (id) => {
      await apiClient.delete(`/consent-forms/${id}`);
    },
    onSuccess: () => {
      queryClient2.invalidateQueries({ queryKey: ["consent-forms"] });
      showToast(__("Consent form deleted successfully"), "success");
      setDeleteConfirm({ isOpen: false, form: null });
    },
    onError: () => {
      showToast(__("Failed to delete consent form"), "error");
    }
  });
  const duplicateMutation = useMutation({
    mutationFn: async (id) => {
      await apiClient.post(`/consent-forms/${id}/duplicate`);
    },
    onSuccess: () => {
      queryClient2.invalidateQueries({ queryKey: ["consent-forms"] });
      showToast(__("Consent form duplicated successfully"), "success");
    },
    onError: () => {
      showToast(__("Failed to duplicate consent form"), "error");
    }
  });
  const bulkMutation = useMutation({
    mutationFn: async ({
      action,
      ids
    }) => {
      return await apiClient.post("/consent-forms/bulk", { action, ids });
    },
    onSuccess: () => {
      queryClient2.invalidateQueries({ queryKey: ["consent-forms"] });
      showToast(__("Action completed successfully"), "success");
      setSelectedIds([]);
      setBulkAction("");
    },
    onError: () => {
      showToast(__("Failed to perform action"), "error");
    }
  });
  const navigateToForm = (action, id) => {
    const params = new URLSearchParams(window.location.search);
    params.set("subpage", "trips");
    params.set("tab", "trip-consent");
    params.set("action", action);
    if (id) params.set("id", id.toString());
    window.history.pushState({}, "", `${window.location.pathname}?${params}`);
    window.dispatchEvent(new PopStateEvent("popstate"));
  };
  const handleEdit = (form) => navigateToForm("edit", form.id);
  const handleBulkApply = () => {
    if (!bulkAction || selectedIds.length === 0) return;
    bulkMutation.mutate({ action: bulkAction, ids: selectedIds });
  };
  const handleResetFilters = () => {
    setSearchTerm("");
    setStatusFilter("all");
    setSortBy("name");
    setSortOrder("asc");
    setPage(1);
  };
  const hasFilters = searchTerm || statusFilter !== "all" || sortBy2 !== "name" || sortOrder !== "asc";
  reactExports.useEffect(() => {
    setSelectedIds(
      (prev) => prev.filter((id) => forms.some((f) => f.id === id))
    );
  }, [forms]);
  const statusCounts = reactExports.useMemo(() => {
    const counts = {
      all: total,
      publish: 0,
      draft: 0,
      archived: 0,
      trash: 0
    };
    forms.forEach((form) => {
      if (counts[form.status] !== void 0) {
        counts[form.status]++;
      }
    });
    return counts;
  }, [forms, total]);
  const viewFilters = [
    { key: "all", label: __("All"), count: statusCounts.all },
    { key: "publish", label: __("Published"), count: statusCounts.publish },
    { key: "draft", label: __("Draft"), count: statusCounts.draft },
    { key: "archived", label: __("Archived"), count: statusCounts.archived },
    { key: "trash", label: __("Trash"), count: statusCounts.trash }
  ];
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      ConfirmationDialog,
      {
        isOpen: deleteConfirm.isOpen,
        onClose: () => setDeleteConfirm({ isOpen: false, form: null }),
        onConfirm: () => deleteConfirm.form && deleteMutation.mutate(deleteConfirm.form.id),
        title: __("Delete Consent Form"),
        message: deleteConfirm.form ? __(
          'Are you sure you want to delete "{name}"? Forms with signed consents will be archived instead.'
        ).replace("{name}", deleteConfirm.form.name) : __("Are you sure you want to delete this consent form?"),
        confirmText: __("Delete"),
        cancelText: __("Cancel"),
        variant: "danger",
        isLoading: deleteMutation.isPending
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-3", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
      SearchFilterToolbar,
      {
        searchTerm,
        onSearchChange: setSearchTerm,
        statusFilter,
        onStatusChange: (value) => {
          setStatusFilter(value);
          setPage(1);
          setSelectedIds([]);
          setBulkAction("");
        },
        statusOptions: [
          { value: "all", label: __("All Status") },
          { value: "publish", label: __("Published") },
          { value: "draft", label: __("Draft") },
          { value: "archived", label: __("Archived") },
          { value: "trash", label: __("Trash") }
        ],
        sortBy: sortBy2,
        onSortByChange: setSortBy,
        sortOrder,
        onSortOrderChange: setSortOrder,
        sortOptions: [
          { value: "name", label: __("Name") },
          { value: "status", label: __("Status") },
          { value: "created_at", label: __("Created At") },
          { value: "updated_at", label: __("Updated At") }
        ],
        onResetFilters: handleResetFilters,
        hasFilters: !!hasFilters,
        placeholder: __("Search consent forms...")
      }
    ) }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_view_trips", children: error ? /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-8 text-center text-red-500", children: __("Error loading consent forms") }) }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        BulkActionToolbar,
        {
          selectedIds,
          bulkAction,
          setBulkAction,
          onApply: handleBulkApply,
          onClearSelection: () => setSelectedIds([]),
          statusFilter,
          setStatusFilter: (value) => {
            setStatusFilter(value);
            setPage(1);
            setSelectedIds([]);
            setBulkAction("");
          },
          statusOptions: viewFilters,
          showColumnsDropdown,
          setShowColumnsDropdown,
          columnOptions: [
            { key: "id", label: __("Form ID"), visible: visibleColumns.id },
            {
              key: "name",
              label: __("Form Name"),
              visible: visibleColumns.name
            },
            {
              key: "status",
              label: __("Status"),
              visible: visibleColumns.status
            },
            {
              key: "applicable_to",
              label: __("Applies To"),
              visible: visibleColumns.applicable_to
            },
            {
              key: "signatures",
              label: __("Signatures"),
              visible: visibleColumns.signatures
            },
            {
              key: "version",
              label: __("Version"),
              visible: visibleColumns.version
            }
          ],
          onToggleColumn: toggleColumn,
          bulkMutationPending: bulkMutation.isPending,
          totalItems: forms.length,
          bulkActionOptions: getDefaultBulkStatusOptions(statusFilter)
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { className: "overflow-visible", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "p-0 overflow-visible", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          Table,
          {
            data: forms,
            columns: [
              {
                key: "id",
                label: __("Form ID"),
                sortable: true,
                visible: visibleColumns.id,
                render: (form) => /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-sm font-mono text-gray-500 dark:text-gray-400", children: [
                  "#",
                  form.id
                ] })
              },
              {
                key: "name",
                label: __("Form Name"),
                sortable: true,
                visible: visibleColumns.name,
                render: (form) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-10 h-10 rounded-lg bg-blue-100 dark:bg-blue-900/30 flex items-center justify-center flex-shrink-0", children: /* @__PURE__ */ jsxRuntimeExports.jsx(FileSignature, { className: "w-5 h-5 text-blue-600 dark:text-blue-400" }) }),
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "a",
                      {
                        href: "#",
                        onClick: (e) => {
                          e.preventDefault();
                          handleEdit(form);
                        },
                        className: "font-medium text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 hover:underline transition-colors cursor-pointer",
                        children: form.name
                      }
                    ),
                    form.description && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-500 dark:text-gray-400 truncate max-w-xs", children: form.description })
                  ] })
                ] })
              },
              {
                key: "status",
                label: __("Status"),
                sortable: true,
                visible: visibleColumns.status,
                render: (form) => {
                  const statusColors = {
                    publish: "bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400",
                    draft: "bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400",
                    archived: "bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-400",
                    trash: "bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400"
                  };
                  return /* @__PURE__ */ jsxRuntimeExports.jsx(Badge, { className: statusColors[form.status] || "", children: form.status.charAt(0).toUpperCase() + form.status.slice(1) });
                }
              },
              {
                key: "applicable_to",
                label: __("Applies To"),
                sortable: false,
                visible: visibleColumns.applicable_to,
                render: (form) => {
                  var _a2;
                  return /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300", children: form.applicable_to === "all" ? __("All Trips") : `${((_a2 = form.trip_ids) == null ? void 0 : _a2.length) || 0} ${__("Trips")}` });
                }
              },
              {
                key: "signatures",
                label: __("Signatures"),
                sortable: false,
                visible: visibleColumns.signatures,
                render: (form) => {
                  const signedCount = form.signed_count || 0;
                  const pendingCount = form.pending_count || 0;
                  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3", children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1 text-sm text-blue-600 dark:text-blue-400", children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx(CheckCircle, { className: "w-4 h-4" }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: signedCount })
                    ] }),
                    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1 text-sm text-gray-500 dark:text-gray-400", children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx(Clock, { className: "w-4 h-4" }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: pendingCount })
                    ] })
                  ] });
                }
              },
              {
                key: "version",
                label: __("Version"),
                sortable: false,
                visible: visibleColumns.version,
                render: (form) => /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-sm text-gray-600 dark:text-gray-400", children: [
                  "v",
                  form.version
                ] })
              }
            ],
            actions: [
              {
                key: "edit",
                label: __("Edit"),
                icon: /* @__PURE__ */ jsxRuntimeExports.jsx(PenSquare, { className: "w-4 h-4" }),
                onClick: handleEdit,
                condition: (form) => form.status !== "trash"
              },
              {
                key: "duplicate",
                label: __("Duplicate"),
                icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Copy, { className: "w-4 h-4" }),
                onClick: (form) => duplicateMutation.mutate(form.id),
                condition: (form) => form.status !== "trash"
              },
              {
                key: "restore",
                label: __("Restore"),
                icon: /* @__PURE__ */ jsxRuntimeExports.jsx(RotateCcw, { className: "w-4 h-4" }),
                onClick: (form) => bulkMutation.mutate({
                  action: "restore",
                  ids: [form.id]
                }),
                condition: (form) => form.status === "trash"
              },
              {
                key: "trash",
                label: __("Move to Trash"),
                icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "w-4 h-4" }),
                onClick: (form) => bulkMutation.mutate({
                  action: "trash",
                  ids: [form.id]
                }),
                condition: (form) => form.status !== "trash"
              },
              {
                key: "delete",
                label: __("Delete Permanently"),
                icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "w-4 h-4" }),
                onClick: (form) => setDeleteConfirm({ isOpen: true, form }),
                variant: "destructive",
                condition: (form) => form.status === "trash"
              }
            ],
            selectedItemIds: selectedIds,
            onSelectItem: (id, checked) => {
              if (checked) {
                setSelectedIds([...selectedIds, id]);
              } else {
                setSelectedIds(selectedIds.filter((i) => i !== id));
              }
            },
            onSelectAll: (checked) => {
              if (checked) {
                setSelectedIds(forms.map((f) => f.id));
              } else {
                setSelectedIds([]);
              }
            },
            isAllSelected: forms.length > 0 && selectedIds.length === forms.length,
            getItemId: (form) => form.id,
            isLoading
          }
        ),
        total > 10 && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "border-t border-gray-200 dark:border-gray-700 p-4", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          Pagination,
          {
            currentPage: page,
            totalPages,
            onPageChange: setPage,
            totalItems: total,
            itemsPerPage: 10,
            itemName: __("forms")
          }
        ) })
      ] }) })
    ] }) })
  ] });
};
const SignedConsentsList = () => {
  var _a;
  const [page, setPage] = reactExports.useState(1);
  const [selectedConsent, setSelectedConsent] = reactExports.useState(
    null
  );
  const [isModalOpen, setIsModalOpen] = reactExports.useState(false);
  const [isDetailLoading, setIsDetailLoading] = reactExports.useState(false);
  const [detailError, setDetailError] = reactExports.useState(null);
  const [searchTerm, setSearchTerm] = reactExports.useState("");
  const [sortBy2, setSortBy] = reactExports.useState("signed_at");
  const [sortOrder, setSortOrder] = reactExports.useState("desc");
  const [statusFilter, setStatusFilter] = reactExports.useState("all");
  const { showToast } = useToast();
  reactExports.useEffect(() => {
  }, [isModalOpen]);
  reactExports.useEffect(() => {
  }, [selectedConsent]);
  const {
    data: consentsData,
    isLoading,
    error
  } = useQuery({
    queryKey: [
      "signed-consents",
      page,
      searchTerm,
      sortBy2,
      sortOrder,
      statusFilter
    ],
    queryFn: async () => {
      const params = {
        page,
        per_page: 15,
        sort_by: sortBy2,
        sort_order: sortOrder
      };
      if (searchTerm) params.search = searchTerm;
      if (statusFilter !== "all") params.status = statusFilter;
      const response = await apiClient.get("/signed-consents", { params });
      return response;
    },
    enabled: isModuleAvailable()
  });
  const consents = (consentsData == null ? void 0 : consentsData.data) || [];
  const total = ((_a = consentsData == null ? void 0 : consentsData.meta) == null ? void 0 : _a.total) || 0;
  const totalPages = Math.ceil(total / 15);
  const formatDate2 = (dateString) => {
    return new Date(dateString).toLocaleDateString("en-US", {
      year: "numeric",
      month: "short",
      day: "numeric",
      hour: "2-digit",
      minute: "2-digit"
    });
  };
  const handleView = async (consent) => {
    setIsModalOpen(true);
    setIsDetailLoading(true);
    setDetailError(null);
    setSelectedConsent(null);
    try {
      const response = await apiClient.get(`/signed-consents/${consent.id}`);
      let consentData = response;
      if (response.data) {
        consentData = response.data;
      }
      setSelectedConsent(consentData);
    } catch (error2) {
      console.error("Error fetching consent details:", error2);
      setDetailError(__("Failed to load consent details"));
    } finally {
      setIsDetailLoading(false);
    }
  };
  const handleCloseModal = () => {
    setIsModalOpen(false);
    setDetailError(null);
    setSelectedConsent(null);
  };
  const handleDownloadPdf = async (consent) => {
    var _a2;
    try {
      const data = await apiService.downloadSignedConsentPdf(consent.id);
      if ((data == null ? void 0 : data.success) && ((_a2 = data == null ? void 0 : data.data) == null ? void 0 : _a2.download_url)) {
        window.open(data.data.download_url, "_blank");
      } else {
        showToast(
          __("Failed to prepare PDF download. Please try again.", "yatra"),
          "error"
        );
      }
    } catch (err) {
      console.error("PDF download error:", err);
      showToast((err == null ? void 0 : err.message) || __("Failed to download PDF", "yatra"), "error");
    }
  };
  const handleResetFilters = () => {
    setSearchTerm("");
    setStatusFilter("all");
    setSortBy("signed_at");
    setSortOrder("desc");
    setPage(1);
  };
  const hasFilters = searchTerm || statusFilter !== "all" || sortBy2 !== "signed_at" || sortOrder !== "desc";
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-3", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
      SearchFilterToolbar,
      {
        searchTerm,
        onSearchChange: (value) => {
          setSearchTerm(value);
          setPage(1);
        },
        statusFilter,
        onStatusChange: (value) => {
          setStatusFilter(value);
          setPage(1);
        },
        statusOptions: [
          { value: "all", label: __("All Status") },
          { value: "signed", label: __("Signed") },
          { value: "pending", label: __("Pending") }
        ],
        sortBy: sortBy2,
        onSortByChange: setSortBy,
        sortOrder,
        onSortOrderChange: setSortOrder,
        sortOptions: [
          { value: "signed_at", label: __("Signed Date") },
          { value: "signer_name", label: __("Signer Name") },
          { value: "form_name", label: __("Form Name") }
        ],
        onResetFilters: handleResetFilters,
        hasFilters: !!hasFilters,
        placeholder: __("Search by name or email...")
      }
    ) }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { className: "overflow-visible", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-0 overflow-visible", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
      Table,
      {
        data: consents,
        columns: [
          {
            key: "signer",
            label: __("Signer"),
            sortable: true,
            visible: true,
            render: (consent) => {
              var _a2, _b;
              return /* @__PURE__ */ jsxRuntimeExports.jsxs(
                "button",
                {
                  type: "button",
                  onClick: () => handleView(consent),
                  className: "flex items-center gap-3 w-full text-left group focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 rounded-lg",
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-10 h-10 rounded-full bg-blue-100 dark:bg-blue-900/30 flex items-center justify-center text-blue-600 dark:text-blue-300 font-semibold", children: ((_b = (_a2 = consent.signer_name) == null ? void 0 : _a2.charAt(0)) == null ? void 0 : _b.toUpperCase()) || "?" }),
                    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col", children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "font-medium text-gray-900 dark:text-white", children: consent.signer_name }),
                      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-sm text-gray-500 flex items-center gap-1", children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsx(Mail, { className: "w-3 h-3" }),
                        consent.signer_email
                      ] }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs text-blue-600 dark:text-blue-300 opacity-0 group-hover:opacity-100 transition-opacity", children: __("View details") })
                    ] })
                  ]
                }
              );
            }
          },
          {
            key: "form",
            label: __("Form"),
            sortable: true,
            visible: true,
            render: (consent) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-900 dark:text-white", children: consent.form_name || sprintf(
                // translators: %d: consent form ID, used as a fallback when the form has no name.
                __("Form #%d", "yatra"),
                consent.form_id
              ) }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-xs text-gray-500", children: [
                "v",
                consent.form_version
              ] })
            ] })
          },
          {
            key: "booking",
            label: __("Booking"),
            sortable: false,
            visible: true,
            render: (consent) => /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm text-gray-600 dark:text-gray-400", children: consent.booking_id > 0 ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
              "#",
              consent.booking_id,
              consent.traveler_index > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "ml-1 text-xs text-gray-400", children: sprintf(
                // translators: %d: traveler sequence number within the booking.
                __("(Traveler %d)", "yatra"),
                consent.traveler_index
              ) })
            ] }) : /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs text-gray-400 italic", children: __("Preview") }) })
          },
          {
            key: "signed_at",
            label: __("Signed At"),
            sortable: true,
            visible: true,
            render: (consent) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1 text-sm text-gray-600 dark:text-gray-400", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Calendar$1, { className: "w-3 h-3" }),
              formatDate2(consent.signed_at)
            ] })
          },
          {
            key: "status",
            label: __("Status"),
            sortable: true,
            visible: true,
            render: (consent) => /* @__PURE__ */ jsxRuntimeExports.jsx(
              Badge,
              {
                variant: consent.status === "signed" ? "success" : "default",
                children: consent.status === "signed" ? __("Signed", "yatra") : consent.status === "expired" ? __("Expired", "yatra") : consent.status === "revoked" ? __("Revoked", "yatra") : consent.status === "pending" ? __("Pending", "yatra") : consent.status
              }
            )
          }
        ],
        actions: [
          {
            key: "view",
            label: __("View Details"),
            icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Eye, { className: "w-4 h-4" }),
            onClick: handleView
          },
          {
            key: "download",
            label: __("Download PDF"),
            icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Download, { className: "w-4 h-4" }),
            onClick: handleDownloadPdf
          }
        ],
        isLoading,
        isError: !!error,
        errorText: __("Error loading signed consents"),
        emptyText: __("No signed consents yet"),
        emptyDescription: __(
          "Signed consent forms will appear here once travelers submit them."
        ),
        getItemId: (consent) => consent.id
      }
    ) }) }),
    total > 15 && /* @__PURE__ */ jsxRuntimeExports.jsx(
      Pagination,
      {
        currentPage: page,
        totalPages,
        onPageChange: setPage,
        totalItems: total,
        itemsPerPage: 15,
        itemName: __("consents")
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      Modal,
      {
        isOpen: isModalOpen,
        onClose: handleCloseModal,
        title: __("Signed Consent Details"),
        size: "xl",
        loading: isDetailLoading,
        error: detailError,
        loadingSkeleton: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-6 animate-pulse", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-2 gap-4", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-3 w-20 bg-gray-200 dark:bg-gray-700 rounded mb-2" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-5 w-32 bg-gray-300 dark:bg-gray-600 rounded" })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-3 w-16 bg-gray-200 dark:bg-gray-700 rounded mb-2" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-5 w-40 bg-gray-300 dark:bg-gray-600 rounded" })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-3 w-24 bg-gray-200 dark:bg-gray-700 rounded mb-2" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-5 w-36 bg-gray-300 dark:bg-gray-600 rounded" })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-3 w-20 bg-gray-200 dark:bg-gray-700 rounded mb-2" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-5 w-28 bg-gray-300 dark:bg-gray-600 rounded" })
            ] })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 w-32 bg-gray-200 dark:bg-gray-700 rounded mb-3" }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-gray-50 dark:bg-gray-800 rounded-lg p-4 space-y-3", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between pb-2 border-b border-gray-200 dark:border-gray-700", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 w-24 bg-gray-200 dark:bg-gray-700 rounded" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 w-32 bg-gray-300 dark:bg-gray-600 rounded" })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between pb-2 border-b border-gray-200 dark:border-gray-700", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 w-28 bg-gray-200 dark:bg-gray-700 rounded" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 w-24 bg-gray-300 dark:bg-gray-600 rounded" })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 w-20 bg-gray-200 dark:bg-gray-700 rounded" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 w-36 bg-gray-300 dark:bg-gray-600 rounded" })
              ] })
            ] })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 w-24 bg-gray-200 dark:bg-gray-700 rounded mb-3" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg p-4", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-24 w-48 bg-gray-200 dark:bg-gray-700 rounded mx-auto" }) })
          ] })
        ] }),
        footer: selectedConsent && !detailError && !isDetailLoading ? /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-end gap-3", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Button,
            {
              variant: "outline",
              onClick: () => handleDownloadPdf(selectedConsent),
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Download, { className: "w-4 h-4 mr-2" }),
                __("Download PDF")
              ]
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { onClick: handleCloseModal, children: __("Close") })
        ] }) : void 0,
        children: selectedConsent && /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-2 gap-4 mb-6", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "text-xs text-gray-500 uppercase", children: __("Signer Name") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "font-medium text-gray-900 dark:text-white", children: selectedConsent.signer_name })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "text-xs text-gray-500 uppercase", children: __("Email") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "font-medium text-gray-900 dark:text-white", children: selectedConsent.signer_email })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "text-xs text-gray-500 uppercase", children: __("Signed At") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "font-medium text-gray-900 dark:text-white", children: formatDate2(selectedConsent.signed_at) })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "text-xs text-gray-500 uppercase", children: __("IP Address") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "font-medium text-gray-900 dark:text-white", children: selectedConsent.ip_address })
            ] })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mb-6", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-sm font-semibold text-gray-700 dark:text-gray-300 mb-3 uppercase", children: __("Form Responses") }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-gray-50 dark:bg-gray-800 rounded-lg p-4 space-y-3", children: [
              selectedConsent.form_data && Object.entries(selectedConsent.form_data).map(
                ([key2, value]) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
                  "div",
                  {
                    className: "flex justify-between border-b border-gray-200 dark:border-gray-700 pb-2 last:border-0 last:pb-0",
                    children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm text-gray-600 dark:text-gray-400", children: key2 }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm font-medium text-gray-900 dark:text-white", children: typeof value === "boolean" ? value ? __("✓ Yes", "yatra") : __("✗ No", "yatra") : String(value) })
                    ]
                  },
                  key2
                )
              ),
              (!selectedConsent.form_data || Object.keys(selectedConsent.form_data).length === 0) && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-500", children: __("No form data recorded") })
            ] })
          ] }),
          selectedConsent.signature_data && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mb-6", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-sm font-semibold text-gray-700 dark:text-gray-300 mb-3 uppercase", children: __("Signature") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "bg-white border border-gray-200 dark:border-gray-700 rounded-lg p-4", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
              "img",
              {
                src: selectedConsent.signature_data,
                alt: __("Signature", "yatra"),
                className: "max-h-24 mx-auto"
              }
            ) })
          ] }),
          selectedConsent.initials_data && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mb-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-sm font-semibold text-gray-700 dark:text-gray-300 mb-3 uppercase", children: __("Initials") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "bg-white border border-gray-200 dark:border-gray-700 rounded-lg p-4", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
              "img",
              {
                src: selectedConsent.initials_data,
                alt: __("Initials", "yatra"),
                className: "max-h-16 mx-auto"
              }
            ) })
          ] })
        ] })
      }
    )
  ] });
};
const TripConsent = () => {
  const getSubtabFromUrl = reactExports.useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get("subtab") || "forms";
  }, []);
  const [activeTab, setActiveTab] = reactExports.useState(
    getSubtabFromUrl
  );
  const updateTabInUrl = (tab) => {
    const params = new URLSearchParams(window.location.search);
    params.set("subpage", "trips");
    params.set("tab", "trip-consent");
    params.set("subtab", tab);
    params.delete("action");
    params.delete("id");
    window.history.pushState({}, "", `${window.location.pathname}?${params}`);
  };
  const handleTabChange = (tab) => {
    setActiveTab(tab);
    updateTabInUrl(tab);
  };
  reactExports.useEffect(() => {
    const handleLocationChange = () => {
      const newSubtab = getSubtabFromUrl;
      if (newSubtab !== activeTab) {
        setActiveTab(newSubtab);
      }
    };
    window.addEventListener("popstate", handleLocationChange);
    const interval = setInterval(() => {
      const currentSearch = window.location.search;
      if (currentSearch !== window.__lastSearch) {
        window.__lastSearch = currentSearch;
        handleLocationChange();
      }
    }, 100);
    return () => {
      window.removeEventListener("popstate", handleLocationChange);
      clearInterval(interval);
    };
  }, [getSubtabFromUrl, activeTab]);
  if (!isModuleAvailable()) {
    return /* @__PURE__ */ jsxRuntimeExports.jsx(TripConsentPremium, {});
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-6", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      PageHeader,
      {
        title: __("Trip Consent Forms"),
        description: __(
          "Manage consent forms, waivers, and digital signatures for your trips."
        ),
        actions: activeTab === "forms" ? /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Button,
          {
            onClick: () => {
              const params = new URLSearchParams(window.location.search);
              params.set("subpage", "trips");
              params.set("tab", "trip-consent");
              params.set("action", "create");
              window.history.pushState(
                {},
                "",
                `${window.location.pathname}?${params}`
              );
              window.dispatchEvent(new PopStateEvent("popstate"));
            },
            className: "bg-blue-600 hover:bg-blue-700",
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Plus, { className: "w-4 h-4 mr-2" }),
              __("Create Form")
            ]
          }
        ) : null
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "border-b border-gray-200 dark:border-gray-700", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("nav", { className: "-mb-px flex space-x-8", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        "button",
        {
          onClick: () => handleTabChange("forms"),
          className: `py-3 px-1 border-b-2 font-medium text-sm ${activeTab === "forms" ? "border-blue-500 text-blue-600 dark:text-blue-400" : "border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 dark:text-gray-400 dark:hover:text-gray-300"}`,
          children: __("Consent Forms")
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        "button",
        {
          onClick: () => handleTabChange("signed"),
          className: `py-3 px-1 border-b-2 font-medium text-sm ${activeTab === "signed" ? "border-blue-500 text-blue-600 dark:text-blue-400" : "border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 dark:text-gray-400 dark:hover:text-gray-300"}`,
          children: __("Signed Consents")
        }
      )
    ] }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-4", children: activeTab === "forms" ? /* @__PURE__ */ jsxRuntimeExports.jsx(ConsentFormsList, {}) : /* @__PURE__ */ jsxRuntimeExports.jsx(SignedConsentsList, {}) })
  ] });
};
async function fetchEmailTemplates() {
  const raw = await apiClient.get(API_ENDPOINTS.EMAIL_TEMPLATES);
  const unwrapped = unwrapApiPayload(raw);
  return Array.isArray(unwrapped) ? unwrapped : [];
}
async function fetchEmailTemplate(id) {
  return unwrapApiPayload(
    await apiClient.get(API_ENDPOINTS.EMAIL_TEMPLATE_GET(id))
  );
}
async function fetchEmailTemplateVariables(eventKey) {
  const url = eventKey && eventKey.trim() !== "" ? `${API_ENDPOINTS.EMAIL_TEMPLATE_VARIABLES}?event_key=${encodeURIComponent(eventKey.trim())}` : API_ENDPOINTS.EMAIL_TEMPLATE_VARIABLES;
  return unwrapApiPayload(await apiClient.get(url));
}
async function createEmailTemplate(data) {
  return apiClient.post(API_ENDPOINTS.EMAIL_TEMPLATES, data);
}
async function updateEmailTemplate(id, data) {
  return apiClient.put(API_ENDPOINTS.EMAIL_TEMPLATE_GET(id), data);
}
async function setEmailTemplateActive(id, is_active) {
  return apiClient.put(API_ENDPOINTS.EMAIL_TEMPLATE_GET(id), { is_active });
}
async function deleteEmailTemplate(id) {
  return apiClient.delete(API_ENDPOINTS.EMAIL_TEMPLATE_GET(id));
}
async function duplicateEmailTemplate(id) {
  return apiClient.post(API_ENDPOINTS.EMAIL_TEMPLATE_DUPLICATE(id));
}
async function previewEmailTemplate(id) {
  const response = await apiClient.post(
    API_ENDPOINTS.EMAIL_TEMPLATE_PREVIEW(id),
    {}
  );
  return unwrapApiPayload(response);
}
async function sendEmailTemplateTest(id, email) {
  return apiClient.post(API_ENDPOINTS.EMAIL_TEMPLATE_TEST(id), { email });
}
async function fetchEmailSequences() {
  const raw = await apiClient.get(API_ENDPOINTS.EMAIL_SEQUENCES);
  const unwrapped = unwrapApiPayload(raw);
  return Array.isArray(unwrapped) ? unwrapped : [];
}
async function fetchEmailSequence(id) {
  return unwrapApiPayload(
    await apiClient.get(API_ENDPOINTS.EMAIL_SEQUENCE_GET(id))
  );
}
async function createEmailSequence(data) {
  return apiClient.post(API_ENDPOINTS.EMAIL_SEQUENCES, data);
}
async function updateEmailSequence(id, data) {
  return apiClient.put(API_ENDPOINTS.EMAIL_SEQUENCE_GET(id), data);
}
async function deleteEmailSequence(id) {
  return apiClient.delete(API_ENDPOINTS.EMAIL_SEQUENCE_GET(id));
}
async function updateEmailSequenceStatus(id, status) {
  return apiClient.put(API_ENDPOINTS.EMAIL_SEQUENCE_GET(id), { status });
}
async function fetchEmailLogs(params) {
  const raw = await apiClient.get(API_ENDPOINTS.EMAIL_LOGS, { params });
  if (raw !== null && typeof raw === "object") {
    const r2 = raw;
    if (r2.success === true && "data" in r2) {
      const meta = r2.meta || {};
      const items2 = Array.isArray(r2.data) ? r2.data : [];
      return {
        items: items2,
        total: Number(meta.total) || items2.length,
        per_page: Number(meta.per_page) || (params == null ? void 0 : params.per_page) || 20,
        current_page: Number(meta.current_page) || (params == null ? void 0 : params.page) || 1
      };
    }
  }
  const fallback = unwrapApiPayload(raw);
  const items = Array.isArray(fallback) ? fallback : [];
  return {
    items,
    total: items.length,
    per_page: (params == null ? void 0 : params.per_page) || 20,
    current_page: (params == null ? void 0 : params.page) || 1
  };
}
const Label = reactExports.forwardRef(
  ({ className = "", ...props }, ref) => {
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "label",
      {
        ref,
        className: `text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 text-gray-900 dark:text-white ${className}`,
        ...props
      }
    );
  }
);
Label.displayName = "Label";
const EmailAutomationPremium = () => {
  const features = [
    {
      icon: FileText,
      title: __("Custom Email Templates"),
      description: __(
        "Edit and customize all system email templates with your branding."
      )
    },
    {
      icon: Clock,
      title: __("Automated Sequences"),
      description: __(
        "Create drip campaigns and automated email sequences for different triggers."
      )
    },
    {
      icon: Send,
      title: __("Smart Triggers"),
      description: __(
        "Set up automatic emails based on booking status, payments, and customer actions."
      )
    },
    {
      icon: BarChart$1,
      title: __("Email Analytics"),
      description: __(
        "Track email delivery rates, open rates, and engagement metrics."
      )
    }
  ];
  const stats = [
    {
      icon: BarChart$1,
      value: "68%",
      label: __("Higher Open Rates")
    },
    {
      icon: Users,
      value: "3.5x",
      label: __("Booking Conversion")
    },
    {
      icon: Zap,
      value: "24/7",
      label: __("Automation")
    }
  ];
  const emailTypes = [
    {
      icon: Bell,
      title: __("Booking Confirmations"),
      description: __("Instant booking confirmation emails with all details."),
      trigger: __("On booking creation")
    },
    {
      icon: CreditCard,
      title: __("Payment Notifications"),
      description: __("Payment received, failed, and refund notifications."),
      trigger: __("On payment status change")
    },
    {
      icon: Calendar$1,
      title: __("Trip Reminders"),
      description: __("Pre-trip reminders and departure notifications."),
      trigger: __("Before trip date")
    },
    {
      icon: Megaphone,
      title: __("Marketing Emails"),
      description: __("Promotional campaigns and newsletter broadcasts."),
      trigger: __("Manual/automated")
    }
  ];
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-8", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "bg-gradient-to-r from-amber-50 to-orange-50 dark:from-amber-900/20 dark:to-orange-900/20 border border-amber-200 dark:border-amber-800 rounded-xl p-6", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Sparkles, { className: "w-6 h-6 text-amber-600 dark:text-amber-400" }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-lg font-semibold text-amber-900 dark:text-amber-100", children: __("Premium Feature") }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-amber-700 dark:text-amber-300 text-sm", children: __(
            "Email Automation is a premium module. Upgrade to Yatra Pro to unlock advanced email marketing."
          ) })
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Button,
        {
          className: "bg-amber-600 text-white hover:bg-amber-700 px-6 py-2 text-sm font-medium",
          onClick: () => window.open(
            "https://wpyatra.com/pricing?module=email-automation",
            "_blank"
          ),
          children: [
            __("Upgrade to Pro"),
            /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowRight, { className: "w-4 h-4 ml-2" })
          ]
        }
      )
    ] }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-center mb-12", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "inline-flex items-center justify-center w-16 h-16 rounded-full bg-blue-100 dark:bg-blue-900 mb-6", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Mail, { className: "w-8 h-8 text-blue-600 dark:text-blue-400" }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex items-center justify-center space-x-2 mb-4", children: /* @__PURE__ */ jsxRuntimeExports.jsx("h1", { className: "text-4xl font-bold text-gray-900 dark:text-white", children: __("Email Automation") }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xl text-gray-600 dark:text-gray-400 max-w-3xl mx-auto", children: __(
        "Create powerful email campaigns, automate customer communication, and track engagement with Yatra Pro."
      ) })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid grid-cols-1 md:grid-cols-3 gap-6 mb-12", children: stats.map((stat, index) => {
      const Icon = stat.icon;
      return /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { className: "text-center", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "pt-6", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-12 h-12 rounded-full bg-blue-100 dark:bg-blue-900 flex items-center justify-center mx-auto mb-4", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Icon, { className: "w-6 h-6 text-blue-600 dark:text-blue-400" }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-2xl font-bold text-gray-900 dark:text-white mb-1", children: stat.value }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-600 dark:text-gray-400", children: stat.label })
      ] }) }, index);
    }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mb-12", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { className: "text-2xl font-bold text-gray-900 dark:text-white mb-8 text-center", children: __("Powerful Email Features") }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6", children: features.map((feature, index) => {
        const Icon = feature.icon;
        return /* @__PURE__ */ jsxRuntimeExports.jsx(
          Card,
          {
            className: "border border-gray-200 dark:border-gray-700",
            children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "pt-6", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-center", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-12 h-12 rounded-full bg-blue-100 dark:bg-blue-900 flex items-center justify-center mx-auto mb-4", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Icon, { className: "w-6 h-6 text-blue-600 dark:text-blue-400" }) }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("h4", { className: "font-semibold mb-2", children: feature.title }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-600 dark:text-gray-400", children: feature.description })
            ] }) })
          },
          index
        );
      }) })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mb-12", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { className: "text-2xl font-bold text-gray-900 dark:text-white mb-8 text-center", children: __("Automated Email Types") }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-6", children: emailTypes.map((emailType, index) => {
        const Icon = emailType.icon;
        return /* @__PURE__ */ jsxRuntimeExports.jsx(
          Card,
          {
            className: "border border-gray-200 dark:border-gray-700",
            children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-6", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start gap-4", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-10 h-10 rounded-full bg-blue-100 dark:bg-blue-900 flex items-center justify-center flex-shrink-0", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Icon, { className: "w-5 h-5 text-blue-600 dark:text-blue-400" }) }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("h4", { className: "font-semibold text-gray-900 dark:text-white mb-2", children: emailType.title }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-600 dark:text-gray-400 mb-3", children: emailType.description }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300", children: emailType.trigger })
              ] })
            ] }) })
          },
          index
        );
      }) })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "bg-gradient-to-r from-blue-50 to-indigo-50 dark:from-blue-900/20 dark:to-indigo-900/20 border border-blue-200 dark:border-blue-800 rounded-xl p-8", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col md:flex-row items-center justify-between", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mb-6 md:mb-0 md:pr-8", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3 mb-4", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-12 h-12 rounded-full bg-blue-100 dark:bg-blue-900 flex items-center justify-center", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Sparkles, { className: "w-6 h-6 text-blue-600 dark:text-blue-400" }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-2xl font-bold text-gray-900 dark:text-white", children: __("Unlock Email Automation") })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-gray-600 dark:text-gray-400 mb-4", children: __(
          "Transform your customer communication with intelligent email automation and drive more bookings with Yatra Pro."
        ) }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CheckCircle, { className: "w-4 h-4 text-green-500" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm text-gray-600 dark:text-gray-400", children: __("Custom email templates") })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CheckCircle, { className: "w-4 h-4 text-green-500" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm text-gray-600 dark:text-gray-400", children: __("Automated sequences") })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CheckCircle, { className: "w-4 h-4 text-green-500" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm text-gray-600 dark:text-gray-400", children: __("Email analytics") })
          ] })
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col items-center", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Button,
          {
            className: "bg-blue-600 text-white hover:bg-blue-700 px-8 py-3 text-sm font-medium mb-3",
            onClick: () => window.open(
              "https://wpyatra.com/pricing?module=email-automation",
              "_blank"
            ),
            children: [
              __("Upgrade to Pro"),
              /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowRight, { className: "w-4 h-4 ml-2" })
            ]
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400", children: __("14-day money-back guarantee") })
      ] })
    ] }) })
  ] });
};
const EMAIL_KEYS = [
  "admin_email",
  "from_email",
  "from_name",
  "email_template_booking",
  "email_template_confirmation",
  "email_template_cancellation",
  "email_template_reminder",
  "email_template_admin_new_booking",
  "email_template_admin_payment",
  "email_template_admin_cancellation",
  "email_template_trip_consent",
  "email_template_customer_verification",
  "smtp_enabled",
  "smtp_host",
  "smtp_port",
  "smtp_username",
  "smtp_password",
  "smtp_encryption",
  "email_tpl_booking_subject",
  "email_tpl_booking_body",
  "email_tpl_payment_subject",
  "email_tpl_payment_body",
  "email_tpl_cancellation_subject",
  "email_tpl_cancellation_body",
  "email_tpl_reminder_subject",
  "email_tpl_reminder_body",
  "email_tpl_admin_booking_subject",
  "email_tpl_admin_booking_body",
  "email_tpl_admin_payment_subject",
  "email_tpl_admin_payment_body",
  "email_tpl_admin_cancellation_subject",
  "email_tpl_admin_cancellation_body",
  "email_tpl_trip_consent_subject",
  "email_tpl_trip_consent_body",
  "email_tpl_customer_verification_subject",
  "email_tpl_customer_verification_body",
  "email_template_booking_completed",
  "email_template_booking_expired_customer",
  "email_template_admin_booking_expired",
  "email_template_scheduled_payment_reminder",
  "email_template_scheduled_payment_succeeded",
  "email_template_scheduled_payment_failed",
  "email_template_admin_scheduled_payment_failed",
  "email_template_enquiry_received",
  "email_template_enquiry_admin",
  "email_template_enquiry_response",
  "email_template_review_request",
  "email_template_abandoned_booking_recovery_first",
  "email_template_abandoned_booking_recovery_second",
  "email_template_abandoned_booking_recovery_final",
  "email_tpl_booking_completed_subject",
  "email_tpl_booking_completed_body",
  "email_tpl_booking_expired_customer_subject",
  "email_tpl_booking_expired_customer_body",
  "email_tpl_admin_booking_expired_subject",
  "email_tpl_admin_booking_expired_body",
  "email_tpl_scheduled_payment_reminder_subject",
  "email_tpl_scheduled_payment_reminder_body",
  "email_tpl_scheduled_payment_succeeded_subject",
  "email_tpl_scheduled_payment_succeeded_body",
  "email_tpl_scheduled_payment_failed_subject",
  "email_tpl_scheduled_payment_failed_body",
  "email_tpl_admin_scheduled_payment_failed_subject",
  "email_tpl_admin_scheduled_payment_failed_body",
  "email_tpl_enquiry_received_subject",
  "email_tpl_enquiry_received_body",
  "email_tpl_enquiry_admin_subject",
  "email_tpl_enquiry_admin_body",
  "email_tpl_enquiry_response_subject",
  "email_tpl_enquiry_response_body",
  "email_tpl_review_request_subject",
  "email_tpl_review_request_body",
  "email_tpl_abandoned_booking_recovery_first_subject",
  "email_tpl_abandoned_booking_recovery_first_body",
  "email_tpl_abandoned_booking_recovery_second_subject",
  "email_tpl_abandoned_booking_recovery_second_body",
  "email_tpl_abandoned_booking_recovery_final_subject",
  "email_tpl_abandoned_booking_recovery_final_body"
];
const BOOL_KEYS = /* @__PURE__ */ new Set([
  "email_template_booking",
  "email_template_confirmation",
  "email_template_cancellation",
  "email_template_reminder",
  "email_template_admin_new_booking",
  "email_template_admin_payment",
  "email_template_admin_cancellation",
  "email_template_trip_consent",
  "email_template_customer_verification",
  "email_template_booking_completed",
  "email_template_booking_expired_customer",
  "email_template_admin_booking_expired",
  "email_template_scheduled_payment_reminder",
  "email_template_scheduled_payment_succeeded",
  "email_template_scheduled_payment_failed",
  "email_template_admin_scheduled_payment_failed",
  "email_template_enquiry_received",
  "email_template_enquiry_admin",
  "email_template_enquiry_response",
  "email_template_review_request",
  "email_template_abandoned_booking_recovery_first",
  "email_template_abandoned_booking_recovery_second",
  "email_template_abandoned_booking_recovery_final",
  "smtp_enabled"
]);
const EMAIL_SETTINGS_DEFAULTS = {
  admin_email: "admin@yatra.com",
  from_email: "noreply@yatra.com",
  from_name: "Yatra Travel",
  email_template_booking: true,
  email_template_confirmation: true,
  email_template_cancellation: true,
  email_template_reminder: true,
  email_template_admin_new_booking: true,
  email_template_admin_payment: true,
  email_template_admin_cancellation: true,
  email_template_trip_consent: true,
  email_template_customer_verification: true,
  email_template_booking_completed: true,
  email_template_booking_expired_customer: true,
  email_template_admin_booking_expired: true,
  email_template_scheduled_payment_reminder: true,
  email_template_scheduled_payment_succeeded: true,
  email_template_scheduled_payment_failed: true,
  email_template_admin_scheduled_payment_failed: true,
  email_template_enquiry_received: true,
  email_template_enquiry_admin: true,
  email_template_enquiry_response: true,
  email_template_review_request: true,
  email_template_abandoned_booking_recovery_first: true,
  email_template_abandoned_booking_recovery_second: true,
  email_template_abandoned_booking_recovery_final: true,
  smtp_enabled: false,
  smtp_host: "smtp.gmail.com",
  smtp_port: 587,
  smtp_username: "",
  smtp_password: "",
  smtp_encryption: "tls",
  email_tpl_booking_subject: "",
  email_tpl_booking_body: "",
  email_tpl_payment_subject: "",
  email_tpl_payment_body: "",
  email_tpl_cancellation_subject: "",
  email_tpl_cancellation_body: "",
  email_tpl_reminder_subject: "",
  email_tpl_reminder_body: "",
  email_tpl_admin_booking_subject: "",
  email_tpl_admin_booking_body: "",
  email_tpl_admin_payment_subject: "",
  email_tpl_admin_payment_body: "",
  email_tpl_admin_cancellation_subject: "",
  email_tpl_admin_cancellation_body: "",
  email_tpl_trip_consent_subject: "",
  email_tpl_trip_consent_body: "",
  email_tpl_customer_verification_subject: "",
  email_tpl_customer_verification_body: "",
  email_tpl_booking_completed_subject: "",
  email_tpl_booking_completed_body: "",
  email_tpl_booking_expired_customer_subject: "",
  email_tpl_booking_expired_customer_body: "",
  email_tpl_admin_booking_expired_subject: "",
  email_tpl_admin_booking_expired_body: "",
  email_tpl_scheduled_payment_reminder_subject: "",
  email_tpl_scheduled_payment_reminder_body: "",
  email_tpl_scheduled_payment_succeeded_subject: "",
  email_tpl_scheduled_payment_succeeded_body: "",
  email_tpl_scheduled_payment_failed_subject: "",
  email_tpl_scheduled_payment_failed_body: "",
  email_tpl_admin_scheduled_payment_failed_subject: "",
  email_tpl_admin_scheduled_payment_failed_body: "",
  email_tpl_enquiry_received_subject: "",
  email_tpl_enquiry_received_body: "",
  email_tpl_enquiry_admin_subject: "",
  email_tpl_enquiry_admin_body: "",
  email_tpl_enquiry_response_subject: "",
  email_tpl_enquiry_response_body: "",
  email_tpl_review_request_subject: "",
  email_tpl_review_request_body: "",
  email_tpl_abandoned_booking_recovery_first_subject: "",
  email_tpl_abandoned_booking_recovery_first_body: "",
  email_tpl_abandoned_booking_recovery_second_subject: "",
  email_tpl_abandoned_booking_recovery_second_body: "",
  email_tpl_abandoned_booking_recovery_final_subject: "",
  email_tpl_abandoned_booking_recovery_final_body: ""
};
function coerceEmailValues(raw) {
  const out = { ...EMAIL_SETTINGS_DEFAULTS };
  if (!raw) return out;
  for (const key2 of EMAIL_KEYS) {
    const v = raw[key2];
    if (v === void 0 || v === null) continue;
    if (key2 === "smtp_port") {
      const n = typeof v === "number" ? v : parseInt(String(v), 10);
      out.smtp_port = Number.isFinite(n) ? n : EMAIL_SETTINGS_DEFAULTS.smtp_port;
    } else if (BOOL_KEYS.has(key2)) {
      out[key2] = v === true || v === "true" || v === 1 || v === "1";
    } else {
      out[key2] = String(v);
    }
  }
  return out;
}
function sliceEqual(a2, b) {
  for (const key2 of EMAIL_KEYS) {
    if (a2[key2] !== b[key2]) return false;
  }
  return true;
}
function applyEmailSlice(base, slice) {
  const next = { ...base };
  for (const key2 of EMAIL_KEYS) {
    next[key2] = slice[key2];
  }
  return next;
}
function useEmailSettingsManager() {
  const queryClient2 = useQueryClient();
  const { showToast } = useToast();
  const { can } = usePermissions();
  const { data: settings2, isLoading } = useQuery({
    queryKey: ["settings"],
    queryFn: async () => {
      try {
        return await fetchSettings();
      } catch (error) {
        const message2 = error instanceof Error ? error.message : __("Failed to load settings", "yatra");
        showToast(message2, "error");
        throw error;
      }
    },
    // Was `manage_yatra` — that's not a registered Yatra cap, so the
    // check returned false for everyone except admins-via-fallback,
    // which silently broke the Email page on installs where the
    // admin fallback wasn't yet wired (free, or Pro pre-Team). The
    // canonical cap for the Email hub is `yatra_manage_emails`,
    // registered in the Team module's CapabilityRegistry and held
    // by Marketing role + Owner / Manager.
    enabled: can("yatra_manage_emails")
  });
  const serverSlice = reactExports.useMemo(
    () => coerceEmailValues(settings2),
    [settings2]
  );
  const [localSlice, setLocalSlice] = reactExports.useState(
    null
  );
  reactExports.useEffect(() => {
    if (settings2) {
      setLocalSlice(
        (prev) => prev === null ? coerceEmailValues(settings2) : prev
      );
    }
  }, [settings2]);
  const ready = Boolean(settings2) && !isLoading;
  const values = localSlice ?? serverSlice;
  const isDirty = localSlice ? !sliceEqual(localSlice, serverSlice) : false;
  const handleFieldChange = reactExports.useCallback(
    (e) => {
      const field = e.target.name || e.target.id;
      if (!EMAIL_KEYS.includes(field)) return;
      let value;
      if (e.target.type === "checkbox") {
        value = e.target.checked;
      } else if (e.target.type === "number") {
        const num = parseFloat(e.target.value);
        value = Number.isFinite(num) ? num : 0;
      } else {
        value = e.target.value;
      }
      setLocalSlice((prev) => {
        const base = prev ?? (settings2 ? coerceEmailValues(settings2) : { ...EMAIL_SETTINGS_DEFAULTS });
        return { ...base, [field]: value };
      });
    },
    [settings2]
  );
  const saveMutation = useMutation({
    mutationFn: async () => {
      if (!settings2 || !localSlice) {
        throw new Error(__("Settings not loaded", "yatra"));
      }
      const payload = applyEmailSlice(
        settings2,
        localSlice
      );
      await saveSettings(payload);
      return payload;
    },
    onSuccess: (saved) => {
      queryClient2.setQueryData(["settings"], saved);
      setLocalSlice(coerceEmailValues(saved));
      showToast(__("Email settings saved", "yatra"), "success");
    },
    onError: (error) => {
      const message2 = error instanceof Error ? error.message : __("Failed to save settings", "yatra");
      showToast(message2, "error");
    }
  });
  const save = reactExports.useCallback(() => {
    saveMutation.mutate();
  }, [saveMutation]);
  return {
    values,
    handleFieldChange,
    save,
    isLoading,
    ready,
    isSaving: saveMutation.isPending,
    canSave: ready && Boolean(localSlice) && isDirty && !saveMutation.isPending
  };
}
const Field = React.memo(
  ({
    id,
    label,
    description,
    required = false,
    children
  }) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs(Label, { htmlFor: id, className: "flex items-center gap-1.5", children: [
      label,
      required && /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
    ] }),
    description && /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "text-xs text-gray-500 dark:text-gray-400 flex items-start gap-1.5", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(Info, { className: "w-3.5 h-3.5 mt-0.5 flex-shrink-0" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "min-w-0 leading-relaxed", children: description })
    ] }),
    children
  ] })
);
Field.displayName = "Field";
const SectionDivider = ({ title: title2 }) => /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "border-t border-gray-200 dark:border-gray-700 pt-4 mt-6", children: /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-sm font-semibold text-gray-900 dark:text-white mb-4", children: title2 }) });
const EmailDeliverySection = ({
  values,
  onFieldChange
}) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-6", children: [
  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-sm font-semibold text-gray-900 dark:text-white mb-4", children: __("Email Configuration", "yatra") }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-4", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        Field,
        {
          id: "admin_email",
          label: __("Admin Email", "yatra"),
          description: __(
            "Email address to receive admin notifications",
            "yatra"
          ),
          required: true,
          children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            Input,
            {
              id: "admin_email",
              type: "email",
              value: values.admin_email,
              name: "admin_email",
              onChange: onFieldChange,
              placeholder: __("admin@example.com", "yatra")
            }
          )
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        Field,
        {
          id: "from_email",
          label: __("From Email", "yatra"),
          description: __(
            "Email address used as sender for customer emails",
            "yatra"
          ),
          required: true,
          children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            Input,
            {
              id: "from_email",
              type: "email",
              value: values.from_email,
              name: "from_email",
              onChange: onFieldChange,
              placeholder: __("noreply@example.com", "yatra")
            }
          )
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        Field,
        {
          id: "from_name",
          label: __("From Name", "yatra"),
          description: __(
            "Name displayed as sender in customer emails",
            "yatra"
          ),
          children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            Input,
            {
              id: "from_name",
              value: values.from_name,
              name: "from_name",
              onChange: onFieldChange,
              placeholder: __("Travel Agency Name", "yatra")
            }
          )
        }
      )
    ] })
  ] }),
  /* @__PURE__ */ jsxRuntimeExports.jsx(SectionDivider, { title: __("SMTP Settings (Optional)", "yatra") }),
  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-4", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2 p-3 bg-gray-50 dark:bg-gray-800 rounded-md", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        "input",
        {
          type: "checkbox",
          id: "smtp_enabled",
          checked: values.smtp_enabled,
          name: "smtp_enabled",
          onChange: onFieldChange,
          className: "w-4 h-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Label, { htmlFor: "smtp_enabled", className: "font-medium cursor-pointer", children: __("Enable SMTP", "yatra") }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400 mt-0.5", children: __(
          "Use custom SMTP server instead of default WordPress mail",
          "yatra"
        ) })
      ] })
    ] }),
    values.smtp_enabled && /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-4", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          Field,
          {
            id: "smtp_host",
            label: __("SMTP Host", "yatra"),
            description: __("SMTP server address", "yatra"),
            children: /* @__PURE__ */ jsxRuntimeExports.jsx(
              Input,
              {
                id: "smtp_host",
                value: values.smtp_host,
                name: "smtp_host",
                onChange: onFieldChange,
                placeholder: "smtp.gmail.com"
              }
            )
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          Field,
          {
            id: "smtp_port",
            label: __("SMTP Port", "yatra"),
            description: __("SMTP server port (usually 587 or 465)", "yatra"),
            children: /* @__PURE__ */ jsxRuntimeExports.jsx(
              Input,
              {
                id: "smtp_port",
                type: "number",
                value: values.smtp_port,
                name: "smtp_port",
                onChange: onFieldChange,
                placeholder: "587"
              }
            )
          }
        )
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        Field,
        {
          id: "smtp_encryption",
          label: __("Encryption", "yatra"),
          description: __("Connection encryption type", "yatra"),
          children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Select,
            {
              id: "smtp_encryption",
              value: values.smtp_encryption,
              name: "smtp_encryption",
              onChange: onFieldChange,
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "tls", children: __("TLS", "yatra") }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "ssl", children: __("SSL", "yatra") }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "none", children: __("None", "yatra") })
              ]
            }
          )
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        Field,
        {
          id: "smtp_username",
          label: __("SMTP Username", "yatra"),
          description: __("Your SMTP account username", "yatra"),
          children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            Input,
            {
              id: "smtp_username",
              value: values.smtp_username,
              name: "smtp_username",
              onChange: onFieldChange,
              placeholder: __("your-email@gmail.com", "yatra")
            }
          )
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        Field,
        {
          id: "smtp_password",
          label: __("SMTP Password", "yatra"),
          description: __(
            "Your SMTP account password or app password",
            "yatra"
          ),
          children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            Input,
            {
              id: "smtp_password",
              type: "password",
              value: values.smtp_password,
              name: "smtp_password",
              onChange: onFieldChange,
              placeholder: __("Enter SMTP password", "yatra")
            }
          )
        }
      )
    ] })
  ] })
] });
const BRAND_PRO_NAME = brandName() + " Pro";
const BOOKING_RICH_MERGE_TAGS = "{{payment_gateway}}, {{payment_gateway_label}}, {{payment_schedule}}, {{payment_schedule_label}}, {{travelers_list}}, {{travelers_list_html}}, {{traveler_custom_fields_html}}, {{booking_custom_fields_html}}, {{special_requests}}, {{special_requests_html}}";
const CORE_FREE_TEMPLATE_KEYS = [
  "booking_confirmation",
  "payment_received",
  "booking_cancelled",
  "trip_reminder",
  "trip_consent_request",
  "customer_email_verification",
  "booking_completed",
  "booking_expired_customer",
  "admin_booking_expired",
  "scheduled_payment_reminder",
  "scheduled_payment_succeeded",
  "scheduled_payment_failed",
  "admin_scheduled_payment_failed",
  "enquiry_received",
  "enquiry_admin",
  "enquiry_response",
  "review_request",
  "abandoned_booking_recovery_first",
  "abandoned_booking_recovery_second",
  "abandoned_booking_recovery_final",
  "admin_new_booking",
  "admin_payment_received",
  "admin_booking_cancelled"
];
function isCoreTemplateSlug(slug) {
  return !!slug && CORE_FREE_TEMPLATE_KEYS.includes(slug);
}
const EMAIL_TEMPLATES_CATALOG = [
  {
    template_key: "booking_confirmation",
    event_key: "booking.created",
    name: __("Booking Confirmation", "yatra"),
    description: __(
      "Customer email for checkout, admin bookings, and confirmed status.",
      "yatra"
    ),
    category: "booking",
    recipient_type: "customer",
    to_email: "{customer_email}",
    isCoreFree: true,
    settingsFlag: "email_template_booking",
    settingsSubject: "email_tpl_booking_subject",
    settingsBody: "email_tpl_booking_body",
    mergeTags: "{{site_name}}, {{customer_name}}, {{customer_first_name}}, {{booking_reference}}, {{booking_id}}, {{trip_name}}, {{travel_date}}, {{travelers_count}}, {{total_amount_formatted}}, {{amount_due_formatted}}, {{currency}}, {{intro_paragraph}}, {{details_html}}, {{footer_note}}, " + BOOKING_RICH_MERGE_TAGS
  },
  {
    template_key: "payment_received",
    event_key: "payment.received",
    name: __("Payment Received", "yatra"),
    description: __("Sent when a payment is recorded for a booking.", "yatra"),
    category: "payment",
    recipient_type: "customer",
    to_email: "{customer_email}",
    isCoreFree: true,
    settingsFlag: "email_template_confirmation",
    settingsSubject: "email_tpl_payment_subject",
    settingsBody: "email_tpl_payment_body",
    mergeTags: "{{site_name}}, {{customer_name}}, {{customer_first_name}}, {{booking_reference}}, {{trip_name}}, {{travel_date}}, {{payment_amount_formatted}}, {{payment_method}}, {{transaction_id}}, {{total_amount_formatted}}, {{currency}}, " + BOOKING_RICH_MERGE_TAGS
  },
  {
    template_key: "booking_cancelled",
    event_key: "booking.cancelled",
    name: __("Booking Cancellation", "yatra"),
    description: __("Sent when a booking is marked cancelled.", "yatra"),
    category: "booking",
    recipient_type: "customer",
    to_email: "{customer_email}",
    isCoreFree: true,
    settingsFlag: "email_template_cancellation",
    settingsSubject: "email_tpl_cancellation_subject",
    settingsBody: "email_tpl_cancellation_body",
    mergeTags: "{{site_name}}, {{customer_name}}, {{customer_first_name}}, {{booking_reference}}, {{trip_name}}, {{travel_date}}, {{travelers_count}}, " + BOOKING_RICH_MERGE_TAGS
  },
  {
    template_key: "trip_reminder",
    event_key: "reminder.trip",
    name: __("Trip Reminder", "yatra"),
    description: __(
      "Scheduled reminder before departure (see Booking settings).",
      "yatra"
    ),
    category: "reminder",
    recipient_type: "customer",
    to_email: "{customer_email}",
    isCoreFree: true,
    settingsFlag: "email_template_reminder",
    settingsSubject: "email_tpl_reminder_subject",
    settingsBody: "email_tpl_reminder_body",
    mergeTags: "{{site_name}}, {{customer_name}}, {{booking_reference}}, {{trip_name}}, {{travel_date}}, {{travelers_count}}, {{reminder_days}}, {{days_until_trip}}, {{amount_due_formatted}}, {{reminder_extra_html}}, " + BOOKING_RICH_MERGE_TAGS
  },
  {
    template_key: "trip_consent_request",
    event_key: "consent.requested",
    name: __("Trip consent request", "yatra"),
    description: __(
      "Sent when a traveler must sign a trip consent form (Trip Consent module).",
      "yatra"
    ),
    category: "booking",
    recipient_type: "customer",
    to_email: "{customer_email}",
    isCoreFree: true,
    requiresModule: "trip_consent",
    settingsFlag: "email_template_trip_consent",
    settingsSubject: "email_tpl_trip_consent_subject",
    settingsBody: "email_tpl_trip_consent_body",
    mergeTags: "{{site_name}}, {{recipient_name}}, {{form_name}}, {{consent_link}}, {{trip_name}}, {{travel_date}}, {{booking_reference}}, {{expiry_notice_html}}, {{consent_test_notice_html}}"
  },
  {
    template_key: "customer_email_verification",
    event_key: "account.email_verification",
    name: __("Customer email verification", "yatra"),
    description: __(
      "Sent when a customer registers (e.g. from checkout) and must verify their email before logging in.",
      "yatra"
    ),
    category: "account",
    recipient_type: "customer",
    to_email: "{customer_email}",
    isCoreFree: true,
    settingsFlag: "email_template_customer_verification",
    settingsSubject: "email_tpl_customer_verification_subject",
    settingsBody: "email_tpl_customer_verification_body",
    mergeTags: "{{site_name}}, {{site_url}}, {{customer_first_name}}, {{customer_name}}, {{verification_link}}, {{intro_paragraph}}, {{expiry_notice_html}}, {{footer_note}}"
  },
  {
    template_key: "admin_new_booking",
    event_key: "booking.created",
    name: __("Admin: New Booking", "yatra"),
    description: __(
      "Sent to your admin email when a booking is created. Turn off here to stop this email.",
      "yatra"
    ),
    category: "booking",
    recipient_type: "admin",
    to_email: "{{admin_email}}",
    isCoreFree: true,
    settingsFlag: "email_template_admin_new_booking",
    settingsSubject: "email_tpl_admin_booking_subject",
    settingsBody: "email_tpl_admin_booking_body",
    mergeTags: "{{site_name}}, {{site_url}}, {{admin_url}}, {{booking_reference}}, {{booking_id}}, {{customer_name}}, {{customer_email}}, {{customer_phone}}, {{trip_name}}, {{travel_date}}, {{travelers_count}}, {{total_amount_formatted}}, {{currency}}, {{booking_status}}, {{payment_status}}, " + BOOKING_RICH_MERGE_TAGS
  },
  {
    template_key: "admin_payment_received",
    event_key: "payment.received",
    name: __("Admin: Payment received", "yatra"),
    description: __(
      "Sent to your admin email when a payment is recorded. Customer receipt uses the Payment Received template.",
      "yatra"
    ),
    category: "payment",
    recipient_type: "admin",
    to_email: "{{admin_email}}",
    isCoreFree: true,
    settingsFlag: "email_template_admin_payment",
    settingsSubject: "email_tpl_admin_payment_subject",
    settingsBody: "email_tpl_admin_payment_body",
    mergeTags: "{{site_name}}, {{admin_url}}, {{booking_reference}}, {{booking_id}}, {{customer_name}}, {{payment_amount_formatted}}, {{payment_method}}, {{transaction_id}}, " + BOOKING_RICH_MERGE_TAGS
  },
  {
    template_key: "admin_booking_cancelled",
    event_key: "booking.cancelled",
    name: __("Admin: Booking cancelled", "yatra"),
    description: __(
      "Sent to your admin email when a booking is cancelled. Customer notice uses the Booking Cancellation template.",
      "yatra"
    ),
    category: "booking",
    recipient_type: "admin",
    to_email: "{{admin_email}}",
    isCoreFree: true,
    settingsFlag: "email_template_admin_cancellation",
    settingsSubject: "email_tpl_admin_cancellation_subject",
    settingsBody: "email_tpl_admin_cancellation_body",
    mergeTags: "{{site_name}}, {{admin_url}}, {{booking_reference}}, {{booking_id}}, {{customer_name}}, {{trip_name}}, {{travel_date}}, " + BOOKING_RICH_MERGE_TAGS
  },
  {
    template_key: "new_booking",
    event_key: "booking.created",
    name: __("New Booking Confirmation", "yatra"),
    description: __(
      "Pro automation alternative for the free Booking Confirmation template. Enable Email Automation to edit and send.",
      "yatra"
    ),
    category: "booking",
    recipient_type: "customer",
    to_email: "{customer_email}",
    isCoreFree: false,
    // Gate behind Email Automation so the free / Pro versions don't appear as
    // a confusing duplicate in the customer's view (e.g. two "Payment Received"
    // rows). isModuleGatedLocked() reads this and locks the row when the
    // module isn't active.
    requiresModule: "email_automation"
  },
  {
    template_key: "booking_payment",
    event_key: "payment.received",
    name: __("Booking payment notice", "yatra"),
    description: __(
      "Pro automation alternative for the free Payment Received template. Enable Email Automation to edit and send.",
      "yatra"
    ),
    category: "payment",
    recipient_type: "customer",
    to_email: "{customer_email}",
    isCoreFree: false,
    requiresModule: "email_automation"
  },
  {
    template_key: "booking_confirmed",
    event_key: "booking.confirmed",
    name: __("Booking Confirmed", "yatra"),
    description: __(
      "Pro automation template fired on booking confirmation. Enable Email Automation to edit and send.",
      "yatra"
    ),
    category: "booking",
    recipient_type: "customer",
    to_email: "{customer_email}",
    isCoreFree: false,
    requiresModule: "email_automation"
  },
  {
    template_key: "booking_completed",
    event_key: "booking.completed",
    name: __("Trip completed", "yatra"),
    description: __(
      "Sent when a booking is marked completed (after travel).",
      "yatra"
    ),
    category: "booking",
    recipient_type: "customer",
    to_email: "{customer_email}",
    isCoreFree: true,
    settingsFlag: "email_template_booking_completed",
    settingsSubject: "email_tpl_booking_completed_subject",
    settingsBody: "email_tpl_booking_completed_body",
    mergeTags: "{{site_name}}, {{customer_name}}, {{booking_reference}}, {{booking_id}}, {{trip_name}}, {{travel_date}}, {{trip_url}}, " + BOOKING_RICH_MERGE_TAGS
  },
  {
    template_key: "booking_expired_customer",
    event_key: "booking.expired",
    name: __("Booking expired (customer)", "yatra"),
    description: __(
      "Sent when a pending booking is auto-cancelled for non-payment.",
      "yatra"
    ),
    category: "booking",
    recipient_type: "customer",
    to_email: "{customer_email}",
    isCoreFree: true,
    settingsFlag: "email_template_booking_expired_customer",
    settingsSubject: "email_tpl_booking_expired_customer_subject",
    settingsBody: "email_tpl_booking_expired_customer_body",
    mergeTags: "{{site_name}}, {{customer_name}}, {{booking_reference}}, {{trip_name}}, {{travel_date}}, {{trip_url}}, {{expiry_policy_note}}, " + BOOKING_RICH_MERGE_TAGS
  },
  {
    template_key: "admin_booking_expired",
    event_key: "booking.expired",
    name: __("Admin: Booking expired", "yatra"),
    description: __(
      "Admin notice when a booking is auto-cancelled for non-payment.",
      "yatra"
    ),
    category: "booking",
    recipient_type: "admin",
    to_email: "{{admin_email}}",
    isCoreFree: true,
    settingsFlag: "email_template_admin_booking_expired",
    settingsSubject: "email_tpl_admin_booking_expired_subject",
    settingsBody: "email_tpl_admin_booking_expired_body",
    mergeTags: "{{site_name}}, {{admin_url}}, {{booking_reference}}, {{booking_id}}, {{customer_name}}, {{customer_email}}, {{trip_name}}, " + BOOKING_RICH_MERGE_TAGS
  },
  {
    template_key: "scheduled_payment_reminder",
    event_key: "scheduled.payment.reminder",
    name: __("Scheduled payment reminder", "yatra"),
    description: __(
      "Sent before an installment or gateway-scheduled charge when Scheduled payments is enabled in settings.",
      "yatra"
    ),
    category: "payment",
    recipient_type: "customer",
    to_email: "{customer_email}",
    isCoreFree: true,
    requiresModule: "scheduled_payments",
    settingsFlag: "email_template_scheduled_payment_reminder",
    settingsSubject: "email_tpl_scheduled_payment_reminder_subject",
    settingsBody: "email_tpl_scheduled_payment_reminder_body",
    mergeTags: "{{site_name}}, {{customer_first_name}}, {{customer_name}}, {{booking_reference}}, {{booking_id}}, {{trip_name}}, {{trip_url}}, {{scheduled_amount_formatted}}, {{scheduled_date_formatted}}, {{payment_type_label}}, {{scheduled_payment_id}}, {{currency}}, " + BOOKING_RICH_MERGE_TAGS
  },
  {
    template_key: "scheduled_payment_succeeded",
    event_key: "scheduled.payment.succeeded",
    name: __("Scheduled payment succeeded", "yatra"),
    description: __(
      "Sent after a scheduled / installment charge succeeds.",
      "yatra"
    ),
    category: "payment",
    recipient_type: "customer",
    to_email: "{customer_email}",
    isCoreFree: true,
    requiresModule: "scheduled_payments",
    settingsFlag: "email_template_scheduled_payment_succeeded",
    settingsSubject: "email_tpl_scheduled_payment_succeeded_subject",
    settingsBody: "email_tpl_scheduled_payment_succeeded_body",
    mergeTags: "{{site_name}}, {{customer_first_name}}, {{customer_name}}, {{booking_reference}}, {{booking_id}}, {{trip_name}}, {{scheduled_amount_formatted}}, {{payment_type_label}}, {{balance_after_formatted}}, {{scheduled_payment_id}}, {{currency}}, " + BOOKING_RICH_MERGE_TAGS
  },
  {
    template_key: "scheduled_payment_failed",
    event_key: "scheduled.payment.failed",
    name: __("Scheduled payment failed", "yatra"),
    description: __(
      "Sent when a scheduled charge fails (temporary or final).",
      "yatra"
    ),
    category: "payment",
    recipient_type: "customer",
    to_email: "{customer_email}",
    isCoreFree: true,
    requiresModule: "scheduled_payments",
    settingsFlag: "email_template_scheduled_payment_failed",
    settingsSubject: "email_tpl_scheduled_payment_failed_subject",
    settingsBody: "email_tpl_scheduled_payment_failed_body",
    mergeTags: "{{site_name}}, {{customer_first_name}}, {{customer_name}}, {{booking_reference}}, {{booking_id}}, {{trip_name}}, {{scheduled_amount_formatted}}, {{scheduled_payment_id}}, {{failure_reason}}, {{failure_intro_html}}, {{failure_followup_html}}, " + BOOKING_RICH_MERGE_TAGS
  },
  {
    template_key: "admin_scheduled_payment_failed",
    event_key: "scheduled.payment.failed",
    name: __("Admin: Scheduled payment failed", "yatra"),
    description: __(
      "Admin notice when a scheduled payment permanently fails.",
      "yatra"
    ),
    category: "payment",
    recipient_type: "admin",
    to_email: "{{admin_email}}",
    isCoreFree: true,
    requiresModule: "scheduled_payments",
    settingsFlag: "email_template_admin_scheduled_payment_failed",
    settingsSubject: "email_tpl_admin_scheduled_payment_failed_subject",
    settingsBody: "email_tpl_admin_scheduled_payment_failed_body",
    mergeTags: "{{site_name}}, {{admin_url}}, {{booking_reference}}, {{booking_id}}, {{trip_name}}, {{customer_name}}, {{customer_email}}, {{scheduled_amount_formatted}}, {{scheduled_payment_id}}, {{failure_reason}}, " + BOOKING_RICH_MERGE_TAGS
  },
  {
    template_key: "payment_reminder",
    event_key: "payment.reminder",
    name: __("Payment Reminder", "yatra"),
    description: __(
      "Pro automation template. Enable Email Automation to edit and send.",
      "yatra"
    ),
    category: "payment",
    recipient_type: "customer",
    to_email: "{customer_email}",
    isCoreFree: false
  },
  {
    template_key: "enquiry_received",
    event_key: "enquiry.created",
    name: __("Enquiry Received", "yatra"),
    description: __(
      "Confirmation sent to the customer after they submit an enquiry.",
      "yatra"
    ),
    category: "enquiry",
    recipient_type: "customer",
    to_email: "{customer_email}",
    isCoreFree: true,
    settingsFlag: "email_template_enquiry_received",
    settingsSubject: "email_tpl_enquiry_received_subject",
    settingsBody: "email_tpl_enquiry_received_body",
    mergeTags: "{{site_name}}, {{customer_name}}, {{customer_email}}, {{customer_phone}}, {{trip_name}}, {{trip_url}}, {{message}}"
  },
  {
    template_key: "enquiry_admin",
    event_key: "enquiry.created",
    name: __("Admin: New Enquiry", "yatra"),
    description: __(
      "Sent to your admin email when a new enquiry is submitted.",
      "yatra"
    ),
    category: "enquiry",
    recipient_type: "admin",
    to_email: "{{admin_email}}",
    isCoreFree: true,
    settingsFlag: "email_template_enquiry_admin",
    settingsSubject: "email_tpl_enquiry_admin_subject",
    settingsBody: "email_tpl_enquiry_admin_body",
    mergeTags: "{{site_name}}, {{admin_url}}, {{customer_name}}, {{customer_email}}, {{customer_phone}}, {{trip_name}}, {{message}}"
  },
  {
    template_key: "enquiry_response",
    event_key: "enquiry.responded",
    name: __("Enquiry Response", "yatra"),
    description: __(
      "Sent to the customer when you reply to their enquiry.",
      "yatra"
    ),
    category: "enquiry",
    recipient_type: "customer",
    to_email: "{customer_email}",
    isCoreFree: true,
    settingsFlag: "email_template_enquiry_response",
    settingsSubject: "email_tpl_enquiry_response_subject",
    settingsBody: "email_tpl_enquiry_response_body",
    mergeTags: "{{site_name}}, {{customer_name}}, {{customer_email}}, {{trip_name}}, {{trip_url}}, {{response}}, {{response_message}}, {{original_message}}"
  },
  {
    template_key: "review_request",
    event_key: "marketing.review_request",
    name: __("Review Request", "yatra"),
    description: __(
      "Queued when a booking is marked completed, then sent after the delay in Review settings (if reviews are enabled).",
      "yatra"
    ),
    category: "marketing",
    recipient_type: "customer",
    to_email: "{customer_email}",
    isCoreFree: true,
    settingsFlag: "email_template_review_request",
    settingsSubject: "email_tpl_review_request_subject",
    settingsBody: "email_tpl_review_request_body",
    mergeTags: "{{site_name}}, {{customer_name}}, {{trip_name}}, {{review_url}}, {{booking_reference}}, " + BOOKING_RICH_MERGE_TAGS
  },
  {
    template_key: "abandoned_booking_recovery_first",
    event_key: "booking.abandoned_recovery",
    name: __("Abandoned booking recovery (First)", "yatra"),
    description: sprintf(
      /* translators: %s: brand name (e.g. "Yatra Pro" or operator's white-labeled brand) */
      __(
        "First reminder sent by %s abandoned checkout recovery (module copy in {{recovery_intro_html}}).",
        "yatra"
      ),
      BRAND_PRO_NAME
    ),
    category: "booking",
    recipient_type: "customer",
    to_email: "{customer_email}",
    isCoreFree: true,
    requiresModule: "abandoned_booking_recovery",
    settingsFlag: "email_template_abandoned_booking_recovery_first",
    settingsSubject: "email_tpl_abandoned_booking_recovery_first_subject",
    settingsBody: "email_tpl_abandoned_booking_recovery_first_body",
    mergeTags: "{{site_name}}, {{customer_name}}, {{trip_name}}, {{recovery_link}}, {{booking_reference}}, {{recovery_reminder_label}}, {{recovery_intro_html}}, " + BOOKING_RICH_MERGE_TAGS
  },
  {
    template_key: "abandoned_booking_recovery_second",
    event_key: "booking.abandoned_recovery",
    name: __("Abandoned booking recovery (Second)", "yatra"),
    description: sprintf(
      /* translators: %s: brand name */
      __(
        "Second reminder sent by %s abandoned checkout recovery (module copy in {{recovery_intro_html}}).",
        "yatra"
      ),
      BRAND_PRO_NAME
    ),
    category: "booking",
    recipient_type: "customer",
    to_email: "{customer_email}",
    isCoreFree: true,
    requiresModule: "abandoned_booking_recovery",
    settingsFlag: "email_template_abandoned_booking_recovery_second",
    settingsSubject: "email_tpl_abandoned_booking_recovery_second_subject",
    settingsBody: "email_tpl_abandoned_booking_recovery_second_body",
    mergeTags: "{{site_name}}, {{customer_name}}, {{trip_name}}, {{recovery_link}}, {{booking_reference}}, {{recovery_reminder_label}}, {{recovery_intro_html}}, " + BOOKING_RICH_MERGE_TAGS
  },
  {
    template_key: "abandoned_booking_recovery_final",
    event_key: "booking.abandoned_recovery",
    name: __("Abandoned booking recovery (Final)", "yatra"),
    description: sprintf(
      /* translators: %s: brand name */
      __(
        "Final reminder sent by %s abandoned checkout recovery (module copy in {{recovery_intro_html}}).",
        "yatra"
      ),
      BRAND_PRO_NAME
    ),
    category: "booking",
    recipient_type: "customer",
    to_email: "{customer_email}",
    isCoreFree: true,
    requiresModule: "abandoned_booking_recovery",
    settingsFlag: "email_template_abandoned_booking_recovery_final",
    settingsSubject: "email_tpl_abandoned_booking_recovery_final_subject",
    settingsBody: "email_tpl_abandoned_booking_recovery_final_body",
    mergeTags: "{{site_name}}, {{customer_name}}, {{trip_name}}, {{recovery_link}}, {{booking_reference}}, {{recovery_reminder_label}}, {{recovery_intro_html}}, " + BOOKING_RICH_MERGE_TAGS
  }
];
function getCatalogEntryByTemplateKey(key2) {
  return EMAIL_TEMPLATES_CATALOG.find((e) => e.template_key === key2);
}
function getCoreTemplateDefinition(slug) {
  const e = getCatalogEntryByTemplateKey(slug);
  return (e == null ? void 0 : e.isCoreFree) ? e : void 0;
}
function buildLocalTemplateRows(values, options2) {
  const pro = (options2 == null ? void 0 : options2.isProPluginActive) ?? false;
  const moduleOk = (slug) => (options2 == null ? void 0 : options2.isModuleActive) ? options2.isModuleActive(slug) : false;
  return EMAIL_TEMPLATES_CATALOG.map((entry) => {
    const moduleGateOk = !entry.requiresModule || pro && moduleOk(entry.requiresModule);
    const proCatalogLocked = !entry.isCoreFree;
    const moduleContentLocked = Boolean(entry.requiresModule) && !moduleGateOk;
    const is_locked = proCatalogLocked || moduleContentLocked;
    const hasSettingsKeys = Boolean(
      entry.settingsFlag && entry.settingsSubject && entry.settingsBody
    );
    const subject = entry.settingsSubject ? String(values[entry.settingsSubject] ?? "") : "";
    const body = entry.settingsBody ? String(values[entry.settingsBody] ?? "") : "";
    const isActive = entry.settingsFlag ? Boolean(values[entry.settingsFlag]) : false;
    const id = entry.isCoreFree || hasSettingsKeys ? `core:${entry.template_key}` : `locked:${entry.template_key}`;
    return {
      id,
      template_key: entry.template_key,
      event_key: entry.event_key,
      name: entry.name,
      description: entry.description,
      subject,
      body,
      category: entry.category,
      recipient_type: entry.recipient_type,
      to_email: entry.to_email,
      is_active: hasSettingsKeys ? isActive : false,
      is_system: true,
      is_locked,
      variables: []
    };
  });
}
const EmailPreviewModal = ({
  open,
  onClose,
  subject,
  body
}) => /* @__PURE__ */ jsxRuntimeExports.jsx(
  Modal,
  {
    isOpen: open,
    onClose,
    title: /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "flex items-center gap-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        "span",
        {
          className: "flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-full bg-blue-100 dark:bg-blue-900/30",
          "aria-hidden": true,
          children: /* @__PURE__ */ jsxRuntimeExports.jsx(Eye, { className: "h-5 w-5 text-blue-600 dark:text-blue-400" })
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: __("Email Preview", "yatra") })
    ] }),
    description: __("Preview with sample data", "yatra"),
    maxWidthClassName: "max-w-6xl w-[95vw]",
    panelClassName: "yatra-model-ui flex flex-col max-h-[90vh]",
    bodyClassName: "flex flex-1 min-h-0 flex-col px-0 py-0",
    bodyScrollClassName: "flex min-h-0 flex-1 flex-col overflow-hidden",
    footer: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex w-full justify-end", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { variant: "outline", onClick: onClose, type: "button", children: __("Close", "yatra") }) }),
    children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex min-h-0 flex-1 flex-col", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-shrink-0 border-b border-gray-200 bg-white px-6 py-4 dark:border-gray-700 dark:bg-gray-900", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mb-1 flex items-center gap-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Mail, { className: "h-4 w-4 text-gray-400", "aria-hidden": true }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs font-medium uppercase tracking-wide text-gray-500 dark:text-gray-400", children: __("Subject", "yatra") })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-base font-medium text-gray-900 dark:text-white", children: subject })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "min-h-0 flex-1 bg-gray-100 px-6 py-4 dark:bg-gray-950", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex h-full min-h-[min(500px,50vh)] flex-col overflow-hidden rounded-lg border border-gray-200 bg-white shadow-sm", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        "iframe",
        {
          srcDoc: body,
          className: "min-h-[min(500px,50vh)] w-full flex-1 border-0",
          title: __("Email Preview", "yatra"),
          sandbox: "allow-same-origin"
        }
      ) }) })
    ] })
  }
);
const EMAIL_TEMPLATE_VISIBLE_COLUMNS_DEFAULT = {
  name: true,
  event: true,
  subject: true,
  body_preview: true,
  description: true,
  category: true,
  recipient_type: true,
  is_active: true
};
function plainTextEmailPreview(html, maxLen = 100) {
  if (!html) return "";
  const plain = html.replace(/<script[\s\S]*?<\/script>/gi, " ").replace(/<style[\s\S]*?<\/style>/gi, " ").replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim();
  if (plain.length <= maxLen) return plain;
  return `${plain.slice(0, maxLen)}…`;
}
function isModuleGatedLocked(template) {
  const entry = getCatalogEntryByTemplateKey(template.template_key);
  if (!(entry == null ? void 0 : entry.requiresModule)) {
    return false;
  }
  return !isProPluginActive() || !isModuleActive(entry.requiresModule);
}
const getEffectiveRecipientType = (template) => {
  const catalog = getCatalogEntryByTemplateKey(template.template_key);
  if (catalog == null ? void 0 : catalog.recipient_type) {
    return catalog.recipient_type;
  }
  const fromApi = template.recipient_type;
  if (fromApi === "admin" || fromApi === "customer") {
    return fromApi;
  }
  const toEmail = template.to_email || "";
  if (toEmail.includes("{{admin_email}}")) {
    return "admin";
  }
  if (toEmail.includes("{customer_email}") || toEmail.includes("{{customer_email}}")) {
    return "customer";
  }
  return "customer";
};
const categoryIcons = {
  booking: FileText,
  payment: CreditCard,
  enquiry: MessageSquare,
  reminder: Bell,
  marketing: Megaphone
};
const isApiTemplate = (t) => {
  if (t.is_locked) {
    return false;
  }
  if (typeof t.id === "number") {
    return true;
  }
  return typeof t.id === "string" && /^[0-9]+$/.test(String(t.id).trim());
};
function toNumericTemplateId(id) {
  if (id === void 0) {
    return null;
  }
  if (typeof id === "number" && Number.isFinite(id)) {
    return id;
  }
  if (typeof id === "string" && /^[0-9]+$/.test(id.trim())) {
    return Number(id);
  }
  return null;
}
const EmailTemplatesList = ({
  automationModuleActive,
  settingsBridge
}) => {
  const queryClient2 = useQueryClient();
  const { showToast } = useToast();
  const [searchTerm, setSearchTerm] = reactExports.useState("");
  const [categoryFilter, setCategoryFilter] = reactExports.useState("all");
  const [recipientFilter, setRecipientFilter] = reactExports.useState("all");
  const [eventFilter, setEventFilter] = reactExports.useState("all");
  const [statusFilter, setStatusFilter] = reactExports.useState("all");
  const [showColumnsDropdown, setShowColumnsDropdown] = reactExports.useState(false);
  const [selectedIds, setSelectedIds] = reactExports.useState([]);
  const [bulkAction, setBulkAction] = reactExports.useState("");
  const [currentPage, setCurrentPage] = reactExports.useState(1);
  const itemsPerPage = 20;
  const [previewOpen, setPreviewOpen] = reactExports.useState(false);
  const [previewPayload, setPreviewPayload] = reactExports.useState(null);
  const [visibleColumns, setVisibleColumns] = reactExports.useState(() => {
    const saved = localStorage.getItem("yatra-email-templates-columns");
    const parsed = saved ? JSON.parse(saved) : {};
    return { ...EMAIL_TEMPLATE_VISIBLE_COLUMNS_DEFAULT, ...parsed };
  });
  const toggleColumn = (columnKey) => {
    const newVisibleColumns = {
      ...visibleColumns,
      [columnKey]: !visibleColumns[columnKey]
    };
    setVisibleColumns(newVisibleColumns);
    localStorage.setItem(
      "yatra-email-templates-columns",
      JSON.stringify(newVisibleColumns)
    );
  };
  const { data: templatesData, isLoading: apiLoading } = useQuery({
    queryKey: ["email-templates"],
    queryFn: () => fetchEmailTemplates(),
    enabled: automationModuleActive
  });
  const apiTemplates = reactExports.useMemo(() => {
    const raw = Array.isArray(templatesData) ? templatesData : [];
    return raw.map((t) => ({
      ...t,
      is_locked: false
    }));
  }, [templatesData]);
  const localTemplates = reactExports.useMemo(() => {
    if (automationModuleActive || !settingsBridge) return [];
    return buildLocalTemplateRows(settingsBridge.values, {
      isProPluginActive: isProPluginActive(),
      isModuleActive
    });
  }, [automationModuleActive, settingsBridge]);
  const templates = automationModuleActive ? apiTemplates : localTemplates;
  const isLoading = automationModuleActive ? apiLoading : false;
  const toggleMutation = useMutation({
    mutationFn: async ({
      id,
      is_active
    }) => {
      return await setEmailTemplateActive(id, is_active);
    },
    onSuccess: () => {
      queryClient2.invalidateQueries({ queryKey: ["email-templates"] });
      showToast(__("Template updated"), "success");
    }
  });
  const deleteMutation = useMutation({
    mutationFn: async (id) => {
      return await deleteEmailTemplate(id);
    },
    onSuccess: () => {
      queryClient2.invalidateQueries({ queryKey: ["email-templates"] });
      showToast(__("Template deleted"), "success");
    },
    onError: (error) => {
      showToast((error == null ? void 0 : error.message) || __("Failed to delete template"), "error");
    }
  });
  const duplicateMutation = useMutation({
    mutationFn: async (id) => {
      return await duplicateEmailTemplate(id);
    },
    onSuccess: () => {
      queryClient2.invalidateQueries({ queryKey: ["email-templates"] });
      showToast(__("Template duplicated successfully"), "success");
    },
    onError: (error) => {
      showToast((error == null ? void 0 : error.message) || __("Failed to duplicate template"), "error");
    }
  });
  const proPreviewMutation = useMutation({
    mutationFn: (templateId) => previewEmailTemplate(templateId),
    onSuccess: (data) => {
      setPreviewPayload(data);
      setPreviewOpen(true);
    },
    onError: () => {
      showToast(__("Failed to load preview", "yatra"), "error");
    }
  });
  const corePreviewMutation = useMutation({
    mutationFn: (t) => previewCoreEmailTemplate({
      template_key: t.template_key,
      subject: t.subject || "",
      body: t.body || ""
    }),
    onSuccess: (data) => {
      setPreviewPayload(data);
      setPreviewOpen(true);
    },
    onError: () => {
      showToast(__("Failed to load preview", "yatra"), "error");
    }
  });
  const bulkDeleteMutation = useMutation({
    mutationFn: async (ids) => {
      const customTemplateIds = ids.map((id) => toNumericTemplateId(id)).filter((id) => id !== null).filter((id) => {
        const template = templates.find(
          (t) => toNumericTemplateId(t.id) === id
        );
        return template && !template.is_system && isApiTemplate(template);
      });
      if (customTemplateIds.length === 0) {
        throw new Error(
          __(
            "No custom templates selected. System templates cannot be deleted."
          )
        );
      }
      await Promise.all(customTemplateIds.map((id) => deleteEmailTemplate(id)));
      return {
        deleted: customTemplateIds.length,
        skipped: ids.length - customTemplateIds.length
      };
    },
    onSuccess: (data) => {
      queryClient2.invalidateQueries({ queryKey: ["email-templates"] });
      setSelectedIds([]);
      setBulkAction("");
      if (data.skipped > 0) {
        showToast(
          __(
            `Deleted ${data.deleted} template(s). ${data.skipped} system template(s) were skipped.`
          ),
          "success"
        );
      } else {
        showToast(__(`Deleted ${data.deleted} template(s)`), "success");
      }
    },
    onError: (error) => {
      showToast((error == null ? void 0 : error.message) || __("Failed to delete templates"), "error");
    }
  });
  const categories = reactExports.useMemo(
    () => [...new Set(templates.map((t) => t.category))],
    [templates]
  );
  const events = reactExports.useMemo(() => {
    var _a;
    if (automationModuleActive) {
      return ((_a = window.yatraAdmin) == null ? void 0 : _a.emailEvents) || [];
    }
    return [...new Set(EMAIL_TEMPLATES_CATALOG.map((e) => e.event_key))].map(
      (key2) => ({ key: key2, name: key2 })
    );
  }, [automationModuleActive]);
  const filteredTemplates = reactExports.useMemo(() => {
    return templates.filter((t) => {
      const q = searchTerm.toLowerCase();
      const bodyPlain = plainTextEmailPreview(t.body || "", 500).toLowerCase();
      const matchesSearch = !searchTerm || t.name.toLowerCase().includes(q) || (t.description || "").toLowerCase().includes(q) || (t.subject || "").toLowerCase().includes(q) || bodyPlain.includes(q);
      const matchesCategory = categoryFilter === "all" || t.category === categoryFilter;
      const matchesRecipient = recipientFilter === "all" || getEffectiveRecipientType(t) === recipientFilter;
      const matchesEvent = eventFilter === "all" || t.event_key === eventFilter;
      const matchesStatus = statusFilter === "all" || statusFilter === "active" && t.is_active || statusFilter === "inactive" && !t.is_active;
      return matchesSearch && matchesCategory && matchesRecipient && matchesEvent && matchesStatus;
    });
  }, [
    templates,
    searchTerm,
    categoryFilter,
    recipientFilter,
    eventFilter,
    statusFilter
  ]);
  const totalFilteredItems = filteredTemplates.length;
  const totalPages = Math.ceil(totalFilteredItems / itemsPerPage);
  const paginatedTemplates = reactExports.useMemo(() => {
    const startIndex = (currentPage - 1) * itemsPerPage;
    return filteredTemplates.slice(startIndex, startIndex + itemsPerPage);
  }, [filteredTemplates, currentPage, itemsPerPage]);
  reactExports.useMemo(() => {
    setCurrentPage(1);
  }, [searchTerm, categoryFilter, recipientFilter, eventFilter, statusFilter]);
  const handleLockedNavigate = reactExports.useCallback(() => {
    if (isProPluginActive()) {
      window.location.href = "admin.php?page=yatra&subpage=modules";
    } else {
      window.open(
        "https://wpyatra.com/pricing?module=email-automation",
        "_blank"
      );
    }
  }, []);
  const handleEdit = (template) => {
    if (!template.is_locked) {
      const proId = toNumericTemplateId(template.id);
      if (automationModuleActive && proId !== null) {
        window.location.href = `admin.php?page=yatra&subpage=email-automation&tab=templates&action=edit&id=${proId}`;
        return;
      }
      window.location.href = `admin.php?page=yatra&subpage=email-automation&tab=templates&action=edit&core_template=${encodeURIComponent(template.template_key)}`;
      return;
    }
    if (isModuleGatedLocked(template)) {
      window.location.href = `admin.php?page=yatra&subpage=email-automation&tab=templates&action=edit&core_template=${encodeURIComponent(template.template_key)}`;
      return;
    }
    handleLockedNavigate();
  };
  const handlePreview = (template) => {
    if (template.is_locked && !isModuleGatedLocked(template)) {
      return;
    }
    const numericId = toNumericTemplateId(template.id);
    if (automationModuleActive && numericId !== null) {
      proPreviewMutation.mutate(numericId);
    } else {
      corePreviewMutation.mutate(template);
    }
  };
  const [deleteDialog, setDeleteDialog] = reactExports.useState({ isOpen: false, template: null });
  const handleDelete = reactExports.useCallback((template) => {
    setDeleteDialog({ isOpen: true, template });
  }, []);
  const confirmDelete = reactExports.useCallback(() => {
    const t = deleteDialog.template;
    if (!t) {
      setDeleteDialog({ isOpen: false, template: null });
      return;
    }
    const id = toNumericTemplateId(t.id);
    if (id !== null) {
      deleteMutation.mutate(id);
    }
    setDeleteDialog({ isOpen: false, template: null });
  }, [deleteDialog.template, deleteMutation]);
  const cancelDelete = reactExports.useCallback(() => {
    setDeleteDialog({ isOpen: false, template: null });
  }, []);
  const handleDuplicate = (template) => {
    const id = toNumericTemplateId(template.id);
    if (id !== null) {
      duplicateMutation.mutate(id);
    }
  };
  const handleCreate = () => {
    window.location.href = "admin.php?page=yatra&subpage=email-automation&tab=template&action=create";
  };
  const handleBulkAction = () => {
    if (!bulkAction || selectedIds.length === 0) {
      showToast(__("Please select templates and an action"), "error");
      return;
    }
    if (bulkAction === "delete") {
      bulkDeleteMutation.mutate(selectedIds);
    }
  };
  const handleSelectAll = (checked) => {
    if (checked) {
      setSelectedIds(filteredTemplates.map((t) => t.id));
    } else {
      setSelectedIds([]);
    }
  };
  const handleSelectOne = (id, checked) => {
    if (checked) {
      setSelectedIds([...selectedIds, id]);
    } else {
      setSelectedIds(selectedIds.filter((i) => i !== id));
    }
  };
  const formatEventKey = (eventKey) => eventKey || "-";
  const emitSettingsCheckbox = (flagKey, checked) => {
    if (!settingsBridge) return;
    settingsBridge.onFieldChange({
      target: {
        name: flagKey,
        type: "checkbox",
        checked
      }
    });
  };
  const columns = [
    {
      key: "name",
      label: __("Template"),
      visible: visibleColumns.name,
      render: (template) => {
        const CategoryIcon = categoryIcons[template.category] || Mail;
        return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-8 h-8 rounded-lg bg-blue-100 dark:bg-blue-900/30 flex items-center justify-center flex-shrink-0", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CategoryIcon, { className: "w-4 h-4 text-blue-600 dark:text-blue-400" }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            template.is_locked ? /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "button",
              {
                type: "button",
                onClick: () => handleEdit(template),
                className: "text-left font-medium text-gray-600 dark:text-gray-300 hover:text-amber-700 dark:hover:text-amber-400",
                children: [
                  template.name,
                  /* @__PURE__ */ jsxRuntimeExports.jsx(Lock, { className: "inline-block w-3.5 h-3.5 ml-1.5 -mt-0.5 opacity-70" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "ml-2 inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-amber-100 text-amber-800 dark:bg-amber-900/40 dark:text-amber-200", children: isModuleGatedLocked(template) ? __("View only", "yatra") : __("Pro", "yatra") })
                ]
              }
            ) : /* @__PURE__ */ jsxRuntimeExports.jsx(
              "button",
              {
                type: "button",
                onClick: () => handleEdit(template),
                className: "font-medium text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 hover:underline text-left",
                children: template.name
              }
            ),
            template.is_system ? /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "ml-2 inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-400", children: __("System") }) : /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "ml-2 inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400", children: __("Custom") })
          ] })
        ] });
      }
    },
    {
      key: "event",
      label: __("Event"),
      visible: visibleColumns.event,
      render: (template) => {
        const eventInfo = events.find((e) => e.key === template.event_key);
        return /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "span",
          {
            className: "inline-flex items-center gap-1.5 px-2 py-1 rounded-full text-xs font-medium bg-indigo-100 text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-400 cursor-help",
            title: (eventInfo == null ? void 0 : eventInfo.description) || "",
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Zap, { className: "w-3 h-3" }),
              formatEventKey(template.event_key)
            ]
          }
        );
      }
    },
    {
      key: "subject",
      label: __("Subject"),
      visible: visibleColumns.subject,
      render: (template) => /* @__PURE__ */ jsxRuntimeExports.jsx(
        "span",
        {
          className: "text-sm text-gray-800 dark:text-gray-200 font-mono line-clamp-2 max-w-xs",
          title: template.subject || "",
          children: (template.subject || "").trim() || "—"
        }
      )
    },
    {
      key: "body_preview",
      label: __("Body"),
      visible: visibleColumns.body_preview,
      render: (template) => {
        const preview = plainTextEmailPreview(template.body || "");
        return /* @__PURE__ */ jsxRuntimeExports.jsx(
          "span",
          {
            className: "text-sm text-gray-600 dark:text-gray-400 line-clamp-2 max-w-md",
            title: preview,
            children: preview || "—"
          }
        );
      }
    },
    {
      key: "description",
      label: __("Description"),
      visible: visibleColumns.description,
      render: (template) => /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm text-gray-600 dark:text-gray-400 line-clamp-1", children: template.description || "-" })
    },
    {
      key: "category",
      label: __("Category"),
      visible: visibleColumns.category,
      render: (template) => {
        const CategoryIcon = categoryIcons[template.category] || Mail;
        return /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "inline-flex items-center gap-1.5 px-2 py-1 rounded-full text-xs font-medium bg-gray-100 text-gray-700 dark:bg-gray-800 dark:text-gray-300", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CategoryIcon, { className: "w-3 h-3" }),
          template.category.charAt(0).toUpperCase() + template.category.slice(1)
        ] });
      }
    },
    {
      key: "recipient_type",
      label: __("Recipient"),
      visible: visibleColumns.recipient_type,
      render: (template) => {
        const effectiveRecipient = getEffectiveRecipientType(template);
        const toEmail = template.to_email || "";
        return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col gap-1", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "span",
            {
              className: `inline-flex items-center px-2 py-1 rounded-full text-xs font-medium w-fit ${effectiveRecipient === "admin" ? "bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400" : "bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400"}`,
              children: effectiveRecipient === "admin" ? __("Admin") : __("Customer")
            }
          ),
          toEmail && /* @__PURE__ */ jsxRuntimeExports.jsx(
            "span",
            {
              className: "text-xs text-gray-500 dark:text-gray-400 truncate max-w-[150px]",
              title: toEmail,
              children: toEmail
            }
          )
        ] });
      }
    },
    {
      key: "is_active",
      label: __("Status"),
      visible: visibleColumns.is_active,
      render: (template) => /* @__PURE__ */ jsxRuntimeExports.jsx(
        Switch,
        {
          checked: template.is_active,
          disabled: template.is_locked && !isModuleGatedLocked(template) || toggleMutation.isPending,
          onCheckedChange: (checked) => {
            if (template.is_locked && !isModuleGatedLocked(template)) return;
            const proId = toNumericTemplateId(template.id);
            if (automationModuleActive && proId !== null) {
              toggleMutation.mutate({ id: proId, is_active: checked });
              return;
            }
            const entry = EMAIL_TEMPLATES_CATALOG.find(
              (e) => e.template_key === template.template_key
            );
            if (entry == null ? void 0 : entry.settingsFlag) {
              emitSettingsCheckbox(entry.settingsFlag, checked);
            }
          }
        }
      )
    }
  ];
  const actions = [
    {
      key: "preview",
      label: __("Preview", "yatra"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Eye, { className: "w-4 h-4" }),
      onClick: handlePreview,
      condition: (template) => !template.is_locked || isModuleGatedLocked(template)
    },
    {
      key: "edit",
      label: __("Edit"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(PenSquare, { className: "w-4 h-4" }),
      onClick: handleEdit
    },
    {
      key: "duplicate",
      label: __("Duplicate"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Copy, { className: "w-4 h-4" }),
      onClick: handleDuplicate,
      condition: (template) => automationModuleActive && isApiTemplate(template) && !template.is_system
    },
    {
      key: "delete",
      label: __("Delete"),
      icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "w-4 h-4" }),
      onClick: handleDelete,
      condition: (template) => automationModuleActive && isApiTemplate(template) && !template.is_system,
      variant: "destructive"
    }
  ];
  const columnOptions = [
    { key: "name", label: __("Template"), visible: visibleColumns.name },
    { key: "event", label: __("Event"), visible: visibleColumns.event },
    { key: "subject", label: __("Subject"), visible: visibleColumns.subject },
    {
      key: "body_preview",
      label: __("Body"),
      visible: visibleColumns.body_preview
    },
    {
      key: "description",
      label: __("Description"),
      visible: visibleColumns.description
    },
    {
      key: "category",
      label: __("Category"),
      visible: visibleColumns.category
    },
    {
      key: "recipient_type",
      label: __("Recipient"),
      visible: visibleColumns.recipient_type
    },
    {
      key: "is_active",
      label: __("Status"),
      visible: visibleColumns.is_active
    }
  ];
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-4", children: [
    !automationModuleActive && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-600 dark:text-gray-400", children: __(
      "Templates backed by site settings can be edited here. Rows for Yatra Pro Email Automation or optional modules stay visible with their on/off state; open a View only row to inspect content, or enable Pro or the module to edit HTML and unlock automation.",
      "yatra"
    ) }),
    automationModuleActive && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex justify-end", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
      Button,
      {
        onClick: handleCreate,
        className: "bg-blue-600 hover:bg-blue-700 text-white",
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Plus, { className: "w-4 h-4 mr-2" }),
          __("Create Template")
        ]
      }
    ) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-4", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-12 gap-4 items-center", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "lg:col-span-6", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Search, { className: "absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          Input,
          {
            value: searchTerm,
            onChange: (e) => setSearchTerm(e.target.value),
            placeholder: __("Search templates..."),
            className: "pl-10 w-full"
          }
        )
      ] }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "lg:col-span-2", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Select,
        {
          value: categoryFilter,
          onChange: (e) => setCategoryFilter(e.target.value),
          className: "w-full",
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "all", children: __("All Categories") }),
            categories.map((cat) => /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: cat, children: cat.charAt(0).toUpperCase() + cat.slice(1) }, cat))
          ]
        }
      ) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "lg:col-span-2", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Select,
        {
          value: recipientFilter,
          onChange: (e) => setRecipientFilter(e.target.value),
          className: "w-full",
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "all", children: __("All Recipients") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "customer", children: __("Customer") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "admin", children: __("Admin") })
          ]
        }
      ) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "lg:col-span-2", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Select,
        {
          value: eventFilter,
          onChange: (e) => setEventFilter(e.target.value),
          className: "w-full",
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "all", children: __("All Events") }),
            events.map((event) => /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: event.key, children: event.name }, event.key))
          ]
        }
      ) })
    ] }) }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      BulkActionToolbar,
      {
        selectedIds,
        bulkAction,
        setBulkAction,
        onApply: handleBulkAction,
        onClearSelection: () => setSelectedIds([]),
        statusFilter,
        setStatusFilter,
        statusOptions: [
          { key: "all", label: __("All"), count: templates.length },
          {
            key: "active",
            label: __("Active"),
            count: templates.filter((t) => t.is_active).length
          },
          {
            key: "inactive",
            label: __("Inactive"),
            count: templates.filter((t) => !t.is_active).length
          }
        ],
        showColumnsDropdown,
        setShowColumnsDropdown,
        columnOptions,
        onToggleColumn: toggleColumn,
        bulkMutationPending: bulkDeleteMutation.isPending,
        totalItems: filteredTemplates.length,
        bulkActionOptions: automationModuleActive ? [{ value: "delete", label: __("Delete") }] : []
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-0", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
      Table,
      {
        data: paginatedTemplates,
        columns,
        actions,
        isLoading,
        emptyText: __("No templates found"),
        emptyDescription: __(
          "Create your first email template to get started."
        ),
        onCreateClick: automationModuleActive ? handleCreate : void 0,
        getItemId: (template) => template.id,
        capability: "yatra_manage_emails",
        skeletonRows: 5,
        selectedItemIds: selectedIds,
        onSelectItem: handleSelectOne,
        onSelectAll: handleSelectAll,
        isAllSelected: selectedIds.length > 0 && selectedIds.length === paginatedTemplates.length && paginatedTemplates.length > 0
      }
    ) }) }),
    totalFilteredItems > itemsPerPage && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-4", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
      Pagination,
      {
        currentPage,
        totalPages,
        totalItems: totalFilteredItems,
        itemsPerPage,
        onPageChange: setCurrentPage,
        itemName: __("templates")
      }
    ) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      EmailPreviewModal,
      {
        open: previewOpen && Boolean(previewPayload),
        onClose: () => {
          setPreviewOpen(false);
          setPreviewPayload(null);
        },
        subject: (previewPayload == null ? void 0 : previewPayload.subject) ?? "",
        body: (previewPayload == null ? void 0 : previewPayload.body) ?? ""
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      ConfirmationDialog,
      {
        isOpen: deleteDialog.isOpen,
        onClose: cancelDelete,
        onConfirm: confirmDelete,
        title: __("Delete Template"),
        message: deleteDialog.template ? __(
          'Are you sure you want to delete "{name}"? This action cannot be undone.'
        ).replace("{name}", deleteDialog.template.name) : "",
        confirmText: __("Delete"),
        cancelText: __("Cancel"),
        variant: "danger",
        isLoading: deleteMutation.isPending
      }
    )
  ] });
};
const EmailSequencesList = () => {
  var _a;
  const queryClient2 = useQueryClient();
  const { showToast } = useToast();
  const { data: sequencesData, isLoading } = useQuery({
    queryKey: ["email-sequences"],
    queryFn: () => fetchEmailSequences(),
    enabled: isEmailAutomationModuleEnabled()
  });
  const deleteMutation = useMutation({
    mutationFn: async (id) => {
      return await deleteEmailSequence(id);
    },
    onSuccess: () => {
      queryClient2.invalidateQueries({ queryKey: ["email-sequences"] });
      showToast(__("Sequence deleted"), "success");
    }
  });
  const toggleStatusMutation = useMutation({
    mutationFn: async ({ id, status }) => {
      return await updateEmailSequenceStatus(id, status);
    },
    onSuccess: () => {
      queryClient2.invalidateQueries({ queryKey: ["email-sequences"] });
      showToast(__("Sequence status updated"), "success");
    }
  });
  const sequences = Array.isArray(sequencesData) ? sequencesData : [];
  const navigateToCreate = () => {
    window.location.href = "admin.php?page=yatra&subpage=email-automation&tab=sequence&action=create";
  };
  const navigateToEdit = (id) => {
    window.location.href = `admin.php?page=yatra&subpage=email-automation&tab=sequence&action=edit&id=${id}`;
  };
  if (isLoading) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-6 animate-pulse", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-6 w-36 bg-gray-200 dark:bg-gray-700 rounded mb-2" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 w-64 bg-gray-200 dark:bg-gray-700 rounded" })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 w-36 bg-gray-200 dark:bg-gray-700 rounded" })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-4", children: [1, 2, 3].map((i) => /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-4", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3 mb-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-5 w-48 bg-gray-200 dark:bg-gray-700 rounded" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-5 w-16 bg-gray-200 dark:bg-gray-700 rounded" })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 w-72 bg-gray-200 dark:bg-gray-700 rounded mb-2" }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-4", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-3 w-32 bg-gray-200 dark:bg-gray-700 rounded" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-3 w-20 bg-gray-200 dark:bg-gray-700 rounded" })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-8 w-8 bg-gray-200 dark:bg-gray-700 rounded" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-8 w-16 bg-gray-200 dark:bg-gray-700 rounded" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-8 w-8 bg-gray-200 dark:bg-gray-700 rounded" })
        ] })
      ] }) }) }, i)) })
    ] });
  }
  const getStatusBadge = (status) => {
    switch (status) {
      case "active":
        return /* @__PURE__ */ jsxRuntimeExports.jsx(Badge, { className: "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400", children: __("Active") });
      case "paused":
        return /* @__PURE__ */ jsxRuntimeExports.jsx(Badge, { className: "bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400", children: __("Paused") });
      default:
        return /* @__PURE__ */ jsxRuntimeExports.jsx(Badge, { className: "bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-400", children: __("Draft") });
    }
  };
  const emailEvents = ((_a = window.yatraAdmin) == null ? void 0 : _a.emailEvents) || [];
  const getTriggerLabel = (triggerType) => {
    const ev = emailEvents.find((e) => e.key === triggerType);
    return (ev == null ? void 0 : ev.name) || triggerType;
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-6", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { className: "text-lg font-semibold text-gray-900 dark:text-white", children: __("Email Sequences") }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-500 dark:text-gray-400", children: __("Create automated email workflows triggered by events") })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Button,
        {
          onClick: navigateToCreate,
          className: "bg-blue-600 hover:bg-blue-700 text-white",
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Plus, { className: "w-4 h-4 mr-2" }),
            __("Create Sequence")
          ]
        }
      )
    ] }),
    sequences.length === 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "p-8 text-center", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(GitBranch, { className: "w-12 h-12 text-gray-300 dark:text-gray-600 mx-auto mb-4" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-lg font-medium text-gray-900 dark:text-white mb-2", children: __("No Sequences Yet") }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-gray-500 dark:text-gray-400 mb-4", children: __(
        "Create your first automated email sequence to engage customers at the right time."
      ) }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Button,
        {
          onClick: navigateToCreate,
          className: "bg-blue-600 hover:bg-blue-700 text-white",
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Plus, { className: "w-4 h-4 mr-2" }),
            __("Create Your First Sequence")
          ]
        }
      )
    ] }) }) : /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-4", children: sequences.map((sequence) => /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-4", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "font-medium text-gray-900 dark:text-white", children: sequence.name }),
          getStatusBadge(sequence.status)
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-500 dark:text-gray-400 mt-1", children: sequence.description || __("No description") }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-4 mt-2 text-xs text-gray-500 dark:text-gray-400", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "flex items-center gap-1", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Zap, { className: "w-3 h-3" }),
            getTriggerLabel(sequence.trigger_type)
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "flex items-center gap-1", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(GitBranch, { className: "w-3 h-3" }),
            sequence.steps_count || 0,
            " ",
            __("steps")
          ] })
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
        sequence.status === "active" ? /* @__PURE__ */ jsxRuntimeExports.jsx(
          Button,
          {
            variant: "ghost",
            size: "sm",
            onClick: () => toggleStatusMutation.mutate({
              id: sequence.id,
              status: "paused"
            }),
            children: /* @__PURE__ */ jsxRuntimeExports.jsx(Pause, { className: "w-4 h-4 text-yellow-500" })
          }
        ) : /* @__PURE__ */ jsxRuntimeExports.jsx(
          Button,
          {
            variant: "ghost",
            size: "sm",
            onClick: () => toggleStatusMutation.mutate({
              id: sequence.id,
              status: "active"
            }),
            children: /* @__PURE__ */ jsxRuntimeExports.jsx(Play, { className: "w-4 h-4 text-green-500" })
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Button,
          {
            variant: "outline",
            size: "sm",
            onClick: () => navigateToEdit(sequence.id),
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(PenSquare, { className: "w-4 h-4 mr-1" }),
              __("Edit")
            ]
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          Button,
          {
            variant: "ghost",
            size: "sm",
            onClick: () => {
              if (confirm(
                __(
                  "Are you sure you want to delete this sequence?"
                )
              )) {
                deleteMutation.mutate(sequence.id);
              }
            },
            children: /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "w-4 h-4 text-red-500" })
          }
        )
      ] })
    ] }) }) }, sequence.id)) })
  ] });
};
const EmailLogsList = () => {
  const [page, setPage] = reactExports.useState(1);
  const perPage = 20;
  const [viewingLog, setViewingLog] = reactExports.useState(null);
  const { data: logsData, isLoading } = useQuery({
    queryKey: ["email-logs", page, perPage],
    queryFn: () => fetchEmailLogs({ page, per_page: perPage }),
    enabled: isEmailAutomationModuleEnabled()
  });
  const logs = (logsData == null ? void 0 : logsData.items) ?? [];
  const totalItems = (logsData == null ? void 0 : logsData.total) ?? 0;
  const totalPages = Math.max(1, Math.ceil(totalItems / perPage));
  if (isLoading) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-6 w-28 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-0", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "overflow-x-auto", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("table", { className: "w-full", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("thead", { className: "bg-gray-50 dark:bg-gray-800", children: /* @__PURE__ */ jsxRuntimeExports.jsx("tr", { children: [1, 2, 3, 4, 5].map((i) => /* @__PURE__ */ jsxRuntimeExports.jsx("th", { className: "px-4 py-3", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 w-20 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" }) }, i)) }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("tbody", { className: "divide-y divide-gray-200 dark:divide-gray-700", children: [1, 2, 3, 4, 5].map((row) => /* @__PURE__ */ jsxRuntimeExports.jsx("tr", { children: [1, 2, 3, 4, 5].map((col) => /* @__PURE__ */ jsxRuntimeExports.jsx("td", { className: "px-4 py-3", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 w-24 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" }) }, col)) }, row)) })
      ] }) }) })
    ] });
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardTitle, { className: "flex items-center gap-2", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(Clock, { className: "w-5 h-5 text-blue-500" }),
      __("Email Logs")
    ] }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "p-0", children: [
      logs.length === 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-8 text-center text-gray-500 dark:text-gray-400", children: __("No emails sent yet") }) : /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "overflow-x-auto", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("table", { className: "w-full", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("thead", { className: "bg-gray-50 dark:bg-gray-800", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("tr", { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("th", { className: "px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase", children: __("Recipient") }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("th", { className: "px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase", children: __("Subject") }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("th", { className: "px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase", children: __("Template") }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("th", { className: "px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase", children: __("Status") }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("th", { className: "px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase", children: __("Sent") }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("th", { className: "px-4 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase", children: __("Actions") })
        ] }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("tbody", { className: "divide-y divide-gray-200 dark:divide-gray-700", children: logs.map((log2) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "tr",
          {
            className: "hover:bg-gray-50 dark:hover:bg-gray-800/50",
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("td", { className: "px-4 py-3", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm font-medium text-gray-900 dark:text-white", children: log2.recipient_name || "-" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-500 dark:text-gray-400", children: log2.recipient_email })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("td", { className: "px-4 py-3 text-sm text-gray-900 dark:text-white max-w-xs truncate", children: log2.subject }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("td", { className: "px-4 py-3 text-sm text-gray-500 dark:text-gray-400", children: log2.template_key }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("td", { className: "px-4 py-3", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                Badge,
                {
                  className: log2.status === "sent" ? "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400" : log2.status === "failed" ? "bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400" : "bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400",
                  children: log2.status
                }
              ) }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("td", { className: "px-4 py-3 text-sm text-gray-500 dark:text-gray-400", children: log2.sent_at ? new Date(log2.sent_at).toLocaleString() : "—" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("td", { className: "px-4 py-3 text-right", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                "button",
                {
                  type: "button",
                  onClick: () => setViewingLog(log2),
                  className: "text-xs font-medium text-blue-600 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300 hover:underline",
                  children: __("View details", "yatra")
                }
              ) })
            ]
          },
          log2.id
        )) })
      ] }) }),
      logs.length > 0 && totalPages > 1 && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "border-t border-gray-200 px-4 py-3 dark:border-gray-700", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        Pagination,
        {
          currentPage: page,
          totalPages,
          totalItems,
          itemsPerPage: perPage,
          onPageChange: setPage,
          itemName: __("entries", "yatra")
        }
      ) })
    ] }),
    viewingLog && /* @__PURE__ */ jsxRuntimeExports.jsx(
      EmailLogDetailsModal,
      {
        log: viewingLog,
        onClose: () => setViewingLog(null)
      }
    )
  ] });
};
const EmailLogDetailsModal = ({ log: log2, onClose }) => {
  const [bodyView, setBodyView] = reactExports.useState("preview");
  const [copied, setCopied] = reactExports.useState(false);
  const copyRawToClipboard = async () => {
    if (!log2.body) return;
    try {
      await navigator.clipboard.writeText(log2.body);
      setCopied(true);
      window.setTimeout(() => setCopied(false), 1500);
    } catch {
    }
  };
  const metadata = reactExports.useMemo(() => {
    if (!log2.metadata) return null;
    if (typeof log2.metadata === "object")
      return log2.metadata;
    try {
      const parsed = JSON.parse(String(log2.metadata));
      return typeof parsed === "object" && parsed !== null ? parsed : null;
    } catch {
      return null;
    }
  }, [log2.metadata]);
  const statusClass = log2.status === "sent" ? "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400" : log2.status === "failed" ? "bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400" : "bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400";
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    Modal,
    {
      isOpen: true,
      onClose,
      title: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Mail, { className: "w-5 h-5 text-blue-500" }),
        __("Email details", "yatra")
      ] }),
      size: "full",
      footer: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex justify-end", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { variant: "outline", onClick: onClose, children: __("Close", "yatra") }) }),
      children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-4", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "rounded-md border border-gray-200 dark:border-gray-700 p-3 space-y-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Badge, { className: statusClass, children: log2.status }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs text-gray-500 dark:text-gray-400", children: log2.sent_at ? new Date(log2.sent_at).toLocaleString() : "—" })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("dl", { className: "grid grid-cols-1 sm:grid-cols-2 gap-x-4 gap-y-2 text-sm", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs(DetailRow, { label: __("Recipient", "yatra"), children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "font-medium text-gray-900 dark:text-white", children: log2.recipient_name || "—" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-gray-500 dark:text-gray-400 break-all", children: log2.recipient_email })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(DetailRow, { label: __("Subject", "yatra"), children: /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-900 dark:text-white break-words", children: log2.subject || "—" }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(DetailRow, { label: __("Template", "yatra"), children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("code", { className: "text-xs bg-gray-100 dark:bg-gray-800 px-1.5 py-0.5 rounded", children: log2.template_key || "—" }),
              log2.template_id ? /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-xs text-gray-500 ml-1", children: [
                "(id ",
                log2.template_id,
                ")"
              ] }) : null
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(DetailRow, { label: __("Sequence", "yatra"), children: log2.sequence_id ? /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-gray-900 dark:text-white", children: [
              "#",
              log2.sequence_id
            ] }) : /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs text-gray-400", children: __("Transactional (no sequence)", "yatra") }) }),
            (log2.context_type || log2.context_id) && /* @__PURE__ */ jsxRuntimeExports.jsx(DetailRow, { label: __("Context", "yatra"), children: /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-gray-900 dark:text-white", children: [
              log2.context_type || "—",
              log2.context_id ? ` #${log2.context_id}` : ""
            ] }) })
          ] })
        ] }),
        log2.status === "failed" && log2.error_message && /* @__PURE__ */ jsxRuntimeExports.jsx(Alert, { variant: "error", title: __("Send failed", "yatra"), children: /* @__PURE__ */ jsxRuntimeExports.jsx("pre", { className: "text-xs whitespace-pre-wrap break-words font-mono", children: log2.error_message }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-wrap items-center justify-between gap-2 mb-1.5", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Label, { className: "text-sm font-medium", children: __("Message body", "yatra") }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs(
                "div",
                {
                  role: "tablist",
                  "aria-label": __("Body view", "yatra"),
                  className: "inline-flex rounded-md border border-gray-200 dark:border-gray-700 overflow-hidden text-xs",
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "button",
                      {
                        type: "button",
                        role: "tab",
                        "aria-selected": bodyView === "preview",
                        onClick: () => setBodyView("preview"),
                        className: `px-3 py-1 font-medium transition-colors ${bodyView === "preview" ? "bg-blue-600 text-white" : "bg-white dark:bg-gray-800 text-gray-600 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700"}`,
                        children: __("Preview", "yatra")
                      }
                    ),
                    /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "button",
                      {
                        type: "button",
                        role: "tab",
                        "aria-selected": bodyView === "raw",
                        onClick: () => setBodyView("raw"),
                        className: `px-3 py-1 font-medium border-l border-gray-200 dark:border-gray-700 transition-colors ${bodyView === "raw" ? "bg-blue-600 text-white" : "bg-white dark:bg-gray-800 text-gray-600 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700"}`,
                        children: __("Raw HTML", "yatra")
                      }
                    )
                  ]
                }
              ),
              bodyView === "raw" && log2.body && /* @__PURE__ */ jsxRuntimeExports.jsx(
                "button",
                {
                  type: "button",
                  onClick: copyRawToClipboard,
                  className: "text-xs font-medium text-blue-600 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300 hover:underline",
                  children: copied ? __("Copied!", "yatra") : __("Copy", "yatra")
                }
              ),
              bodyView === "preview" && /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs text-gray-400 hidden sm:inline", children: __("Sandboxed — links not clickable", "yatra") })
            ] })
          ] }),
          log2.body && log2.body.trim() !== "" ? bodyView === "preview" ? /* @__PURE__ */ jsxRuntimeExports.jsx(
            "iframe",
            {
              title: __("Email body preview", "yatra"),
              srcDoc: log2.body,
              sandbox: "",
              className: "w-full h-[480px] rounded-md border border-gray-200 dark:border-gray-700 bg-white"
            }
          ) : /* @__PURE__ */ jsxRuntimeExports.jsx("pre", { className: "w-full h-[480px] text-xs bg-gray-50 dark:bg-gray-900/40 border border-gray-200 dark:border-gray-700 rounded-md p-3 overflow-auto whitespace-pre-wrap break-all font-mono text-gray-800 dark:text-gray-200", children: log2.body }) : /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-400 italic rounded-md border border-dashed border-gray-200 dark:border-gray-700 p-4 text-center", children: __("(Body not recorded for this log entry.)", "yatra") })
        ] }),
        metadata && Object.keys(metadata).length > 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Label, { className: "text-sm font-medium block mb-1.5", children: __("Metadata", "yatra") }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("pre", { className: "text-xs bg-gray-50 dark:bg-gray-900/40 border border-gray-200 dark:border-gray-700 rounded-md p-3 overflow-x-auto max-h-48 overflow-y-auto font-mono", children: JSON.stringify(metadata, null, 2) })
        ] })
      ] })
    }
  );
};
const DetailRow = ({
  label,
  children
}) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
  /* @__PURE__ */ jsxRuntimeExports.jsx("dt", { className: "text-[11px] uppercase tracking-wide text-gray-500 dark:text-gray-400 font-medium", children: label }),
  /* @__PURE__ */ jsxRuntimeExports.jsx("dd", { className: "mt-0.5", children })
] });
function getInitialEmailHubTab() {
  if (typeof window === "undefined") return "delivery";
  const tab = new URLSearchParams(window.location.search).get("tab");
  if (tab === "sequences" || tab === "sequence") return "sequences";
  if (tab === "template" || tab === "templates") return "templates";
  if (tab === "logs") return "logs";
  if (tab === "delivery" || tab === "core") return "delivery";
  return "delivery";
}
const EmailAutomationModulePrompt = () => /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "rounded-xl border border-amber-200 bg-amber-50 p-6 dark:border-amber-800 dark:bg-amber-950/30", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between", children: [
  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-3", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(Settings2, { className: "mt-0.5 h-6 w-6 shrink-0 text-amber-600 dark:text-amber-400" }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-base font-semibold text-amber-900 dark:text-amber-100", children: __("Enable the Email Automation module", "yatra") }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm text-amber-800/90 dark:text-amber-200/90", children: __(
        "Yatra Pro is active. Turn on Email Automation under Modules to use custom templates, sequences, and send logs.",
        "yatra"
      ) })
    ] })
  ] }),
  /* @__PURE__ */ jsxRuntimeExports.jsx(
    Button,
    {
      type: "button",
      variant: "outline",
      className: "shrink-0 border-amber-300 bg-white hover:bg-amber-100 dark:border-amber-700 dark:bg-amber-950 dark:hover:bg-amber-900",
      onClick: () => {
        window.location.href = "admin.php?page=yatra&subpage=modules";
      },
      children: __("Open Modules", "yatra")
    }
  )
] }) });
const EmailAutomation = () => {
  const emailMgr = useEmailSettingsManager();
  const [activeTab, setActiveTab] = reactExports.useState(() => {
    const t = getInitialEmailHubTab();
    if (!isProPluginActive() && (t === "sequences" || t === "logs")) {
      return "delivery";
    }
    return t;
  });
  React.useEffect(() => {
    if (typeof window === "undefined") return;
    const url = new URL(window.location.href);
    if (url.searchParams.get("tab") === activeTab) return;
    url.searchParams.set("tab", activeTab);
    window.history.replaceState({}, "", url.toString());
  }, [activeTab]);
  const switchTab = (next) => setActiveTab(next);
  const showProAutomationExtras = isProPluginActive();
  const automationReady = isEmailAutomationModuleEnabled();
  const tabs = [
    {
      key: "delivery",
      label: __("Delivery", "yatra"),
      icon: Send
    },
    {
      key: "templates",
      label: __("Templates", "yatra"),
      icon: FileText
    },
    ...showProAutomationExtras ? [
      {
        key: "sequences",
        label: __("Sequences", "yatra"),
        icon: GitBranch
      },
      {
        key: "logs",
        label: __("Email logs", "yatra"),
        icon: Mail
      }
    ] : []
  ];
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-6", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      PageHeader,
      {
        description: __(
          "Delivery (addresses & SMTP), core templates for everyone, and optional Pro sequences and logs.",
          "yatra"
        )
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "border-b border-gray-200 dark:border-gray-700", children: /* @__PURE__ */ jsxRuntimeExports.jsx("nav", { className: "flex flex-wrap gap-1 px-4", children: tabs.map((tab) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "button",
        {
          type: "button",
          onClick: () => switchTab(tab.key),
          className: `flex items-center gap-2 px-4 py-3 border-b-2 font-medium text-sm transition-colors ${activeTab === tab.key ? "border-blue-500 text-blue-600 dark:text-blue-400" : "border-transparent text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 hover:border-gray-300 dark:hover:border-gray-600"}`,
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(tab.icon, { className: "w-4 h-4" }),
            tab.label
          ]
        },
        tab.key
      )) }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "p-6", children: [
        activeTab === "delivery" && /* @__PURE__ */ jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: !emailMgr.ready ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex justify-center py-16", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Loader2, { className: "h-10 w-10 animate-spin text-gray-400" }) }) : /* @__PURE__ */ jsxRuntimeExports.jsx(
          EmailDeliverySection,
          {
            values: emailMgr.values,
            onFieldChange: emailMgr.handleFieldChange
          }
        ) }),
        activeTab === "templates" && /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
          automationReady && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mb-6 text-sm text-gray-600 dark:text-gray-400", children: __(
            "Customer booking, payment, cancellation, and trip-reminder emails use the matching template when its body is filled; otherwise the free plugin defaults or settings HTML apply. Admin: New Booking sends when that template has a body (plain-text admin notices from checkout and notifications are skipped to avoid duplicates). Other booking.created templates send in addition to the customer email. Booking Confirmed uses the “Booking Confirmed” row when a booking moves to confirmed; Trip Completed uses its template instead of the generic completed email when the body is filled.",
            "yatra"
          ) }),
          !emailMgr.ready && !automationReady ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex justify-center py-16", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Loader2, { className: "h-10 w-10 animate-spin text-gray-400" }) }) : /* @__PURE__ */ jsxRuntimeExports.jsx(
            EmailTemplatesList,
            {
              automationModuleActive: automationReady,
              settingsBridge: automationReady ? void 0 : {
                values: emailMgr.values,
                onFieldChange: emailMgr.handleFieldChange
              }
            }
          )
        ] }),
        activeTab === "sequences" && (automationReady ? /* @__PURE__ */ jsxRuntimeExports.jsx(EmailSequencesList, {}) : isProPluginActive() ? /* @__PURE__ */ jsxRuntimeExports.jsx(EmailAutomationModulePrompt, {}) : /* @__PURE__ */ jsxRuntimeExports.jsx(EmailAutomationPremium, {})),
        activeTab === "logs" && (automationReady ? /* @__PURE__ */ jsxRuntimeExports.jsx(EmailLogsList, {}) : isProPluginActive() ? /* @__PURE__ */ jsxRuntimeExports.jsx(EmailAutomationModulePrompt, {}) : /* @__PURE__ */ jsxRuntimeExports.jsx(EmailAutomationPremium, {}))
      ] }),
      (activeTab === "delivery" || activeTab === "templates") && emailMgr.ready && /* @__PURE__ */ jsxRuntimeExports.jsx(CardFooter, { className: "flex justify-end border-t border-gray-100 pt-4 dark:border-gray-700/50", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        Button,
        {
          type: "button",
          onClick: emailMgr.save,
          disabled: !emailMgr.canSave,
          className: "flex items-center gap-2",
          children: emailMgr.isSaving ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Loader2, { className: "h-4 w-4 animate-spin" }),
            __("Saving…", "yatra")
          ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Save, { className: "h-4 w-4" }),
            __("Save email settings", "yatra")
          ] })
        }
      ) })
    ] })
  ] });
};
const TONE_PRESETS = [
  { id: "warm-professional", label: "Warm + professional" },
  { id: "friendly-casual", label: "Friendly + casual" },
  { id: "concise-formal", label: "Concise + formal" },
  { id: "excited-promotional", label: "Excited + promotional" }
];
const AiEmailTemplateModal = ({
  open,
  onClose,
  templateKey,
  templateName,
  templateDescription,
  recipientType = "customer",
  mergeTags,
  currentSubject,
  currentBody,
  onAccept
}) => {
  const [tone, setTone] = reactExports.useState(TONE_PRESETS[0].id);
  const [extraContext, setExtraContext] = reactExports.useState("");
  const [isGenerating, setIsGenerating] = reactExports.useState(false);
  const [error, setError] = reactExports.useState(null);
  const [draft, setDraft] = reactExports.useState(
    null
  );
  React.useEffect(() => {
    if (open) {
      setError(null);
      setDraft(null);
      setIsGenerating(false);
    }
  }, [open]);
  if (!open) return null;
  if (!isAiReady()) {
    return /* @__PURE__ */ jsxRuntimeExports.jsx(Modal, { isOpen: open, onClose, size: "md", hideHeader: true, hideFooter: true, children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "p-6", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "font-semibold text-gray-900 dark:text-white", children: __("AI Assistant not configured", "yatra") }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm text-gray-600 dark:text-gray-300", children: __(
        "Add an OpenAI or Anthropic key under Yatra → AI Assistant first.",
        "yatra"
      ) }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-3 flex gap-2", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { asChild: true, children: /* @__PURE__ */ jsxRuntimeExports.jsx("a", { href: "admin.php?page=yatra&subpage=ai-assistant", children: __("Open AI settings", "yatra") }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { variant: "outline", onClick: onClose, children: __("Cancel", "yatra") })
      ] })
    ] }) });
  }
  const generate = async () => {
    var _a, _b;
    setIsGenerating(true);
    setError(null);
    try {
      const result = await aiApi.generateEmailTemplate({
        template_key: templateKey,
        template_name: templateName,
        template_description: templateDescription,
        recipient_type: recipientType,
        merge_tags: mergeTags,
        current_subject: currentSubject,
        current_body: currentBody,
        tone: ((_a = TONE_PRESETS.find((t) => t.id === tone)) == null ? void 0 : _a.label) ?? tone,
        extra_context: extraContext
      });
      setDraft({ subject: result.subject, body: result.body });
    } catch (e) {
      const data = ((_b = e == null ? void 0 : e.response) == null ? void 0 : _b.data) ?? (e == null ? void 0 : e.data) ?? null;
      const msg = data && typeof data === "object" && typeof data.message === "string" ? data.message : (e == null ? void 0 : e.message) || __("AI generation failed.", "yatra");
      setError(msg);
    } finally {
      setIsGenerating(false);
    }
  };
  const accept = () => {
    if (!draft) return;
    onAccept({ subject: draft.subject, body: draft.body });
    onClose();
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsx(Modal, { isOpen: open, onClose, size: "xl", hideHeader: true, hideFooter: true, children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex max-h-[90vh] min-h-[420px] min-w-[640px] max-w-[860px] flex-col", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between border-b border-gray-200 px-6 py-4 dark:border-gray-700", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "rounded-md bg-gradient-to-br from-blue-600 to-blue-700 p-1.5 text-white", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Sparkles, { className: "h-4 w-4" }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { className: "text-base font-semibold text-gray-900 dark:text-white", children: __("Generate email with AI", "yatra") }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-xs text-gray-500 dark:text-gray-400", children: templateName || templateKey })
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        "button",
        {
          type: "button",
          onClick: onClose,
          className: "rounded text-gray-400 hover:text-gray-600",
          "aria-label": __("Close", "yatra"),
          children: /* @__PURE__ */ jsxRuntimeExports.jsx(X, { className: "h-5 w-5" })
        }
      )
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1 overflow-y-auto px-6 py-4 space-y-4", children: [
      !draft && /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-600 dark:text-gray-300", children: templateDescription || __(
          "AI will write a fresh subject and body using only the merge tags this template supports.",
          "yatra"
        ) }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "mb-1 block text-xs font-medium text-gray-700 dark:text-gray-200", children: __("Tone", "yatra") }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid grid-cols-2 gap-2 sm:grid-cols-4", children: TONE_PRESETS.map((t) => /* @__PURE__ */ jsxRuntimeExports.jsx(
            "button",
            {
              type: "button",
              onClick: () => setTone(t.id),
              className: `rounded-md border px-2.5 py-1.5 text-xs ${tone === t.id ? "border-blue-500 bg-blue-50 text-blue-700 dark:border-blue-400 dark:bg-blue-900/30 dark:text-blue-200" : "border-gray-200 bg-white text-gray-700 hover:bg-gray-50 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-200"}`,
              children: t.label
            },
            t.id
          )) })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("label", { className: "mb-1 block text-xs font-medium text-gray-700 dark:text-gray-200", children: [
            __("Anything else AI should know", "yatra"),
            " ",
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-[10px] font-normal text-gray-400", children: __("(optional)", "yatra") })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "textarea",
            {
              rows: 3,
              className: "w-full rounded-md border border-gray-300 bg-white p-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-400 dark:border-gray-600 dark:bg-gray-800",
              placeholder: __(
                "e.g. Mention our 24/7 support hotline. Keep total length under 120 words. Emphasize peace of mind.",
                "yatra"
              ),
              value: extraContext,
              onChange: (e) => setExtraContext(e.target.value)
            }
          )
        ] }),
        mergeTags.length > 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "rounded-md border border-gray-200 bg-gray-50 p-3 dark:border-gray-700 dark:bg-gray-800/40", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mb-1 text-[11px] font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400", children: __("Available merge tags", "yatra") }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-wrap gap-1.5", children: [
            mergeTags.slice(0, 24).map((t) => /* @__PURE__ */ jsxRuntimeExports.jsx(
              "code",
              {
                className: "rounded bg-white px-1.5 py-0.5 text-[10px] text-gray-700 dark:bg-gray-900 dark:text-gray-200",
                children: `{{${t}}}`
              },
              t
            )),
            mergeTags.length > 24 && /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-[10px] text-gray-500", children: [
              "+",
              mergeTags.length - 24,
              " ",
              __("more", "yatra")
            ] })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1.5 text-[11px] text-gray-500 dark:text-gray-400", children: __(
            "AI will only use tags from this list; it won't invent new ones.",
            "yatra"
          ) })
        ] })
      ] }),
      error && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "rounded-md border border-red-200 bg-red-50 p-3 text-sm text-red-700 dark:border-red-500/40 dark:bg-red-900/20 dark:text-red-300", children: error }),
      draft && /* @__PURE__ */ jsxRuntimeExports.jsx(DraftEditor, { draft, onChange: (d) => setDraft(d) })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-end gap-2 border-t border-gray-200 px-6 py-3 dark:border-gray-700", children: [
      !draft && /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          Button,
          {
            variant: "outline",
            onClick: onClose,
            disabled: isGenerating,
            children: __("Cancel", "yatra")
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { onClick: generate, disabled: isGenerating, children: isGenerating ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Loader2, { className: "mr-2 h-4 w-4 animate-spin" }),
          __("Generating…", "yatra")
        ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Sparkles, { className: "mr-2 h-4 w-4" }),
          __("Generate", "yatra")
        ] }) })
      ] }),
      draft && /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { variant: "outline", onClick: () => setDraft(null), children: __("Discard, try again", "yatra") }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Button, { onClick: accept, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Check, { className: "mr-2 h-4 w-4" }),
          __("Use this", "yatra")
        ] })
      ] })
    ] })
  ] }) });
};
const DraftEditor = ({ draft, onChange }) => {
  const [tab, setTab] = reactExports.useState("preview");
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "mb-1 block text-xs font-medium text-gray-700 dark:text-gray-200", children: __("Subject", "yatra") }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        "input",
        {
          type: "text",
          className: "w-full rounded-md border border-gray-300 bg-white p-2 font-mono text-sm dark:border-gray-600 dark:bg-gray-800",
          value: draft.subject,
          onChange: (e) => onChange({ ...draft, subject: e.target.value })
        }
      )
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mb-1 flex items-center justify-between", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "block text-xs font-medium text-gray-700 dark:text-gray-200", children: __("Body", "yatra") }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "div",
          {
            role: "tablist",
            className: "inline-flex overflow-hidden rounded-md border border-gray-200 dark:border-gray-700",
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "button",
                {
                  type: "button",
                  role: "tab",
                  "aria-selected": tab === "preview",
                  onClick: () => setTab("preview"),
                  className: `px-2.5 py-1 text-[11px] font-medium ${tab === "preview" ? "bg-blue-600 text-white" : "bg-white text-gray-700 hover:bg-gray-50 dark:bg-gray-800 dark:text-gray-200"}`,
                  children: __("Preview", "yatra")
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "button",
                {
                  type: "button",
                  role: "tab",
                  "aria-selected": tab === "html",
                  onClick: () => setTab("html"),
                  className: `px-2.5 py-1 text-[11px] font-medium ${tab === "html" ? "bg-blue-600 text-white" : "bg-white text-gray-700 hover:bg-gray-50 dark:bg-gray-800 dark:text-gray-200"}`,
                  children: __("HTML", "yatra")
                }
              )
            ]
          }
        )
      ] }),
      tab === "preview" ? /* @__PURE__ */ jsxRuntimeExports.jsx(EmailPreview, { html: draft.body }) : /* @__PURE__ */ jsxRuntimeExports.jsx(
        "textarea",
        {
          rows: 14,
          className: "w-full rounded-md border border-gray-300 bg-white p-2 font-mono text-xs dark:border-gray-600 dark:bg-gray-800",
          value: draft.body,
          onChange: (e) => onChange({ ...draft, body: e.target.value })
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-[11px] text-gray-500 dark:text-gray-400", children: __(
        "Preview shows the rendered email; HTML tab lets you edit. Merge tags like {{customer_name}} stay as-is — they're replaced when the email actually sends.",
        "yatra"
      ) })
    ] })
  ] });
};
const EmailPreview = ({ html }) => {
  const doc = `<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
</head>
<body style="margin:0;padding:24px 16px;background:#f3f4f6;font-family:Arial,Helvetica,sans-serif;">
  <div style="max-width:600px;margin:0 auto;background:#ffffff;border:1px solid #e5e7eb;border-radius:10px;padding:28px 24px;">
    ${html}
  </div>
</body>
</html>`;
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    "iframe",
    {
      title: "Email preview",
      sandbox: "allow-same-origin",
      srcDoc: doc,
      className: "w-full rounded-md border border-gray-200 bg-white dark:border-gray-700",
      style: { height: "420px" }
    }
  );
};
const EmailTemplateForm = () => {
  var _a, _b, _c, _d;
  const { id, isCreateMode, coreTemplateSlug, coreReadOnlyParam } = reactExports.useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    const templateId = params.get("id");
    const action = params.get("action");
    const core = params.get("core_template") || "";
    return {
      id: templateId,
      isCreateMode: action === "create",
      coreTemplateSlug: core,
      coreReadOnlyParam: params.get("readonly") === "1"
    };
  }, []);
  const isCoreSettingsEdit = isCoreTemplateSlug(coreTemplateSlug);
  const coreDef = isCoreSettingsEdit ? getCoreTemplateDefinition(coreTemplateSlug) : void 0;
  const catalogEntryForCore = reactExports.useMemo(
    () => coreTemplateSlug ? getCatalogEntryByTemplateKey(coreTemplateSlug) : void 0,
    [coreTemplateSlug]
  );
  const isCoreStrictViewOnly = isCoreSettingsEdit && Boolean(coreReadOnlyParam);
  const isCoreModuleBodyLocked = reactExports.useMemo(() => {
    if (!isCoreSettingsEdit || isCoreStrictViewOnly) {
      return false;
    }
    const req = catalogEntryForCore == null ? void 0 : catalogEntryForCore.requiresModule;
    if (!req) {
      return false;
    }
    return !isProPluginActive() || !isModuleActive(req);
  }, [isCoreSettingsEdit, isCoreStrictViewOnly, catalogEntryForCore]);
  const isCoreBodyReadOnly = isCoreStrictViewOnly || isCoreModuleBodyLocked;
  const isCoreViewMode = isCoreStrictViewOnly || isCoreModuleBodyLocked;
  const goBack = () => {
    window.location.href = `admin.php?page=yatra&subpage=email-automation&tab=templates`;
  };
  const queryClient2 = useQueryClient();
  const { showToast } = useToast();
  const [formData, setFormData] = reactExports.useState({
    name: "",
    description: "",
    from_name: "",
    from_email: "",
    to_email: "",
    reply_to: "",
    subject: "",
    body: "",
    event_key: "",
    is_active: true
  });
  const [showPreview, setShowPreview] = reactExports.useState(false);
  const [previewData, setPreviewData] = reactExports.useState(null);
  const [testEmail, setTestEmail] = reactExports.useState("");
  const [copiedVar, setCopiedVar] = reactExports.useState(null);
  const [showEventDropdown, setShowEventDropdown] = reactExports.useState(false);
  const [showAiModal, setShowAiModal] = reactExports.useState(false);
  reactExports.useEffect(() => {
    if (isCreateMode && !isEmailAutomationModuleEnabled()) {
      window.location.href = "admin.php?page=yatra&subpage=email-automation&tab=templates";
    }
  }, [isCreateMode]);
  reactExports.useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    if (params.get("action") !== "edit") return;
    const ct = params.get("core_template");
    if (ct && !isCoreTemplateSlug(ct)) {
      window.location.href = "admin.php?page=yatra&subpage=email-automation&tab=templates";
    }
  }, []);
  const { data: settings2, isLoading: settingsLoading } = useQuery({
    queryKey: ["settings"],
    queryFn: () => fetchSettings(),
    enabled: isCoreSettingsEdit
  });
  const { data: templateData, isLoading } = useQuery({
    queryKey: ["email-template", id],
    queryFn: () => fetchEmailTemplate(id),
    enabled: Boolean(id) && !isCoreSettingsEdit
  });
  const { data: variablesData } = useQuery({
    queryKey: ["email-variables", formData.event_key || ""],
    queryFn: () => fetchEmailTemplateVariables(formData.event_key || ""),
    enabled: !isCoreSettingsEdit && isEmailAutomationModuleEnabled()
  });
  const events = ((_a = window.yatraAdmin) == null ? void 0 : _a.emailEvents) || [];
  reactExports.useEffect(() => {
    if (!templateData || typeof templateData !== "object") return;
    const t = templateData;
    setFormData({
      name: String(t.name ?? ""),
      description: String(t.description ?? ""),
      from_name: String(t.from_name ?? ""),
      from_email: String(t.from_email ?? ""),
      to_email: String(t.to_email ?? ""),
      reply_to: String(t.reply_to ?? ""),
      subject: String(t.subject ?? ""),
      body: String(t.body ?? ""),
      event_key: String(t.event_key ?? ""),
      is_active: Boolean(t.is_active ?? true)
    });
  }, [templateData]);
  reactExports.useEffect(() => {
    if (!isCoreSettingsEdit || !settings2 || !coreDef) return;
    const flag2 = coreDef.settingsFlag;
    const subj = coreDef.settingsSubject;
    const bodyKey = coreDef.settingsBody;
    if (!flag2 || !subj || !bodyKey) return;
    const s2 = settings2;
    setFormData({
      name: coreDef.name,
      description: coreDef.description,
      from_name: "",
      from_email: "",
      to_email: coreDef.to_email || "",
      reply_to: "",
      subject: String(s2[subj] ?? ""),
      body: String(s2[bodyKey] ?? ""),
      event_key: coreDef.event_key,
      is_active: Boolean(s2[flag2])
    });
  }, [isCoreSettingsEdit, settings2, coreDef]);
  const saveMutation = useMutation({
    mutationFn: async (data) => {
      if (isCreateMode) {
        const response = await createEmailTemplate(data);
        const r2 = response;
        if (r2 && r2.success === false) {
          throw new Error(r2.message || __("Failed to create template"));
        }
        return response;
      }
      return await updateEmailTemplate(id, data);
    },
    onSuccess: (response) => {
      var _a2;
      queryClient2.invalidateQueries({ queryKey: ["email-templates"] });
      if (isCreateMode) {
        showToast(__("Template created successfully"), "success");
        const newId = (_a2 = response == null ? void 0 : response.data) == null ? void 0 : _a2.id;
        if (newId) {
          window.location.href = `admin.php?page=yatra&subpage=email-automation&tab=template&action=edit&id=${newId}`;
        } else {
          window.location.href = "admin.php?page=yatra&subpage=email-automation&tab=templates";
        }
      } else {
        queryClient2.invalidateQueries({ queryKey: ["email-template", id] });
        showToast(__("Template saved successfully"), "success");
      }
    },
    onError: (error) => {
      const message2 = (error == null ? void 0 : error.message) || (isCreateMode ? __("Failed to create template") : __("Failed to save template"));
      showToast(message2, "error");
    }
  });
  const saveCoreMutation = useMutation({
    mutationFn: async () => {
      if (isCoreStrictViewOnly) {
        throw new Error(__("This template is view-only.", "yatra"));
      }
      if (!(coreDef == null ? void 0 : coreDef.settingsFlag) || !coreDef.settingsSubject || !coreDef.settingsBody) {
        throw new Error(__("Invalid template", "yatra"));
      }
      if (!settings2) {
        throw new Error(__("Settings not loaded", "yatra"));
      }
      const base = { ...settings2 };
      if (isCoreModuleBodyLocked) {
        base[coreDef.settingsFlag] = formData.is_active;
        await saveSettings(base);
        return base;
      }
      base[coreDef.settingsSubject] = formData.subject;
      base[coreDef.settingsBody] = formData.body;
      base[coreDef.settingsFlag] = formData.is_active;
      await saveSettings(base);
      return base;
    },
    onSuccess: (saved) => {
      queryClient2.setQueryData(["settings"], saved);
      showToast(__("Template saved", "yatra"), "success");
    },
    onError: (error) => {
      const message2 = error instanceof Error ? error.message : __("Failed to save", "yatra");
      showToast(message2, "error");
    }
  });
  const previewMutation = useMutation({
    mutationFn: async () => {
      return previewEmailTemplate(id);
    },
    onSuccess: (data) => {
      setPreviewData(data);
      setShowPreview(true);
    },
    onError: () => {
      showToast(__("Failed to load preview"), "error");
    }
  });
  const corePreviewMutation = useMutation({
    mutationFn: async () => {
      if (!coreTemplateSlug) {
        throw new Error(__("Invalid template", "yatra"));
      }
      return previewCoreEmailTemplate({
        template_key: coreTemplateSlug,
        subject: formData.subject,
        body: formData.body
      });
    },
    onSuccess: (data) => {
      setPreviewData(data);
      setShowPreview(true);
    },
    onError: (error) => {
      const message2 = error instanceof Error ? error.message : __("Preview failed", "yatra");
      showToast(message2, "error");
    }
  });
  const testMutation = useMutation({
    mutationFn: async (email) => {
      return sendEmailTemplateTest(id, email);
    },
    onSuccess: () => {
      showToast(__("Test email sent successfully"), "success");
      setTestEmail("");
    },
    onError: () => {
      showToast(__("Failed to send test email"), "error");
    }
  });
  const handleSubmit = (e) => {
    if (e) e.preventDefault();
    if (isCoreSettingsEdit) {
      if (isCoreStrictViewOnly) {
        return;
      }
      saveCoreMutation.mutate();
      return;
    }
    if (!formData.name.trim()) {
      showToast(__("Template name is required"), "error");
      return;
    }
    if (!formData.subject.trim()) {
      showToast(__("Subject line is required"), "error");
      return;
    }
    saveMutation.mutate(formData);
  };
  const copyVariable = (variable) => {
    navigator.clipboard.writeText(`{{${variable}}}`);
    setCopiedVar(variable);
    setTimeout(() => setCopiedVar(null), 2e3);
  };
  const insertVariable = (variable) => {
    if (isCoreBodyReadOnly) {
      return;
    }
    const textarea = document.getElementById(
      "email-body"
    );
    if (textarea) {
      const start = textarea.selectionStart;
      const end = textarea.selectionEnd;
      const text = formData.body;
      const newText = text.substring(0, start) + `{{${variable}}}` + text.substring(end);
      setFormData({ ...formData, body: newText });
    }
  };
  const showEditSkeleton = !isCreateMode && (isCoreSettingsEdit ? settingsLoading : isLoading);
  if (showEditSkeleton) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-6", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between animate-pulse", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-4", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 w-20 bg-gray-200 dark:bg-gray-700 rounded" }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-8 w-56 bg-gray-200 dark:bg-gray-700 rounded mb-2" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 w-40 bg-gray-200 dark:bg-gray-700 rounded" })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 w-24 bg-gray-200 dark:bg-gray-700 rounded" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 w-32 bg-gray-200 dark:bg-gray-700 rounded" })
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-3 gap-6", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "lg:col-span-2 space-y-6", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-6 w-36 bg-gray-200 dark:bg-gray-700 rounded" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-6 w-20 bg-gray-200 dark:bg-gray-700 rounded" })
            ] }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-4", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 w-28 bg-gray-200 dark:bg-gray-700 rounded" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 w-full bg-gray-200 dark:bg-gray-700 rounded" })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 w-24 bg-gray-200 dark:bg-gray-700 rounded" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 w-full bg-gray-200 dark:bg-gray-700 rounded" })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 w-20 bg-gray-200 dark:bg-gray-700 rounded" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 w-full bg-gray-200 dark:bg-gray-700 rounded" })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 w-32 bg-gray-200 dark:bg-gray-700 rounded" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-64 w-full bg-gray-200 dark:bg-gray-700 rounded" })
              ] })
            ] })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-6 w-32 bg-gray-200 dark:bg-gray-700 rounded" }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-3", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 flex-1 bg-gray-200 dark:bg-gray-700 rounded" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 w-10 bg-gray-200 dark:bg-gray-700 rounded" })
            ] }) })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-6", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-6 w-36 bg-gray-200 dark:bg-gray-700 rounded" }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-4", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 w-full bg-gray-200 dark:bg-gray-700 rounded" }),
              [1, 2, 3].map((group) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-3 w-20 bg-gray-200 dark:bg-gray-700 rounded" }),
                [1, 2, 3].map((item) => /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "div",
                  {
                    className: "h-12 w-full bg-gray-200 dark:bg-gray-700 rounded"
                  },
                  item
                ))
              ] }, group))
            ] })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-6 w-28 bg-gray-200 dark:bg-gray-700 rounded" }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "space-y-3", children: [1, 2, 3].map((i) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 w-16 bg-gray-200 dark:bg-gray-700 rounded" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 w-24 bg-gray-200 dark:bg-gray-700 rounded" })
            ] }, i)) })
          ] })
        ] })
      ] })
    ] });
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-6", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-4", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Button, { variant: "ghost", onClick: () => goBack(), children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowLeft, { className: "w-4 h-4 mr-2" }),
          __("Back")
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("h1", { className: "text-2xl font-bold text-gray-900 dark:text-white flex items-center gap-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Mail, { className: "w-6 h-6 text-blue-500" }),
            isCreateMode ? __("Create Email Template") : isCoreViewMode ? __("View email template", "yatra") : __("Edit Email Template")
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-gray-500 dark:text-gray-400 mt-1", children: isCreateMode ? __("Create a new custom email template") : isCoreSettingsEdit ? isCoreViewMode ? __(
            "This template uses site settings. Enable Yatra Pro and the required module to edit subject and HTML body.",
            "yatra"
          ) : __(
            "Core customer email (saved with site settings). From address is set under Email → Delivery.",
            "yatra"
          ) : String((templateData == null ? void 0 : templateData.name) ?? "") })
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3", children: [
        !isCreateMode && /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Button,
          {
            variant: "outline",
            onClick: () => isCoreSettingsEdit ? corePreviewMutation.mutate() : previewMutation.mutate(),
            disabled: previewMutation.isPending || corePreviewMutation.isPending,
            children: [
              previewMutation.isPending || corePreviewMutation.isPending ? /* @__PURE__ */ jsxRuntimeExports.jsx(Loader2, { className: "w-4 h-4 mr-2 animate-spin" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(Eye, { className: "w-4 h-4 mr-2" }),
              __("Preview")
            ]
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Button,
          {
            onClick: handleSubmit,
            disabled: saveMutation.isPending || saveCoreMutation.isPending || isCoreStrictViewOnly,
            className: "bg-blue-600 hover:bg-blue-700 text-white",
            children: [
              saveMutation.isPending || saveCoreMutation.isPending ? /* @__PURE__ */ jsxRuntimeExports.jsx(Loader2, { className: "w-4 h-4 mr-2 animate-spin" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(Save, { className: "w-4 h-4 mr-2" }),
              isCreateMode ? __("Create Template") : __("Save Template")
            ]
          }
        )
      ] })
    ] }),
    isCoreBodyReadOnly && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start gap-2 rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-900 dark:border-amber-800 dark:bg-amber-950/40 dark:text-amber-100", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(Info, { className: "w-5 h-5 flex-shrink-0 mt-0.5" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { children: isCoreStrictViewOnly ? __(
        "This link is view-only. Subject, body, and status cannot be changed from this screen.",
        "yatra"
      ) : __(
        "Subject and HTML body are read-only until the required module is active. You can still turn this email on or off below; values reflect your site settings.",
        "yatra"
      ) })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-3 gap-6", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "lg:col-span-2 space-y-6", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardTitle, { className: "flex items-center justify-between", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: __("Template Details") }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "span",
                {
                  className: `text-sm ${formData.is_active ? "text-green-600 dark:text-green-400" : "text-gray-500"}`,
                  children: formData.is_active ? __("Active") : __("Inactive")
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Switch,
                {
                  checked: formData.is_active,
                  disabled: isCoreStrictViewOnly,
                  onCheckedChange: (checked) => setFormData({ ...formData, is_active: checked })
                }
              )
            ] })
          ] }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-4", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1", children: __("Template Name") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Input,
                {
                  value: formData.name,
                  onChange: (e) => setFormData({ ...formData, name: e.target.value }),
                  placeholder: __("Enter template name"),
                  readOnly: isCoreSettingsEdit,
                  className: isCoreSettingsEdit ? "bg-gray-50 dark:bg-gray-900/40" : ""
                }
              )
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1", children: __("Description") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Input,
                {
                  value: formData.description,
                  onChange: (e) => setFormData({ ...formData, description: e.target.value }),
                  placeholder: __(
                    "Brief description of when this email is sent"
                  ),
                  readOnly: isCoreSettingsEdit,
                  className: isCoreSettingsEdit ? "bg-gray-50 dark:bg-gray-900/40" : ""
                }
              )
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1", children: __("Trigger Event") }),
              Boolean(templateData == null ? void 0 : templateData.is_system) || isCoreSettingsEdit ? /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "inline-flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium bg-indigo-100 text-indigo-800 dark:bg-indigo-900/30 dark:text-indigo-400 border border-indigo-200 dark:border-indigo-800", children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(Zap, { className: "w-4 h-4" }),
                    formData.event_key || "-"
                  ] }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs text-gray-500 dark:text-gray-400", children: __("System templates cannot change events") })
                ] }),
                formData.event_key && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-3 bg-indigo-50 dark:bg-indigo-900/20 rounded-lg border border-indigo-200 dark:border-indigo-800", children: /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-indigo-800 dark:text-indigo-300", children: ((_b = events.find((e) => e.key === formData.event_key)) == null ? void 0 : _b.description) || "" }) })
              ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs(
                  "button",
                  {
                    type: "button",
                    onClick: () => setShowEventDropdown(!showEventDropdown),
                    className: "w-full px-3 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-left flex items-center justify-between hover:border-gray-400 dark:hover:border-gray-500 transition-colors",
                    children: [
                      formData.event_key ? /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsx(Zap, { className: "w-4 h-4 text-blue-500" }),
                        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm font-medium text-gray-900 dark:text-white", children: ((_c = events.find(
                          (e) => e.key === formData.event_key
                        )) == null ? void 0 : _c.name) || formData.event_key })
                      ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsx(Mail, { className: "w-4 h-4 text-gray-400" }),
                        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm text-gray-500 dark:text-gray-400", children: __("No Event (Sequence Only)") })
                      ] }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx(
                        ChevronDown,
                        {
                          className: `w-4 h-4 text-gray-400 transition-transform ${showEventDropdown ? "rotate-180" : ""}`
                        }
                      )
                    ]
                  }
                ),
                showEventDropdown && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "absolute z-50 w-full mt-1 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg max-h-80 overflow-y-auto", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-2 border-b border-gray-200 dark:border-gray-700", children: /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400 px-2", children: __(
                    "Select an event to trigger this email, or leave empty for sequence use"
                  ) }) }),
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "py-1", children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "button",
                      {
                        type: "button",
                        onClick: () => {
                          setFormData({ ...formData, event_key: "" });
                          setShowEventDropdown(false);
                        },
                        className: `w-full px-3 py-3 text-left hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors border-b border-gray-100 dark:border-gray-700 ${!formData.event_key ? "bg-indigo-50 dark:bg-indigo-900/20" : ""}`,
                        children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start gap-2", children: [
                          /* @__PURE__ */ jsxRuntimeExports.jsx(
                            Mail,
                            {
                              className: `w-4 h-4 mt-0.5 flex-shrink-0 ${!formData.event_key ? "text-blue-500" : "text-gray-400"}`
                            }
                          ),
                          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1 min-w-0", children: [
                            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex items-center gap-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                              "span",
                              {
                                className: `text-sm font-medium ${!formData.event_key ? "text-blue-800 dark:text-blue-400" : "text-gray-900 dark:text-white"}`,
                                children: __("No Event (Sequence Only)")
                              }
                            ) }),
                            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400 mt-0.5", children: __(
                              "This template will only be used in email sequences"
                            ) })
                          ] }),
                          !formData.event_key && /* @__PURE__ */ jsxRuntimeExports.jsx(Check, { className: "w-4 h-4 text-blue-500 flex-shrink-0" })
                        ] })
                      }
                    ),
                    events.map((event) => /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "button",
                      {
                        type: "button",
                        onClick: () => {
                          setFormData({
                            ...formData,
                            event_key: event.key
                          });
                          setShowEventDropdown(false);
                        },
                        className: `w-full px-3 py-3 text-left hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors border-b border-gray-100 dark:border-gray-700 last:border-b-0 ${formData.event_key === event.key ? "bg-indigo-50 dark:bg-indigo-900/20" : ""}`,
                        children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start gap-2", children: [
                          /* @__PURE__ */ jsxRuntimeExports.jsx(
                            Zap,
                            {
                              className: `w-4 h-4 mt-0.5 flex-shrink-0 ${formData.event_key === event.key ? "text-blue-500" : "text-gray-400"}`
                            }
                          ),
                          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1 min-w-0", children: [
                            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
                              /* @__PURE__ */ jsxRuntimeExports.jsx(
                                "span",
                                {
                                  className: `text-sm font-medium ${formData.event_key === event.key ? "text-blue-800 dark:text-blue-400" : "text-gray-900 dark:text-white"}`,
                                  children: event.name
                                }
                              ),
                              /* @__PURE__ */ jsxRuntimeExports.jsx("code", { className: "text-xs px-1.5 py-0.5 bg-gray-100 dark:bg-gray-700 text-gray-500 dark:text-gray-400 rounded", children: event.key })
                            ] }),
                            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400 mt-0.5 line-clamp-2", children: event.description })
                          ] }),
                          formData.event_key === event.key && /* @__PURE__ */ jsxRuntimeExports.jsx(Check, { className: "w-4 h-4 text-blue-500 flex-shrink-0" })
                        ] })
                      },
                      event.key
                    ))
                  ] })
                ] }),
                showEventDropdown && /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "div",
                  {
                    className: "fixed inset-0 z-40",
                    onClick: () => setShowEventDropdown(false)
                  }
                )
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400 mt-1", children: __(
                "This email will be triggered when the selected event occurs"
              ) })
            ] }),
            !isCoreSettingsEdit && /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-4", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1", children: __("From Name") }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    Input,
                    {
                      value: formData.from_name,
                      onChange: (e) => setFormData({
                        ...formData,
                        from_name: e.target.value
                      }),
                      placeholder: __("e.g., Travel Agency Name")
                    }
                  ),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400 mt-1", children: __("Leave empty to use site default") })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1", children: __("From Email") }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    Input,
                    {
                      type: "email",
                      value: formData.from_email,
                      onChange: (e) => setFormData({
                        ...formData,
                        from_email: e.target.value
                      }),
                      placeholder: __("e.g., noreply@yoursite.com")
                    }
                  ),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400 mt-1", children: __("Leave empty to use site default") })
                ] })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-4", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1", children: __("To Email") }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    Input,
                    {
                      type: "email",
                      value: formData.to_email,
                      onChange: (e) => setFormData({ ...formData, to_email: e.target.value }),
                      placeholder: __("e.g., {{customer_email}}")
                    }
                  ),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400 mt-1", children: __(
                    "Recipient email. Use variables or leave empty for default"
                  ) })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1", children: __("Reply-To Email") }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    Input,
                    {
                      type: "email",
                      value: formData.reply_to,
                      onChange: (e) => setFormData({ ...formData, reply_to: e.target.value }),
                      placeholder: __("e.g., support@yoursite.com")
                    }
                  ),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400 mt-1", children: __(
                    "Where replies will be sent. Leave empty to use From Email"
                  ) })
                ] })
              ] })
            ] }),
            isCoreSettingsEdit && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-600 dark:text-gray-400 rounded-lg border border-gray-200 dark:border-gray-600 p-3 bg-gray-50 dark:bg-gray-800/50", children: __(
              "From / reply addresses are configured under Email → Delivery. Recipient uses the customer on the booking.",
              "yatra"
            ) }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1", children: __("Subject Line") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Input,
                {
                  value: formData.subject,
                  onChange: (e) => setFormData({ ...formData, subject: e.target.value }),
                  placeholder: __("Email subject with {{variables}}"),
                  readOnly: isCoreBodyReadOnly,
                  className: `font-mono text-sm ${isCoreBodyReadOnly ? "bg-gray-50 dark:bg-gray-900/40" : ""}`
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400 mt-1", children: __("Use {{variable}} syntax to insert dynamic content") })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mb-1 flex items-center justify-between", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300", children: __("Email Body (HTML)") }),
                !isCoreBodyReadOnly && isAiEligible() && isAiModuleEnabled() && /* @__PURE__ */ jsxRuntimeExports.jsxs(
                  Button,
                  {
                    type: "button",
                    variant: "outline",
                    size: "sm",
                    onClick: () => setShowAiModal(true),
                    className: "border-blue-300 text-blue-700 hover:bg-blue-50 dark:border-blue-500/40 dark:text-blue-200 dark:hover:bg-blue-900/30",
                    children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx(Sparkles, { className: "mr-1.5 h-3.5 w-3.5" }),
                      __("Generate with AI", "yatra")
                    ]
                  }
                )
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "textarea",
                {
                  id: "email-body",
                  value: formData.body,
                  onChange: (e) => setFormData({ ...formData, body: e.target.value }),
                  rows: 20,
                  readOnly: isCoreBodyReadOnly,
                  className: `w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg font-mono text-sm ${isCoreBodyReadOnly ? "bg-gray-50 dark:bg-gray-900/40 text-gray-900 dark:text-white" : "bg-white dark:bg-gray-800 text-gray-900 dark:text-white"}`,
                  placeholder: __("HTML email content...")
                }
              )
            ] })
          ] })
        ] }),
        !isCreateMode && !isCoreSettingsEdit && /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardTitle, { className: "flex items-center gap-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Send, { className: "w-5 h-5 text-blue-500" }),
            __("Send Test Email")
          ] }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-3", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Input,
                {
                  type: "email",
                  value: testEmail,
                  onChange: (e) => setTestEmail(e.target.value),
                  placeholder: __("Enter email address"),
                  className: "flex-1"
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Button,
                {
                  onClick: () => testMutation.mutate(testEmail),
                  disabled: !testEmail || testMutation.isPending,
                  children: testMutation.isPending ? /* @__PURE__ */ jsxRuntimeExports.jsx(Loader2, { className: "w-4 h-4 animate-spin" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(Send, { className: "w-4 h-4" })
                }
              )
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400 mt-2", children: __(
              "Send a test email with sample data to preview how it looks"
            ) })
          ] })
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-6", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardTitle, { className: "flex items-center gap-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Code, { className: "w-5 h-5 text-blue-500" }),
            __("Available Variables")
          ] }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-4", children: [
            !isCoreSettingsEdit && /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-500 dark:text-gray-400", children: __("Click to copy, double-click to insert at cursor") }),
              formData.event_key ? (
                // Show the technical event KEY (dot-notation, monospace)
                // as the primary label so it can't be confused with the
                // template's display title — earlier versions showed
                // the event's friendly name, which often matches what
                // operators name their templates ("Customer email
                // verification" appears as both the event name and a
                // common template title) and made it unclear what the
                // chip was scoped to. Friendly name still appears as
                // the parenthesised clarifier.
                /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "text-xs text-blue-700 dark:text-blue-300 bg-blue-50 dark:bg-blue-950/30 rounded px-2 py-1.5", children: [
                  __("Variables available for trigger event:", "yatra"),
                  " ",
                  /* @__PURE__ */ jsxRuntimeExports.jsx("code", { className: "font-mono text-blue-800 dark:text-blue-200 bg-blue-100 dark:bg-blue-900/40 px-1 rounded", children: formData.event_key }),
                  (() => {
                    const match2 = events.find(
                      (e) => e.key === formData.event_key
                    );
                    return (match2 == null ? void 0 : match2.name) ? /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-blue-600/80 dark:text-blue-400/80", children: [
                      " ",
                      "(",
                      match2.name,
                      ")"
                    ] }) : null;
                  })()
                ] })
              ) : /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-amber-700 dark:text-amber-400 bg-amber-50 dark:bg-amber-950/30 rounded px-2 py-1.5", children: __(
                "Pick a trigger event below to see the variables that apply to that event. Showing the full catalog until then.",
                "yatra"
              ) })
            ] }),
            isCoreSettingsEdit && (coreDef == null ? void 0 : coreDef.mergeTags) ? /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase", children: __("Merge tags", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400", children: __(
                "Click a tag to copy; paste into subject or HTML body.",
                "yatra"
              ) }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex flex-wrap gap-1", children: coreDef.mergeTags.split(",").map((raw) => {
                const tag2 = raw.trim();
                const inner = tag2.replace(/\{\{|\}\}/g, "").trim();
                if (!inner) return null;
                return /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "button",
                  {
                    type: "button",
                    onClick: () => copyVariable(inner),
                    className: "rounded border border-gray-200 dark:border-gray-600 px-2 py-1 text-xs font-mono text-blue-600 dark:text-blue-400 hover:bg-gray-50 dark:hover:bg-gray-800",
                    children: tag2
                  },
                  tag2
                );
              }) })
            ] }) : variablesData && Object.entries(variablesData).map(
              ([category, variables]) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("h4", { className: "text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase mb-2", children: category }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-1", children: variables.map((v) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
                  "button",
                  {
                    type: "button",
                    onClick: () => copyVariable(v.key),
                    onDoubleClick: () => insertVariable(v.key),
                    className: "w-full text-left px-2 py-1.5 rounded hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors group",
                    children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsx("code", { className: "text-xs text-blue-600 dark:text-blue-400", children: `{{${v.key}}}` }),
                        copiedVar === v.key ? /* @__PURE__ */ jsxRuntimeExports.jsx(Check, { className: "w-3 h-3 text-green-500" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(Copy, { className: "w-3 h-3 text-gray-400 opacity-0 group-hover:opacity-100" })
                      ] }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400 mt-0.5", children: v.description })
                    ]
                  },
                  v.key
                )) })
              ] }, category)
            )
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardTitle, { className: "flex items-center gap-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Info, { className: "w-5 h-5 text-gray-500" }),
            isCreateMode ? __("New Template") : __("Template Info")
          ] }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3 text-sm", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between items-center", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-500 dark:text-gray-400", children: __("Event") }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "inline-flex items-center gap-1.5 px-2 py-1 rounded-full text-xs font-medium bg-indigo-100 text-indigo-800 dark:bg-indigo-900/30 dark:text-indigo-400", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(Zap, { className: "w-3 h-3" }),
                  formData.event_key || "-"
                ] })
              ] }),
              formData.event_key && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400 italic", children: ((_d = events.find((e) => e.key === formData.event_key)) == null ? void 0 : _d.description) || "" })
            ] }),
            isCreateMode ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-500 dark:text-gray-400", children: __("Type") }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-900 dark:text-white", children: __("Custom") })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-3 bg-blue-50 dark:bg-blue-900/20 rounded-lg border border-blue-200 dark:border-blue-800", children: /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-blue-700 dark:text-blue-300", children: __(
                "Custom templates can be edited and deleted. Select an event to trigger this email automatically."
              ) }) })
            ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-500 dark:text-gray-400", children: __("Key") }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("code", { className: "text-xs bg-gray-100 dark:bg-gray-800 px-2 py-0.5 rounded", children: isCoreSettingsEdit ? coreDef == null ? void 0 : coreDef.template_key : String((templateData == null ? void 0 : templateData.template_key) ?? "") })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-500 dark:text-gray-400", children: __("Category") }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(Badge, { className: "bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400", children: isCoreSettingsEdit ? coreDef == null ? void 0 : coreDef.category : String((templateData == null ? void 0 : templateData.category) ?? "") })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-500 dark:text-gray-400", children: __("Recipient") }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "span",
                  {
                    className: `inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${(isCoreSettingsEdit ? coreDef == null ? void 0 : coreDef.recipient_type : String((templateData == null ? void 0 : templateData.recipient_type) ?? "")) === "admin" ? "bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400" : "bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400"}`,
                    children: (isCoreSettingsEdit ? coreDef == null ? void 0 : coreDef.recipient_type : String((templateData == null ? void 0 : templateData.recipient_type) ?? "")) === "admin" ? __("Admin") : __("Customer")
                  }
                )
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-500 dark:text-gray-400", children: __("Type") }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-900 dark:text-white", children: isCoreSettingsEdit || Boolean(templateData == null ? void 0 : templateData.is_system) ? __("System") : __("Custom") })
              ] })
            ] })
          ] })
        ] })
      ] })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      EmailPreviewModal,
      {
        open: showPreview && Boolean(previewData),
        onClose: () => {
          setShowPreview(false);
          setPreviewData(null);
        },
        subject: (previewData == null ? void 0 : previewData.subject) ?? "",
        body: (previewData == null ? void 0 : previewData.body) ?? ""
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      AiEmailTemplateModal,
      {
        open: showAiModal,
        onClose: () => setShowAiModal(false),
        templateKey: coreTemplateSlug || formData.event_key || "custom_template",
        templateName: (coreDef == null ? void 0 : coreDef.name) || formData.name || formData.event_key,
        templateDescription: (coreDef == null ? void 0 : coreDef.description) || formData.description,
        recipientType: (catalogEntryForCore == null ? void 0 : catalogEntryForCore.recipient_type) || "customer",
        mergeTags: (() => {
          const raw = (catalogEntryForCore == null ? void 0 : catalogEntryForCore.mergeTags) ?? "";
          if (!raw) {
            return [
              "site_name",
              "site_url",
              "customer_name",
              "customer_email",
              "booking_reference",
              "trip_name",
              "travel_date",
              "total_amount",
              "currency"
            ];
          }
          return raw.split(",").map(
            (s2) => s2.trim().replace(/^\{\{|\}\}$/g, "").trim()
          ).filter(Boolean);
        })(),
        currentSubject: formData.subject,
        currentBody: formData.body,
        onAccept: ({ subject, body }) => setFormData({ ...formData, subject, body })
      }
    )
  ] });
};
const delayUnits = [
  { value: "minutes", label: __("Minutes") },
  { value: "hours", label: __("Hours") },
  { value: "days", label: __("Days") },
  { value: "weeks", label: __("Weeks") }
];
const EmailSequenceForm = () => {
  var _a;
  const id = reactExports.useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get("id");
  }, []);
  const isEditing = !!id;
  const goBack = () => {
    window.location.href = `admin.php?page=yatra&subpage=email-automation&tab=sequences`;
  };
  const queryClient2 = useQueryClient();
  const { showToast } = useToast();
  const [formData, setFormData] = reactExports.useState({
    name: "",
    description: "",
    trigger_type: "booking.created",
    trigger_config: {},
    status: "draft",
    applicable_to: "all",
    trip_ids: []
  });
  const [steps, setSteps] = reactExports.useState([
    {
      step_order: 0,
      delay_value: 0,
      delay_unit: "minutes",
      template_id: null,
      custom_subject: "",
      custom_body: "",
      conditions: [],
      is_active: true
    }
  ]);
  const [openTemplateDropdown, setOpenTemplateDropdown] = reactExports.useState(null);
  const events = ((_a = window.yatraAdmin) == null ? void 0 : _a.emailEvents) || [];
  const { data: sequenceData, isLoading: isLoadingSequence } = useQuery({
    queryKey: ["email-sequence", id],
    queryFn: () => fetchEmailSequence(id),
    enabled: isEditing
  });
  const { data: templatesData } = useQuery({
    queryKey: ["email-templates"],
    queryFn: () => fetchEmailTemplates()
  });
  const templates = Array.isArray(templatesData) ? templatesData : [];
  const allTriggerEvents = reactExports.useMemo(() => {
    return events.map((e) => ({
      key: e.key,
      name: e.name,
      description: e.description,
      category: e.category
    }));
  }, [events]);
  const [openTriggerDropdown, setOpenTriggerDropdown] = reactExports.useState(false);
  const sequenceTemplates = reactExports.useMemo(() => {
    return templates.filter((t) => t.recipient_type !== "admin");
  }, [templates]);
  reactExports.useEffect(() => {
    if (!sequenceData || typeof sequenceData !== "object") {
      return;
    }
    const loaded = sequenceData;
    setFormData({
      name: loaded.name || "",
      description: loaded.description || "",
      trigger_type: loaded.trigger_type || "booking.created",
      trigger_config: loaded.trigger_config || {},
      status: loaded.status || "draft",
      applicable_to: loaded.applicable_to || "all",
      trip_ids: loaded.trip_ids || []
    });
    if (loaded.steps && loaded.steps.length > 0) {
      setSteps(loaded.steps);
    }
  }, [sequenceData]);
  const createMutation = useMutation({
    mutationFn: async (data) => {
      return await createEmailSequence(data);
    },
    onSuccess: () => {
      queryClient2.invalidateQueries({ queryKey: ["email-sequences"] });
      showToast(__("Sequence created successfully"), "success");
      goBack();
    },
    onError: () => {
      showToast(__("Failed to create sequence"), "error");
    }
  });
  const updateMutation = useMutation({
    mutationFn: async (data) => {
      return await updateEmailSequence(id, data);
    },
    onSuccess: () => {
      queryClient2.invalidateQueries({ queryKey: ["email-sequences"] });
      queryClient2.invalidateQueries({ queryKey: ["email-sequence", id] });
      showToast(__("Sequence updated successfully"), "success");
    },
    onError: () => {
      showToast(__("Failed to update sequence"), "error");
    }
  });
  const handleSubmit = (e) => {
    e.preventDefault();
    const payload = {
      ...formData,
      steps: steps.map((step, index) => ({
        ...step,
        step_order: index
      }))
    };
    if (isEditing) {
      updateMutation.mutate(payload);
    } else {
      createMutation.mutate(payload);
    }
  };
  const addStep = () => {
    setSteps([
      ...steps,
      {
        step_order: steps.length,
        delay_value: 1,
        delay_unit: "days",
        template_id: null,
        custom_subject: "",
        custom_body: "",
        conditions: [],
        is_active: true
      }
    ]);
  };
  const removeStep = (index) => {
    if (steps.length > 1) {
      setSteps(steps.filter((_, i) => i !== index));
    }
  };
  const updateStep = (index, field, value) => {
    const newSteps = [...steps];
    newSteps[index][field] = value;
    setSteps(newSteps);
  };
  const selectedTrigger = allTriggerEvents.find(
    (t) => t.key === formData.trigger_type
  );
  const isPending = createMutation.isPending || updateMutation.isPending;
  if (isEditing && isLoadingSequence) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-6", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between animate-pulse", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-4", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 w-20 bg-gray-200 dark:bg-gray-700 rounded" }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-8 w-48 bg-gray-200 dark:bg-gray-700 rounded mb-2" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 w-32 bg-gray-200 dark:bg-gray-700 rounded" })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 w-32 bg-gray-200 dark:bg-gray-700 rounded" })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-3 gap-6", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "lg:col-span-2 space-y-6", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-6 w-40 bg-gray-200 dark:bg-gray-700 rounded" }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-4", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 w-24 bg-gray-200 dark:bg-gray-700 rounded" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 w-full bg-gray-200 dark:bg-gray-700 rounded" })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 w-20 bg-gray-200 dark:bg-gray-700 rounded" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 w-full bg-gray-200 dark:bg-gray-700 rounded" })
              ] })
            ] })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-6 w-24 bg-gray-200 dark:bg-gray-700 rounded" }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-3", children: [1, 2, 3, 4, 5, 6].map((i) => /* @__PURE__ */ jsxRuntimeExports.jsx(
              "div",
              {
                className: "h-24 bg-gray-200 dark:bg-gray-700 rounded-lg"
              },
              i
            )) }) })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-6 w-32 bg-gray-200 dark:bg-gray-700 rounded" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-8 w-24 bg-gray-200 dark:bg-gray-700 rounded" })
            ] }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-4", children: [1, 2].map((i) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "div",
              {
                className: "border border-gray-200 dark:border-gray-700 rounded-lg p-4",
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-6 w-20 bg-gray-200 dark:bg-gray-700 rounded mb-4" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-2 gap-4", children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 bg-gray-200 dark:bg-gray-700 rounded" }),
                    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 bg-gray-200 dark:bg-gray-700 rounded" })
                  ] })
                ]
              },
              i
            )) }) })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-6", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-6 w-36 bg-gray-200 dark:bg-gray-700 rounded" }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 w-full bg-gray-200 dark:bg-gray-700 rounded" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 w-3/4 bg-gray-200 dark:bg-gray-700 rounded" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 w-full bg-gray-200 dark:bg-gray-700 rounded" })
            ] })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-6 w-20 bg-gray-200 dark:bg-gray-700 rounded" }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "space-y-3", children: [1, 2, 3].map((i) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 w-24 bg-gray-200 dark:bg-gray-700 rounded" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 w-16 bg-gray-200 dark:bg-gray-700 rounded" })
            ] }, i)) })
          ] })
        ] })
      ] })
    ] });
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-6", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-4", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Button, { variant: "ghost", onClick: goBack, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowLeft, { className: "w-4 h-4 mr-2" }),
          __("Back")
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("h1", { className: "text-2xl font-bold text-gray-900 dark:text-white flex items-center gap-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(GitBranch, { className: "w-6 h-6 text-blue-500" }),
            isEditing ? __("Edit Sequence") : __("Create Sequence")
          ] }),
          isEditing && formData.name && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-gray-500 dark:text-gray-400 mt-1", children: formData.name })
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex items-center gap-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Button,
        {
          onClick: handleSubmit,
          disabled: isPending || !formData.name,
          className: "bg-blue-600 hover:bg-blue-700 text-white",
          children: [
            isPending ? /* @__PURE__ */ jsxRuntimeExports.jsx(Loader2, { className: "w-4 h-4 mr-2 animate-spin" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(Save, { className: "w-4 h-4 mr-2" }),
            isEditing ? __("Save Changes") : __("Create Sequence")
          ]
        }
      ) })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-3 gap-6", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "lg:col-span-2 space-y-6", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardTitle, { className: "flex items-center justify-between", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: __("Sequence Details") }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex items-center gap-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
              Select,
              {
                value: formData.status,
                onChange: (e) => setFormData({
                  ...formData,
                  status: e.target.value
                }),
                className: "w-32",
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "draft", children: __("Draft") }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "active", children: __("Active") }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "paused", children: __("Paused") })
                ]
              }
            ) })
          ] }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-4", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1", children: [
                __("Sequence Name"),
                " ",
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Input,
                {
                  value: formData.name,
                  onChange: (e) => setFormData({ ...formData, name: e.target.value }),
                  placeholder: __("e.g., Post-Booking Welcome Series"),
                  required: true
                }
              )
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1", children: __("Description") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Input,
                {
                  value: formData.description,
                  onChange: (e) => setFormData({ ...formData, description: e.target.value }),
                  placeholder: __(
                    "Brief description of what this sequence does"
                  )
                }
              )
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardTitle, { className: "flex items-center gap-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Zap, { className: "w-5 h-5 text-yellow-500" }),
            __("Trigger")
          ] }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-4", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2", children: __("When should this sequence start?") }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs(
                "button",
                {
                  type: "button",
                  onClick: () => setOpenTriggerDropdown(!openTriggerDropdown),
                  className: "w-full px-3 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-left flex items-center justify-between hover:border-gray-400 dark:hover:border-gray-500 transition-colors",
                  children: [
                    selectedTrigger ? /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx(Zap, { className: "w-4 h-4 text-blue-500" }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm font-medium text-gray-900 dark:text-white", children: selectedTrigger.name })
                    ] }) : /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm text-gray-500 dark:text-gray-400", children: __("Select a trigger event...") }),
                    /* @__PURE__ */ jsxRuntimeExports.jsx(
                      ChevronDown,
                      {
                        className: `w-4 h-4 text-gray-400 transition-transform ${openTriggerDropdown ? "rotate-180" : ""}`
                      }
                    )
                  ]
                }
              ),
              openTriggerDropdown && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "absolute z-50 w-full mt-1 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg max-h-80 overflow-y-auto", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-2 border-b border-gray-200 dark:border-gray-700", children: /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400 px-2", children: __("Select an event to trigger this sequence") }) }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "py-1", children: allTriggerEvents.map((trigger) => {
                  const isSelected = formData.trigger_type === trigger.key;
                  return /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "button",
                    {
                      type: "button",
                      onClick: () => {
                        setFormData({
                          ...formData,
                          trigger_type: trigger.key
                        });
                        setOpenTriggerDropdown(false);
                      },
                      className: `w-full px-3 py-3 text-left hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors border-b border-gray-100 dark:border-gray-700 last:border-b-0 ${isSelected ? "bg-blue-50 dark:bg-blue-900/20" : ""}`,
                      children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start gap-2", children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsx(
                          Zap,
                          {
                            className: `w-4 h-4 mt-0.5 flex-shrink-0 ${isSelected ? "text-blue-500" : "text-gray-400"}`
                          }
                        ),
                        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1 min-w-0", children: [
                          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
                            /* @__PURE__ */ jsxRuntimeExports.jsx(
                              "span",
                              {
                                className: `text-sm font-medium ${isSelected ? "text-blue-700 dark:text-blue-400" : "text-gray-900 dark:text-white"}`,
                                children: trigger.name
                              }
                            ),
                            /* @__PURE__ */ jsxRuntimeExports.jsx("code", { className: "text-xs px-1.5 py-0.5 bg-gray-100 dark:bg-gray-700 text-gray-500 dark:text-gray-400 rounded", children: trigger.key }),
                            isSelected && /* @__PURE__ */ jsxRuntimeExports.jsx(Check, { className: "w-4 h-4 text-blue-500" })
                          ] }),
                          /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400 mt-0.5 line-clamp-2", children: trigger.description })
                        ] })
                      ] })
                    },
                    trigger.key
                  );
                }) })
              ] }),
              openTriggerDropdown && /* @__PURE__ */ jsxRuntimeExports.jsx(
                "div",
                {
                  className: "fixed inset-0 z-40",
                  onClick: () => setOpenTriggerDropdown(false)
                }
              )
            ] }),
            (formData.trigger_type === "schedule.days_before_trip" || formData.trigger_type === "schedule.days_after_trip") && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "pt-4 border-t border-gray-200 dark:border-gray-700", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1", children: __("Number of Days") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Input,
                {
                  type: "number",
                  min: "1",
                  value: formData.trigger_config.days || 7,
                  onChange: (e) => setFormData({
                    ...formData,
                    trigger_config: {
                      ...formData.trigger_config,
                      days: parseInt(e.target.value)
                    }
                  }),
                  className: "w-32"
                }
              )
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardTitle, { className: "flex items-center justify-between", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(GitBranch, { className: "w-5 h-5 text-purple-500" }),
              __("Sequence Steps")
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              Button,
              {
                type: "button",
                variant: "outline",
                size: "sm",
                onClick: addStep,
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(Plus, { className: "w-4 h-4 mr-1" }),
                  __("Add Step")
                ]
              }
            )
          ] }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-4", children: steps.map((step, index) => {
              var _a2, _b;
              return /* @__PURE__ */ jsxRuntimeExports.jsxs(
                "div",
                {
                  className: "border border-gray-200 dark:border-gray-700 rounded-lg",
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between px-4 py-3 bg-gray-50 dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700", children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3", children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsx(GripVertical, { className: "w-4 h-4 text-gray-400" }),
                        /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "font-medium text-gray-900 dark:text-white", children: [
                          __("Step"),
                          " ",
                          index + 1
                        ] }),
                        index === 0 && /* @__PURE__ */ jsxRuntimeExports.jsx(Badge, { className: "bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400", children: __("First Email") })
                      ] }),
                      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsx(
                          Switch,
                          {
                            checked: step.is_active,
                            onCheckedChange: (checked) => updateStep(index, "is_active", checked)
                          }
                        ),
                        steps.length > 1 && /* @__PURE__ */ jsxRuntimeExports.jsx(
                          Button,
                          {
                            type: "button",
                            variant: "ghost",
                            size: "sm",
                            onClick: () => removeStep(index),
                            className: "text-red-500 hover:text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20",
                            children: /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "w-4 h-4" })
                          }
                        )
                      ] })
                    ] }),
                    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "p-4 space-y-4", children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1", children: index === 0 ? __("Send after trigger") : __("Wait before sending") }),
                        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
                          /* @__PURE__ */ jsxRuntimeExports.jsx(
                            Input,
                            {
                              type: "number",
                              min: "0",
                              value: step.delay_value,
                              onChange: (e) => updateStep(
                                index,
                                "delay_value",
                                parseInt(e.target.value) || 0
                              ),
                              className: "w-24"
                            }
                          ),
                          /* @__PURE__ */ jsxRuntimeExports.jsx(
                            Select,
                            {
                              value: step.delay_unit,
                              onChange: (e) => updateStep(index, "delay_unit", e.target.value),
                              className: "w-32",
                              children: delayUnits.map((unit2) => /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: unit2.value, children: unit2.label }, unit2.value))
                            }
                          ),
                          index === 0 && step.delay_value === 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-sm text-gray-500 dark:text-gray-400", children: [
                            "(",
                            __("Immediately"),
                            ")"
                          ] })
                        ] })
                      ] }),
                      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative", children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1", children: __("Email Template") }),
                        /* @__PURE__ */ jsxRuntimeExports.jsxs(
                          "button",
                          {
                            type: "button",
                            onClick: () => setOpenTemplateDropdown(
                              openTemplateDropdown === index ? null : index
                            ),
                            className: "w-full flex items-center justify-between px-3 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-left hover:border-blue-400 dark:hover:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500 transition-colors",
                            children: [
                              step.template_id ? /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2 min-w-0", children: [
                                /* @__PURE__ */ jsxRuntimeExports.jsx(Mail, { className: "w-4 h-4 text-blue-500 flex-shrink-0" }),
                                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-900 dark:text-white truncate", children: ((_a2 = sequenceTemplates.find(
                                  (t) => t.id === step.template_id
                                )) == null ? void 0 : _a2.name) || ((_b = templates.find(
                                  (t) => t.id === step.template_id
                                )) == null ? void 0 : _b.name) || __("Unknown Template") })
                              ] }) : /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-500 dark:text-gray-400", children: __("Select a template...") }),
                              /* @__PURE__ */ jsxRuntimeExports.jsx(
                                ChevronDown,
                                {
                                  className: `w-4 h-4 text-gray-400 flex-shrink-0 transition-transform ${openTemplateDropdown === index ? "rotate-180" : ""}`
                                }
                              )
                            ]
                          }
                        ),
                        openTemplateDropdown === index && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "absolute z-50 mt-1 w-full bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg max-h-80 overflow-y-auto", children: sequenceTemplates.length === 0 ? /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "p-4 text-center text-gray-500 dark:text-gray-400", children: [
                          /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "font-medium", children: __("No templates available") }),
                          /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs mt-1", children: __(
                            "Add customer email templates under Email → Templates first."
                          ) })
                        ] }) : sequenceTemplates.map((template) => {
                          const isSelected = step.template_id === template.id;
                          return /* @__PURE__ */ jsxRuntimeExports.jsx(
                            "button",
                            {
                              type: "button",
                              onClick: () => {
                                updateStep(
                                  index,
                                  "template_id",
                                  template.id
                                );
                                setOpenTemplateDropdown(null);
                              },
                              className: `w-full text-left p-3 border-b border-gray-100 dark:border-gray-700 last:border-b-0 hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors ${isSelected ? "bg-blue-50 dark:bg-blue-900/20" : ""}`,
                              children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start justify-between gap-2", children: [
                                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "min-w-0 flex-1", children: [
                                  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
                                    /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-medium text-gray-900 dark:text-white", children: template.name }),
                                    isSelected && /* @__PURE__ */ jsxRuntimeExports.jsx(Check, { className: "w-4 h-4 text-blue-500 flex-shrink-0" })
                                  ] }),
                                  template.description && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400 mt-0.5 line-clamp-2", children: template.description })
                                ] }),
                                /* @__PURE__ */ jsxRuntimeExports.jsx(
                                  Badge,
                                  {
                                    variant: "outline",
                                    className: "text-xs flex-shrink-0",
                                    children: template.category
                                  }
                                )
                              ] })
                            },
                            template.id
                          );
                        }) }),
                        openTemplateDropdown === index && /* @__PURE__ */ jsxRuntimeExports.jsx(
                          "div",
                          {
                            className: "fixed inset-0 z-40",
                            onClick: () => setOpenTemplateDropdown(null)
                          }
                        ),
                        !step.template_id && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-amber-600 dark:text-amber-400 mt-1", children: __("Please select a template for this step") })
                      ] })
                    ] })
                  ]
                },
                index
              );
            }) }),
            steps.length === 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-center py-8 text-gray-500 dark:text-gray-400", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(GitBranch, { className: "w-12 h-12 mx-auto mb-3 opacity-50" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { children: __("No steps added yet") }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs(
                Button,
                {
                  type: "button",
                  variant: "outline",
                  size: "sm",
                  onClick: addStep,
                  className: "mt-3",
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(Plus, { className: "w-4 h-4 mr-1" }),
                    __("Add First Step")
                  ]
                }
              )
            ] })
          ] })
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-6", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardTitle, { className: "flex items-center gap-2", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Info, { className: "w-5 h-5 text-gray-500" }),
            __("How Sequences Work")
          ] }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3 text-sm text-gray-600 dark:text-gray-400", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("p", { children: __(
              "Email sequences are automated workflows that send emails based on triggers and timing."
            ) }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("ol", { className: "list-decimal list-inside space-y-2", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("li", { children: __("Choose a trigger event (e.g., booking created)") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("li", { children: __("Add steps with delays and email templates") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("li", { children: __("Set the sequence to Active") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("li", { children: __("Emails will be sent automatically!") })
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { children: __("Status") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm text-gray-500 dark:text-gray-400", children: __("Current Status") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Badge,
                {
                  className: formData.status === "active" ? "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400" : formData.status === "paused" ? "bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400" : "bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-400",
                  children: formData.status === "active" ? __("Active") : formData.status === "paused" ? __("Paused") : __("Draft")
                }
              )
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm text-gray-500 dark:text-gray-400", children: __("Steps") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm font-medium text-gray-900 dark:text-white", children: steps.length })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm text-gray-500 dark:text-gray-400", children: __("Trigger") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-sm font-medium text-gray-900 dark:text-white", children: selectedTrigger == null ? void 0 : selectedTrigger.label })
            ] })
          ] })
        ] })
      ] })
    ] })
  ] });
};
const fieldTypeOptions = [
  { value: "text_field", label: "Text Field" },
  { value: "number", label: "Number" },
  { value: "email", label: "Email" },
  { value: "url", label: "URL" },
  { value: "textarea", label: "Textarea" },
  { value: "select", label: "Select Dropdown" },
  { value: "radio", label: "Radio Buttons" },
  { value: "checkbox", label: "Checkbox" },
  { value: "date", label: "Date" },
  { value: "time", label: "Time" },
  { value: "color", label: "Color" }
];
const Attributes = () => {
  const [searchTerm, setSearchTerm] = reactExports.useState("");
  const [statusFilter, setStatusFilter] = reactExports.useState("all");
  const [sortBy2, setSortBy] = reactExports.useState("id");
  const [sortOrder, setSortOrder] = reactExports.useState("desc");
  const [page, setPage] = reactExports.useState(1);
  const [selectedIds, setSelectedIds] = reactExports.useState([]);
  const [bulkAction, setBulkAction] = reactExports.useState("");
  const [showColumnsDropdown, setShowColumnsDropdown] = reactExports.useState(false);
  const [visibleColumns, setVisibleColumns] = reactExports.useState(() => {
    const saved = localStorage.getItem("yatra-attributes-columns");
    return saved ? JSON.parse(saved) : {
      name: true,
      field_type: true,
      required: true,
      show_on_frontend: true,
      show_in_filters: true,
      searchable: true,
      status: true,
      created_at: false,
      updated_at: false,
      description: false,
      display_order: false
    };
  });
  const [permanentDeleteConfirm, setPermanentDeleteConfirm] = reactExports.useState({
    isOpen: false,
    attribute: null
  });
  const [individualActionConfirm, setIndividualActionConfirm] = reactExports.useState({
    isOpen: false,
    action: "",
    attribute: null
  });
  const queryClient2 = useQueryClient();
  const { can } = usePermissions();
  const { showToast } = useToast();
  reactExports.useEffect(() => {
    const handler = (event) => {
      const target2 = event.target;
      if (target2.closest("[data-columns-trigger]") || target2.closest("[data-columns-content]"))
        return;
      setShowColumnsDropdown(false);
    };
    if (showColumnsDropdown) {
      document.addEventListener("click", handler);
      return () => document.removeEventListener("click", handler);
    }
  }, [showColumnsDropdown]);
  const queryParams = reactExports.useMemo(() => {
    const params = {
      page,
      per_page: 10,
      orderby: sortBy2,
      order: sortOrder
    };
    if (searchTerm) params.search = searchTerm;
    if (statusFilter !== "all") params.status = statusFilter;
    return params;
  }, [page, sortBy2, sortOrder, searchTerm, statusFilter]);
  const { data: statsData } = useQuery({
    queryKey: ["attributes-stats", searchTerm, statusFilter, page],
    queryFn: async () => {
      try {
        const response = await apiClient.get("/attributes/stats");
        return response || { all: 0, publish: 0, draft: 0, trash: 0 };
      } catch {
        return { all: 0, publish: 0, draft: 0, trash: 0 };
      }
    },
    enabled: can("yatra_view_trips"),
    staleTime: 0,
    gcTime: 0,
    refetchOnMount: "always"
  });
  const {
    data: attributesData,
    isLoading,
    error
  } = useQuery({
    queryKey: ["attributes", searchTerm, statusFilter, sortBy2, sortOrder, page],
    queryFn: async () => {
      const response = await apiClient.get("/attributes", {
        params: queryParams
      });
      return response;
    },
    enabled: can("yatra_view_trips")
  });
  const attributes = (attributesData == null ? void 0 : attributesData.data) || [];
  const total = (attributesData == null ? void 0 : attributesData.total) || 0;
  const totalPages = Math.ceil(total / 10);
  const errorContext = getErrorContext(error);
  const apiErrorMessage = (attributesData == null ? void 0 : attributesData.error) || (attributesData == null ? void 0 : attributesData.message);
  const isAttributesError = !!error || !!apiErrorMessage;
  const statusCounts = reactExports.useMemo(() => {
    if (statsData) {
      return {
        all: (statsData == null ? void 0 : statsData.all) ?? 0,
        publish: (statsData == null ? void 0 : statsData.publish) ?? 0,
        draft: (statsData == null ? void 0 : statsData.draft) ?? 0,
        trash: (statsData == null ? void 0 : statsData.trash) ?? 0
      };
    }
    return { all: 0, publish: 0, draft: 0, trash: 0 };
  }, [statsData]);
  const bulkMutation = useMutation({
    mutationFn: async ({
      action,
      ids
    }) => {
      return await apiClient.post("/attributes/bulk", { action, ids });
    },
    onSuccess: () => {
      queryClient2.invalidateQueries({ queryKey: ["attributes"] });
      queryClient2.invalidateQueries({ queryKey: ["attributes-stats"] });
      showToast(__("Bulk action completed successfully", "yatra"), "success");
      setSelectedIds([]);
      setBulkAction("");
    },
    onError: (err) => {
      showToast(
        (err == null ? void 0 : err.message) || __("Failed to perform bulk action", "yatra"),
        "error"
      );
    }
  });
  const handleEdit = (attribute) => {
    var _a;
    window.location.href = `${((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=trips&tab=attributes&action=edit&id=${attribute.id}`;
  };
  const handleCreateAttribute = () => {
    var _a;
    window.location.href = `${((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=trips&tab=attributes&action=create`;
  };
  const handleBulkApply = () => {
    if (!bulkAction) {
      showToast(__("Select a bulk action first.", "yatra"), "warning");
      return;
    }
    if (selectedIds.length === 0) {
      showToast(__("Select at least one attribute.", "yatra"), "warning");
      return;
    }
    bulkMutation.mutate({ action: bulkAction, ids: selectedIds });
  };
  const handleResetFilters = () => {
    setSearchTerm("");
    setStatusFilter("all");
    setSortBy("id");
    setSortOrder("desc");
    setPage(1);
    setSelectedIds([]);
    setBulkAction("");
  };
  const handleSort = (field) => {
    if (sortBy2 === field) {
      setSortOrder(sortOrder === "asc" ? "desc" : "asc");
    } else {
      setSortBy(field);
      setSortOrder("asc");
    }
  };
  reactExports.useEffect(() => {
    setSelectedIds(
      (prev) => prev.filter((id) => attributes.some((a2) => a2.id === id))
    );
  }, [attributes]);
  const attributeColumns = reactExports.useMemo(() => {
    const formatBoolean = (value) => value === true || value === "1" || value === 1;
    return [
      {
        key: "name",
        label: __("Attribute", "yatra"),
        sortable: true,
        visible: visibleColumns.name,
        render: (attribute) => {
          var _a;
          return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-10 h-10 rounded-lg bg-purple-100 dark:bg-purple-900/30 flex items-center justify-center flex-shrink-0", children: attribute.icon ? attribute.icon.type === "image" ? /* @__PURE__ */ jsxRuntimeExports.jsx(
              "img",
              {
                src: attribute.icon.value,
                alt: attribute.name,
                className: "w-6 h-6 object-cover rounded"
              }
            ) : /* @__PURE__ */ jsxRuntimeExports.jsx(
              IconSelector,
              {
                iconName: attribute.icon.value,
                provider: attribute.icon.provider ?? "yatra",
                size: 16,
                className: "text-purple-600 dark:text-purple-400"
              }
            ) : /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-5 h-5 text-purple-600 dark:text-purple-400 flex items-center justify-center text-xs font-semibold", children: attribute.name.charAt(0).toUpperCase() }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "a",
                {
                  href: `${((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=trips&tab=attributes&action=edit&id=${attribute.id}`,
                  className: "font-medium text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 hover:underline transition-colors cursor-pointer",
                  children: attribute.name
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-sm text-gray-500 dark:text-gray-400 flex items-center gap-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: attribute.slug }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-[11px] text-gray-400 dark:text-gray-500", children: [
                  "(",
                  __("ID:", "yatra"),
                  " ",
                  attribute.id,
                  ")"
                ] })
              ] })
            ] })
          ] });
        }
      },
      {
        key: "field_type",
        label: __("Field Type", "yatra"),
        sortable: true,
        visible: visibleColumns.field_type,
        render: (attribute) => {
          var _a;
          return /* @__PURE__ */ jsxRuntimeExports.jsx(Badge, { variant: "outline", children: ((_a = fieldTypeOptions.find((opt) => opt.value === attribute.field_type)) == null ? void 0 : _a.label) || attribute.field_type });
        }
      },
      {
        key: "required",
        label: __("Required", "yatra"),
        sortable: true,
        visible: visibleColumns.required,
        render: (attribute) => /* @__PURE__ */ jsxRuntimeExports.jsx(
          Badge,
          {
            variant: formatBoolean(attribute.required) ? "default" : "outline",
            children: formatBoolean(attribute.required) ? "Yes" : "No"
          }
        )
      },
      {
        key: "show_on_frontend",
        label: __("Frontend", "yatra"),
        sortable: true,
        visible: visibleColumns.show_on_frontend,
        render: (attribute) => /* @__PURE__ */ jsxRuntimeExports.jsx(
          Badge,
          {
            variant: formatBoolean(attribute.show_on_frontend) ? "default" : "outline",
            children: formatBoolean(attribute.show_on_frontend) ? "Yes" : "No"
          }
        )
      },
      {
        key: "show_in_filters",
        label: __("Filters", "yatra"),
        sortable: true,
        visible: visibleColumns.show_in_filters,
        render: (attribute) => /* @__PURE__ */ jsxRuntimeExports.jsx(
          Badge,
          {
            variant: formatBoolean(attribute.show_in_filters) ? "default" : "outline",
            children: formatBoolean(attribute.show_in_filters) ? "Yes" : "No"
          }
        )
      },
      {
        key: "searchable",
        label: __("Searchable", "yatra"),
        sortable: true,
        visible: visibleColumns.searchable,
        render: (attribute) => /* @__PURE__ */ jsxRuntimeExports.jsx(
          Badge,
          {
            variant: formatBoolean(attribute.searchable) ? "default" : "outline",
            children: formatBoolean(attribute.searchable) ? "Yes" : "No"
          }
        )
      },
      {
        key: "status",
        label: __("Status", "yatra"),
        sortable: true,
        visible: visibleColumns.status,
        render: (attribute) => /* @__PURE__ */ jsxRuntimeExports.jsx(
          "span",
          {
            className: `inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${attribute.status === "trash" || statusFilter === "trash" ? "bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400" : attribute.status === "publish" ? "bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400" : "bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400"}`,
            children: attribute.status === "trash" || statusFilter === "trash" ? __("Trash", "yatra") : attribute.status === "publish" ? __("Published", "yatra") : __("Draft", "yatra")
          }
        )
      },
      {
        key: "created_at",
        label: __("Created Date", "yatra"),
        sortable: true,
        visible: visibleColumns.created_at,
        render: (attribute) => /* @__PURE__ */ jsxRuntimeExports.jsx(
          "span",
          {
            className: attribute.status === "trash" || statusFilter === "trash" ? "text-gray-400 dark:text-gray-600" : "text-gray-600 dark:text-gray-400",
            children: new Date(attribute.created_at).toLocaleDateString("en-US", {
              year: "numeric",
              month: "short",
              day: "numeric",
              hour: "2-digit",
              minute: "2-digit"
            })
          }
        )
      },
      {
        key: "updated_at",
        label: __("Updated Date", "yatra"),
        sortable: true,
        visible: visibleColumns.updated_at,
        render: (attribute) => /* @__PURE__ */ jsxRuntimeExports.jsx(
          "span",
          {
            className: attribute.status === "trash" || statusFilter === "trash" ? "text-gray-400 dark:text-gray-600" : "text-gray-600 dark:text-gray-400",
            children: new Date(attribute.updated_at).toLocaleDateString("en-US", {
              year: "numeric",
              month: "short",
              day: "numeric",
              hour: "2-digit",
              minute: "2-digit"
            })
          }
        )
      },
      {
        key: "description",
        label: __("Description", "yatra"),
        visible: visibleColumns.description,
        render: (attribute) => /* @__PURE__ */ jsxRuntimeExports.jsx(
          "span",
          {
            className: attribute.status === "trash" || statusFilter === "trash" ? "text-gray-400 dark:text-gray-600" : "text-gray-600 dark:text-gray-400",
            children: attribute.description || __("No description", "yatra")
          }
        )
      },
      {
        key: "display_order",
        label: __("Order", "yatra"),
        sortable: true,
        visible: visibleColumns.display_order,
        render: (attribute) => /* @__PURE__ */ jsxRuntimeExports.jsx(
          "span",
          {
            className: attribute.status === "trash" || statusFilter === "trash" ? "text-gray-400 dark:text-gray-600" : "text-gray-600 dark:text-gray-400",
            children: attribute.display_order
          }
        )
      }
    ];
  }, [visibleColumns, statusFilter]);
  const hasFilters = !!(searchTerm || statusFilter !== "all" || sortBy2 !== "id" || sortOrder !== "desc");
  const toggleColumn = (columnKey) => {
    const next = { ...visibleColumns, [columnKey]: !visibleColumns[columnKey] };
    setVisibleColumns(next);
    localStorage.setItem("yatra-attributes-columns", JSON.stringify(next));
  };
  const viewFilters = [
    { key: "all", label: __("All", "yatra"), count: statusCounts.all ?? 0 },
    {
      key: "publish",
      label: __("Published", "yatra"),
      count: statusCounts.publish ?? 0
    },
    {
      key: "draft",
      label: __("Draft", "yatra"),
      count: statusCounts.draft ?? 0
    },
    {
      key: "trash",
      label: __("Trash", "yatra"),
      count: statusCounts.trash ?? 0
    }
  ];
  const handlePermanentDelete = (attribute) => {
    setPermanentDeleteConfirm({ isOpen: true, attribute });
  };
  const confirmPermanentDelete = () => {
    if (permanentDeleteConfirm.attribute) {
      bulkMutation.mutate({
        action: "delete",
        ids: [permanentDeleteConfirm.attribute.id]
      });
      setPermanentDeleteConfirm({ isOpen: false, attribute: null });
    }
  };
  const confirmIndividualAction = () => {
    if (individualActionConfirm.attribute) {
      const action = individualActionConfirm.action === "restore" ? "restore" : "trash";
      bulkMutation.mutate({
        action,
        ids: [individualActionConfirm.attribute.id]
      });
      setIndividualActionConfirm({
        isOpen: false,
        action: "",
        attribute: null
      });
    }
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      ConfirmationDialog,
      {
        isOpen: permanentDeleteConfirm.isOpen,
        onClose: () => setPermanentDeleteConfirm({ isOpen: false, attribute: null }),
        onConfirm: confirmPermanentDelete,
        title: __("Delete Attribute Permanently", "yatra"),
        message: permanentDeleteConfirm.attribute ? __(
          'Are you sure you want to permanently delete "{name}"? This action cannot be undone.',
          "yatra"
        ).replace("{name}", permanentDeleteConfirm.attribute.name) : __(
          "Are you sure you want to permanently delete this attribute? This action cannot be undone.",
          "yatra"
        ),
        confirmText: __("Delete Permanently", "yatra"),
        cancelText: __("Cancel", "yatra"),
        variant: "danger",
        isLoading: bulkMutation.isPending
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      ConfirmationDialog,
      {
        isOpen: individualActionConfirm.isOpen,
        onClose: () => setIndividualActionConfirm({
          isOpen: false,
          action: "",
          attribute: null
        }),
        onConfirm: confirmIndividualAction,
        title: individualActionConfirm.action === "trash" ? __("Move to Trash", "yatra") : __("Restore Attribute", "yatra"),
        message: individualActionConfirm.attribute ? individualActionConfirm.action === "trash" ? __(
          'Are you sure you want to move "{name}" to trash?',
          "yatra"
        ).replace("{name}", individualActionConfirm.attribute.name) : __(
          'Are you sure you want to restore "{name}"?',
          "yatra"
        ).replace("{name}", individualActionConfirm.attribute.name) : individualActionConfirm.action === "trash" ? __(
          "Are you sure you want to move this attribute to trash?",
          "yatra"
        ) : __("Are you sure you want to restore this attribute?", "yatra"),
        confirmText: individualActionConfirm.action === "trash" ? __("Move to Trash", "yatra") : __("Restore", "yatra"),
        cancelText: __("Cancel", "yatra"),
        variant: "warning",
        isLoading: bulkMutation.isPending
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      PageHeader,
      {
        title: __("Attributes", "yatra"),
        description: __(
          "Manage your travel attributes and their properties",
          "yatra"
        ),
        actionCapability: "yatra_edit_trips",
        actions: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Button,
          {
            onClick: handleCreateAttribute,
            className: "flex items-center gap-2",
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Plus, { className: "w-4 h-4" }),
              __("Add New Attribute", "yatra")
            ]
          }
        )
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-3", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
      SearchFilterToolbar,
      {
        searchTerm,
        onSearchChange: setSearchTerm,
        statusFilter,
        onStatusChange: (value) => {
          setStatusFilter(value);
          setPage(1);
          setSelectedIds([]);
          setBulkAction("");
        },
        statusOptions: [
          { value: "all", label: __("All Status", "yatra") },
          { value: "publish", label: __("Published", "yatra") },
          { value: "draft", label: __("Draft", "yatra") },
          { value: "trash", label: __("Trash", "yatra") }
        ],
        sortBy: sortBy2,
        onSortByChange: setSortBy,
        sortOrder,
        onSortOrderChange: setSortOrder,
        sortOptions: [
          { value: "id", label: __("ID", "yatra") },
          { value: "name", label: __("Name", "yatra") },
          { value: "field_type", label: __("Field Type", "yatra") },
          { value: "status", label: __("Status", "yatra") },
          { value: "created_at", label: __("Created At", "yatra") },
          { value: "updated_at", label: __("Updated At", "yatra") }
        ],
        onResetFilters: handleResetFilters,
        hasFilters,
        placeholder: __("Search attributes...", "yatra")
      }
    ) }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_view_trips", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
      !isAttributesError && /* @__PURE__ */ jsxRuntimeExports.jsx(
        BulkActionToolbar,
        {
          selectedIds,
          bulkAction,
          setBulkAction,
          onApply: handleBulkApply,
          onClearSelection: () => setSelectedIds([]),
          statusFilter,
          setStatusFilter: (value) => {
            setStatusFilter(value);
            setPage(1);
            setSelectedIds([]);
            setBulkAction("");
          },
          statusOptions: viewFilters,
          showColumnsDropdown,
          setShowColumnsDropdown,
          columnOptions: [
            {
              key: "name",
              label: __("Attribute", "yatra"),
              visible: visibleColumns.name
            },
            {
              key: "field_type",
              label: __("Field Type", "yatra"),
              visible: visibleColumns.field_type
            },
            {
              key: "required",
              label: __("Required", "yatra"),
              visible: visibleColumns.required
            },
            {
              key: "show_on_frontend",
              label: __("Frontend", "yatra"),
              visible: visibleColumns.show_on_frontend
            },
            {
              key: "show_in_filters",
              label: __("Filters", "yatra"),
              visible: visibleColumns.show_in_filters
            },
            {
              key: "searchable",
              label: __("Searchable", "yatra"),
              visible: visibleColumns.searchable
            },
            {
              key: "status",
              label: __("Status", "yatra"),
              visible: visibleColumns.status
            },
            {
              key: "created_at",
              label: __("Created", "yatra"),
              visible: visibleColumns.created_at
            },
            {
              key: "updated_at",
              label: __("Updated", "yatra"),
              visible: visibleColumns.updated_at
            },
            {
              key: "description",
              label: __("Description", "yatra"),
              visible: visibleColumns.description
            },
            {
              key: "display_order",
              label: __("Display Order", "yatra"),
              visible: visibleColumns.display_order
            }
          ],
          onToggleColumn: toggleColumn,
          bulkMutationPending: bulkMutation.isPending,
          totalItems: total,
          bulkActionOptions: getDefaultBulkStatusOptions(statusFilter)
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { className: "overflow-visible", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-0 overflow-visible", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        Table,
        {
          data: attributes,
          columns: attributeColumns,
          actions: [
            {
              key: "edit",
              label: __("Edit", "yatra"),
              icon: /* @__PURE__ */ jsxRuntimeExports.jsx(PenSquare, { className: "w-4 h-4" }),
              onClick: handleEdit,
              condition: () => can("yatra_view_trips")
            },
            {
              key: "restore",
              label: __("Restore", "yatra"),
              icon: /* @__PURE__ */ jsxRuntimeExports.jsx(RotateCcw, { className: "w-4 h-4" }),
              onClick: (attribute) => bulkMutation.mutate({
                action: "restore",
                ids: [attribute.id]
              }),
              condition: (attribute) => (attribute.status === "trash" || statusFilter === "trash") && can("yatra_view_trips")
            },
            {
              key: "trash",
              label: __("Move to Trash", "yatra"),
              icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "w-4 h-4" }),
              onClick: (attribute) => bulkMutation.mutate({
                action: "trash",
                ids: [attribute.id]
              }),
              condition: (attribute) => attribute.status !== "trash" && statusFilter !== "trash" && can("yatra_view_trips")
            },
            {
              key: "delete",
              label: __("Delete Permanently", "yatra"),
              icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "w-4 h-4" }),
              onClick: handlePermanentDelete,
              condition: (attribute) => (attribute.status === "trash" || statusFilter === "trash") && can("yatra_view_trips"),
              variant: "destructive"
            }
          ],
          isLoading,
          isError: isAttributesError,
          errorText: __("Failed to load attributes", "yatra"),
          errorDescription: __(
            "We couldn’t connect to the attributes service. Please refresh or try again shortly.",
            "We couldn’t connect to the attributes service. Please refresh or try again shortly."
          ),
          errorDetails: errorContext.details || apiErrorMessage,
          errorRequestInfo: errorContext.requestInfo,
          onRetry: () => queryClient2.invalidateQueries({ queryKey: ["attributes"] }),
          emptyText: __("No attributes found", "yatra"),
          emptyDescription: hasFilters ? __(
            "Try adjusting your filters to see more results.",
            "yatra"
          ) : __(
            "Get started by creating your first attribute.",
            "yatra"
          ),
          onCreateClick: can("yatra_view_trips") ? handleCreateAttribute : void 0,
          onSort: handleSort,
          selectedItemIds: selectedIds,
          onSelectItem: (id, checked) => {
            if (checked) {
              setSelectedIds([...selectedIds, id]);
            } else {
              setSelectedIds(
                selectedIds.filter((selectedId) => selectedId !== id)
              );
            }
          },
          onSelectAll: (checked) => {
            if (checked) {
              setSelectedIds(attributes.map((a2) => a2.id));
            } else {
              setSelectedIds([]);
            }
          },
          isAllSelected: attributes.length > 0 && selectedIds.length === attributes.length,
          getItemId: (attribute) => attribute.id,
          getItemStatus: (attribute) => attribute.status,
          statusFilter,
          skeletonRows: 5,
          capability: "yatra_view_trips"
        }
      ) }) })
    ] }) }),
    total > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-4", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
      Pagination,
      {
        currentPage: page,
        totalPages,
        totalItems: total,
        itemsPerPage: 10,
        onPageChange: (newPage) => setPage(newPage),
        itemName: __("attributes", "yatra")
      }
    ) })
  ] });
};
function parseFieldOptionRows(raw) {
  if (Array.isArray(raw)) {
    return raw.map((o) => ({
      label: String((o == null ? void 0 : o.label) ?? ""),
      value: String((o == null ? void 0 : o.value) ?? "")
    }));
  }
  if (typeof raw === "string" && raw.trim()) {
    try {
      const p = JSON.parse(raw);
      if (Array.isArray(p)) {
        return p.map((o) => ({
          label: String((o == null ? void 0 : o.label) ?? ""),
          value: String((o == null ? void 0 : o.value) ?? "")
        }));
      }
    } catch {
      return [];
    }
  }
  return [];
}
function unwrapAttributePayload(raw) {
  if (raw == null || typeof raw !== "object") {
    return {};
  }
  const o = raw;
  if ("id" in o) {
    return o;
  }
  const inner = o.data;
  if (inner && typeof inner === "object" && !Array.isArray(inner) && "id" in inner) {
    return inner;
  }
  return {};
}
function iconFromAttributeApiRaw(raw) {
  if (raw == null || raw === "") {
    return null;
  }
  let ic = raw;
  if (typeof ic === "string") {
    const t = ic.trim();
    if (t.startsWith("{")) {
      try {
        ic = JSON.parse(t);
      } catch {
        return t ? { type: "icon", value: t, provider: "yatra" } : null;
      }
    } else if (t !== "") {
      return { type: "icon", value: t, provider: "yatra" };
    } else {
      return null;
    }
  }
  if (typeof ic !== "object" || ic === null || Array.isArray(ic)) {
    return null;
  }
  const io = ic;
  const val = io.value !== void 0 && io.value !== null ? String(io.value) : "";
  if (io.type === "image") {
    if (!val) {
      return null;
    }
    return { type: "image", value: val };
  }
  if (val === "") {
    return null;
  }
  const p = io.provider;
  const provider = p === "fa-solid" || p === "fa-regular" || p === "yatra" ? p : "yatra";
  return { type: "icon", value: val, provider };
}
function normalizeAttributeStatusForForm(raw) {
  const s2 = typeof raw === "string" ? raw.trim().toLowerCase() : "";
  if (s2 === "publish" || s2 === "draft" || s2 === "trash") {
    return s2;
  }
  return "publish";
}
const AttributeForm = () => {
  const queryClient2 = useQueryClient();
  const { showToast } = useToast();
  const [formData, setFormData] = reactExports.useState({
    name: "",
    slug: "",
    description: "",
    icon: null,
    field_type: "text_field",
    field_option_rows: [],
    default_value: "",
    placeholder: "",
    required: false,
    validation_rules: "",
    display_order: 0,
    show_on_frontend: true,
    show_in_filters: false,
    filter_type: "dropdown",
    searchable: false,
    status: "publish"
  });
  const [errors, setErrors] = reactExports.useState({});
  const [isSubmitting, setIsSubmitting] = reactExports.useState(false);
  const [isSlugEditable, setIsSlugEditable] = reactExports.useState(false);
  const action = reactExports.useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get("action") || "create";
  }, []);
  const attributeId = reactExports.useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get("id");
  }, []);
  const isEditMode = action === "edit" && attributeId;
  const fieldTypeOptions2 = [
    { value: "text_field", label: "Text Field" },
    { value: "textarea", label: "Textarea" },
    { value: "number", label: "Number" },
    { value: "email", label: "Email" },
    { value: "url", label: "URL" },
    { value: "date", label: "Date" },
    { value: "time", label: "Time" },
    { value: "color", label: "Color" },
    { value: "select", label: "Select Dropdown" },
    { value: "radio", label: "Radio Buttons" },
    { value: "checkbox", label: "Checkbox" },
    { value: "file", label: "File Upload" }
  ];
  const handleFieldChange = (field, value) => {
    if (field === "field_type") {
      setFormData((prev) => {
        const nextNeeds = value === "select" || value === "radio" || value === "checkbox";
        const wasNeeds = prev.field_type === "select" || prev.field_type === "radio" || prev.field_type === "checkbox";
        let rows = prev.field_option_rows;
        if (nextNeeds && !wasNeeds && rows.length === 0) {
          rows = [{ label: "", value: "" }];
        }
        return { ...prev, field_type: value, field_option_rows: rows };
      });
      if (errors.field_type) {
        setErrors((prev) => ({ ...prev, field_type: "" }));
      }
      if (errors.field_options) {
        setErrors((prev) => ({ ...prev, field_options: "" }));
      }
      return;
    }
    setFormData((prev) => ({ ...prev, [field]: value }));
    if (field === "name" && !isEditMode && !isSlugEditable) {
      setFormData((prev) => ({
        ...prev,
        name: value,
        slug: generateSlug(value)
      }));
    }
    if (errors[field]) {
      setErrors((prev) => ({ ...prev, [field]: "" }));
    }
  };
  const updateOptionRow = (index, key2, val) => {
    setFormData((prev) => {
      const next = [...prev.field_option_rows];
      next[index] = { ...next[index], [key2]: val };
      return { ...prev, field_option_rows: next };
    });
    if (errors.field_options) {
      setErrors((prev) => ({ ...prev, field_options: "" }));
    }
  };
  const addOptionRow = () => {
    setFormData((prev) => ({
      ...prev,
      field_option_rows: [...prev.field_option_rows, { label: "", value: "" }]
    }));
  };
  const removeOptionRow = (index) => {
    setFormData((prev) => ({
      ...prev,
      field_option_rows: prev.field_option_rows.filter((_, i) => i !== index)
    }));
  };
  const generateUniqueSlug = async (baseSlug) => {
    try {
      const response = await apiClient.get(
        `/attributes/check-slug?slug=${encodeURIComponent(baseSlug)}${isEditMode && attributeId ? `&exclude_id=${attributeId}` : ""}`
      );
      if (response.data.exists && response.data.suggested_slug) {
        return response.data.suggested_slug;
      }
      return baseSlug;
    } catch (error) {
      let slug = baseSlug;
      let counter = 1;
      while (counter <= 100) {
        const testSlug = counter === 1 ? baseSlug : `${baseSlug}-${counter}`;
        {
          return testSlug;
        }
      }
      return slug;
    }
  };
  const toggleSlugEdit = () => {
    if (isSlugEditable) {
      const newSlug = generateSlug(formData.name);
      setFormData((prev) => ({ ...prev, slug: newSlug }));
    }
    setIsSlugEditable(!isSlugEditable);
  };
  const validateForm = () => {
    const newErrors = {};
    if (!formData.name.trim()) {
      newErrors.name = __("Name is required", "yatra");
    }
    if (!formData.field_type) {
      newErrors.field_type = __("Field type is required", "yatra");
    }
    if (formData.field_type === "select" || formData.field_type === "radio" || formData.field_type === "checkbox") {
      const built = formData.field_option_rows.map((r2) => {
        const label = r2.label.trim();
        const value = r2.value.trim() || (label ? generateSlug(label) : "");
        return { label, value };
      }).filter((r2) => r2.label !== "" && r2.value !== "");
      if (built.length === 0) {
        newErrors.field_options = __(
          "Add at least one option with a label (value can be left blank to auto-generate from the label).",
          "yatra"
        );
      }
    }
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };
  const {
    data: attribute,
    isLoading: isLoadingAttribute,
    error: attributeError
  } = useQuery({
    queryKey: ["attribute", attributeId],
    queryFn: async () => {
      if (!attributeId) return null;
      const response = await apiClient.get(`/attributes/${attributeId}`);
      return response;
    },
    enabled: Boolean(isEditMode),
    retry: 2,
    retryDelay: 1e3
  });
  const fetchDirectDatabaseValues = async (attributeId2) => {
    var _a;
    try {
      const data = await ajaxService.post("yatra_get_attribute_direct", {
        attribute_id: attributeId2,
        nonce: ((_a = window.yatraAdmin) == null ? void 0 : _a.nonce) || ""
      });
      if ((data == null ? void 0 : data.success) && (data == null ? void 0 : data.data)) {
        return data.data;
      }
    } catch (error) {
      console.warn("Direct database query failed", { error, attributeId: attributeId2 });
    }
    return null;
  };
  reactExports.useEffect(() => {
    if (!attribute || !attributeId) {
      return;
    }
    const fromRest = unwrapAttributePayload(attribute);
    fetchDirectDatabaseValues(Number(attributeId) || 0).then((directData) => {
      const direct = directData && typeof directData === "object" ? directData : {};
      const finalAttribute = { ...fromRest, ...direct };
      const convertedData = {
        name: String(finalAttribute.name ?? ""),
        slug: String(finalAttribute.slug ?? ""),
        description: String(finalAttribute.description ?? ""),
        icon: iconFromAttributeApiRaw(finalAttribute.icon),
        field_type: String(finalAttribute.field_type ?? "text_field"),
        field_option_rows: (() => {
          const rows = parseFieldOptionRows(finalAttribute.field_options);
          return rows.length > 0 ? rows : ["select", "radio", "checkbox"].includes(
            String(finalAttribute.field_type ?? "")
          ) ? [{ label: "", value: "" }] : [];
        })(),
        default_value: String(finalAttribute.default_value ?? ""),
        placeholder: String(finalAttribute.placeholder ?? ""),
        required: finalAttribute.required === "1" || finalAttribute.required === 1 || finalAttribute.required === true,
        validation_rules: String(finalAttribute.validation_rules ?? ""),
        display_order: Number(finalAttribute.display_order) || 0,
        show_on_frontend: finalAttribute.show_on_frontend === "1" || finalAttribute.show_on_frontend === 1 || finalAttribute.show_on_frontend === true,
        show_in_filters: finalAttribute.show_in_filters === "1" || finalAttribute.show_in_filters === 1 || finalAttribute.show_in_filters === true,
        filter_type: String(finalAttribute.filter_type ?? "dropdown"),
        searchable: finalAttribute.searchable === "1" || finalAttribute.searchable === 1 || finalAttribute.searchable === true,
        status: normalizeAttributeStatusForForm(finalAttribute.status)
      };
      setFormData(convertedData);
    });
  }, [attribute, attributeId]);
  reactExports.useEffect(() => {
    if (attributeError) {
      showToast(__("Failed to load attribute data", "yatra"), "error");
    }
  }, [attributeError, showToast]);
  const saveMutation = useMutation({
    mutationFn: async (data) => {
      let slug = data.slug.trim();
      if (!isEditMode) {
        slug = await generateUniqueSlug(slug);
      }
      const needsOptionRows = data.field_type === "select" || data.field_type === "radio" || data.field_type === "checkbox";
      const fieldOptionsPayload = needsOptionRows ? data.field_option_rows.map((r2) => {
        const label = r2.label.trim();
        const value = r2.value.trim() || (label ? generateSlug(label) : "");
        return { label, value };
      }).filter((r2) => r2.label !== "" && r2.value !== "") : [];
      const payload = {
        name: data.name.trim(),
        slug,
        description: data.description.trim(),
        icon: data.icon,
        field_type: data.field_type,
        default_value: data.default_value.trim(),
        placeholder: data.placeholder.trim(),
        required: Boolean(data.required),
        validation_rules: data.validation_rules.trim(),
        display_order: Number(data.display_order),
        show_on_frontend: Boolean(data.show_on_frontend),
        show_in_filters: Boolean(data.show_in_filters),
        filter_type: data.filter_type,
        searchable: Boolean(data.searchable),
        status: normalizeAttributeStatusForForm(data.status)
      };
      if (needsOptionRows) {
        payload.field_options = fieldOptionsPayload;
      }
      if (isEditMode && isSlugEditable) {
        payload.preserve_slug = true;
      }
      try {
        if (isEditMode && attributeId) {
          const response = await apiClient.put(
            `/attributes/${attributeId}`,
            payload
          );
          return response;
        } else {
          const response = await apiClient.post("/attributes", payload);
          return response;
        }
      } catch (error) {
        throw error;
      }
    },
    onSuccess: (response) => {
      var _a, _b, _c;
      setIsSubmitting(false);
      queryClient2.invalidateQueries({ queryKey: ["attributes"] });
      queryClient2.invalidateQueries({ queryKey: ["attributes-stats"] });
      if (attributeId) {
        queryClient2.invalidateQueries({ queryKey: ["attribute", attributeId] });
      }
      showToast(
        isEditMode ? __("Attribute updated successfully", "yatra") : __("Attribute created successfully", "yatra"),
        "success"
      );
      if (!isEditMode) {
        const newId = ((_a = response == null ? void 0 : response.data) == null ? void 0 : _a.id) || (response == null ? void 0 : response.id) || ((_c = (_b = response == null ? void 0 : response.data) == null ? void 0 : _b.data) == null ? void 0 : _c.id);
        if (newId) {
          setTimeout(() => {
            var _a2;
            window.location.href = `${((_a2 = window.yatraAdmin) == null ? void 0 : _a2.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=trips&tab=attributes&action=edit&id=${newId}`;
          }, 1e3);
        } else {
          console.error(
            "AttributeForm - Could not extract ID from response for redirect"
          );
        }
      }
    },
    onError: (error) => {
      const errorMessage = (error == null ? void 0 : error.message) || __("An error occurred while saving the attribute", "yatra");
      showToast(errorMessage, "error");
      setIsSubmitting(false);
    }
  });
  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!validateForm()) {
      return;
    }
    setIsSubmitting(true);
    saveMutation.mutate(formData);
  };
  const handleCancel = () => {
    var _a;
    window.location.href = `${((_a = window.yatraAdmin) == null ? void 0 : _a.siteUrl) || ""}/wp-admin/admin.php?page=yatra&subpage=trips&tab=attributes`;
  };
  if (isLoadingAttribute) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-8 bg-gray-200 dark:bg-gray-700 rounded w-48 mb-2 animate-pulse" }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-3 gap-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "lg:col-span-2 space-y-3", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "p-6 space-y-4", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-16 mb-2 animate-pulse" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-24 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" })
          ] }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "p-6 space-y-4", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-20 mb-2 animate-pulse" }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-2 gap-4", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-40 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" })
          ] }) })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "p-6 space-y-4", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-12 mb-2 animate-pulse" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" })
          ] }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "p-6 space-y-4", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 bg-gray-200 dark:bg-gray-700 rounded w-16 mb-2 animate-pulse" }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-8 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-8 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-8 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-8 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" })
            ] })
          ] }) })
        ] })
      ] })
    ] });
  }
  if (attributeError && isEditMode) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        PageHeader,
        {
          title: __("Error Loading Attribute", "yatra"),
          description: __(
            "Unable to load attribute data. Please try again.",
            "yatra"
          ),
          actions: /* @__PURE__ */ jsxRuntimeExports.jsxs(
            Button,
            {
              variant: "outline",
              onClick: handleCancel,
              className: "flex items-center gap-2",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowLeft, { className: "w-4 h-4" }),
                __("Back", "yatra")
              ]
            }
          )
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "p-6 text-center", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-red-500 mb-4", children: __(
          "Failed to load attribute data. The attribute may not exist or there might be a server error.",
          "yatra"
        ) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { variant: "outline", onClick: () => window.location.reload(), children: __("Try Again", "yatra") })
      ] }) })
    ] });
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      PageHeader,
      {
        title: isEditMode ? __("Edit Attribute", "yatra") : __("Add New Attribute", "yatra"),
        description: isEditMode ? __("Update attribute information", "yatra") : __("Create a new trip attribute", "yatra"),
        actions: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Button,
          {
            variant: "outline",
            onClick: handleCancel,
            className: "flex items-center gap-2",
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowLeft, { className: "w-4 h-4" }),
              __("Back", "yatra")
            ]
          }
        )
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(ConditionalRender, { capability: "yatra_edit_trips", children: /* @__PURE__ */ jsxRuntimeExports.jsx("form", { onSubmit: handleSubmit, children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-3 gap-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "lg:col-span-2 space-y-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Basic Information", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs(
                "label",
                {
                  htmlFor: "name",
                  className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                  children: [
                    __("Name", "yatra"),
                    " ",
                    /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
                  ]
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Input,
                {
                  id: "name",
                  value: formData.name,
                  onChange: (e) => handleFieldChange("name", e.target.value),
                  placeholder: __("Enter attribute name", "yatra"),
                  className: errors.name ? "border-red-500" : ""
                }
              ),
              errors.name && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm text-red-500", children: errors.name })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "label",
                {
                  htmlFor: "slug",
                  className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                  children: __("Slug", "yatra")
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Input,
                  {
                    id: "slug",
                    value: formData.slug,
                    onChange: (e) => handleFieldChange("slug", e.target.value),
                    placeholder: __("attribute-slug", "yatra"),
                    disabled: !isSlugEditable,
                    className: `flex-1 ${errors.slug ? "border-red-500" : ""}`
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Button,
                  {
                    type: "button",
                    variant: "outline",
                    size: "sm",
                    onClick: toggleSlugEdit,
                    className: "px-3 py-2",
                    children: isSlugEditable ? /* @__PURE__ */ jsxRuntimeExports.jsx(Save, { className: "w-4 h-4" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(Pen, { className: "w-4 h-4" })
                  }
                )
              ] }),
              isSlugEditable ? /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-xs text-gray-500 dark:text-gray-400", children: __(
                "Click the save icon to preserve your custom slug.",
                "yatra"
              ) }) : /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-xs text-gray-500 dark:text-gray-400", children: __(
                "Auto-generated from name. Click edit icon to customize.",
                "yatra"
              ) })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "label",
                {
                  htmlFor: "description",
                  className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                  children: __("Description", "yatra")
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "textarea",
                {
                  id: "description",
                  value: formData.description,
                  onChange: (e) => handleFieldChange("description", e.target.value),
                  placeholder: __("Enter attribute description", "yatra"),
                  rows: 6,
                  className: "flex w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm ring-offset-white placeholder:text-gray-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 dark:border-gray-600 dark:bg-gray-800 dark:ring-offset-gray-900 dark:placeholder:text-gray-400 dark:focus-visible:ring-blue-400 resize-none"
                }
              )
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Field Configuration", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-3", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs(
                  "label",
                  {
                    htmlFor: "field_type",
                    className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                    children: [
                      __("Field Type", "yatra"),
                      " ",
                      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
                    ]
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Select,
                  {
                    id: "field_type",
                    value: formData.field_type,
                    onChange: (e) => handleFieldChange("field_type", e.target.value),
                    className: errors.field_type ? "border-red-500" : "",
                    children: fieldTypeOptions2.map((option) => /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: option.value, children: option.label }, option.value))
                  }
                ),
                errors.field_type && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm text-red-500", children: errors.field_type })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "label",
                  {
                    htmlFor: "display_order",
                    className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                    children: __("Display Order", "yatra")
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Input,
                  {
                    id: "display_order",
                    type: "number",
                    value: formData.display_order,
                    onChange: (e) => handleFieldChange(
                      "display_order",
                      parseInt(e.target.value) || 0
                    ),
                    placeholder: "0"
                  }
                )
              ] })
            ] }),
            (formData.field_type === "select" || formData.field_type === "radio" || formData.field_type === "checkbox") && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between mb-1.5", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("label", { className: "block text-sm font-medium text-gray-700 dark:text-gray-300", children: [
                  __("Field Options", "yatra"),
                  " ",
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-red-500", children: "*" })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs(
                  Button,
                  {
                    type: "button",
                    variant: "outline",
                    size: "sm",
                    className: "gap-1 h-8",
                    onClick: addOptionRow,
                    children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx(Plus, { className: "w-3.5 h-3.5" }),
                      __("Add option", "yatra")
                    ]
                  }
                )
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400 mb-2", children: __(
                "Each row is one choice. Leave value empty to auto-generate a slug from the label.",
                "yatra"
              ) }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "div",
                {
                  className: `space-y-2 rounded-md border p-3 ${errors.field_options ? "border-red-500" : "border-gray-200 dark:border-gray-600"}`,
                  children: (formData.field_option_rows.length > 0 ? formData.field_option_rows : [{ label: "", value: "" }]).map((row, index) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
                    "div",
                    {
                      className: "flex flex-col sm:flex-row gap-2 sm:items-end",
                      children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1 min-w-0", children: [
                          /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "text-xs text-gray-500 dark:text-gray-400 block mb-1", children: __("Label", "yatra") }),
                          /* @__PURE__ */ jsxRuntimeExports.jsx(
                            Input,
                            {
                              value: row.label,
                              onChange: (e) => {
                                if (formData.field_option_rows.length === 0) {
                                  setFormData((prev) => ({
                                    ...prev,
                                    field_option_rows: [
                                      {
                                        label: e.target.value,
                                        value: ""
                                      }
                                    ]
                                  }));
                                } else {
                                  updateOptionRow(
                                    index,
                                    "label",
                                    e.target.value
                                  );
                                }
                              },
                              placeholder: __("Display name", "yatra")
                            }
                          )
                        ] }),
                        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1 min-w-0", children: [
                          /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: "text-xs text-gray-500 dark:text-gray-400 block mb-1", children: __("Value", "yatra") }),
                          /* @__PURE__ */ jsxRuntimeExports.jsx(
                            Input,
                            {
                              value: row.value,
                              onChange: (e) => {
                                if (formData.field_option_rows.length === 0) {
                                  setFormData((prev) => ({
                                    ...prev,
                                    field_option_rows: [
                                      {
                                        label: "",
                                        value: e.target.value
                                      }
                                    ]
                                  }));
                                } else {
                                  updateOptionRow(
                                    index,
                                    "value",
                                    e.target.value
                                  );
                                }
                              },
                              placeholder: __(
                                "Stored value (optional)",
                                "yatra"
                              )
                            }
                          )
                        ] }),
                        /* @__PURE__ */ jsxRuntimeExports.jsx(
                          Button,
                          {
                            type: "button",
                            variant: "ghost",
                            size: "sm",
                            className: "text-red-600 hover:text-red-700 shrink-0",
                            onClick: () => removeOptionRow(index),
                            disabled: formData.field_option_rows.length <= 1,
                            "aria-label": __("Remove option", "yatra"),
                            children: /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "w-4 h-4" })
                          }
                        )
                      ]
                    },
                    index
                  ))
                }
              ),
              errors.field_options && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-1 text-sm text-red-500", children: errors.field_options })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "label",
                {
                  htmlFor: "default_value",
                  className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                  children: __("Default Value", "yatra")
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Input,
                {
                  id: "default_value",
                  value: formData.default_value,
                  onChange: (e) => handleFieldChange("default_value", e.target.value),
                  placeholder: __("Default value for the field", "yatra")
                }
              )
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "label",
                {
                  htmlFor: "placeholder",
                  className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                  children: __("Placeholder", "yatra")
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Input,
                {
                  id: "placeholder",
                  value: formData.placeholder,
                  onChange: (e) => handleFieldChange("placeholder", e.target.value),
                  placeholder: __(
                    "Placeholder text for input field",
                    "yatra"
                  )
                }
              )
            ] })
          ] })
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Status", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "space-y-3", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "label",
              {
                htmlFor: "status",
                className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5",
                children: __("Status", "yatra")
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              Select,
              {
                id: "status",
                value: formData.status,
                onChange: (e) => handleFieldChange("status", e.target.value),
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "draft", children: __("Draft", "yatra") }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "publish", children: __("Publish", "yatra") }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("option", { value: "trash", children: __("Trash", "yatra") })
                ]
              }
            )
          ] }) })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Field Options", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "space-y-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "label",
                {
                  htmlFor: "show_on_frontend",
                  className: "text-sm font-medium text-gray-700 dark:text-gray-300 cursor-pointer",
                  children: __("Show on Frontend", "yatra")
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Switch,
                {
                  checked: formData.show_on_frontend,
                  onCheckedChange: (checked) => handleFieldChange("show_on_frontend", checked)
                }
              )
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "label",
                {
                  htmlFor: "show_in_filters",
                  className: "text-sm font-medium text-gray-700 dark:text-gray-300 cursor-pointer",
                  children: __("Show in Filters", "yatra")
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Switch,
                {
                  checked: formData.show_in_filters,
                  onCheckedChange: (checked) => handleFieldChange("show_in_filters", checked)
                }
              )
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "label",
                {
                  htmlFor: "searchable",
                  className: "text-sm font-medium text-gray-700 dark:text-gray-300 cursor-pointer",
                  children: __("Searchable", "yatra")
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Switch,
                {
                  checked: formData.searchable,
                  onCheckedChange: (checked) => handleFieldChange("searchable", checked)
                }
              )
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "label",
                {
                  htmlFor: "required",
                  className: "text-sm font-medium text-gray-700 dark:text-gray-300 cursor-pointer",
                  children: __("Required Field", "yatra")
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Switch,
                {
                  checked: formData.required,
                  onCheckedChange: (checked) => handleFieldChange("required", checked)
                }
              )
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardTitle, { className: "text-base", children: __("Attribute Icon", "yatra") }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            IconPicker,
            {
              value: formData.icon,
              onChange: (value) => handleFieldChange("icon", value),
              label: __("Icon or Image", "yatra"),
              helpText: __(
                "Select an icon from the library or upload a custom image for this attribute.",
                "yatra"
              ),
              allowImageUpload: true,
              allowIconSelection: true,
              size: "md"
            }
          ) })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-3", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-2", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Button,
            {
              type: "submit",
              disabled: isSubmitting,
              className: "flex-1 flex items-center justify-center gap-2",
              children: isSubmitting ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Loader2, { className: "w-4 h-4 animate-spin" }),
                __("Saving...", "yatra")
              ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Save, { className: "w-4 h-4" }),
                isEditMode ? __("Update Attribute", "yatra") : __("Create Attribute", "yatra")
              ] })
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            Button,
            {
              type: "button",
              variant: "outline",
              onClick: handleCancel,
              disabled: isSubmitting,
              children: __("Cancel", "yatra")
            }
          )
        ] }) }) }) })
      ] })
    ] }) }) })
  ] });
};
const License = () => {
  var _a, _b, _c, _d, _e, _f, _g, _h;
  const [licenseKey, setLicenseKey] = reactExports.useState("");
  const [showKey, setShowKey] = reactExports.useState(false);
  const [debugMode, setDebugMode] = reactExports.useState(false);
  const [debugData, setDebugData] = reactExports.useState(null);
  const [showDeactivateConfirm, setShowDeactivateConfirm] = reactExports.useState(false);
  const queryClient2 = useQueryClient();
  const { showToast } = useToast();
  const yatraAdmin = window == null ? void 0 : window.yatraAdmin;
  const isPro = (yatraAdmin == null ? void 0 : yatraAdmin.isPro) || false;
  const { data: licenseData, isLoading } = useQuery({
    queryKey: ["license"],
    queryFn: async () => {
      const response = await apiClient.get("/license");
      return response;
    }
  });
  reactExports.useEffect(() => {
    var _a2;
    if ((_a2 = licenseData == null ? void 0 : licenseData.license_info) == null ? void 0 : _a2.key) {
      setLicenseKey(licenseData.license_info.key);
    }
  }, [licenseData]);
  const activateMutation = useMutation({
    mutationFn: async (key2) => {
      try {
        const response = await apiClient.post("/license/activate", {
          license_key: key2
        });
        return response;
      } catch (error) {
        console.error("License activation error:", error);
        throw error;
      }
    },
    onSuccess: (data) => {
      const debugInfo = {
        type: "activate",
        request: { license_key: licenseKey },
        response: data,
        timestamp: (/* @__PURE__ */ new Date()).toISOString()
      };
      setDebugData(debugInfo);
      if ((data == null ? void 0 : data.status) === "valid") {
        showToast(data.notice || "License activated successfully!", "success");
        queryClient2.invalidateQueries({ queryKey: ["license"] });
        window.dispatchEvent(
          new CustomEvent("yatra-license-status-updated", {
            detail: { status: "active" }
          })
        );
      } else {
        showToast((data == null ? void 0 : data.notice) || "License activation failed.", "error");
      }
    },
    onError: (error) => {
      var _a2, _b2, _c2, _d2;
      const errorMsg = ((_b2 = (_a2 = error.response) == null ? void 0 : _a2.data) == null ? void 0 : _b2.message) || "Failed to activate license. Please try again.";
      showToast(errorMsg, "error");
      setDebugData({
        type: "activate",
        request: { license_key: licenseKey },
        response: (_c2 = error.response) == null ? void 0 : _c2.data,
        error: ((_d2 = error.response) == null ? void 0 : _d2.data) || error.message,
        timestamp: (/* @__PURE__ */ new Date()).toISOString()
      });
    }
  });
  const deactivateMutation = useMutation({
    mutationFn: async () => {
      const response = await apiClient.post("/license/deactivate");
      return response.data;
    },
    onSuccess: (data) => {
      setDebugData({
        type: "deactivate",
        request: {},
        response: data,
        timestamp: (/* @__PURE__ */ new Date()).toISOString()
      });
      setLicenseKey("");
      showToast((data == null ? void 0 : data.notice) || "License deactivated successfully!", "success");
      queryClient2.invalidateQueries({ queryKey: ["license"] });
      window.dispatchEvent(
        new CustomEvent("yatra-license-status-updated", {
          detail: { status: "inactive" }
        })
      );
    },
    onError: (error) => {
      var _a2, _b2, _c2, _d2;
      const errorMsg = ((_b2 = (_a2 = error.response) == null ? void 0 : _a2.data) == null ? void 0 : _b2.message) || "Failed to deactivate license. Please try again.";
      showToast(errorMsg, "error");
      setDebugData({
        type: "deactivate",
        request: {},
        response: (_c2 = error.response) == null ? void 0 : _c2.data,
        error: ((_d2 = error.response) == null ? void 0 : _d2.data) || error.message,
        timestamp: (/* @__PURE__ */ new Date()).toISOString()
      });
    }
  });
  const saveMutation = useMutation({
    mutationFn: async (key2) => {
      const response = await apiClient.post("/license/save", {
        license_key: key2
      });
      return response;
    },
    onSuccess: (data) => {
      showToast((data == null ? void 0 : data.notice) || "License key saved successfully!", "success");
      queryClient2.invalidateQueries({ queryKey: ["license"] });
    },
    onError: (error) => {
      var _a2, _b2;
      const errorMsg = ((_b2 = (_a2 = error.response) == null ? void 0 : _a2.data) == null ? void 0 : _b2.message) || "Failed to save license key.";
      showToast(errorMsg, "error");
    }
  });
  const checkMutation = useMutation({
    mutationFn: async () => {
      const response = await apiClient.post("/license/check");
      return response;
    },
    onSuccess: (data) => {
      var _a2;
      setDebugData({
        type: "check",
        request: {},
        response: data,
        timestamp: (/* @__PURE__ */ new Date()).toISOString()
      });
      showToast((data == null ? void 0 : data.notice) || "License status updated.", "success");
      queryClient2.invalidateQueries({ queryKey: ["license"] });
      if ((_a2 = data == null ? void 0 : data.license_info) == null ? void 0 : _a2.status) {
        window.dispatchEvent(
          new CustomEvent("yatra-license-status-updated", {
            detail: { status: data.license_info.status }
          })
        );
      }
    },
    onError: (error) => {
      var _a2, _b2, _c2, _d2;
      const errorMsg = ((_b2 = (_a2 = error.response) == null ? void 0 : _a2.data) == null ? void 0 : _b2.message) || "Failed to check license status.";
      showToast(errorMsg, "error");
      setDebugData({
        type: "check",
        request: {},
        response: (_c2 = error.response) == null ? void 0 : _c2.data,
        error: ((_d2 = error.response) == null ? void 0 : _d2.data) || error.message,
        timestamp: (/* @__PURE__ */ new Date()).toISOString()
      });
    }
  });
  const handleActivate = (e) => {
    e.preventDefault();
    if (!licenseKey.trim()) {
      showToast("Please enter a license key.", "error");
      return;
    }
    activateMutation.mutate(licenseKey);
  };
  const handleDeactivate = () => {
    setShowDeactivateConfirm(true);
  };
  const confirmDeactivate = () => {
    setShowDeactivateConfirm(false);
    deactivateMutation.mutate();
  };
  const handleCheckStatus = () => {
    checkMutation.mutate();
  };
  const maskLicenseKey = (key2) => {
    if (!key2 || key2.length < 8) return key2;
    return key2.substring(0, 4) + "••••••••••••" + key2.substring(key2.length - 4);
  };
  const getStatusBadge = (status) => {
    const statusConfig = {
      active: {
        bg: "bg-green-100 dark:bg-green-900/20",
        text: "text-green-800 dark:text-green-400",
        label: "Active"
      },
      valid: {
        bg: "bg-green-100 dark:bg-green-900/20",
        text: "text-green-800 dark:text-green-400",
        label: "Active"
      },
      inactive: {
        bg: "bg-gray-100 dark:bg-gray-800",
        text: "text-gray-800 dark:text-gray-300",
        label: "Inactive"
      },
      expired: {
        bg: "bg-red-100 dark:bg-red-900/20",
        text: "text-red-800 dark:text-red-400",
        label: "Expired"
      },
      disabled: {
        bg: "bg-red-100 dark:bg-red-900/20",
        text: "text-red-800 dark:text-red-400",
        label: "Disabled"
      },
      invalid: {
        bg: "bg-yellow-100 dark:bg-yellow-900/20",
        text: "text-yellow-800 dark:text-yellow-400",
        label: "Invalid"
      }
    };
    const config2 = statusConfig[status] || statusConfig.inactive;
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "span",
      {
        className: `inline-flex items-center px-3 py-1 rounded-full text-sm font-medium ${config2.bg} ${config2.text}`,
        children: config2.label
      }
    );
  };
  const SkeletonLoader = () => /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "max-w-4xl mx-auto p-6", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "border-b border-gray-200 dark:border-gray-700 px-6 py-4", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-6 h-6 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-8 w-48 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" })
    ] }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-6 space-y-6", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-gray-50 dark:bg-gray-900/50 rounded-lg p-6", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-6 w-64 bg-gray-200 dark:bg-gray-700 rounded animate-pulse mb-4" }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 w-full bg-gray-200 dark:bg-gray-700 rounded animate-pulse" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-4 w-3/4 bg-gray-200 dark:bg-gray-700 rounded animate-pulse" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-10 w-full bg-gray-200 dark:bg-gray-700 rounded animate-pulse mt-4" })
      ] })
    ] }) })
  ] }) });
  if (isLoading) {
    return /* @__PURE__ */ jsxRuntimeExports.jsx(SkeletonLoader, {});
  }
  if (!isPro) {
    return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "max-w-4xl mx-auto p-6", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "border-b border-gray-200 dark:border-gray-700 px-6 py-4", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Key, { className: "w-6 h-6 text-gray-600 dark:text-gray-400" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("h1", { className: "text-2xl font-semibold text-gray-900 dark:text-white", children: __("License", "yatra") })
      ] }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-6", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-center py-12", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "inline-flex items-center justify-center w-16 h-16 bg-blue-100 dark:bg-blue-900/20 rounded-full mb-4", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Key, { className: "w-8 h-8 text-blue-600 dark:text-blue-400" }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { className: "text-xl font-semibold text-gray-900 dark:text-white mb-2", children: "Yatra Free Version" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-gray-600 dark:text-gray-400 mb-6 max-w-md mx-auto", children: "You're using the free version of Yatra. No license is required for the free version." }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-blue-50 dark:bg-blue-900/10 border border-blue-200 dark:border-blue-800 rounded-lg p-6 mb-6 max-w-2xl mx-auto", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-lg font-semibold text-gray-900 dark:text-white mb-3", children: "Upgrade to Yatra Pro" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-gray-600 dark:text-gray-400 mb-4", children: "Unlock premium features with Yatra Pro:" }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("ul", { className: "text-left space-y-2 mb-6", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { className: "flex items-start gap-2", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Check, { className: "w-5 h-5 text-green-600 dark:text-green-400 flex-shrink-0 mt-0.5" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-700 dark:text-gray-300", children: "Dynamic Pricing & Revenue Management" })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { className: "flex items-start gap-2", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Check, { className: "w-5 h-5 text-green-600 dark:text-green-400 flex-shrink-0 mt-0.5" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-700 dark:text-gray-300", children: __("Advanced Booking Management", "yatra") })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { className: "flex items-start gap-2", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Check, { className: "w-5 h-5 text-green-600 dark:text-green-400 flex-shrink-0 mt-0.5" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-700 dark:text-gray-300", children: __("Premium Payment Gateways", "yatra") })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { className: "flex items-start gap-2", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Check, { className: "w-5 h-5 text-green-600 dark:text-green-400 flex-shrink-0 mt-0.5" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-gray-700 dark:text-gray-300", children: "Priority Support & Updates" })
            ] })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "a",
            {
              href: "https://wpyatra.com/pricing",
              target: "_blank",
              rel: "noopener noreferrer",
              className: "inline-flex items-center gap-2 px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition-colors",
              children: [
                "Upgrade to Pro",
                /* @__PURE__ */ jsxRuntimeExports.jsx(ExternalLink, { className: "w-4 h-4" })
              ]
            }
          )
        ] })
      ] }) })
    ] }) });
  }
  const licenseInfo = licenseData == null ? void 0 : licenseData.license_info;
  const isActive = (licenseInfo == null ? void 0 : licenseInfo.status) === "active" || (licenseInfo == null ? void 0 : licenseInfo.status) === "valid";
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "max-w-4xl mx-auto p-6", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "border-b border-gray-200 dark:border-gray-700 px-6 py-4", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Key, { className: "w-6 h-6 text-gray-600 dark:text-gray-400" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("h1", { className: "text-2xl font-semibold text-gray-900 dark:text-white", children: __("License Management", "yatra") })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3", children: [
          (licenseInfo == null ? void 0 : licenseInfo.status) && getStatusBadge(licenseInfo.status),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "button",
            {
              onClick: () => setDebugMode(!debugMode),
              className: `flex items-center gap-2 px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${debugMode ? "bg-purple-100 dark:bg-purple-900/20 text-purple-700 dark:text-purple-400" : "bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400 hover:bg-gray-200 dark:hover:bg-gray-600"}`,
              title: "Toggle debug mode to see API requests and responses",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(Bug, { className: "w-4 h-4" }),
                "Debug"
              ]
            }
          )
        ] })
      ] }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "p-6 space-y-6", children: [
        !isActive && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-gray-50 dark:bg-gray-900/50 rounded-lg p-6", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { className: "text-lg font-semibold text-gray-900 dark:text-white mb-4", children: "Activate Your License" }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("form", { onSubmit: handleActivate, className: "space-y-4", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "label",
                {
                  htmlFor: "license-key",
                  className: "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",
                  children: "License Key"
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "input",
                {
                  type: "text",
                  id: "license-key",
                  value: licenseKey,
                  onChange: (e) => setLicenseKey(e.target.value),
                  placeholder: "Enter your license key",
                  className: "w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-transparent",
                  disabled: activateMutation.isPending
                }
              )
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-wrap gap-3", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "button",
                {
                  type: "button",
                  onClick: (e) => {
                    e.preventDefault();
                    if (!licenseKey.trim()) {
                      showToast("Please enter a license key.", "error");
                      return;
                    }
                    saveMutation.mutate(licenseKey);
                  },
                  disabled: activateMutation.isPending || saveMutation.isPending,
                  className: "inline-flex items-center justify-center gap-2 px-6 py-2.5 bg-gray-900 hover:bg-black dark:bg-gray-800 dark:hover:bg-gray-900 disabled:opacity-50 disabled:cursor-not-allowed text-white font-semibold rounded-lg transition-all shadow-md hover:shadow-lg border border-gray-800 dark:border-gray-700",
                  children: saveMutation.isPending ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "animate-spin rounded-full h-4 w-4 border-b-2 border-white" }),
                    "Saving..."
                  ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(Key, { className: "w-4 h-4" }),
                    "Save"
                  ] })
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "button",
                {
                  type: "submit",
                  disabled: activateMutation.isPending,
                  className: "inline-flex items-center gap-2 px-6 py-2.5 bg-blue-600 hover:bg-blue-700 dark:bg-blue-500 dark:hover:bg-blue-600 disabled:bg-gray-400 dark:disabled:bg-gray-500 text-white font-medium rounded-lg transition-colors shadow-sm",
                  children: activateMutation.isPending ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "animate-spin rounded-full h-4 w-4 border-b-2 border-white" }),
                    "Activating..."
                  ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(Check, { className: "w-4 h-4" }),
                    "Save & Activate"
                  ] })
                }
              )
            ] })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "mt-4 text-sm text-gray-600 dark:text-gray-400", children: [
            "Don't have a license key?",
            " ",
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "a",
              {
                href: "https://store.mantrabrain.com/account/",
                target: "_blank",
                rel: "noopener noreferrer",
                className: "text-blue-600 dark:text-blue-400 hover:underline",
                children: "Get it from your account"
              }
            )
          ] })
        ] }),
        isActive && licenseInfo && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-6", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-gray-50 dark:bg-gray-900/50 rounded-lg p-6", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between mb-4", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-lg font-semibold text-gray-900 dark:text-white", children: __("License Key", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "button",
                {
                  onClick: () => setShowKey(!showKey),
                  className: "text-sm text-blue-600 dark:text-blue-400 hover:underline flex items-center gap-1",
                  children: showKey ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(EyeOff, { className: "w-4 h-4" }),
                    "Hide"
                  ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(Eye, { className: "w-4 h-4" }),
                    "Show"
                  ] })
                }
              )
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "font-mono text-sm bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded px-4 py-3 text-gray-900 dark:text-white", children: showKey ? licenseInfo.key : maskLicenseKey(licenseInfo.key) })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-4", children: [
            ((_a = licenseInfo.plan) == null ? void 0 : _a.name) && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-gray-50 dark:bg-gray-900/50 rounded-lg p-4", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-600 dark:text-gray-400 mb-1", children: __("Plan", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-medium text-gray-900 dark:text-white", children: licenseInfo.plan.name }),
                licenseInfo.plan.is_agency && /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[11px] font-semibold bg-gradient-to-r from-purple-600 to-indigo-500 text-white", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(Crown, { className: "w-3 h-3" }),
                  __("Scale", "yatra")
                ] }),
                licenseInfo.plan.is_growth && /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[11px] font-semibold bg-blue-600 text-white", children: __("Growth", "yatra") }),
                licenseInfo.plan.is_lifetime && /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[11px] font-semibold bg-gradient-to-r from-amber-500 to-orange-500 text-white", children: __("Lifetime", "yatra") })
              ] }),
              licenseInfo.plan.matched_by === "label" && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-2 text-[11px] text-gray-500 dark:text-gray-400", children: __(
                "Detected from plan label (the original price ID was re-numbered on the store).",
                "yatra"
              ) }),
              licenseInfo.plan.matched_by === "fallback" && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-2 text-[11px] text-amber-600 dark:text-amber-400", children: __(
                "Could not match price ID or label — defaulted to Starter. Contact support if your subscription is Growth or Scale.",
                "yatra"
              ) })
            ] }),
            ((_b = licenseInfo.server_response) == null ? void 0 : _b.customer_name) && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-gray-50 dark:bg-gray-900/50 rounded-lg p-4", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-600 dark:text-gray-400 mb-1", children: __("Licensed To", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "font-medium text-gray-900 dark:text-white", children: licenseInfo.server_response.customer_name })
            ] }),
            ((_c = licenseInfo.server_response) == null ? void 0 : _c.customer_email) && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-gray-50 dark:bg-gray-900/50 rounded-lg p-4", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-600 dark:text-gray-400 mb-1", children: __("Email", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "font-medium text-gray-900 dark:text-white", children: licenseInfo.server_response.customer_email })
            ] }),
            ((_d = licenseInfo.server_response) == null ? void 0 : _d.expires) && licenseInfo.server_response.expires !== "lifetime" && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-gray-50 dark:bg-gray-900/50 rounded-lg p-4", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-600 dark:text-gray-400 mb-1", children: __("Expires", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "font-medium text-gray-900 dark:text-white", children: (() => {
                try {
                  const date2 = new Date(
                    licenseInfo.server_response.expires
                  );
                  return isNaN(date2.getTime()) ? licenseInfo.server_response.expires : date2.toLocaleDateString(void 0, {
                    year: "numeric",
                    month: "long",
                    day: "numeric"
                  });
                } catch {
                  return licenseInfo.server_response.expires;
                }
              })() })
            ] }),
            ((_e = licenseInfo.server_response) == null ? void 0 : _e.expires) === "lifetime" && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-gray-50 dark:bg-gray-900/50 rounded-lg p-4", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-600 dark:text-gray-400 mb-1", children: __("Expires", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "font-medium text-green-600 dark:text-green-400", children: __("Lifetime License", "yatra") })
            ] }),
            ((_f = licenseInfo.server_response) == null ? void 0 : _f.site_count) !== void 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-gray-50 dark:bg-gray-900/50 rounded-lg p-4", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-600 dark:text-gray-400 mb-1", children: __("Active Sites", "yatra") }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "font-medium text-gray-900 dark:text-white", children: [
                licenseInfo.server_response.site_count,
                " /",
                " ",
                licenseInfo.server_response.license_limit || "∞"
              ] })
            ] })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-wrap gap-3 pt-4 border-t border-gray-200 dark:border-gray-700", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "button",
              {
                onClick: handleCheckStatus,
                disabled: checkMutation.isPending,
                className: "px-4 py-2 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 text-gray-900 dark:text-white font-medium rounded-lg transition-colors flex items-center gap-2",
                children: checkMutation.isPending ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "animate-spin rounded-full h-4 w-4 border-b-2 border-gray-900 dark:border-white" }),
                  "Checking..."
                ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(RefreshCw, { className: "w-4 h-4" }),
                  "Check Status"
                ] })
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "button",
              {
                onClick: handleDeactivate,
                disabled: deactivateMutation.isPending,
                className: "px-4 py-2 bg-red-600 hover:bg-red-700 disabled:bg-gray-400 text-white font-medium rounded-lg transition-colors flex items-center gap-2",
                children: deactivateMutation.isPending ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "animate-spin rounded-full h-4 w-4 border-b-2 border-white" }),
                  "Deactivating..."
                ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(XCircle, { className: "w-4 h-4" }),
                  "Deactivate License"
                ] })
              }
            )
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-blue-50 dark:bg-blue-900/10 border border-blue-200 dark:border-blue-800 rounded-lg p-4", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-sm font-semibold text-gray-900 dark:text-white mb-2", children: "Need Help?" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-600 dark:text-gray-400 mb-3", children: "If you're having trouble with your license, please contact our support team." }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-wrap gap-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "a",
              {
                href: "https://store.mantrabrain.com/account/",
                target: "_blank",
                rel: "noopener noreferrer",
                className: "text-sm text-blue-600 dark:text-blue-400 hover:underline flex items-center gap-1",
                children: [
                  "Manage License",
                  /* @__PURE__ */ jsxRuntimeExports.jsx(ExternalLink, { className: "w-3 h-3" })
                ]
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "a",
              {
                href: "https://mantrabrain.com/contact/",
                target: "_blank",
                rel: "noopener noreferrer",
                className: "text-sm text-blue-600 dark:text-blue-400 hover:underline flex items-center gap-1",
                children: [
                  "Contact Support",
                  /* @__PURE__ */ jsxRuntimeExports.jsx(ExternalLink, { className: "w-3 h-3" })
                ]
              }
            )
          ] })
        ] }),
        debugMode && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "bg-purple-50 dark:bg-purple-900/10 border border-purple-200 dark:border-purple-800 rounded-lg p-4", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between mb-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("h3", { className: "text-sm font-semibold text-purple-900 dark:text-purple-300 flex items-center gap-2", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Bug, { className: "w-4 h-4" }),
              "Debug Information"
            ] }),
            debugData && /* @__PURE__ */ jsxRuntimeExports.jsx(
              "button",
              {
                onClick: () => setDebugData(null),
                className: "text-xs text-purple-600 dark:text-purple-400 hover:underline",
                children: __("Clear", "yatra")
              }
            )
          ] }),
          debugData ? /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-3", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-xs font-semibold text-purple-700 dark:text-purple-300 uppercase", children: [
                "Operation: ",
                debugData.type
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "ml-3 text-xs text-gray-500 dark:text-gray-400", children: debugData.timestamp })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between mb-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(ChevronDown, { className: "w-3 h-3 text-blue-600 dark:text-blue-400" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs font-semibold text-blue-700 dark:text-blue-300", children: "Full Response Body:" })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs(
                  "button",
                  {
                    onClick: () => {
                      var _a2;
                      const text = JSON.stringify(
                        debugData.response,
                        null,
                        2
                      );
                      if ((_a2 = navigator == null ? void 0 : navigator.clipboard) == null ? void 0 : _a2.writeText) {
                        navigator.clipboard.writeText(text);
                        showToast(
                          "Response copied to clipboard!",
                          "success"
                        );
                      } else {
                        const textArea = document.createElement("textarea");
                        textArea.value = text;
                        document.body.appendChild(textArea);
                        textArea.select();
                        try {
                          document.execCommand("copy");
                          showToast(
                            "Response copied to clipboard!",
                            "success"
                          );
                        } catch (err) {
                          showToast("Failed to copy to clipboard", "error");
                        }
                        document.body.removeChild(textArea);
                      }
                    },
                    className: "text-xs text-blue-600 dark:text-blue-400 hover:underline flex items-center gap-1",
                    children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx(
                        "svg",
                        {
                          className: "w-3 h-3",
                          fill: "none",
                          stroke: "currentColor",
                          viewBox: "0 0 24 24",
                          children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                            "path",
                            {
                              strokeLinecap: "round",
                              strokeLinejoin: "round",
                              strokeWidth: 2,
                              d: "M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"
                            }
                          )
                        }
                      ),
                      "Copy"
                    ]
                  }
                )
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("pre", { className: "bg-white dark:bg-gray-900 border border-blue-200 dark:border-blue-800 rounded p-3 text-xs overflow-x-auto max-h-96 overflow-y-auto", children: /* @__PURE__ */ jsxRuntimeExports.jsx("code", { className: "text-gray-800 dark:text-gray-200", children: JSON.stringify(debugData.response, null, 2) }) })
            ] }),
            ((_g = debugData.response) == null ? void 0 : _g.edd_api_request) && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between mb-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(ChevronDown, { className: "w-3 h-3 text-purple-600 dark:text-purple-400" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs font-semibold text-purple-700 dark:text-purple-300", children: "EDD API Request (to store.mantrabrain.com):" })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs(
                  "button",
                  {
                    onClick: () => {
                      var _a2;
                      const text = JSON.stringify(
                        debugData.response.edd_api_request,
                        null,
                        2
                      );
                      if ((_a2 = navigator == null ? void 0 : navigator.clipboard) == null ? void 0 : _a2.writeText) {
                        navigator.clipboard.writeText(text);
                        showToast(
                          "Request copied to clipboard!",
                          "success"
                        );
                      } else {
                        const textArea = document.createElement("textarea");
                        textArea.value = text;
                        document.body.appendChild(textArea);
                        textArea.select();
                        try {
                          document.execCommand("copy");
                          showToast(
                            "Request copied to clipboard!",
                            "success"
                          );
                        } catch (err) {
                          showToast(
                            "Failed to copy to clipboard",
                            "error"
                          );
                        }
                        document.body.removeChild(textArea);
                      }
                    },
                    className: "text-xs text-purple-600 dark:text-purple-400 hover:underline flex items-center gap-1",
                    children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx(
                        "svg",
                        {
                          className: "w-3 h-3",
                          fill: "none",
                          stroke: "currentColor",
                          viewBox: "0 0 24 24",
                          children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                            "path",
                            {
                              strokeLinecap: "round",
                              strokeLinejoin: "round",
                              strokeWidth: 2,
                              d: "M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"
                            }
                          )
                        }
                      ),
                      "Copy"
                    ]
                  }
                )
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("pre", { className: "bg-white dark:bg-gray-900 border border-purple-200 dark:border-purple-800 rounded p-3 text-xs overflow-x-auto", children: /* @__PURE__ */ jsxRuntimeExports.jsx("code", { className: "text-gray-800 dark:text-gray-200", children: JSON.stringify(
                debugData.response.edd_api_request,
                null,
                2
              ) }) })
            ] }),
            ((_h = debugData.response) == null ? void 0 : _h.edd_api_response) && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between mb-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(ChevronDown, { className: "w-3 h-3 text-green-600 dark:text-green-400" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs font-semibold text-green-700 dark:text-green-300", children: "EDD API Response (from store.mantrabrain.com):" })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs(
                  "button",
                  {
                    onClick: () => {
                      var _a2;
                      const text = JSON.stringify(
                        debugData.response.edd_api_response,
                        null,
                        2
                      );
                      if ((_a2 = navigator == null ? void 0 : navigator.clipboard) == null ? void 0 : _a2.writeText) {
                        navigator.clipboard.writeText(text);
                        showToast(
                          "Response copied to clipboard!",
                          "success"
                        );
                      } else {
                        const textArea = document.createElement("textarea");
                        textArea.value = text;
                        document.body.appendChild(textArea);
                        textArea.select();
                        try {
                          document.execCommand("copy");
                          showToast(
                            "Response copied to clipboard!",
                            "success"
                          );
                        } catch (err) {
                          showToast(
                            "Failed to copy to clipboard",
                            "error"
                          );
                        }
                        document.body.removeChild(textArea);
                      }
                    },
                    className: "text-xs text-green-600 dark:text-green-400 hover:underline flex items-center gap-1",
                    children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx(
                        "svg",
                        {
                          className: "w-3 h-3",
                          fill: "none",
                          stroke: "currentColor",
                          viewBox: "0 0 24 24",
                          children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                            "path",
                            {
                              strokeLinecap: "round",
                              strokeLinejoin: "round",
                              strokeWidth: 2,
                              d: "M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"
                            }
                          )
                        }
                      ),
                      "Copy"
                    ]
                  }
                )
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("pre", { className: "bg-white dark:bg-gray-900 border border-green-200 dark:border-green-800 rounded p-3 text-xs overflow-x-auto", children: /* @__PURE__ */ jsxRuntimeExports.jsx("code", { className: "text-gray-800 dark:text-gray-200", children: JSON.stringify(
                debugData.response.edd_api_response,
                null,
                2
              ) }) })
            ] }),
            debugData.error && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between mb-2", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(ChevronDown, { className: "w-3 h-3 text-red-600 dark:text-red-400" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs font-semibold text-red-700 dark:text-red-300", children: "Error Data:" })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs(
                  "button",
                  {
                    onClick: () => {
                      var _a2;
                      const text = JSON.stringify(
                        debugData.error,
                        null,
                        2
                      );
                      if ((_a2 = navigator == null ? void 0 : navigator.clipboard) == null ? void 0 : _a2.writeText) {
                        navigator.clipboard.writeText(text);
                        showToast(
                          "Error copied to clipboard!",
                          "success"
                        );
                      } else {
                        const textArea = document.createElement("textarea");
                        textArea.value = text;
                        document.body.appendChild(textArea);
                        textArea.select();
                        try {
                          document.execCommand("copy");
                          showToast(
                            "Error copied to clipboard!",
                            "success"
                          );
                        } catch (err) {
                          showToast(
                            "Failed to copy to clipboard",
                            "error"
                          );
                        }
                        document.body.removeChild(textArea);
                      }
                    },
                    className: "text-xs text-red-600 dark:text-red-400 hover:underline flex items-center gap-1",
                    children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx(
                        "svg",
                        {
                          className: "w-3 h-3",
                          fill: "none",
                          stroke: "currentColor",
                          viewBox: "0 0 24 24",
                          children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                            "path",
                            {
                              strokeLinecap: "round",
                              strokeLinejoin: "round",
                              strokeWidth: 2,
                              d: "M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"
                            }
                          )
                        }
                      ),
                      "Copy"
                    ]
                  }
                )
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("pre", { className: "bg-white dark:bg-gray-900 border border-red-200 dark:border-red-800 rounded p-3 text-xs overflow-x-auto", children: /* @__PURE__ */ jsxRuntimeExports.jsx("code", { className: "text-gray-800 dark:text-gray-200", children: JSON.stringify(debugData.error, null, 2) }) })
            ] })
          ] }) : /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-purple-600 dark:text-purple-400", children: "Perform a license operation (activate, deactivate, or check status) to see debug information here." })
        ] })
      ] })
    ] }),
    showDeactivateConfirm && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm px-4", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-md w-full p-6", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start gap-4", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex-shrink-0", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "w-12 h-12 rounded-full bg-red-100 dark:bg-red-900/20 flex items-center justify-center", children: /* @__PURE__ */ jsxRuntimeExports.jsx(XCircle, { className: "w-6 h-6 text-red-600 dark:text-red-400" }) }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex-1", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "text-lg font-semibold text-gray-900 dark:text-white mb-2", children: "Deactivate License" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-600 dark:text-gray-400 mb-6", children: "Are you sure you want to deactivate this license? You will lose support and updates for Yatra Pro." }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-3 justify-end", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "button",
            {
              onClick: () => setShowDeactivateConfirm(false),
              className: "px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-lg transition-colors",
              children: "Cancel"
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "button",
            {
              onClick: confirmDeactivate,
              disabled: deactivateMutation.isPending,
              className: "px-4 py-2 text-sm font-medium text-white bg-red-600 hover:bg-red-700 disabled:bg-gray-400 rounded-lg transition-colors flex items-center gap-2",
              children: deactivateMutation.isPending ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "animate-spin rounded-full h-4 w-4 border-b-2 border-white" }),
                "Deactivating..."
              ] }) : "Deactivate"
            }
          )
        ] })
      ] })
    ] }) }) })
  ] });
};
const TripForm = reactExports.lazy(() => __vitePreload(() => import("../../../dist/js/TripForm-tFMoMuMs.js"), true ? __vite__mapDeps([0,1,2,3,4,5,6]) : void 0, import.meta.url));
const Settings = reactExports.lazy(() => __vitePreload(() => import("../../../dist/js/Settings-DZPiAnb3.js"), true ? __vite__mapDeps([7,1,2,3,4,6]) : void 0, import.meta.url));
const Team = reactExports.lazy(() => __vitePreload(() => import("../../../dist/js/Team-CFV2Lcc6.js"), true ? __vite__mapDeps([8,1,2,3,4]) : void 0, import.meta.url));
const Reports = reactExports.lazy(() => __vitePreload(() => import("../../../dist/js/Reports-sGU73NQH.js"), true ? __vite__mapDeps([9,1,2,3,4]) : void 0, import.meta.url));
const DiscountForm = reactExports.lazy(() => __vitePreload(() => import("../../../dist/js/DiscountForm-CWIQB0xy.js"), true ? __vite__mapDeps([10,1,2,3,4,11]) : void 0, import.meta.url));
const Itinerary = reactExports.lazy(() => __vitePreload(() => import("../../../dist/js/Itinerary-Ap1hthK0.js"), true ? __vite__mapDeps([12,1,2,3,4,5]) : void 0, import.meta.url));
const RecurringRuleForm = reactExports.lazy(() => __vitePreload(() => import("../../../dist/js/RecurringRuleForm-qprdlB53.js"), true ? __vite__mapDeps([13,1,2,3,4]) : void 0, import.meta.url));
const Whatsapp = reactExports.lazy(() => __vitePreload(() => import("./Whatsapp.js"), true ? __vite__mapDeps([14,1,2,3,4,15]) : void 0, import.meta.url));
const ChannelManager = reactExports.lazy(() => __vitePreload(() => import("../../../dist/js/ChannelManager-BumsBhiQ.js"), true ? __vite__mapDeps([16,1,2,3,4,15]) : void 0, import.meta.url));
const Webhooks = reactExports.lazy(() => __vitePreload(() => import("../../../dist/js/Webhooks-BmhRcymQ.js"), true ? __vite__mapDeps([17,1,2,3,4,15]) : void 0, import.meta.url));
const TripConsentForm = reactExports.lazy(() => __vitePreload(() => import("../../../dist/js/TripConsentForm-DeH_xgzl.js"), true ? __vite__mapDeps([18,1,2,11,3,4]) : void 0, import.meta.url));
const BookingForm = reactExports.lazy(() => __vitePreload(() => import("../../../dist/js/BookingForm-DFFoFfQO.js"), true ? __vite__mapDeps([19,1,2,3,4]) : void 0, import.meta.url));
const ViewBooking = reactExports.lazy(() => __vitePreload(() => import("../../../dist/js/ViewBooking-D0U0ZXpB.js"), true ? __vite__mapDeps([20,1,2,3,4]) : void 0, import.meta.url));
const AvailabilityForm = reactExports.lazy(() => __vitePreload(() => import("../../../dist/js/AvailabilityForm-BPWy1f1h.js"), true ? __vite__mapDeps([21,1,2,3,4]) : void 0, import.meta.url));
const DynamicPricing = reactExports.lazy(() => __vitePreload(() => import("../../../dist/js/DynamicPricing-DTdy3svi.js"), true ? __vite__mapDeps([22,1,2,23,3,4,24]) : void 0, import.meta.url));
const DynamicPricingRuleForm = reactExports.lazy(
  () => __vitePreload(() => import("../../../dist/js/DynamicPricingRuleForm-wUY86s8E.js"), true ? __vite__mapDeps([25,1,2,23,3,4]) : void 0, import.meta.url)
);
const AiAssistant = reactExports.lazy(() => __vitePreload(() => import("../../../dist/js/AiAssistant-2YNozU84.js"), true ? __vite__mapDeps([26,1,2,3,4,15]) : void 0, import.meta.url));
const AbandonedRecovery = reactExports.lazy(() => __vitePreload(() => import("../../../dist/js/AbandonedRecovery-BXWfwama.js"), true ? __vite__mapDeps([27,1,2,24,3,4]) : void 0, import.meta.url));
const WhiteLabel = reactExports.lazy(() => __vitePreload(() => import("../../../dist/js/WhiteLabel-DoUclAt1.js"), true ? __vite__mapDeps([28,1,2,3,4,15]) : void 0, import.meta.url));
const PageLoadingFallback = () => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-6", children: [
  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-2", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-6 w-1/3" }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-4 w-2/3" })
  ] }),
  /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-12 w-full" }),
  /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-64 w-full" })
] });
const App = () => {
  const [urlKey, setUrlKey] = reactExports.useState(0);
  reactExports.useEffect(() => {
    const handleLocationChange = () => {
      setUrlKey((prev) => prev + 1);
    };
    window.addEventListener("popstate", handleLocationChange);
    const interval = setInterval(() => {
      const currentSearch = window.location.search;
      if (currentSearch !== window.__lastSearch) {
        window.__lastSearch = currentSearch;
        handleLocationChange();
      }
    }, 100);
    return () => {
      window.removeEventListener("popstate", handleLocationChange);
      clearInterval(interval);
    };
  }, []);
  const subpage = reactExports.useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get("subpage") || "dashboard";
  }, [urlKey]);
  const tab = reactExports.useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get("tab") || "all";
  }, [urlKey]);
  const action = reactExports.useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get("action");
  }, [urlKey, subpage]);
  const renderPage = () => {
    switch (subpage.toLowerCase()) {
      case "trips":
        switch (tab.toLowerCase()) {
          case "activities":
            if (action === "create" || action === "edit") {
              return /* @__PURE__ */ jsxRuntimeExports.jsx(ActivityForm, {});
            }
            return /* @__PURE__ */ jsxRuntimeExports.jsx(Activities, {});
          case "destinations":
            if (action === "create" || action === "edit") {
              return /* @__PURE__ */ jsxRuntimeExports.jsx(DestinationForm, {});
            }
            return /* @__PURE__ */ jsxRuntimeExports.jsx(Destinations, {});
          case "categories":
            if (action === "create" || action === "edit") {
              return /* @__PURE__ */ jsxRuntimeExports.jsx(CategoryForm, {});
            }
            return /* @__PURE__ */ jsxRuntimeExports.jsx(Categories, {});
          case "difficulty-levels":
            if (action === "create" || action === "edit") {
              return /* @__PURE__ */ jsxRuntimeExports.jsx(DifficultyLevelForm, {});
            }
            return /* @__PURE__ */ jsxRuntimeExports.jsx(DifficultyLevels, {});
          case "availability":
            if (action === "create-rule" || action === "edit-rule") {
              return /* @__PURE__ */ jsxRuntimeExports.jsx(RecurringRuleForm, {});
            }
            if (action === "create" || action === "edit") {
              return /* @__PURE__ */ jsxRuntimeExports.jsx(AvailabilityForm, {});
            }
            return /* @__PURE__ */ jsxRuntimeExports.jsx(Availability, {});
          case "additional-services":
            if (action === "create" || action === "edit") {
              return /* @__PURE__ */ jsxRuntimeExports.jsx(AdditionalServicesForm, {});
            }
            return /* @__PURE__ */ jsxRuntimeExports.jsx(AdditionalServices, {});
          case "trip-consent":
            if (action === "create" || action === "edit") {
              return /* @__PURE__ */ jsxRuntimeExports.jsx(TripConsentForm, {});
            }
            return /* @__PURE__ */ jsxRuntimeExports.jsx(TripConsent, {});
          case "attributes":
            if (action === "create" || action === "edit") {
              return /* @__PURE__ */ jsxRuntimeExports.jsx(AttributeForm, {});
            }
            return /* @__PURE__ */ jsxRuntimeExports.jsx(Attributes, {});
          case "all":
          default:
            if (action === "create" || action === "edit") {
              return /* @__PURE__ */ jsxRuntimeExports.jsx(TripForm, {});
            }
            return /* @__PURE__ */ jsxRuntimeExports.jsx(Trips, {});
        }
      case "bookings":
        if (action === "view") {
          return /* @__PURE__ */ jsxRuntimeExports.jsx(ViewBooking, {});
        }
        if (action === "create" || action === "edit") {
          return /* @__PURE__ */ jsxRuntimeExports.jsx(BookingForm, {});
        }
        return /* @__PURE__ */ jsxRuntimeExports.jsx(Bookings, {});
      case "customers":
        if (action === "view") {
          return /* @__PURE__ */ jsxRuntimeExports.jsx(ViewCustomer, {});
        }
        if (action === "create" || action === "edit") {
          return /* @__PURE__ */ jsxRuntimeExports.jsx(CustomerForm, {});
        }
        return /* @__PURE__ */ jsxRuntimeExports.jsx(Customers, {});
      case "travelers":
        return /* @__PURE__ */ jsxRuntimeExports.jsx(Travelers, {});
      case "enquiries":
        if (action === "view") {
          return /* @__PURE__ */ jsxRuntimeExports.jsx(ViewEnquiry, {});
        }
        if (action === "edit" || action === "new") {
          return /* @__PURE__ */ jsxRuntimeExports.jsx(EnquiryForm, {});
        }
        return /* @__PURE__ */ jsxRuntimeExports.jsx(Enquiries, {});
      case "reviews":
        if (action === "view") {
          return /* @__PURE__ */ jsxRuntimeExports.jsx(ViewReview, {});
        }
        if (action === "create" || action === "edit") {
          return /* @__PURE__ */ jsxRuntimeExports.jsx(ReviewForm, {});
        }
        return /* @__PURE__ */ jsxRuntimeExports.jsx(Reviews, {});
      case "email-automation":
        if (action === "create" && tab === "template") {
          return /* @__PURE__ */ jsxRuntimeExports.jsx(EmailTemplateForm, {});
        }
        if (action === "edit" && tab === "template") {
          return /* @__PURE__ */ jsxRuntimeExports.jsx(EmailTemplateForm, {});
        }
        if (action === "create" && tab === "sequence") {
          return /* @__PURE__ */ jsxRuntimeExports.jsx(EmailSequenceForm, {});
        }
        if (action === "edit" && tab === "sequence") {
          return /* @__PURE__ */ jsxRuntimeExports.jsx(EmailSequenceForm, {});
        }
        if (action === "edit") {
          return /* @__PURE__ */ jsxRuntimeExports.jsx(EmailTemplateForm, {});
        }
        return /* @__PURE__ */ jsxRuntimeExports.jsx(EmailAutomation, {});
      case "itinerary":
        switch (tab.toLowerCase()) {
          case "item-types":
            if (action === "create" || action === "edit") {
              return /* @__PURE__ */ jsxRuntimeExports.jsx(ItemTypeForm, {});
            }
            return /* @__PURE__ */ jsxRuntimeExports.jsx(ItemTypes, {});
          case "items":
            if (action === "create" || action === "edit") {
              return /* @__PURE__ */ jsxRuntimeExports.jsx(ItemForm, {});
            }
            return /* @__PURE__ */ jsxRuntimeExports.jsx(Items, {});
          case "itinerary":
            if (action === "create" || action === "edit") {
              return /* @__PURE__ */ jsxRuntimeExports.jsx(ItineraryForm, {});
            }
            return /* @__PURE__ */ jsxRuntimeExports.jsx(Itinerary, {});
          default:
            return /* @__PURE__ */ jsxRuntimeExports.jsx(ItemTypes, {});
        }
      case "departures":
        if (action === "view") {
          return /* @__PURE__ */ jsxRuntimeExports.jsx(ViewDeparture, {});
        }
        if (action === "create" || action === "edit") {
          return /* @__PURE__ */ jsxRuntimeExports.jsx(DepartureForm, {});
        }
        return /* @__PURE__ */ jsxRuntimeExports.jsx(Departures, {});
      case "discounts":
        if (action === "create" || action === "edit") {
          return /* @__PURE__ */ jsxRuntimeExports.jsx(DiscountForm, {});
        }
        return /* @__PURE__ */ jsxRuntimeExports.jsx(Discounts, {});
      case "payments":
        if (action === "view") {
          return /* @__PURE__ */ jsxRuntimeExports.jsx(ViewPayment, {});
        }
        if (action === "create" || action === "edit") {
          return /* @__PURE__ */ jsxRuntimeExports.jsx(PaymentForm, {});
        }
        return /* @__PURE__ */ jsxRuntimeExports.jsx(Payments, {});
      case "traveler-categories":
        if (action === "create" || action === "edit") {
          return /* @__PURE__ */ jsxRuntimeExports.jsx(TravelerCategoryForm, {});
        }
        return /* @__PURE__ */ jsxRuntimeExports.jsx(TravelerCategories, {});
      case "reports":
        return /* @__PURE__ */ jsxRuntimeExports.jsx(Reports, {});
      case "tools":
        return /* @__PURE__ */ jsxRuntimeExports.jsx(Tools, {});
      case "settings":
        return /* @__PURE__ */ jsxRuntimeExports.jsx(Settings, {});
      case "modules":
        return /* @__PURE__ */ jsxRuntimeExports.jsx(Modules, {});
      case "google-calendar":
        return /* @__PURE__ */ jsxRuntimeExports.jsx(GoogleCalendar, {});
      case "additional-services":
        if (action === "create" || action === "edit") {
          return /* @__PURE__ */ jsxRuntimeExports.jsx(AdditionalServicesForm, {});
        }
        return /* @__PURE__ */ jsxRuntimeExports.jsx(AdditionalServices, {});
      case "trip-consent":
        if (action === "create" || action === "edit") {
          return /* @__PURE__ */ jsxRuntimeExports.jsx(TripConsentForm, {});
        }
        return /* @__PURE__ */ jsxRuntimeExports.jsx(TripConsent, {});
      case "abandoned-recovery":
        return /* @__PURE__ */ jsxRuntimeExports.jsx(AbandonedRecovery, { tab });
      case "dynamic-pricing":
        if (action === "create-pricing-rule" || action === "edit-pricing-rule") {
          return /* @__PURE__ */ jsxRuntimeExports.jsx(DynamicPricingRuleForm, {});
        }
        return /* @__PURE__ */ jsxRuntimeExports.jsx(DynamicPricing, {});
      case "license":
        return /* @__PURE__ */ jsxRuntimeExports.jsx(License, {});
      case "white-label":
        return /* @__PURE__ */ jsxRuntimeExports.jsx(WhiteLabel, {});
      case "ai-assistant":
        return /* @__PURE__ */ jsxRuntimeExports.jsx(AiAssistant, {});
      case "whatsapp":
        return /* @__PURE__ */ jsxRuntimeExports.jsx(Whatsapp, {});
      case "channel-manager":
        return /* @__PURE__ */ jsxRuntimeExports.jsx(ChannelManager, {});
      case "webhooks":
        return /* @__PURE__ */ jsxRuntimeExports.jsx(Webhooks, {});
      case "team":
        return /* @__PURE__ */ jsxRuntimeExports.jsx(Team, {});
      case "dashboard":
      default:
        return /* @__PURE__ */ jsxRuntimeExports.jsx(Dashboard, {});
    }
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsx(Layout, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(reactExports.Suspense, { fallback: /* @__PURE__ */ jsxRuntimeExports.jsx(PageLoadingFallback, {}), children: renderPage() }) });
};
let queryClient;
try {
  queryClient = new QueryClient({
    defaultOptions: {
      queries: {
        refetchOnWindowFocus: false,
        retry: 1,
        staleTime: 5 * 60 * 1e3
        // 5 minutes
      }
    }
  });
} catch (error) {
  console.error("Error initializing QueryClient:", error);
  queryClient = new QueryClient();
}
const rootElement = document.getElementById("yatra-app-root");
if (rootElement) {
  try {
    const root2 = client.createRoot(rootElement);
    root2.render(
      /* @__PURE__ */ jsxRuntimeExports.jsx(React.StrictMode, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(QueryClientProvider, { client: queryClient, children: /* @__PURE__ */ jsxRuntimeExports.jsx(ToastProvider, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(App, {}) }) }) })
    );
  } catch (error) {
    console.error("Error rendering React app:", error);
    rootElement.innerHTML = '<div style="padding: 40px; text-align: center;"><h2>Error loading Yatra Admin</h2><p>Please refresh the page or contact support.</p></div>';
  }
}
export {
  BookingsOverviewChart as $,
  Alert as A,
  Button as B,
  Card as C,
  DatePicker as D,
  saveSettings as E,
  buildYatraListingPublicUrl as F,
  postInsertBookingShortcode as G,
  HelpText as H,
  Input as I,
  postFlushRewriteRules as J,
  fetchBookingPageShortcodeStatus as K,
  LocationPicker as L,
  Modal as M,
  fetchPaymentGatewayDefinitions as N,
  fetchWordPressPages as O,
  PageHeader as P,
  Skeleton as Q,
  RichTextEditor as R,
  Select as S,
  TimePicker as T,
  Table as U,
  Tooltip$1 as V,
  Pagination as W,
  Switch as X,
  setUserCaps as Y,
  canCap as Z,
  BookingStatusChart as _,
  isAiModuleEnabled as a,
  isProPluginActive as a0,
  isModuleActive as a1,
  BulkActionToolbar as a2,
  IconSelector as a3,
  useNavigate as a4,
  Table$1 as a5,
  TableHeader as a6,
  TableRow as a7,
  TableHead as a8,
  TableBody as a9,
  CartesianGrid as aA,
  Tooltip as aB,
  DEFAULT_MENU_ITEMS as aC,
  useWordPressMedia as aD,
  MenuIcon as aE,
  ICON_MAP as aF,
  TableCell as aa,
  formatDateForInput as ab,
  getCountryOptions as ac,
  getCountryName as ad,
  formatDate$1 as ae,
  clsx as af,
  Dot as ag,
  findAllByType as ah,
  ErrorBar as ai,
  Layer as aj,
  filterProps as ak,
  Curve as al,
  interpolateNumber$2 as am,
  isNil$1 as an,
  hasClipDot as ao,
  LabelList as ap,
  getValueByDataKey as aq,
  uniqueId as ar,
  Global as as,
  getCateCoordinateOfLine as at,
  generateCategoricalChart as au,
  XAxis as av,
  YAxis as aw,
  formatAxisMap as ax,
  SearchFilterToolbar as ay,
  ResponsiveContainer as az,
  isAiReady as b,
  aiApi as c,
  CardContent as d,
  Badge as e,
  CardHeader as f,
  CardTitle as g,
  CardDescription as h,
  isAiEligible as i,
  getErrorContext as j,
  ConfirmationDialog as k,
  buildYatraSinglePublicUrls as l,
  isWordPressPlainPermalink as m,
  IconPicker as n,
  prepareWordPressMediaFrameOpen as o,
  parseItineraryText as p,
  fetchSettings as q,
  unwrapApiPayload as r,
  ConditionalRender as s,
  CardFooter as t,
  usePermissions as u,
  PremiumUpgradeDialog as v,
  Label as w,
  SearchableSelect as x,
  buildYatraAccountViewUrl as y,
  navigateMenu as z
};
//# sourceMappingURL=app.js.map

```
