import {
  agentGuiWorkbenchDockEntryId,
  agentGuiWorkbenchProviderFromIdentifier,
  agentGuiWorkbenchTypeId,
  createAgentGuiWorkbenchLaunchDescriptor
} from "./chunk-3735XYFZ.js";
import {
  agentGuiWorkbenchProviderFromInstanceId,
  createAgentGuiWorkbenchNodeStateSource,
  normalizeAgentGuiWorkbenchNodeState,
  normalizeAgentGuiWorkbenchState
} from "./chunk-GEXHKJK5.js";
import {
  agentGuiWorkbenchProviderLabels,
  agentGuiWorkbenchProviders,
  isAgentGuiWorkbenchDefaultDockProvider,
  resolveAgentGuiWorkbenchProviderLabel
} from "./chunk-22L4VWUR.js";
import {
  agentGuiDockIconUrls,
  resolveAgentGUIExpandedWindowFrame,
  shouldAutoCollapseAgentGUIConversationRail
} from "./chunk-GYG57VTA.js";

// workbench/contribution.ts
import { createElement as createElement2 } from "react";
import {
  getWorkbenchLayoutFrame
} from "@tutti-os/workbench-surface";

// workbench/header.ts
import { createElement } from "react";
import { Button, PanelIcon, cn } from "@tutti-os/ui-system";
function AgentGuiWorkbenchHeader({
  className,
  copy,
  defaultActions,
  isConversationRailAutoCollapsed,
  isConversationRailCollapsed,
  onToggleConversationRail,
  title,
  ...headerProps
}) {
  const toggleLabel = isConversationRailCollapsed ? copy.expandConversationRail : copy.collapseConversationRail;
  return createElement(
    "header",
    {
      ...headerProps,
      className: cn(
        "flex h-full min-h-0 items-center justify-between gap-3 bg-[var(--background-panel)] px-2 pl-3",
        className
      )
    },
    createElement(
      "div",
      { className: "flex min-w-0 items-center gap-2" },
      createElement(
        "span",
        {
          className: "min-w-0 truncate text-[13px] font-semibold leading-5 text-[var(--text-primary)]"
        },
        title?.trim() || copy.fallbackAgentLabel
      ),
      createElement(
        Button,
        {
          "aria-label": toggleLabel,
          className: "cursor-pointer rounded-md",
          "data-agent-gui-conversation-rail-auto-collapsed": isConversationRailAutoCollapsed ? "true" : void 0,
          "data-agent-gui-conversation-rail-collapsed": isConversationRailCollapsed ? "true" : void 0,
          "data-testid": "agent-gui-toggle-conversation-rail",
          size: "icon-sm",
          title: toggleLabel,
          type: "button",
          variant: "ghost",
          onClick: (event) => {
            event.stopPropagation();
            onToggleConversationRail(!isConversationRailCollapsed);
          },
          onDoubleClick: (event) => event.stopPropagation(),
          onPointerDown: (event) => event.stopPropagation()
        },
        createElement(PanelIcon, { className: "size-[18px]" })
      )
    ),
    createElement(
      "div",
      {
        className: "flex flex-none items-center gap-1",
        onDoubleClick: (event) => event.stopPropagation(),
        onPointerDown: (event) => event.stopPropagation()
      },
      defaultActions
    )
  );
}

// workbench/contribution.ts
var agentGuiWorkbenchDefaultNodeFrame = {
  height: 560,
  width: 1040,
  x: 140,
  y: 48
};
var agentGuiWorkbenchDefaultUsableHeightRatio = 0.7;
var agentGuiWorkbenchCompactVisibleAreaRatio = 0.9;
var AGENT_GUI_WORKBENCH_CONVERSATION_RAIL_TOGGLE_EVENT = "nextop:agent-gui-workbench-conversation-rail-toggle";
var agentGuiWorkbenchDefaultCopy = {
  collapseConversationRail: "Collapse conversation rail",
  expandConversationRail: "Expand conversation rail",
  fallbackAgentLabel: "Agent",
  nodeTitle: "Agent"
};
function createAgentGuiWorkbenchContribution(input) {
  const nodeStateSource = createAgentGuiWorkbenchNodeStateSource({
    workspaceId: input.workspaceId
  });
  const frame = input.frame ?? agentGuiWorkbenchDefaultNodeFrame;
  const copy = resolveAgentGuiWorkbenchContributionCopy(input.copy);
  return {
    dockEntries: agentGuiWorkbenchProviders.map(
      (provider, index) => createAgentGuiWorkbenchDockEntry({
        label: agentGuiWorkbenchProviderLabels[provider],
        iconUrl: input.dockIconUrls?.[provider] ?? agentGuiDockIconUrls[provider],
        order: index,
        provider,
        renderPreview: input.renderPreview,
        sectionId: input.dockSectionId ?? "agents",
        visibility: input.resolveDockEntryVisibility?.(provider) ?? (isAgentGuiWorkbenchDefaultDockProvider(provider) ? "always" : "never")
      })
    ),
    externalStateSource: nodeStateSource.externalStateSource,
    id: input.id ?? "workspace-agent-gui",
    nodes: [
      {
        frame,
        instance: { mode: "multi" },
        renderBody: (context) => input.renderBody(
          context,
          {
            nodeTypeId: agentGuiWorkbenchTypeId,
            onStateChange: (state) => {
              nodeStateSource.writeNodeState({
                instanceId: context.instanceId,
                state,
                typeId: agentGuiWorkbenchTypeId
              });
            },
            provider: agentGuiWorkbenchProviderFromInstanceId(
              context.instanceId
            )
          }
        ),
        renderHeader: ({
          defaultActions,
          dragHandleProps,
          externalNodeState,
          instanceId,
          isFocused,
          node,
          surfaceSize,
          windowActions
        }) => {
          const provider = agentGuiWorkbenchProviderFromInstanceId(instanceId);
          const title = resolveAgentGuiWorkbenchProviderLabel(provider);
          const workbenchState = normalizeAgentGuiWorkbenchState(
            externalNodeState ?? node.data.runtimeNodeState
          );
          const nodeState = normalizeAgentGuiWorkbenchNodeState(
            workbenchState,
            provider
          );
          const isConversationRailAutoCollapsed = shouldAutoCollapseAgentGUIConversationRail(node.frame.width);
          const isConversationRailCollapsed = nodeState.conversationRailCollapsed === true || isConversationRailAutoCollapsed;
          const persistConversationRailCollapsed = (collapsed) => {
            nodeStateSource.writeNodeState({
              instanceId,
              state: {
                ...workbenchState,
                conversationRailCollapsed: collapsed
              },
              typeId: agentGuiWorkbenchTypeId
            });
          };
          const announceConversationRailCollapsed = (collapsed) => {
            window.dispatchEvent(
              new CustomEvent(
                AGENT_GUI_WORKBENCH_CONVERSATION_RAIL_TOGGLE_EVENT,
                {
                  detail: {
                    conversationRailCollapsed: collapsed,
                    instanceId
                  }
                }
              )
            );
          };
          return createElement2(AgentGuiWorkbenchHeader, {
            copy,
            defaultActions,
            isConversationRailAutoCollapsed,
            isConversationRailCollapsed,
            title,
            ...dragHandleProps,
            onPointerDown: (event) => {
              dragHandleProps.onPointerDown?.(event);
              if (!isFocused) {
                windowActions.focus();
              }
            },
            onToggleConversationRail: (nextCollapsed) => {
              announceConversationRailCollapsed(nextCollapsed);
              if (isConversationRailCollapsed && nextCollapsed === false && node.displayMode !== "fullscreen") {
                const expandedFrame = resolveAgentGUIExpandedWindowFrame({
                  conversationRailWidthPx: nodeState.conversationRailWidthPx,
                  desktopSize: surfaceSize,
                  height: node.frame.height,
                  position: {
                    x: node.frame.x,
                    y: node.frame.y
                  },
                  width: node.frame.width
                });
                windowActions.resize({
                  ...node.frame,
                  height: expandedFrame.size.height,
                  width: expandedFrame.size.width,
                  x: expandedFrame.position.x,
                  y: expandedFrame.position.y
                });
              }
              persistConversationRailCollapsed(nextCollapsed);
            }
          });
        },
        title: copy.nodeTitle,
        typeId: agentGuiWorkbenchTypeId,
        window: {
          closable: true,
          defaultOpen: false,
          minimizedDock: {
            kind: "snapshot"
          },
          minimizable: true
        }
      }
    ],
    onLaunchRequest: (request) => {
      if (request.typeId !== agentGuiWorkbenchTypeId) {
        return null;
      }
      const {
        activation,
        dockEntryId,
        instanceId,
        provider,
        reuseDockEntryNode,
        targetAgentSessionId
      } = createAgentGuiWorkbenchLaunchDescriptor(request);
      const title = resolveAgentGuiWorkbenchProviderLabel(provider);
      if (targetAgentSessionId) {
        const previousState = nodeStateSource.readNodeState({
          instanceId,
          typeId: agentGuiWorkbenchTypeId
        });
        nodeStateSource.writeNodeState({
          instanceId,
          state: {
            ...previousState ?? normalizeAgentGuiWorkbenchState(null),
            ...targetAgentSessionId ? { lastActiveAgentSessionId: targetAgentSessionId } : {}
          },
          typeId: agentGuiWorkbenchTypeId
        });
      }
      const defaultFrame = resolveAgentGuiWorkbenchDefaultLaunchFrame({
        frame,
        request
      });
      return {
        activation,
        defaultFrame,
        dockEntryId,
        framePolicy: isAgentGuiWorkbenchCompactVisibleFrame(defaultFrame, frame) ? "absolute" : "cascade-same-type-centered",
        instanceId,
        reuseDockEntryNode,
        title,
        typeId: agentGuiWorkbenchTypeId
      };
    }
  };
}
function resolveAgentGuiWorkbenchDefaultLaunchFrame(input) {
  const layoutFrame = getWorkbenchLayoutFrame(
    input.request.surfaceSize,
    input.request.layoutConstraints
  );
  const defaultHeight = Math.round(
    layoutFrame.height * agentGuiWorkbenchDefaultUsableHeightRatio
  );
  if (layoutFrame.width < input.frame.width || layoutFrame.height < input.frame.height) {
    const width = Math.round(
      layoutFrame.width * agentGuiWorkbenchCompactVisibleAreaRatio
    );
    const height = Math.round(
      layoutFrame.height * agentGuiWorkbenchCompactVisibleAreaRatio
    );
    return {
      height,
      width,
      x: Math.round(layoutFrame.x + (layoutFrame.width - width) / 2),
      y: Math.round(layoutFrame.y + (layoutFrame.height - height) / 2)
    };
  }
  return {
    ...input.frame,
    height: defaultHeight
  };
}
function isAgentGuiWorkbenchCompactVisibleFrame(frame, defaultFrame) {
  return frame.width !== defaultFrame.width || frame.x !== defaultFrame.x;
}
function resolveAgentGuiWorkbenchContributionCopy(copy) {
  return {
    ...agentGuiWorkbenchDefaultCopy,
    ...copy
  };
}
function createAgentGuiWorkbenchDockEntry(input) {
  return {
    icon: createElement2("img", {
      alt: "",
      draggable: false,
      src: input.iconUrl
    }),
    iconSize: "large",
    id: agentGuiWorkbenchDockEntryId(input.provider),
    label: input.label,
    launchBehavior: "enabled",
    launchPayload: { provider: input.provider },
    matchNode: (node) => node.data.typeId === agentGuiWorkbenchTypeId && agentGuiWorkbenchProviderFromIdentifier(node.data.instanceId) === input.provider,
    order: input.order,
    providePopupItemPreview: (item) => {
      if (!input.renderPreview) {
        return null;
      }
      const { externalNodeState, node } = item;
      const state = externalNodeState ?? {};
      const title = resolveAgentGuiWorkbenchDockPopupTitle(externalNodeState) ?? node.title;
      const lines = [input.label, state.lastActiveAgentSessionId].filter(
        (line) => Boolean(line?.trim())
      );
      const revision = `${input.provider}
${title}
${lines.join("\n")}`;
      return {
        element: input.renderPreview(
          createAgentGuiWorkbenchPreviewBodyContext(item),
          {
            nodeTypeId: agentGuiWorkbenchTypeId,
            onStateChange: () => void 0,
            provider: input.provider
          }
        ),
        kind: "component",
        revision
      };
    },
    resolvePopupItem: ({ externalNodeState }) => {
      const title = resolveAgentGuiWorkbenchDockPopupTitle(externalNodeState);
      return {
        revision: `${input.provider}
${title ?? ""}`,
        title
      };
    },
    sectionId: input.sectionId,
    typeId: agentGuiWorkbenchTypeId,
    visibility: input.visibility
  };
}
function resolveAgentGuiWorkbenchDockPopupTitle(state) {
  const title = state?.lastActiveConversationTitle;
  return typeof title === "string" && title.trim() ? title.trim() : null;
}
function createAgentGuiWorkbenchPreviewBodyContext(input) {
  return {
    activation: null,
    displayMode: input.node.displayMode,
    externalNodeState: input.externalNodeState,
    externalWorkspaceState: input.externalWorkspaceState,
    focus: () => void 0,
    host: input.host,
    instanceId: input.node.data.instanceId,
    instanceKey: input.node.data.instanceKey ?? null,
    isFocused: false,
    node: input.node,
    setNodeRuntimeState: () => void 0,
    setSnapshotNodeState: () => void 0
  };
}

export {
  AgentGuiWorkbenchHeader,
  agentGuiWorkbenchDefaultNodeFrame,
  agentGuiWorkbenchDefaultUsableHeightRatio,
  agentGuiWorkbenchCompactVisibleAreaRatio,
  AGENT_GUI_WORKBENCH_CONVERSATION_RAIL_TOGGLE_EVENT,
  agentGuiWorkbenchDefaultCopy,
  createAgentGuiWorkbenchContribution,
  resolveAgentGuiWorkbenchDefaultLaunchFrame,
  resolveAgentGuiWorkbenchContributionCopy
};
//# sourceMappingURL=chunk-4RB33ETE.js.map