import type { ComponentType, DragEvent as ReactDragEvent, MouseEvent as ReactMouseEvent, ReactNode } from "react";

export type ApiSettings = {
  apiBaseUrl: string;
  apiKey: string;
  accessToken: string;
};

export type DeltaDeletedItem = {
  id: string;
  resource_type?: string | null;
  revision?: string | null;
  deleted_at?: string | null;
};

export type DeltaCollectionResponse<TItem, TDeleted extends DeltaDeletedItem = DeltaDeletedItem> = {
  items: TItem[];
  deleted: TDeleted[];
  watermark?: string | null;
  has_more?: boolean;
  full?: boolean;
};

export type DeltaQueryOptions = {
  since?: string | null;
  limit?: number;
  include_deleted?: boolean;
};

export type AuthUser = {
  id: string;
  account_id: string;
  email: string;
  display_name?: string | null;
  tenant_display_name?: string | null;
  is_tenant_admin?: boolean;
  password_reset_required?: boolean;
  preferred_language?: string | null;
  enabled_language_codes?: string[];
  ui_preferences?: UserUiPreferences;
};

export type UserUiTheme = "system" | "light" | "dark";

export type UserUiPreferences = {
  compact_tables: boolean;
  show_inline_help_hints: boolean;
  reduce_motion: boolean;
  sticky_section_sidebars: boolean;
  theme: UserUiTheme;
};

export type AuthTenant = {
  id: string;
  slug: string;
  name: string;
  is_active?: boolean;
  default_locale?: string;
  enabled_language_codes?: string[];
};

export type AuthTenantMembership = AuthTenant & {
  roles?: string[];
  is_active?: boolean;
};

export type AuthRole = {
  id: string;
  slug: string;
  name: string;
  permissions: string[];
  level?: "tenant" | "system";
};

export type AuthGroup = {
  id: string;
  slug: string;
  name: string;
};

export type PrincipalContext = {
  account_id: string;
  membership_id?: string | null;
  tenant_id?: string | null;
  identity_id?: string | null;
  scopes: string[];
  group_ids: string[];
  role_ids?: string[];
  function_assignment_ids?: string[];
  delegation_ids?: string[];
  auth_method: "session" | "api_key" | "service_account";
  api_key_id?: string | null;
  session_id?: string | null;
  service_account_id?: string | null;
  acting_assignment_id?: string | null;
  acting_for_account_id?: string | null;
  email?: string | null;
  display_name?: string | null;
};

export type ActingContextSelectorProps = {
  settings: ApiSettings;
  auth: AuthInfo;
  onAuthChange: (auth: AuthUpdate | null, accessToken?: string) => void;
};

export type ActingContextRuntimeUiCapability = {
  Selector: ComponentType<ActingContextSelectorProps>;
};

export type AuthInfo = {
  user: AuthUser;
  // Backwards-compatible active tenant alias returned by older/newer APIs.
  tenant: AuthTenant;
  active_tenant?: AuthTenant;
  tenants?: AuthTenantMembership[];
  scopes: string[];
  roles: AuthRole[];
  groups: AuthGroup[];
  principal?: PrincipalContext | null;
  available_languages?: Array<{ code: string; label: string; native_label?: string | null }>;
  enabled_language_codes?: string[];
  default_language?: string;
  profile_loaded: boolean;
  roles_loaded: boolean;
  groups_loaded: boolean;
};

export type AuthUpdate = Partial<Omit<AuthInfo, "user" | "tenant" | "active_tenant" | "tenants">> & {
  user?: Partial<AuthUser> | null;
  tenant?: AuthTenant | null;
  active_tenant?: AuthTenant | null;
  tenants?: AuthTenantMembership[] | null;
};

export type AuthSessionInfo = {
  authenticated: boolean;
  auth_method: "session" | "api_key";
  user: Pick<AuthUser, "id" | "account_id" | "email" | "display_name" | "tenant_display_name" | "is_tenant_admin" | "password_reset_required">;
  tenant: AuthTenant;
  active_tenant: AuthTenant;
  session_id?: string | null;
  api_key_id?: string | null;
  expires_at?: string | null;
};

export type AuthShellInfo = {
  user: AuthUser;
  tenant: AuthTenant;
  active_tenant: AuthTenant;
  tenants?: AuthTenantMembership[];
  scopes: string[];
  principal?: PrincipalContext | null;
  profile_loaded?: boolean;
  roles_loaded?: boolean;
  groups_loaded?: boolean;
};

export type AuthProfileInfo = AuthUpdate & {
  user: AuthUser;
  tenant: AuthTenant;
  active_tenant: AuthTenant;
  available_languages?: Array<{ code: string; label: string; native_label?: string | null }>;
  enabled_language_codes?: string[];
  default_language?: string;
  profile_loaded: true;
};

export type AuthRolesInfo = {
  roles: AuthRole[];
  roles_loaded: true;
};

export type AuthGroupsInfo = {
  groups: AuthGroup[];
  groups_loaded: true;
};

export type LoginResponse = AuthInfo & {
  access_token: string;
  token_type: "bearer";
  expires_at: string;
};

export type NavSection =
  | "dashboard"
  | "campaigns"
  | "files"
  | "address-book"
  | "templates"
  | "reports"
  | "admin"
  | "settings";

export type CampaignWorkspaceSection =
  | "overview"
  | "campaign"
  | "global-settings"
  | "policies"
  | "fields"
  | "recipients"
  | "recipient-data"
  | "template"
  | "files"
  | "mail-settings"
  | "mail-policy"
  | "review"
  | "report"
  | "audit"
  | "json";

export type WizardStep = {
  id: string;
  label: string;
  description?: string;
  status?: "todo" | "active" | "done" | "warning" | "blocked";
};

export type CampaignListItem = {
  id: string;
  external_id?: string;
  name: string;
  description?: string | null;
  status: string;
  current_version_id?: string | null;
  owner_user_id?: string | null;
  owner_group_id?: string | null;
  created_at?: string;
  updated_at?: string;
  updatedAt?: string;
  ready?: number;
  warnings?: number;
  blocked?: number;
  sent?: number;
  failed?: number;
};


export type PlatformIconName = string;

export type PlatformViewSurfaceKind =
  | "module"
  | "navigation"
  | "route"
  | "section"
  | "action"
  | "selector";

export type PlatformViewSurface = {
  id: string;
  moduleId: string;
  kind: PlatformViewSurfaceKind;
  label: string;
  parentId?: string | null;
  description?: string | null;
  order?: number;
  defaultVisible?: boolean;
  required?: boolean;
};

export type PlatformNavItem = {
  to: string;
  label: string;
  /** Resolved by core. Modules should provide iconName, not imported icon components. */
  iconName?: PlatformIconName | null;
  /** Runtime-renderable icon, assigned by core after resolving iconName. */
  icon?: ComponentType<{ size?: number }>;
  anyOf?: string[];
  allOf?: string[];
  order?: number;
  surfaceId?: string;
};

export type PlatformRouteContext = {
  settings: ApiSettings;
  auth: AuthInfo;
  onAuthChange?: (auth: AuthUpdate | null, accessToken?: string) => void;
};

export type WizardDirectoryContext = PlatformRouteContext & {
  contextId: string;
  resourceId?: string;
};

export type WizardDirectoryEntry = {
  id: string;
  moduleId: string;
  label: string;
  description?: string;
  to: string;
  actionLabel?: string;
  category?: string;
  order?: number;
  anyOf?: string[];
  allOf?: string[];
  available?: boolean;
  unavailableReason?: string;
};

export type WizardDirectoryContribution = {
  id: string;
  moduleId: string;
  contextId: string;
  order?: number;
  entries: (context: WizardDirectoryContext) => WizardDirectoryEntry[];
};

export type WizardDirectoriesUiCapability = {
  directories: WizardDirectoryContribution[];
};

export type PlatformPublicRouteContext = {
  settings: ApiSettings;
  auth: AuthInfo | null;
  onAuthChange?: (auth: AuthUpdate | null, accessToken?: string) => void;
};

export type AdminSectionGroup = "ROOT" | "SYSTEM" | "TENANT" | "GROUP" | "USER" | string;

export type AdminSectionRenderContext = PlatformRouteContext & {
  refreshAuth: () => Promise<void>;
  availableSections: ReadonlySet<string>;
  selectSection: (section: string) => void;
};

export type AdminSectionContribution = {
  id: string;
  label: string;
  /** Owning module, used to group module-specific administration. */
  moduleId?: string;
  /** Distinguishes operational management pages from configurable settings. */
  kind?: "management" | "settings";
  /** Optional parent section for future embedded or nested settings surfaces. */
  parentId?: string;
  group?: AdminSectionGroup;
  order?: number;
  anyOf?: string[];
  allOf?: string[];
  surfaceId?: string;
  render: (context: AdminSectionRenderContext) => ReactNode;
};

export type AdminSectionsUiCapability = {
  sections: AdminSectionContribution[];
};

export type SettingsSectionGroup = "account" | "ui" | string;

export type SettingsSectionRenderContext = PlatformRouteContext & {
  activeSection: string;
  availableSections: ReadonlySet<string>;
  selectSection: (section: string) => void;
};

export type SettingsSectionContribution = {
  id: string;
  label: string;
  group?: SettingsSectionGroup;
  groupTitle?: string;
  order?: number;
  anyOf?: string[];
  allOf?: string[];
  surfaceId?: string;
  render: (context: SettingsSectionRenderContext) => ReactNode;
};

export type SettingsSectionsUiCapability = {
  sections: SettingsSectionContribution[];
};

export type PlatformRouteContribution = {
  path: string;
  anyOf?: string[];
  allOf?: string[];
  order?: number;
  surfaceId?: string;
  render: (context: PlatformRouteContext) => ReactNode;
};

export type PlatformPublicRouteContribution = {
  path: string;
  order?: number;
  render: (context: PlatformPublicRouteContext) => ReactNode;
};

export type PlatformUiCapabilities = Record<string, unknown>;

export type PlatformTranslationDictionary = Record<string, string>;

export type PlatformTranslations = Record<string, PlatformTranslationDictionary>;

export type PlatformWebModule = {
  id: string;
  label: string;
  version: string;
  dependencies?: string[];
  optionalDependencies?: string[];
  remoteAssetManifest?: string | null;
  remoteAssetSignature?: string | null;
  remoteAssetPublicKeyId?: string | null;
  remoteAssetIntegrity?: string | null;
  remoteAssetContractVersion?: string | null;
  navItems?: PlatformNavItem[];
  routes?: PlatformRouteContribution[];
  publicRoutes?: PlatformPublicRouteContribution[];
  translations?: PlatformTranslations;
  uiCapabilities?: PlatformUiCapabilities;
  runtimeUiCapabilities?: PlatformUiCapabilities;
  viewSurfaces?: PlatformViewSurface[];
};

export type EffectiveViewOption = {
  id: string;
  name: string;
  description?: string | null;
  revisionId: string;
};

export type EffectiveViewProjection = {
  activeViewId: string | null;
  activeRevisionId: string | null;
  activeViewName: string | null;
  visibleSurfaceIds: string[];
  projectionActive?: boolean;
  locked: boolean;
  availableViews: EffectiveViewOption[];
  provenance: Array<{
    source: string;
    scopeType?: string | null;
    scopeId?: string | null;
    detail?: string | null;
  }>;
  diagnostics: Array<{
    severity: "warning" | "error";
    code: string;
    message: string;
    surfaceIds: string[];
  }>;
};

export type ViewSelectorProps = {
  settings: ApiSettings;
  auth: AuthInfo;
  projection: EffectiveViewProjection | null;
};

export type ViewsRuntimeUiCapability = {
  loadEffectiveView: (
    settings: ApiSettings,
    auth: AuthInfo
  ) => Promise<EffectiveViewProjection>;
  activateView: (
    settings: ApiSettings,
    viewId: string | null
  ) => Promise<EffectiveViewProjection>;
  resolveWorkflowView: (
    settings: ApiSettings,
    context: {
      viewId: string;
      revisionId?: string | null;
      visibleSurfaceIds?: string[];
    }
  ) => Promise<EffectiveViewProjection>;
  Selector?: ComponentType<ViewSelectorProps>;
};

export type SearchContextContribution = {
  id: string;
  moduleId: string;
  label: string;
  pathPrefixes: string[];
  resourceTypes?: string[];
  placeholder?: string;
  surfaceId?: string;
  order?: number;
};

export type SearchContextsUiCapability = {
  contexts: SearchContextContribution[];
};

export type GlobalSearchProps = {
  settings: ApiSettings;
  auth: AuthInfo;
};

export type SearchRuntimeUiCapability = {
  GlobalSearch: ComponentType<GlobalSearchProps>;
  anyOf?: string[];
};

export type DashboardWidgetSize = "small" | "medium" | "wide" | "full";

export type DashboardWidgetTone = "neutral" | "good" | "warning" | "danger" | "info";

export type DashboardWidgetConfigurationValue =
  | string
  | number
  | boolean
  | null;

export type DashboardWidgetConfiguration = Record<
  string,
  DashboardWidgetConfigurationValue
>;

export type DashboardWidgetConfigurationOption = {
  value: string;
  label: string;
};

export type DashboardWidgetConfigurationField = {
  id: string;
  label: string;
  description?: string;
  kind: "text" | "number" | "boolean" | "select";
  required?: boolean;
  placeholder?: string;
  min?: number;
  max?: number;
  step?: number;
  options?: DashboardWidgetConfigurationOption[];
};

export type DashboardWidgetRenderContext = PlatformRouteContext & {
  modules: PlatformWebModule[];
  effectiveView: EffectiveViewProjection | null;
  instanceId: string;
  widgetId: string;
  refreshKey: number;
  size: DashboardWidgetSize;
  configuration: DashboardWidgetConfiguration;
};

export type DashboardWidgetContribution = {
  id: string;
  title: string;
  description?: string;
  moduleId?: string;
  category?: string;
  order?: number;
  surfaceId?: string;
  defaultVisible?: boolean;
  defaultSize?: DashboardWidgetSize;
  supportedSizes?: DashboardWidgetSize[];
  allowMultiple?: boolean;
  defaultConfiguration?: DashboardWidgetConfiguration;
  configurationFields?: DashboardWidgetConfigurationField[];
  refreshIntervalMs?: number;
  anyOf?: string[];
  allOf?: string[];
  render: (context: DashboardWidgetRenderContext) => ReactNode;
};

export type DashboardWidgetsUiCapability = {
  widgets: DashboardWidgetContribution[];
};

export type OrganizationFunctionActionContext = PlatformRouteContext & {
  function: {
    id: string;
    tenant_id: string;
    organization_unit_id: string;
    slug: string;
    name: string;
  };
};

export type OrganizationFunctionActionContribution = {
  id: string;
  label: string;
  icon: ReactNode;
  order?: number;
  anyOf?: string[];
  allOf?: string[];
  surfaceId?: string;
  onClick: (context: OrganizationFunctionActionContext) => void;
};

export type OrganizationFunctionActionsUiCapability = {
  actions: OrganizationFunctionActionContribution[];
};

export type OrganizationFunctionSelection = {
  sourceModule: "organizations";
  functionId: string;
  label?: string | null;
  organizationUnitId?: string | null;
  organizationUnitLabel?: string | null;
};

export type OrganizationFunctionPickerContext = PlatformRouteContext & {
  value: OrganizationFunctionSelection | null;
  disabled?: boolean;
  onChange: (value: OrganizationFunctionSelection | null) => void;
};

export type OrganizationFunctionLabelContext = PlatformRouteContext & {
  sourceModule: string;
  functionId: string;
  fallback?: ReactNode;
};

export type OrganizationFunctionPickerUiCapability = {
  sourceModule: "organizations";
  renderPicker: (context: OrganizationFunctionPickerContext) => ReactNode;
  renderLabel?: (context: OrganizationFunctionLabelContext) => ReactNode;
};

export type CalendarPickerProps = PlatformRouteContext & {
  value: string;
  onChange: (calendarId: string) => void;
  id?: string;
  name?: string;
  label?: ReactNode;
  emptyLabel?: ReactNode;
  disabled?: boolean;
  required?: boolean;
  className?: string;
};

export type CalendarPickerUiCapability = {
  CalendarPicker: ComponentType<CalendarPickerProps>;
};

export type MailSecurity = "plain" | "tls" | "starttls";
export type MailProfileScope = "system" | "tenant" | "user" | "group" | "campaign";

export type MailProfileTargetOption = {
  id: string;
  label: string;
  secondary?: string | null;
};

export type MailTransportCredentials = {
  username?: string | null;
  password?: string | null;
};

export type MailTransportSettings = {
  host?: string | null;
  port?: number | null;
  username?: string | null;
  password?: string | null;
  security?: MailSecurity | string | null;
  timeout_seconds?: number | null;
};

export type MailImapTransportSettings = MailTransportSettings & {
  sent_folder?: string | null;
};

export type MailServerProfileCredentials = {
  smtp?: MailTransportCredentials | null;
  imap?: MailTransportCredentials | null;
};

export type CredentialEnvelopeSummary = {
  id: string;
  tenant_id?: string | null;
  scope_type: MailProfileScope;
  scope_id?: string | null;
  name: string;
  description?: string | null;
  credential_kind: string;
  public_data: Record<string, unknown>;
  secret_keys: string[];
  secret_configured: boolean;
  allowed_modules: string[];
  allowed_server_refs: string[];
  inherit_to_lower_scopes: boolean;
  is_active: boolean;
  revision: string;
  created_at?: string;
  updated_at?: string;
  deleted_at?: string | null;
};

export type MailCredentialEnvelope = CredentialEnvelopeSummary & {
  binding_id?: string | null;
  server_id?: string | null;
  is_default: boolean;
};

export type MailServerEndpoint = {
  id: string;
  profile_id: string;
  tenant_id?: string | null;
  protocol: "smtp" | "imap";
  name: string;
  config: MailTransportSettings | MailImapTransportSettings;
  scope_type: MailProfileScope;
  scope_id?: string | null;
  inherit_to_lower_scopes: boolean;
  is_default: boolean;
  is_active: boolean;
  transport_revision: string;
  credentials: MailCredentialEnvelope[];
  created_at?: string;
  updated_at?: string;
};

export type MailServerProfile = {
  id: string;
  tenant_id?: string | null;
  scope_type: MailProfileScope;
  scope_id?: string | null;
  name: string;
  slug: string;
  description?: string | null;
  is_active: boolean;
  inherit_to_lower_scopes?: boolean;
  smtp: MailTransportSettings;
  imap?: MailImapTransportSettings | null;
  credentials?: MailServerProfileCredentials | null;
  smtp_password_configured?: boolean;
  imap_password_configured?: boolean;
  servers?: MailServerEndpoint[];
  created_at?: string;
  updated_at?: string;
};

export type MailCredentialPolicy = {
  inherit?: boolean | null;
  allow_override?: boolean | null;
};

export type MailProfilePatternKey = "smtp_hosts" | "imap_hosts" | "envelope_senders" | "from_headers" | "recipient_domains";

export type MailProfilePolicy = {
  allowed_profile_ids?: string[] | null;
  allow_user_profiles?: boolean | null;
  allow_group_profiles?: boolean | null;
  allow_campaign_profiles?: boolean | null;
  smtp_credentials?: MailCredentialPolicy | null;
  imap_credentials?: MailCredentialPolicy | null;
  whitelist?: Partial<Record<MailProfilePatternKey, string[]>> | null;
  blacklist?: Partial<Record<MailProfilePatternKey, string[]>> | null;
  allow_lower_level_limits?: Partial<Record<string, boolean>> | null;
};

export type MailPolicyValidationInput = {
  smtpHost?: string | null;
  imapHost?: string | null;
  envelopeSender?: string | null;
  fromHeader?: string | null;
  recipientDomains?: Array<string | null | undefined> | null;
};

export type MailPolicyValidationMessage = {
  key: MailProfilePatternKey;
  label: string;
  value: string;
  message: string;
  severity?: "warning" | "danger";
};

export type MailPolicyValidationFn = (
  policy: MailProfilePolicy | null | undefined,
  input: MailPolicyValidationInput,
) => MailPolicyValidationMessage[];

export type MailProfileScopeManagerProps = {
  settings: ApiSettings;
  scopeType: MailProfileScope;
  scopeId?: string | null;
  targetOptions?: MailProfileTargetOption[];
  targetLabel?: string;
  profileTitle?: string;
  policyTitle?: string;
  canWriteProfiles: boolean;
  canManageCredentials: boolean;
  canWritePolicy: boolean;
};

export type MailProfilePolicyEditorProps = {
  settings: ApiSettings;
  scopeType: MailProfileScope;
  scopeId?: string | null;
  campaignId?: string | null;
  profiles: MailServerProfile[];
  ownerUserId?: string | null;
  ownerGroupId?: string | null;
  canWrite: boolean;
  locked?: boolean;
  title?: string;
  description?: string;
  onSaved?: () => void | Promise<void>;
};

export type MailProfilesUiCapability = {
  MailProfileScopeManager: ComponentType<MailProfileScopeManagerProps>;
  MailProfilePolicyEditor: ComponentType<MailProfilePolicyEditorProps>;
  validateMailPolicy?: MailPolicyValidationFn;
};

export type FileConnectorScope = "system" | "tenant" | "user" | "group";

export type FileConnectorTargetOption = {
  id: string;
  label: string;
  secondary?: string | null;
};

export type FileConnectorScopeManagerProps = {
  settings: ApiSettings;
  scopeType: FileConnectorScope;
  scopeId?: string | null;
  targetOptions?: FileConnectorTargetOption[];
  targetLabel?: string;
  title?: string;
  canWrite: boolean;
};

export type FilesConnectorsUiCapability = {
  FileConnectorScopeManager: ComponentType<FileConnectorScopeManagerProps>;
};

export type MailDevMailboxUiCapability = {
  enabled: boolean;
  label?: string;
};

export type FilesFolderNode = {
  name: string;
  path: string;
  children: FilesFolderNode[];
  fileCount: number;
  persisted: boolean;
};

export type FilesFileActionTarget = {
  spaceId: string;
  folderPath: string;
};

export type FilesFolderTreeProps = {
  nodes: FilesFolderNode[];
  activeSpaceId: string;
  spaceId: string;
  currentFolder: string;
  dropTargetKey?: string;
  expandedKeys: Set<string>;
  onOpen: (spaceId: string, path: string) => void;
  onToggle: (spaceId: string, path: string) => void;
  onContextMenu?: (event: ReactMouseEvent<HTMLElement>, spaceId: string, path: string) => void;
  onDragOverTarget?: (event: ReactDragEvent<HTMLElement>, target: FilesFileActionTarget) => void;
  onDropOnTarget?: (event: ReactDragEvent<HTMLElement>, target: FilesFileActionTarget) => Promise<void>;
  onClearDropState?: () => void;
  onRequestDragExpand?: (spaceId: string, path: string) => void;
  onDragStartFolder?: (spaceId: string, path: string, event: ReactDragEvent<HTMLElement>) => void;
  onDragEndFolder?: () => void;
  dragDropEnabled?: boolean;
  contextMenuEnabled?: boolean;
  disabled?: boolean;
  depth?: number;
};

export type FilesOwnerType = "user" | "group";

export type FilesFileSpace = {
  id: string;
  label: string;
  owner_type: FilesOwnerType;
  owner_id: string;
  description?: string | null;
  space_type?: "managed" | "connector";
  connector_space_id?: string | null;
  connector_profile_id?: string | null;
  provider?: string | null;
  library_id?: string | null;
  remote_path?: string | null;
  sync_mode?: string | null;
  read_only?: boolean;
};

export type FilesFileShare = {
  id: string;
  target_type: string;
  target_id: string;
  permission: string;
  created_at: string;
  revoked_at?: string | null;
};

export type FilesManagedFile = {
  id: string;
  tenant_id: string;
  owner_type: FilesOwnerType;
  owner_id: string;
  display_path: string;
  filename: string;
  description?: string | null;
  size_bytes: number;
  content_type?: string | null;
  checksum_sha256: string;
  version_id: string;
  created_at: string;
  updated_at: string;
  deleted_at?: string | null;
  audit_relevant: boolean;
  metadata?: Record<string, unknown> | null;
  shares?: FilesFileShare[];
};

export type FilesFileFolder = {
  id: string;
  tenant_id: string;
  owner_type: FilesOwnerType;
  owner_id: string;
  path: string;
  created_at: string;
  updated_at: string;
  deleted_at?: string | null;
};

export type FilesFileSpacesResponse = { spaces: FilesFileSpace[] };
export type FilesFileListResponse = { files: FilesManagedFile[]; total: number; cursor?: string | null; next_cursor?: string | null };
export type FilesFileFoldersResponse = { folders: FilesFileFolder[]; cursor?: string | null; next_cursor?: string | null };
export type FilesFileDeltaResponse = {
  files: FilesManagedFile[];
  folders: FilesFileFolder[];
  deleted: DeltaDeletedItem[];
  watermark?: string | null;
  has_more?: boolean;
  full?: boolean;
};
export type FilesPatternResolveResponse = {
  patterns: { pattern: string; matches: FilesManagedFile[] }[];
  unmatched: FilesManagedFile[];
};
export type FilesFileBulkShareResponse = { shares: FilesFileShare[]; shared_count: number };

export type FilesManagedFileLinkTarget = {
  type: string;
  id: string;
  label?: string;
  permission?: string;
};

export type FilesManagedFileChooserMode = "folder" | "attachment";
export type FilesManagedAttachmentChoiceMode = "file" | "pattern";

export type FilesManagedFolderSelection = {
  space: FilesFileSpace;
  folderPath: string;
  source: string;
};

export type FilesManagedAttachmentSelection = FilesManagedFolderSelection & {
  fileFilter: string;
  matchCount: number;
  fileIds: string[];
  selectionType: FilesManagedAttachmentChoiceMode;
};

export type FilesManagedFileChooserProps = {
  open: boolean;
  settings: ApiSettings;
  mode: FilesManagedFileChooserMode;
  storageScope?: string;
  source?: string;
  basePath?: string;
  initialPattern?: string;
  rememberKey?: string;
  previewContext?: Record<string, string>;
  linkTarget?: FilesManagedFileLinkTarget;
  renderPatternPreview?: (pattern: string, context?: Record<string, string>) => string;
  onClose: () => void;
  onSelectFolder?: (selection: FilesManagedFolderSelection) => void;
  onSelectAttachment?: (selection: FilesManagedAttachmentSelection) => void;
};

export type FilesFileExplorerUiCapability = {
  FolderTree: ComponentType<FilesFolderTreeProps>;
  ManagedFileChooser?: ComponentType<FilesManagedFileChooserProps>;
  listFileSpaces?: (settings: ApiSettings) => Promise<FilesFileSpacesResponse>;
  listFiles?: (settings: ApiSettings, params?: { owner_type?: FilesOwnerType | string; owner_id?: string; campaign_id?: string; path_prefix?: string; campaign_usage?: "linked" | "unlinked"; audit_relevant?: boolean; page_size?: number; cursor?: string | null }) => Promise<FilesFileListResponse>;
  listFilesDelta?: (settings: ApiSettings, params?: { owner_type?: FilesOwnerType | string; owner_id?: string; campaign_id?: string; path_prefix?: string; since?: string | null; limit?: number }) => Promise<FilesFileDeltaResponse>;
  listFolders?: (settings: ApiSettings, params: { owner_type: FilesOwnerType; owner_id: string; page_size?: number; cursor?: string | null }) => Promise<FilesFileFoldersResponse>;
  resolveFilePatterns?: (
    settings: ApiSettings,
    payload: { patterns: string[]; owner_type?: FilesOwnerType; owner_id?: string; campaign_id?: string; path_prefix?: string; include_unmatched?: boolean; case_sensitive?: boolean }
  ) => Promise<FilesPatternResolveResponse>;
  shareFilesWithTarget?: (settings: ApiSettings, fileIds: string[], target: FilesManagedFileLinkTarget) => Promise<FilesFileBulkShareResponse>;
};

export type PlatformFrontendRouteInfo = {
  path: string;
  component: string;
  required_all: string[];
  required_any: string[];
  order: number;
  surface_id?: string | null;
};

export type PlatformFrontendModuleInfo = {
  module_id: string;
  package_name?: string | null;
  asset_manifest?: string | null;
  asset_manifest_signature?: string | null;
  asset_manifest_public_key_id?: string | null;
  asset_manifest_integrity?: string | null;
  asset_manifest_contract_version?: string | null;
  routes: PlatformFrontendRouteInfo[];
  public_routes: Array<{
    path: string;
    component: string;
    order: number;
  }>;
  nav: Array<{
    path: string;
    label: string;
    icon?: string | null;
    section?: string | null;
    required_all: string[];
    required_any: string[];
    order: number;
    surface_id?: string | null;
  }>;
  settings_routes: PlatformFrontendRouteInfo[];
  view_surface_contract_version?: string | null;
  view_surfaces?: Array<{
    id: string;
    module_id: string;
    kind: PlatformViewSurfaceKind;
    label: string;
    parent_id?: string | null;
    description?: string | null;
    order: number;
    default_visible: boolean;
    required: boolean;
  }>;
};

export type PlatformPublicModuleInfo = {
  id: string;
  name: string;
  version: string;
  frontend: Pick<
    PlatformFrontendModuleInfo,
    | "module_id"
    | "package_name"
    | "asset_manifest"
    | "asset_manifest_signature"
    | "asset_manifest_public_key_id"
    | "asset_manifest_integrity"
    | "asset_manifest_contract_version"
    | "public_routes"
  >;
};

export type PlatformModuleInfo = {
  id: string;
  name: string;
  version: string;
  dependencies: string[];
  optional_dependencies: string[];
  enabled: boolean;
  architecture?: {
    contract_version: string;
    layer: string;
    kind: string;
    maturity: string;
    evidence: Array<{ kind: string; reference: string; summary: string }>;
    known_limits: string[];
    supported_authority_modes: string[];
    owned_concepts: string[];
    non_owned_concepts: string[];
    reference_packages: string[];
    target_tested_providers: string[];
    documentation: Record<string, string[]>;
  } | null;
  external_providers?: Array<{
    contract_version: string;
    id: string;
    module_id: string;
    label: string;
    maturity: string;
    operations: string[];
    authority_modes: string[];
    objects: Array<Record<string, unknown>>;
    behavior: Record<string, unknown>;
  }>;
  runtime_ui_capabilities?: string[];
  nav: Array<{
    path: string;
    label: string;
    icon?: string | null;
    section?: string | null;
    required_all: string[];
    required_any: string[];
    order: number;
    surface_id?: string | null;
  }>;
  frontend?: PlatformFrontendModuleInfo | null;
};
