"use client";
export { WorkflowCanvasShell } from '../chunk-ARLYOLSO.mjs';
export { AdminOrganizationForm, AdminOrganizationList, AdminPermissionList, AdminUserForm, AdminUserList } from '../chunk-ZQEMKEEH.mjs';
export { ConsentScreen, ForgotPassword, MfaChallenge, PasswordlessSignIn, ResetPassword, SignIn, SignUp, SsoConnectorList, SsoEmailForm, UserButton, VerifyEmail } from '../chunk-2ZY3IQ2I.mjs';
export { UpgradePrompt } from '../chunk-DJ33CSGJ.mjs';
export { ImpersonationBanner } from '../chunk-SJ6SUS7H.mjs';
import { UsersPageView, RolesPageView } from '../chunk-GQWC4EKE.mjs';
export { WorkflowWorkspace } from '../chunk-GQWC4EKE.mjs';
export { PlatformSettings } from '../chunk-OEZ7GAJY.mjs';
export { AdminOrganizationDetail } from '../chunk-2E7HYTS7.mjs';
export { LinkedAccountsTabContent, MfaManage, MfaSetup, ProfileTabContent, SecurityTabContent, SessionsTabContent, UserProfile } from '../chunk-WS3IJFPW.mjs';
export { AuthLayout, BackupCodeGrid, OtpInput, PasswordStrengthMeter, SocialLoginButtons } from '../chunk-3VYD7QL2.mjs';
export { BillingPanel } from '../chunk-PD3JLDA5.mjs';
export { AgentsWorkspace, applyWorkflowExecutionEventToStore, resetWorkflowRunPresentation, useRunEvents, useWorkflowExecution, useWorkflowRunPresentation } from '../chunk-BWUFLW5W.mjs';
import '../chunk-6QJI5YOJ.mjs';
import { usePlatformState } from '../chunk-OVQ4MKCV.mjs';
export { PlatformAppShell, PlatformStateProvider, usePlatformState } from '../chunk-OVQ4MKCV.mjs';
export { createPlatformRbac } from '../chunk-BUDZNAKL.mjs';
import { createUser, listUsers, addOrganizationMember } from '../chunk-UHHPBREK.mjs';
export { addOrganizationDomain, addOrganizationMember, createOrganization, createOrganizationInvitation, createPermission, createSecret, createUser, deleteOrganization, deletePermission, deleteUser, disableSecret, getSecret, getUserPermissions, listOrganizationDomains, listOrganizationInvitations, listOrganizationMembers, listOrganizations, listPermissions, listSecrets, listUsers, removeOrganizationMember, resetUserPassword, rotateSecret, setUserPermissions, setWindsockAdminClient, updateOrganization, updatePermission, updateUser, verifyOrganizationDomain } from '../chunk-UHHPBREK.mjs';
import '../chunk-AXBD6OAF.mjs';
import '../chunk-JB6RNAD2.mjs';
import '../chunk-LEXBTVGM.mjs';
import '../chunk-EAIE4QGD.mjs';
import { Select, useAuth, usePlatformPreferences, filterByPermission, AppNavigation, GlassModal, useNotifications, Textarea } from '../chunk-ZQRUAXGP.mjs';
import { useTranslations, useLocale } from '../chunk-7VJ7CMMT.mjs';
import { listModelProviderConnections, listWorkflowTemplates, createWorkflowFromTemplate, aiGenerateWorkflow, createWorkflow, saveWorkflowDraft } from '../chunk-RHRJXK5R.mjs';
import '../chunk-3AY5HIQ6.mjs';
import '../chunk-PLTLRL2V.mjs';
import { Button, IconButton, Badge } from '../chunk-WR55H7DH.mjs';
import '../chunk-D2JF6C3E.mjs';
import { usePathname, useRouter } from '../chunk-QWG2FMUN.mjs';
import '../chunk-G7JQ4OCE.mjs';
import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
import { useState, useMemo, useCallback, useEffect } from 'react';
import { SunIcon, MoonIcon } from '@heroicons/react/24/outline';
import { SUPPORTED_LOCALES, LANGUAGE_META, applyClientLocale, LOCALE_TO_SHORT } from '@datatechsolutions/shared-domain/i18n';

function SessionSwitcher({
  organizations,
  users,
  organizationId,
  userEmail,
  onOrganizationChange,
  onUserChange
}) {
  const tSession = useTranslations("platform.session");
  const tCommon = useTranslations("common");
  return /* @__PURE__ */ jsxs("div", { className: "session-switcher", children: [
    /* @__PURE__ */ jsx(
      Select,
      {
        value: organizationId,
        "aria-label": tSession("organization"),
        onChange: (event) => {
          onOrganizationChange(event.target.value);
        },
        options: organizations,
        placeholder: tSession("organization")
      }
    ),
    /* @__PURE__ */ jsx(
      Select,
      {
        value: userEmail,
        "aria-label": tSession("user"),
        onChange: (event) => {
          onUserChange(event.target.value);
        },
        options: users,
        placeholder: tSession("user")
      }
    ),
    /* @__PURE__ */ jsx(Button, { outline: true, onClick: () => globalThis.location.reload(), children: tCommon("refresh") })
  ] });
}
function PlatformDockContainer({
  actor,
  navigationItems,
  dashboardPath = "/dashboard",
  signOutPath = "/login"
}) {
  const pathname = usePathname();
  const router = useRouter();
  const { logout } = useAuth();
  const tCommon = useTranslations("common");
  const {
    dockPosition,
    dockAutoHide,
    dockEnabled
  } = usePlatformPreferences();
  const [profileOpen, setProfileOpen] = useState(false);
  const filteredItems = useMemo(
    () => filterByPermission(navigationItems, actor?.permissions ?? []),
    [navigationItems, actor]
  );
  const handleNavigate = useCallback((href) => router.push(href), [router]);
  const handleSignOut = useCallback(() => {
    void logout(signOutPath);
  }, [logout, signOutPath]);
  if (pathname === dashboardPath) return null;
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(
      AppNavigation,
      {
        items: filteredItems,
        pathname,
        dockEnabled,
        dockPosition,
        dockAutoHide,
        showLaunchpad: false,
        onNavigate: handleNavigate,
        onOpenProfile: () => setProfileOpen(true),
        onSignOut: handleSignOut,
        labels: {
          home: tCommon("home"),
          profile: tCommon("profile"),
          signOut: tCommon("signOut")
        }
      }
    ),
    /* @__PURE__ */ jsx(
      GlassModal,
      {
        open: profileOpen,
        onClose: () => setProfileOpen(false),
        title: tCommon("profile"),
        children: /* @__PURE__ */ jsx("div", {})
      }
    )
  ] });
}
function useLocaleSwitcher() {
  const locale = useLocale();
  const { client } = useAuth();
  const setLocale = useCallback(
    (newLocale) => {
      const resolved = applyClientLocale(newLocale);
      client.updateLocale(resolved);
    },
    [client]
  );
  return {
    locale,
    shortCode: LOCALE_TO_SHORT[locale] || "pt",
    setLocale,
    locales: SUPPORTED_LOCALES
  };
}
var LOCALE_OPTIONS = SUPPORTED_LOCALES.map((code) => ({
  value: code,
  label: LANGUAGE_META[code].nativeName
}));
function PreferencesControls() {
  const { locale, setLocale } = useLocaleSwitcher();
  const { theme, setTheme } = usePlatformPreferences();
  const toggleTheme = () => setTheme(theme === "dark" ? "light" : "dark");
  const t = useTranslations("platform.preferences");
  return /* @__PURE__ */ jsxs("div", { className: "preferences-controls", children: [
    /* @__PURE__ */ jsx(
      Select,
      {
        value: locale,
        options: LOCALE_OPTIONS,
        onChange: (event) => setLocale(event.target.value)
      }
    ),
    /* @__PURE__ */ jsx(
      IconButton,
      {
        label: t("theme"),
        icon: theme === "dark" ? /* @__PURE__ */ jsx(SunIcon, {}) : /* @__PURE__ */ jsx(MoonIcon, {}),
        onClick: toggleTheme,
        variant: "outline"
      }
    )
  ] });
}

// src/platform/windsock-mappers.ts
function mapAuthOrg(raw) {
  return {
    id: raw.id,
    name: raw.displayName ?? raw.name,
    currency: "BRL",
    country: "BR"
  };
}
function mapAdminUser(row, normalizeRole) {
  return {
    id: row.id,
    email: row.email,
    name: row.name ?? row.email,
    role: normalizeRole(row.role),
    active: row.status === "active"
  };
}
var ORG_ROLE_MAP = {
  owner: "owner",
  admin: "admin",
  manager: "admin",
  analyst: "member",
  operator: "member",
  viewer: "viewer",
  finance: "member",
  sales: "member",
  support: "member",
  member: "member"
};
function mapRoleToOrgRole(role) {
  return ORG_ROLE_MAP[role] ?? "member";
}
function UsersSettingsSection({ normalizeRole }) {
  const t = useTranslations("platform.users");
  const { currentOrganizationId } = usePlatformState();
  const { error: notifyError, success: notifySuccess } = useNotifications();
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const reload = async () => {
    try {
      const result = await listUsers({ organizationId: currentOrganizationId });
      setUsers(result.items.map((row) => mapAdminUser(row, normalizeRole)));
    } catch (error) {
      notifyError(error.message);
    } finally {
      setLoading(false);
    }
  };
  useEffect(() => {
    void reload();
  }, [currentOrganizationId]);
  return /* @__PURE__ */ jsx(
    UsersPageView,
    {
      labels: {
        title: t("title"),
        subtitle: t("subtitle"),
        create: t("create"),
        list: t("list"),
        add: t("add"),
        statusActive: t("statusActive"),
        statusInactive: t("statusInactive"),
        name: t("name"),
        email: t("email"),
        role: t("role"),
        status: t("status"),
        save: t("save"),
        userNamePlaceholder: t("userNamePlaceholder"),
        userEmailPlaceholder: t("userEmailPlaceholder")
      },
      users: loading ? [] : users,
      onCreateUser: async ({ name, email, role }) => {
        try {
          await createUser({ name, email, role, organizationId: currentOrganizationId });
          notifySuccess(t("add"));
          await reload();
        } catch (error) {
          notifyError(error.message);
        }
      },
      onUpdateRole: () => {
        notifyError(t("reassignInRolesTab"));
      }
    }
  );
}
function RolesSettingsSection({ roleDefinitions, roleOptions, normalizeRole }) {
  const t = useTranslations("platform.roles");
  const { currentOrganizationId } = usePlatformState();
  const { error: notifyError, success: notifySuccess } = useNotifications();
  const [users, setUsers] = useState([]);
  useEffect(() => {
    listUsers({ organizationId: currentOrganizationId }).then((result) => setUsers(result.items.map((row) => mapAdminUser(row, normalizeRole)))).catch((error) => notifyError(error.message));
  }, [currentOrganizationId, notifyError, normalizeRole]);
  return /* @__PURE__ */ jsx(
    RolesPageView,
    {
      roleDefinitions,
      roleOptions,
      labels: {
        title: t("title"),
        subtitle: t("subtitle"),
        definitions: t("definitions"),
        assign: t("assign"),
        current: t("current"),
        permissionsEnabled: t("permissionsEnabled"),
        apply: t("apply"),
        role: t("role"),
        description: t("description"),
        user: t("user"),
        email: t("email"),
        userEmail: t("userEmail")
      },
      users,
      onAssignRole: async ({ email, role }) => {
        const target = users.find((user) => user.email.toLowerCase() === email.toLowerCase());
        if (!target) {
          notifyError(t("userNotFound"));
          return;
        }
        try {
          await addOrganizationMember(currentOrganizationId, target.id, mapRoleToOrgRole(role));
          notifySuccess(t("apply"));
        } catch (error) {
          notifyError(error.message);
        }
      }
    }
  );
}
function AiWorkflowGenerateModal({ open, onClose, onGenerated }) {
  const { error: notifyError, success: notifySuccess } = useNotifications();
  const t = useTranslations("agents.workflow");
  const [connections, setConnections] = useState([]);
  const [connectionId, setConnectionId] = useState("");
  const [prompt, setPrompt] = useState("");
  const [busy, setBusy] = useState(false);
  useEffect(() => {
    if (!open) return;
    listModelProviderConnections().then((items) => {
      setConnections(items);
      const firstEnabled = items.find((item) => item.enabled) ?? items[0];
      setConnectionId(firstEnabled?.id ?? "");
    }).catch((error) => notifyError(error.message));
  }, [open, notifyError]);
  async function handleSubmit() {
    if (!connectionId) {
      notifyError(t("aiErrorMissingConnection"));
      return;
    }
    if (prompt.trim().length === 0) {
      notifyError(t("aiErrorMissingPrompt"));
      return;
    }
    setBusy(true);
    try {
      const generation = await aiGenerateWorkflow({ prompt: prompt.trim(), connectionId });
      const workflow = await createWorkflow({ name: deriveWorkflowName(prompt) });
      const saved = await saveWorkflowDraft(workflow.id, generation.graph, { name: workflow.name });
      if (!generation.ok) {
        notifyError(
          t("aiWarnValidation"),
          [...generation.structuralIssues, ...generation.nodeIssues.map((issue) => `${issue.nodeId}: ${issue.message}`)].join("\n")
        );
      } else {
        notifySuccess(t("aiSuccessGenerated"));
      }
      onGenerated(saved);
      onClose();
      setPrompt("");
    } catch (error) {
      notifyError(error.message);
    } finally {
      setBusy(false);
    }
  }
  return /* @__PURE__ */ jsx(
    GlassModal,
    {
      open,
      onClose,
      title: t("aiTitle"),
      subtitle: t("aiSubtitle"),
      onSubmit: handleSubmit,
      showFormFooter: true,
      submitLabel: busy ? t("aiGenerateBusy") : t("aiGenerate"),
      cancelLabel: t("aiCancel"),
      submitDisabled: busy,
      isLoading: busy,
      children: /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
        /* @__PURE__ */ jsxs("label", { className: "block text-sm font-medium text-slate-700 dark:text-slate-200", children: [
          t("aiConnection"),
          /* @__PURE__ */ jsxs(
            "select",
            {
              className: "mt-1 w-full rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm text-slate-900 dark:border-white/10 dark:bg-white/5 dark:text-slate-100",
              value: connectionId,
              onChange: (event) => setConnectionId(event.target.value),
              disabled: busy,
              children: [
                /* @__PURE__ */ jsx("option", { value: "", children: t("aiConnectionPlaceholder") }),
                connections.map((connection) => /* @__PURE__ */ jsxs("option", { value: connection.id, children: [
                  connection.name,
                  " ",
                  connection.enabled ? "" : t("aiDisabledSuffix")
                ] }, connection.id))
              ]
            }
          )
        ] }),
        /* @__PURE__ */ jsxs("label", { className: "block text-sm font-medium text-slate-700 dark:text-slate-200", children: [
          t("aiPromptLabel"),
          /* @__PURE__ */ jsx(
            Textarea,
            {
              rows: 6,
              className: "mt-1 w-full",
              placeholder: t("aiPromptPlaceholder"),
              value: prompt,
              onChange: (event) => setPrompt(event.target.value),
              disabled: busy
            }
          )
        ] }),
        /* @__PURE__ */ jsx("p", { className: "text-xs text-slate-500 dark:text-slate-400", children: t("aiFooterNote") })
      ] })
    }
  );
}
function deriveWorkflowName(prompt) {
  const trimmed = prompt.trim().replace(/\s+/g, " ");
  if (trimmed.length <= 60) return trimmed;
  return `${trimmed.slice(0, 57)}\u2026`;
}
function WorkflowTemplateModal({ open, onClose, onCreated }) {
  const tWorkflow = useTranslations("agents.workflow");
  const tCommon = useTranslations("common");
  const { error: notifyError, success: notifySuccess } = useNotifications();
  const [templates, setTemplates] = useState([]);
  const [connections, setConnections] = useState([]);
  const [templateId, setTemplateId] = useState("");
  const [connectionId, setConnectionId] = useState("");
  const [name, setName] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  useEffect(() => {
    if (!open) return;
    let cancelled = false;
    setIsLoading(true);
    setTemplateId("");
    setConnectionId("");
    setName("");
    (async () => {
      try {
        const [tpls, conns] = await Promise.all([
          listWorkflowTemplates(),
          listModelProviderConnections()
        ]);
        if (cancelled) return;
        setTemplates(tpls);
        setConnections(conns);
        if (tpls.length > 0) {
          const firstTemplate = tpls[0];
          if (firstTemplate) setTemplateId(firstTemplate.id);
        }
        if (conns.length > 0) {
          const firstConnection = conns[0];
          if (firstConnection) setConnectionId(firstConnection.id);
        }
      } catch (error) {
        if (!cancelled) notifyError(error.message);
      } finally {
        if (!cancelled) setIsLoading(false);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [open, notifyError]);
  const selectedTemplate = useMemo(
    () => templates.find((t) => t.id === templateId),
    [templates, templateId]
  );
  const canSubmit = !isLoading && !isSubmitting && templateId.length > 0 && connectionId.length > 0;
  const handleSubmit = useCallback(async () => {
    if (!canSubmit) return;
    setIsSubmitting(true);
    try {
      const created = await createWorkflowFromTemplate(templateId, {
        connectionId,
        name: name.trim().length > 0 ? name.trim() : void 0
      });
      notifySuccess(tWorkflow("templateCreatedSuccess"));
      onCreated(created);
      onClose();
    } catch (error) {
      notifyError(error.message);
    } finally {
      setIsSubmitting(false);
    }
  }, [canSubmit, templateId, connectionId, name, onCreated, onClose, notifySuccess, notifyError, tWorkflow]);
  return /* @__PURE__ */ jsx(
    GlassModal,
    {
      open,
      onClose,
      title: tWorkflow("createFromTemplate"),
      subtitle: selectedTemplate?.description ?? tWorkflow("createFromTemplateSubtitle"),
      gradient: "from-indigo-500 to-purple-600",
      showFormFooter: true,
      onSubmit: (event) => {
        event.preventDefault();
        void handleSubmit();
      },
      isLoading: isSubmitting,
      submitDisabled: !canSubmit,
      submitLabel: tCommon("create"),
      cancelLabel: tCommon("cancel"),
      maxWidth: "lg",
      children: /* @__PURE__ */ jsx("div", { className: "space-y-4", children: isLoading ? /* @__PURE__ */ jsx("div", { className: "shimmer h-32 w-full rounded-xl" }) : templates.length === 0 ? /* @__PURE__ */ jsx("p", { className: "text-sm text-gray-500 dark:text-gray-400", children: tWorkflow("noTemplatesAvailable") }) : /* @__PURE__ */ jsxs(Fragment, { children: [
        /* @__PURE__ */ jsxs("label", { className: "block", children: [
          /* @__PURE__ */ jsx("span", { className: "mb-1 block text-xs font-medium text-gray-700 dark:text-gray-300", children: tWorkflow("template") }),
          /* @__PURE__ */ jsx(
            "select",
            {
              className: "w-full rounded-lg border border-white/20 bg-white/70 px-3 py-2 text-sm text-gray-900 shadow-sm backdrop-blur dark:bg-gray-800/70 dark:text-gray-100",
              value: templateId,
              onChange: (event) => setTemplateId(event.target.value),
              children: templates.map((template) => /* @__PURE__ */ jsx("option", { value: template.id, children: template.name }, template.id))
            }
          )
        ] }),
        /* @__PURE__ */ jsxs("label", { className: "block", children: [
          /* @__PURE__ */ jsx("span", { className: "mb-1 block text-xs font-medium text-gray-700 dark:text-gray-300", children: tWorkflow("llmConnection") }),
          connections.length === 0 ? /* @__PURE__ */ jsx("p", { className: "rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-800 dark:border-amber-500/30 dark:bg-amber-500/10 dark:text-amber-200", children: tWorkflow("noConnectionsHint") }) : /* @__PURE__ */ jsx(
            "select",
            {
              className: "w-full rounded-lg border border-white/20 bg-white/70 px-3 py-2 text-sm text-gray-900 shadow-sm backdrop-blur dark:bg-gray-800/70 dark:text-gray-100",
              value: connectionId,
              onChange: (event) => setConnectionId(event.target.value),
              children: connections.map((connection) => /* @__PURE__ */ jsxs("option", { value: connection.id, children: [
                connection.name,
                connection.providerSlug ? ` \xB7 ${connection.providerSlug}` : ""
              ] }, connection.id))
            }
          )
        ] }),
        /* @__PURE__ */ jsxs("label", { className: "block", children: [
          /* @__PURE__ */ jsxs("span", { className: "mb-1 block text-xs font-medium text-gray-700 dark:text-gray-300", children: [
            tWorkflow("workflowName"),
            /* @__PURE__ */ jsxs("span", { className: "ml-1 text-[10px] text-gray-400", children: [
              "(",
              tCommon("optional"),
              ")"
            ] })
          ] }),
          /* @__PURE__ */ jsx(
            "input",
            {
              type: "text",
              value: name,
              placeholder: selectedTemplate?.name ?? "",
              onChange: (event) => setName(event.target.value),
              className: "w-full rounded-lg border border-white/20 bg-white/70 px-3 py-2 text-sm text-gray-900 shadow-sm backdrop-blur dark:bg-gray-800/70 dark:text-gray-100"
            }
          )
        ] }),
        selectedTemplate && selectedTemplate.tags.length > 0 ? /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-1.5", children: selectedTemplate.tags.map((tag) => /* @__PURE__ */ jsx(Badge, { color: "indigo", size: "xs", children: tag }, tag)) }) : null
      ] }) })
    }
  );
}

export { AiWorkflowGenerateModal, ORG_ROLE_MAP, PlatformDockContainer, PreferencesControls, RolesSettingsSection, SessionSwitcher, UsersSettingsSection, WorkflowTemplateModal, mapAdminUser, mapAuthOrg, mapRoleToOrgRole, useLocaleSwitcher };
//# sourceMappingURL=index.mjs.map
//# sourceMappingURL=index.mjs.map