import { a as usePortalTenantClient, t as accountKeys } from "./query-keys-Dtps6P1q.mjs";
import { n as createDomainTranslations, t as createStaticDictAdapter } from "./static-dict-adapter-B8kVuZyL.mjs";
import { p as usePortalProductsApi } from "./SearchSort-DuTESNHX.mjs";
import { i as shareablesKeys, n as ShareablesApiProvider, r as useShareablesApi } from "./use-share-link-CkTsZcjg.mjs";
import { createContext, use, useContext, useMemo } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { jsx } from "react/jsx-runtime";
import { z } from "zod";
//#region \0rolldown/runtime.js
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
var __exportAll = (all, no_symbols) => {
	let target = {};
	for (var name in all) __defProp(target, name, {
		get: all[name],
		enumerable: true
	});
	if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
	return target;
};
var __copyProps = (to, from, except, desc) => {
	if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
		key = keys[i];
		if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
			get: ((k) => from[k]).bind(null, key),
			enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
		});
	}
	return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
	value: mod,
	enumerable: true
}) : target, mod));
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, { get: (a, b) => (typeof require !== "undefined" ? require : a)[b] }) : x)(function(x) {
	if (typeof require !== "undefined") return require.apply(this, arguments);
	throw Error("Calling `require` for \"" + x + "\" in an environment that doesn't expose the `require` function. See https://rolldown.rs/in-depth/bundling-cjs#require-external-modules for more details.");
});
//#endregion
//#region ../core/src/account-api-context.ts
const AccountApiContext = createContext(null);
const AccountApiProvider = AccountApiContext.Provider;
function useAccountApi() {
	const api = use(AccountApiContext);
	if (!api) throw new Error("useAccountApi must be used within an AccountApiProvider");
	return api;
}
//#endregion
//#region ../../api-clients/portal-tenant/src/namespaces/portal_tenant.ts
/**
* Get current account
* Returns the authenticated member's account profile and company context. This is the primary endpoint the SPA calls to check auth status and display user information.
*
* @param client - Fetch client instance

*/
async function account_show(client) {
	return client.get(`/api/account`);
}
/**
* Update current account
* Updates the authenticated member's profile fields such as name, phone, bio, avatar, and social links.
*
* @param client - Fetch client instance
* @param body - body
*/
async function account_update(client, body) {
	return client.patch(`/api/account`, body);
}
/**
* Get store branding and feature flags
* Returns the tenant company's store branding (logo, icon, app store URLs) and feature flags such as whether subscription bundling is enabled.
*
* @param client - Fetch client instance

*/
async function store_show(client) {
	return client.get(`/api/store`);
}
/**
* Get the app manifest
* Returns the rendered manifest for the tenant company's active FluidOS definition, matched against the current user's country, rank, and roles.
*
* @param client - Fetch client instance

*/
async function app_manifest_show(client) {
	return client.get(`/api/app/manifest`);
}
/**
* List calendar events
* Returns a paginated list of upcoming and ongoing calendar events for the tenant company, optionally filtered by the authenticated member's country when one is set.
*
* @param client - Fetch client instance
* @param [params] - params
*/
async function calendar_events_list(client, params) {
	return client.get(`/api/calendar/events`, params);
}
/**
* List recent activities
* Returns a paginated list of recent activities for the authenticated member, ordered by most recent first. Each activity includes pre-computed user_name and target_name fields ready for direct rendering by the portal SPA.
*
* @param client - Fetch client instance
* @param [params] - params
*/
async function activities_list(client, params) {
	return client.get(`/api/activities`, params);
}
/**
* List catch-up suggestions
* Returns a paginated list of catch-up suggestions for the authenticated member. Limited to suggestions with at least one pending action that have not expired.
*
* @param client - Fetch client instance
* @param [params] - params
*/
async function catch_ups_list(client, params) {
	return client.get(`/api/catch_ups`, params);
}
/**
* List orders
* Returns a paginated list of orders placed through the tenant company, optionally filtered by status.
*
* @param client - Fetch client instance
* @param [params] - params
*/
async function orders_list(client, params) {
	return client.get(`/api/orders`, params);
}
/**
* Get an order
* Returns a single order by token with its line items.
*
* @param client - Fetch client instance
* @param token - token
*/
async function orders_show(client, token) {
	return client.get(`/api/orders/${token}`);
}
/**
* List products
* Returns a paginated list of products available in the tenant company's catalog. Supports sorting and filtering by title, product type, collection, and stock availability.
*
* @param client - Fetch client instance
* @param [params] - params
*/
async function products_list(client, params) {
	return client.get(`/api/products`, params);
}
/**
* Get a product
* Returns a single product by ID with its variants.
*
* @param client - Fetch client instance
* @param id - id
*/
async function products_show(client, id) {
	return client.get(`/api/products/${id}`);
}
/**
* Search products
* Searches the tenant company's product catalog by keyword, returning paginated results.
*
* @param client - Fetch client instance
* @param [params] - params
*/
async function products_search(client, params) {
	return client.get(`/api/products/search`, params);
}
/**
* List product media
* Returns all media (images, videos) attached to a product.
*
* @param client - Fetch client instance
* @param id - id
*/
async function products_media_list(client, id) {
	return client.get(`/api/products/${id}/media`);
}
/**
* List enrollment packs
* Returns a paginated list of active, non-discarded enrollment packs scoped to the current portal tenant's company. Each pack carries an empty `products` array — fetch a single pack via `/api/enrollment_packs/{id}` to load its visible products.
*
* @param client - Fetch client instance
* @param [params] - params
*/
async function enrollment_packs_list(client, params) {
	return client.get(`/api/enrollment_packs`, params);
}
/**
* Get an enrollment pack
* Returns a single active, non-discarded enrollment pack scoped to the current portal tenant's company.
*
* @param client - Fetch client instance
* @param id - id
*/
async function enrollment_packs_show(client, id) {
	return client.get(`/api/enrollment_packs/${id}`);
}
/**
* List subscription bundles
* Returns the runtime bundle groupings for the authenticated customer's active subscriptions. Bundles are computed at request time by grouping subscriptions that share customer, address (physical only), volume rep, next bill date, and digital flag — they have no persistent id. The response is unpaginated; customers typically have a small number of bundles.
*
* @param client - Fetch client instance

*/
async function subscription_bundles_list(client) {
	return client.get(`/api/subscription_bundles`);
}
/**
* List subscriptions
* Returns a paginated list of the member's active and historical subscriptions. Supports filtering by lifecycle state and a free-text search across product and plan names.
*
* @param client - Fetch client instance
* @param [params] - params
*/
async function subscriptions_list(client, params) {
	return client.get(`/api/subscriptions`, params);
}
/**
* Get a subscription
* Returns a single subscription by its token.
*
* @param client - Fetch client instance
* @param token - token
*/
async function subscriptions_show(client, token) {
	return client.get(`/api/subscriptions/${token}`);
}
/**
* Update a subscription
* Updates a subscription's default payment method or quantity.
*
* @param client - Fetch client instance
* @param token - token
* @param body - body
*/
async function subscriptions_update(client, token, body) {
	return client.put(`/api/subscriptions/${token}`, body);
}
/**
* Pause a subscription
* Pauses billing on an active subscription. When neither `next_bill_date` nor `number_of_orders` is provided, the subscription is paused indefinitely. Specifying both is rejected.
*
* @param client - Fetch client instance
* @param token - token
* @param [body] - body
*/
async function subscriptions_pause(client, token, body) {
	return client.post(`/api/subscriptions/${token}/pause`, body);
}
/**
* Resume a subscription
* Resumes billing on a paused subscription. When `next_bill_date` is omitted, the plan's next bill date from today is used.
*
* @param client - Fetch client instance
* @param token - token
* @param [body] - body
*/
async function subscriptions_resume(client, token, body) {
	return client.post(`/api/subscriptions/${token}/resume`, body);
}
/**
* Skip next billing cycle
* Skips the next billing cycle for a subscription without pausing it.
*
* @param client - Fetch client instance
* @param token - token
*/
async function subscriptions_skip(client, token) {
	return client.post(`/api/subscriptions/${token}/skip_next_billing`);
}
/**
* Cancel a subscription
* Cancels an active subscription.
*
* @param client - Fetch client instance
* @param token - token
*/
async function subscriptions_cancel(client, token) {
	return client.post(`/api/subscriptions/${token}/cancel`);
}
/**
* Reactivate a subscription
* Reactivates a previously cancelled subscription.
*
* @param client - Fetch client instance
* @param token - token
*/
async function subscriptions_reactivate(client, token) {
	return client.post(`/api/subscriptions/${token}/reactivate`);
}
/**
* Retry billing on a past-due subscription
* Queues an immediate retry on a past-due subscription against whatever payment method is currently on file. The customer-facing UI calls this after a successful payment-method update so the customer controls when the retry runs (vs. having it implicitly fire as a side-effect of the update).


The endpoint returns 200 for found subscriptions in normal operation, regardless of status — it is intentionally idempotent so the client can call it unconditionally after a payment-method update without first checking status. A 422 can still be returned if the server cannot persist the retry state. Use the response's `queued` field to distinguish the two outcomes:

- `queued: true`  — the subscription was past_due; a retry has been scheduled and `next_retry_at` is set to "now".
- `queued: false` — the subscription was not past_due and no state change occurred. Treat as a no-op.
*
* @param client - Fetch client instance
* @param token - token
*/
async function subscriptions_retry(client, token) {
	return client.post(`/api/subscriptions/${token}/retry`);
}
/**
* Create a subscription bundle
* Bundles two or more existing subscriptions onto a shared bill date, address, and volume rep. All subscriptions must belong to the authenticated customer. Bundles are not persisted entities — the endpoint aligns each subscription's billing attributes so that they share a runtime grouping key.
*
* @param client - Fetch client instance
* @param body - body
*/
async function subscription_bundles_create(client, body) {
	return client.post(`/api/subscription_bundles/bundle`, body);
}
/**
* List todos
* Returns a paginated list of tasks scoped to the authenticated member. Filter by completion state via the `state` query parameter; defaults to `incomplete` for backwards compatibility. Incomplete tasks are ordered by due date ascending (nulls last); completed tasks by completion time descending.
*
* @param client - Fetch client instance
* @param [params] - params
*/
async function todos_list(client, params) {
	return client.get(`/api/todos`, params);
}
/**
* Create a todo
* Creates a todo owned by the authenticated member. `contact_id` is optional — omit it (or send null) to create a standalone todo not attached to a contact, matching mobile widget parity. When `contact_id` is supplied the caller must own the contact.
*
* @param client - Fetch client instance
* @param body - body
*/
async function todos_create(client, body) {
	return client.post(`/api/todos`, body);
}
/**
* Update a todo
* Updates the given todo. Any non-empty subset of `body`, `due_at`, and `completed` is accepted. Sending `completed: true` stamps `completed_at` with the current time; `false` clears it. The existing widget call sending only `{ completed }` continues to work unchanged.
*
* @param client - Fetch client instance
* @param id - id
* @param body - body
*/
async function todos_update(client, id, body) {
	return client.patch(`/api/todos/${id}`, body);
}
/**
* Delete a todo
* Deletes the given todo. Only the owning member can delete. Deleting a todo not visible to the acting member returns 404 (do not leak existence). Soft vs hard delete follows the Task model's existing destroy semantics.
*
* @param client - Fetch client instance
* @param id - id
*/
async function todos_destroy(client, id) {
	return client.delete(`/api/todos/${id}`);
}
/**
* Top products by direct visits
* Ranked list of the company's products by total visits to the product page (aggregates metrics_product_visits across all visit sources).
*
* @param client - Fetch client instance
* @param [params] - params
*/
async function product_by_visits(client, params) {
	return client.get(`/api/products/by-visits`, params);
}
/**
* Top products by share-link visits
* Ranked list of the company's products by click-throughs on rep share links (aggregates metrics_share_shareable_visits where shareable_type='Product').
*
* @param client - Fetch client instance
* @param [params] - params
*/
async function product_by_shares(client, params) {
	return client.get(`/api/products/by-shares`, params);
}
/**
* Top enrollment packs by direct visits
* Ranked list of the company's enrollment packs by total visits to the pack page (aggregates metrics_enrollment_pack_visits across all visit sources).
*
* @param client - Fetch client instance
* @param [params] - params
*/
async function enrollment_pack_by_visits(client, params) {
	return client.get(`/api/enrollment_packs/by-visits`, params);
}
/**
* Top enrollment packs by share-link visits
* Ranked list of the company's enrollment packs by click-throughs on rep share links (aggregates metrics_share_shareable_visits where shareable_type='EnrollmentPack').
*
* @param client - Fetch client instance
* @param [params] - params
*/
async function enrollment_pack_by_shares(client, params) {
	return client.get(`/api/enrollment_packs/by-shares`, params);
}
//#endregion
//#region ../../api-clients/portal-tenant-content/src/namespaces/portal_tenant_content.ts
/**
* List media (own uploads and company share media)
* Returns a paginated list of the member's own uploads and company share media. Training and update media are excluded.
*
* @param client - Fetch client instance
* @param [params] - params
*/
async function media_list(client, params) {
	return client.get(`/api/content/media`, params);
}
/**
* Create a new media item
* Creates a new media item record.
*
* @param client - Fetch client instance
* @param body - body
*/
async function media_create(client, body) {
	return client.post(`/api/content/media`, body);
}
/**
* Get a specific media item
* Returns a single media item by ID. When language_iso is provided, translatable fields (title, description, url) are returned for that language with no fallback — empty values indicate an untranslated field.
*
* @param client - Fetch client instance
* @param id - id
* @param [params] - params
*/
async function media_show(client, id, params) {
	return client.get(`/api/content/media/${id}`, params);
}
/**
* Update a media item (own uploads only)
* Updates a media item's title, description, status, url, content_format, thumbnail, CTA, and SEO. When language_iso is provided, translatable fields are written against that language's translation row instead of the default locale.
*
* @param client - Fetch client instance
* @param id - id
* @param body - body
* @param [params] - params
*/
async function media_update(client, id, body, params) {
	return client.patch(`/api/content/media/${id}`, body, { params });
}
/**
* Delete a media item (own uploads only)
* Removes a media item.
*
* @param client - Fetch client instance
* @param id - id
*/
async function media_destroy(client, id) {
	return client.delete(`/api/content/media/${id}`);
}
/**
* List products associated with a media item
* Returns a paginated list of products associated with a media item.
*
* @param client - Fetch client instance
* @param medium_id - medium_id
* @param [params] - params
*/
async function media_products_list(client, medium_id, params) {
	return client.get(`/api/content/media/${medium_id}/products`, params);
}
/**
* Associate a product with a media item
* Creates a product association for a media item.
*
* @param client - Fetch client instance
* @param medium_id - medium_id
* @param body - body
*/
async function media_products_add(client, medium_id, body) {
	return client.post(`/api/content/media/${medium_id}/products`, body);
}
/**
* Remove a product association from a media item
* Removes a single product association from a media item.
*
* @param client - Fetch client instance
* @param medium_id - medium_id
* @param id - id
*/
async function media_products_remove(client, medium_id, id) {
	return client.delete(`/api/content/media/${medium_id}/products/${id}`);
}
/**
* List playlists with cursor pagination
* Returns a paginated list of playlists.
*
* @param client - Fetch client instance
* @param [params] - params
*/
async function playlists_list(client, params) {
	return client.get(`/api/content/playlists`, params);
}
/**
* Create a new playlist
* Creates a new playlist.
*
* @param client - Fetch client instance
* @param body - body
*/
async function playlists_create(client, body) {
	return client.post(`/api/content/playlists`, body);
}
/**
* Get a specific playlist
* Returns a single playlist by ID.
*
* @param client - Fetch client instance
* @param id - id
*/
async function playlists_show(client, id) {
	return client.get(`/api/content/playlists/${id}`);
}
/**
* Update a playlist
* Updates a playlist's title or metadata.
*
* @param client - Fetch client instance
* @param id - id
* @param body - body
*/
async function playlists_update(client, id, body) {
	return client.patch(`/api/content/playlists/${id}`, body);
}
/**
* Delete a playlist
* Removes a playlist.
*
* @param client - Fetch client instance
* @param id - id
*/
async function playlists_destroy(client, id) {
	return client.delete(`/api/content/playlists/${id}`);
}
/**
* List items in a playlist
* Returns a paginated list of items in a playlist.
*
* @param client - Fetch client instance
* @param playlist_id - playlist_id
* @param [params] - params
*/
async function playlists_items_list(client, playlist_id, params) {
	return client.get(`/api/content/playlists/${playlist_id}/items`, params);
}
/**
* Add an item to a playlist
* Adds a content item (media, page, product, or enrollment_pack) to a playlist.
*
* @param client - Fetch client instance
* @param playlist_id - playlist_id
* @param body - body
*/
async function playlists_items_add(client, playlist_id, body) {
	return client.post(`/api/content/playlists/${playlist_id}/items`, body);
}
/**
* Reorder items in a playlist
* Sets the order of items in a playlist. Items not included in the payload are not moved. Flips the playlist to manual ordering.
*
* @param client - Fetch client instance
* @param playlist_id - playlist_id
* @param body - body
*/
async function playlists_items_reorder(client, playlist_id, body) {
	return client.patch(`/api/content/playlists/${playlist_id}/items/reorder`, body);
}
/**
* Remove an item from a playlist
* Removes a single item from a playlist.
*
* @param client - Fetch client instance
* @param playlist_id - playlist_id
* @param id - id
*/
async function playlists_items_remove(client, playlist_id, id) {
	return client.delete(`/api/content/playlists/${playlist_id}/items/${id}`);
}
/**
* List pages for the company
* Returns a paginated list of published pages for the authenticated rep's company. Members have read-only access — there is no create, update, or destroy action for pages in the portal BFF. Response shape matches pages_show (PortalTenant::Api::PageBlueprinter).
*
* @param client - Fetch client instance
* @param [params] - params
*/
async function pages_list(client, params) {
	return client.get(`/api/content/pages`, params);
}
/**
* Get a specific page
* Returns a single page by ID, scoped to the authenticated rep's company. Response is a lean portal-BFF shape rendered by PortalTenant::Api::PageBlueprinter — not the legacy admin shape. Admin-only fields (html_code, application_theme_template, search_engine_optimizer, open_graph, prompts, etc.) are intentionally omitted.
*
* @param client - Fetch client instance
* @param id - id
* @param [params] - params
*/
async function pages_show(client, id, params) {
	return client.get(`/api/content/pages/${id}`, params);
}
/**
* List share links for the current user
* Returns a paginated list of share links.
*
* @param client - Fetch client instance
* @param [params] - params
*/
async function shares_list(client, params) {
	return client.get(`/api/shares`, params);
}
/**
* Create a share link
* Creates a new share link for content.
*
* @param client - Fetch client instance
* @param body - body
*/
async function shares_create(client, body) {
	return client.post(`/api/shares`, body);
}
/**
* List DAM assets
* Returns a paginated list of DAM assets for the company.
*
* @param client - Fetch client instance
* @param [params] - params
*/
async function dam_assets_list(client, params) {
	return client.get(`/api/content/dam/assets`, params);
}
/**
* Create a DAM asset
* Creates a new DAM asset. Supports two modes:
1. **JSON placeholder** — send `application/json` with `asset[name]` to
create a placeholder record for later file upload.

2. **File upload** — send `multipart/form-data` with `asset[file]`,
`asset[name]`, and optionally `asset[description]` and `asset[tags]`
to upload a file and create the full asset with variants.
*
* @param client - Fetch client instance
* @param body - body
*/
async function dam_assets_create(client, body) {
	return client.post(`/api/content/dam/assets`, body);
}
/**
* List paths for a DAM asset
* Returns a paginated list of path aliases for a DAM asset.
*
* @param client - Fetch client instance
* @param asset_code - asset_code
* @param [params] - params
*/
async function dam_asset_paths_list(client, asset_code, params) {
	return client.get(`/api/content/dam/assets/${asset_code}/paths`, params);
}
/**
* Create a path alias for a DAM asset
* Creates a new path alias for an existing DAM asset.
*
* @param client - Fetch client instance
* @param asset_code - asset_code
* @param body - body
*/
async function dam_asset_paths_create(client, asset_code, body) {
	return client.post(`/api/content/dam/assets/${asset_code}/paths`, body);
}
/**
* Query DAM assets using tree paths and tags
* Searches and retrieves DAM assets using tree path pattern matching, tag-based variant filtering, wildcard name matching, and partial search. Supports cursor pagination for large result sets.
*
* @param client - Fetch client instance
* @param body - body
*/
async function dam_query(client, body) {
	return client.post(`/api/content/dam/query`, body);
}
/**
* Delete a DAM asset
* Permanently destroys a DAM asset, including its ImageKit storage, variants, and database records.
*
* @param client - Fetch client instance
* @param code - code
*/
async function dam_assets_destroy(client, code) {
	return client.delete(`/api/content/dam/assets/${code}`);
}
/**
* Discard (soft-delete) a DAM asset
* Soft-deletes a DAM asset. Used to discard an in-progress upload without permanently removing the record.
*
* @param client - Fetch client instance
* @param code - code
*/
async function dam_assets_discard(client, code) {
	return client.patch(`/api/content/dam/assets/${code}/discard`);
}
/**
* Top media by direct visits
* Ranked list of the company's media by total visits (aggregates metrics_media_visits across all visit sources).
*
* @param client - Fetch client instance
* @param [params] - params
*/
async function content_media_by_visits(client, params) {
	return client.get(`/api/content/media/by-visits`, params);
}
/**
* Top media by share-link visits
* Ranked list of the company's media by click-throughs on rep share links (aggregates metrics_share_shareable_visits where shareable_type='Medium').
*
* @param client - Fetch client instance
* @param [params] - params
*/
async function content_media_by_shares(client, params) {
	return client.get(`/api/content/media/by-shares`, params);
}
/**
* Top playlists by direct visits
* Ranked list of the company's playlists by total visits (aggregates metrics_library_visits since playlists are stored in the libraries table).
*
* @param client - Fetch client instance
* @param [params] - params
*/
async function content_playlists_by_visits(client, params) {
	return client.get(`/api/content/playlists/by-visits`, params);
}
/**
* Top playlists by share-link visits
* Ranked list of the company's playlists by click-throughs on rep share links (aggregates metrics_share_shareable_visits where shareable_type='Library').
*
* @param client - Fetch client instance
* @param [params] - params
*/
async function content_playlists_by_shares(client, params) {
	return client.get(`/api/content/playlists/by-shares`, params);
}
/**
* Top pages by direct visits
* Ranked list of the company's pages by total visits (aggregates metrics_page_visits across all visit sources).
*
* @param client - Fetch client instance
* @param [params] - params
*/
async function content_pages_by_visits(client, params) {
	return client.get(`/api/content/pages/by-visits`, params);
}
/**
* Top pages by share-link visits
* Ranked list of the company's pages by click-throughs on rep share links (aggregates metrics_share_shareable_visits where shareable_type='Page').
*
* @param client - Fetch client instance
* @param [params] - params
*/
async function content_pages_by_shares(client, params) {
	return client.get(`/api/content/pages/by-shares`, params);
}
//#endregion
//#region ../../shareables/core/src/context.tsx
const ShareablesCoreContext = createContext(null);
function ShareablesCoreProvider({ config, children }) {
	return /* @__PURE__ */ jsx(ShareablesCoreContext.Provider, {
		value: config,
		children
	});
}
function useShareablesClient() {
	const ctx = use(ShareablesCoreContext);
	if (!ctx) throw new Error("useShareablesClient must be used within a ShareablesCoreProvider");
	return ctx.client ?? null;
}
function useShareablesUser() {
	const ctx = use(ShareablesCoreContext);
	if (!ctx) throw new Error("useShareablesUser must be used within a ShareablesCoreProvider");
	return ctx.user;
}
function useRepContext() {
	return use(ShareablesCoreContext)?.repContext ?? false;
}
//#endregion
//#region ../../shareables/core/src/hooks/use-media-mutations.ts
const useCreateMediaMutation = (options) => {
	const api = useShareablesApi();
	const queryClient = useQueryClient();
	return useMutation({
		mutationFn: (payload) => {
			return api.media.createMedia(payload);
		},
		onSuccess: (data) => {
			queryClient.invalidateQueries({ queryKey: shareablesKeys.media.all });
			options?.onSuccess?.(data);
		},
		onError: (error) => {
			console.error("Error creating media:", error);
			options?.onError?.(error);
		}
	});
};
//#endregion
//#region ../../shareables/core/src/utils.ts
/**
* Check if an error is a cancellation/abort error from TanStack Query or AbortController.
*/
function isCancellationError(error) {
	return !!error && typeof error === "object" && "name" in error && (error.name === "CancelledError" || error.name === "AbortError");
}
//#endregion
//#region ../../shareables/core/src/hooks/use-playlist-mutations.ts
function updatePlaylistDetailItems(old, updateItems) {
	if (!old || typeof old !== "object" || !("playlist" in old)) return old;
	const playlistData = old;
	return {
		...playlistData,
		playlist: {
			...playlistData.playlist,
			items: updateItems(playlistData.playlist.items ?? [])
		}
	};
}
function rollbackPlaylistDetailEntries(queryClient, previousData) {
	for (const [queryKey, data] of previousData ?? []) queryClient.setQueryData(queryKey, data);
}
const useAddItemToPlaylistMutation = (options) => {
	const api = useShareablesApi();
	const queryClient = useQueryClient();
	return useMutation({
		mutationFn: ({ playlistId, data }) => {
			return api.playlists.addItemToPlaylist(playlistId, { items: [data] });
		},
		onMutate: async ({ playlistId, newItem }) => {
			const detailPrefix = shareablesKeys.playlists.detailById(playlistId);
			await queryClient.cancelQueries({ queryKey: detailPrefix });
			const previousData = queryClient.getQueriesData({ queryKey: detailPrefix });
			queryClient.setQueriesData({ queryKey: detailPrefix }, (old) => updatePlaylistDetailItems(old, (items) => [...items, newItem]));
			return { previousData };
		},
		onSuccess: (_, { playlistId }) => {
			queryClient.invalidateQueries({ queryKey: shareablesKeys.playlists.detailById(playlistId) });
			queryClient.invalidateQueries({ queryKey: shareablesKeys.playlists.all });
			options?.onSuccess?.(playlistId);
		},
		onError: (error, { playlistId }, context) => {
			rollbackPlaylistDetailEntries(queryClient, context?.previousData);
			if (isCancellationError(error)) return;
			console.error("Error adding item to playlist:", error);
			options?.onError?.(error, playlistId);
		}
	});
};
const useRemoveItemsFromPlaylistMutation = (options) => {
	const api = useShareablesApi();
	const queryClient = useQueryClient();
	return useMutation({
		mutationFn: ({ playlistId, itemIds }) => {
			return api.playlists.removeItemsFromPlaylist(playlistId, { item_ids: itemIds });
		},
		onMutate: async ({ playlistId, itemIds }) => {
			const detailPrefix = shareablesKeys.playlists.detailById(playlistId);
			await queryClient.cancelQueries({ queryKey: detailPrefix });
			const previousData = queryClient.getQueriesData({ queryKey: detailPrefix });
			queryClient.setQueriesData({ queryKey: detailPrefix }, (old) => updatePlaylistDetailItems(old, (items) => items.filter((item) => item.id != null && !itemIds.includes(item.id))));
			return { previousData };
		},
		onSuccess: (_, { playlistId }) => {
			queryClient.invalidateQueries({ queryKey: shareablesKeys.playlists.detailById(playlistId) });
			queryClient.invalidateQueries({ queryKey: shareablesKeys.playlists.all });
			options?.onSuccess?.(playlistId);
		},
		onError: (error, { playlistId }, context) => {
			rollbackPlaylistDetailEntries(queryClient, context?.previousData);
			if (isCancellationError(error)) return;
			if ((error && typeof error === "object" && "message" in error ? String(error.message) : "").includes("No valid playlist items found")) {
				queryClient.invalidateQueries({ queryKey: shareablesKeys.playlists.detailById(playlistId) });
				options?.onSuccess?.(playlistId);
				return;
			}
			console.error("Error removing item from playlist:", error);
			options?.onError?.(error, playlistId);
		}
	});
};
const useCreatePlaylistMutation = (options) => {
	const api = useShareablesApi();
	const queryClient = useQueryClient();
	return useMutation({
		mutationFn: (input) => {
			return api.playlists.createPlaylist(input);
		},
		onSuccess: (createdPlaylist) => {
			queryClient.invalidateQueries({ queryKey: shareablesKeys.playlists.all });
			options?.onSuccess?.(createdPlaylist);
		},
		onError: (error) => {
			if (isCancellationError(error)) return;
			console.error("Error creating playlist:", error);
			options?.onError?.(error);
		}
	});
};
const useUpdatePlaylistMutation = (options) => {
	const api = useShareablesApi();
	const queryClient = useQueryClient();
	return useMutation({
		mutationFn: ({ playlistId, data }) => {
			return api.playlists.updatePlaylist(playlistId, data);
		},
		onSuccess: (_, { playlistId }) => {
			queryClient.invalidateQueries({ queryKey: shareablesKeys.playlists.all });
			queryClient.invalidateQueries({ queryKey: shareablesKeys.playlists.detail(playlistId) });
			options?.onSuccess?.(playlistId);
		},
		onError: (error) => {
			if (isCancellationError(error)) return;
			console.error("Error updating playlist:", error);
			options?.onError?.(error);
		}
	});
};
const useReorderPlaylistItemsMutation = (options) => {
	const api = useShareablesApi();
	const queryClient = useQueryClient();
	return useMutation({
		mutationFn: ({ playlistId, data }) => {
			if (!api.playlists.reorderPlaylistItems) return Promise.resolve();
			return api.playlists.reorderPlaylistItems(playlistId, data);
		},
		onSuccess: (_, { playlistId }) => {
			if (api.playlists.reorderPlaylistItems) queryClient.invalidateQueries({ queryKey: shareablesKeys.playlists.detail(playlistId) });
			options?.onSuccess?.(playlistId);
		},
		onError: (error, { playlistId }) => {
			if (isCancellationError(error)) return;
			console.error("Error reordering playlist items:", error);
			options?.onError?.(error, playlistId);
		}
	});
};
//#endregion
//#region ../../file-picker/core/src/file-picker-api-context.ts
const FilePickerApiContext = createContext(null);
const FilePickerApiProvider = FilePickerApiContext.Provider;
function useFilePickerApi() {
	const api = useContext(FilePickerApiContext);
	if (!api) throw new Error("useFilePickerApi must be used within a FilePickerApiProvider");
	return api;
}
//#endregion
//#region ../../file-picker/core/src/schemas/dam.ts
const damVariantSchema = z.object({
	id: z.string(),
	url: z.string().nullable(),
	file_name: z.string(),
	mime_type: z.string(),
	content: z.any().nullable(),
	created_at: z.string(),
	updated_at: z.string(),
	default: z.boolean(),
	is_original: z.boolean(),
	is_text: z.boolean(),
	media_type: z.string(),
	processing_status: z.string(),
	tags: z.array(z.string())
});
const damAssetSchema = z.object({
	id: z.number(),
	canonical_path: z.string(),
	category: z.string(),
	code: z.string(),
	company: z.string(),
	created_at: z.string(),
	default_variant_id: z.string(),
	default_variant_url: z.string().optional(),
	description: z.string(),
	name: z.string(),
	updated_at: z.string(),
	variants: z.array(damVariantSchema).optional()
});
const damTreeFolderNodeSchema = z.object({
	asset_code: z.union([z.string(), z.record(z.string(), z.unknown())]).optional(),
	name: z.union([z.string(), z.record(z.string(), z.unknown())]).optional(),
	category: z.union([z.string(), z.record(z.string(), z.unknown())]).optional(),
	variants: z.union([z.array(z.unknown()), z.record(z.string(), z.unknown())]).optional()
}).passthrough();
const damTreeSchema = z.record(z.string(), z.union([
	z.lazy(() => damTreeSchema),
	damAssetSchema,
	damTreeFolderNodeSchema
]));
const damQueryResponseSchema = z.object({
	path: z.string(),
	tree: damTreeSchema,
	meta: z.object({
		next_cursor: z.string().optional(),
		total_count: z.number().optional()
	}).optional()
});
z.object({ asset: z.object({
	file: z.any(),
	name: z.string(),
	description: z.string().optional(),
	tags: z.string().optional()
}) });
z.object({
	asset: damAssetSchema,
	meta: z.object({
		request_id: z.string(),
		timestamp: z.string()
	})
});
z.object({
	placeholder_asset: z.object({
		mime_type: z.string(),
		name: z.string().optional(),
		description: z.string().optional()
	}),
	skip_autotagging: z.boolean().optional()
});
z.object({
	asset: z.object({
		file: z.any(),
		name: z.string(),
		description: z.string().optional(),
		tags: z.string().optional()
	}).optional(),
	text_asset: z.object({
		file_name: z.string(),
		mime_type: z.string(),
		text: z.string(),
		name: z.string().optional(),
		description: z.string().optional(),
		tags: z.string().optional()
	}).optional(),
	placeholder_asset: z.object({
		mime_type: z.string(),
		name: z.string().optional(),
		description: z.string().optional()
	}).optional(),
	skip_autotagging: z.boolean().optional()
});
z.object({
	asset: z.object({
		id: z.number(),
		canonical_path: z.string(),
		name: z.string()
	}),
	meta: z.object({
		request_id: z.string(),
		timestamp: z.string()
	})
});
//#endregion
//#region ../../file-picker/api-client/src/api/url-proxy.ts
const urlProxyResponseSchema = z.object({
	data: z.string(),
	contentType: z.string(),
	size: z.number()
});
/**
* Proxy a URL fetch through the backend to bypass CORS restrictions.
* The backend fetches the file and returns it as base64-encoded data.
*
* @param url - The URL to fetch
* @param proxyEndpoint - The proxy endpoint (defaults to "/api/proxy-url")
*/
async function proxyUrlFetch(url, proxyEndpoint = "/api/proxy-url") {
	const response = await fetch(proxyEndpoint, {
		method: "POST",
		headers: { "Content-Type": "application/json" },
		body: JSON.stringify({ url })
	});
	if (!response.ok) {
		const errorData = await response.json().catch(() => ({ error: "Failed to proxy URL fetch" }));
		throw new Error(errorData.error || `HTTP ${response.status}`);
	}
	const data = await response.json();
	return urlProxyResponseSchema.parse(data);
}
//#endregion
//#region src/adapters/file-picker-api-adapter.ts
/**
* Maps a BFF DAM asset to the file-picker port's DamAssetCreateResponse shape.
*
* The BFF response includes nullable meta.request_id (from Api::Response),
* while the port schema requires a string. We coalesce to empty string.
*/
function mapCreateResponse(response) {
	const raw = response.asset ?? {};
	return {
		asset: damAssetSchema.parse({
			...raw,
			canonical_path: raw.canonical_path ?? "",
			category: raw.category ?? "",
			company: raw.company ?? "",
			description: raw.description ?? "",
			default_variant_id: raw.default_variant_id ?? ""
		}),
		meta: {
			request_id: response.meta?.request_id ?? "",
			timestamp: response.meta?.timestamp ?? (/* @__PURE__ */ new Date()).toISOString()
		}
	};
}
/**
* Maps a BFF asset path response to the file-picker port's shape.
*/
function mapAssetPathCreateResponse(response) {
	const assetPath = response.asset_path ?? {};
	return {
		asset: {
			id: assetPath.id ?? 0,
			canonical_path: assetPath.path ?? "",
			name: assetPath.asset_code ?? ""
		},
		meta: {
			request_id: response.meta?.request_id ?? "",
			timestamp: response.meta?.timestamp ?? (/* @__PURE__ */ new Date()).toISOString()
		}
	};
}
/**
* Creates a FilePickerApi adapter backed by the portal-tenant BFF's
* `/api/content/dam/*` endpoints, using cookie-based auth via the
* provided FetchClient.
*
* Unsplash search is not available through the BFF — callers that need
* Unsplash should use the legacy adapter or provide their own
* implementation.
*
* The `onProgress` callback in `createDamAsset` is not supported — the
* underlying `fetch` API does not expose upload progress events.
*
* URL proxy delegates to the same-origin `/api/proxy-url` endpoint
* (served by the hosting app, not the BFF) for CORS bypass, identical
* to the legacy adapter behaviour.
*/
function createFilePickerApiAdapter(client) {
	return {
		createDamAsset: async (params) => {
			const formData = new FormData();
			formData.append("asset[file]", params.file);
			formData.append("asset[name]", params.name);
			if (params.description) formData.append("asset[description]", params.description);
			if (params.tags && params.tags.length > 0) formData.append("asset[tags]", params.tags.join(","));
			return mapCreateResponse(await client.requestWithFormData("/api/content/dam/assets", formData, { method: "POST" }));
		},
		queryDamAssets: async (params) => {
			const response = await dam_query(client, params);
			return damQueryResponseSchema.parse({
				...response,
				meta: response.meta ? { next_cursor: response.meta.pagination?.next_cursor ?? void 0 } : void 0
			});
		},
		deleteDamAsset: async (code) => {
			return dam_assets_destroy(client, code);
		},
		discardDamAsset: async (code) => {
			return dam_assets_discard(client, code);
		},
		createDamAssetPathForAssets: async (params) => {
			return mapAssetPathCreateResponse(await dam_asset_paths_create(client, params.code, { asset_path: { path: params.asset_paths.join(",") } }));
		},
		searchUnsplash: async (_query, _page, _perPage) => {
			throw new Error("Unsplash search is not available through the portal-tenant BFF. Configure an Unsplash access key and use the standard FilePickerApi adapter instead.");
		},
		proxyUrlFetch: (url) => proxyUrlFetch(url)
	};
}
//#endregion
//#region src/adapters/content-api-adapter.ts
function mapMedia(raw) {
	return {
		id: raw.id ?? 0,
		title: raw.title ?? "",
		description: raw.description ?? null,
		content_format: raw.content_format ?? null,
		status: raw.status ?? "active",
		url: raw.url ?? null,
		thumbnail_url: raw.thumbnail_url ?? null,
		owner_type: raw.owner_type ?? "",
		cta: raw.cta ? {
			enabled: raw.cta.enabled ?? null,
			type: raw.cta.type ?? null,
			button_text: raw.cta.button_text ?? null,
			button_color: raw.cta.button_color ?? null,
			button_description: raw.cta.button_description ?? null,
			action_url: raw.cta.action_url ?? null
		} : null,
		seo: raw.seo ? {
			title: raw.seo.title ?? null,
			description: raw.seo.description ?? null,
			image_url: raw.seo.image_url ?? null,
			block_crawler: raw.seo.block_crawler ?? null
		} : null,
		created_at: raw.created_at ?? "",
		updated_at: raw.updated_at ?? ""
	};
}
function mapMediaMeta(raw) {
	return {
		request_id: raw?.request_id ?? null,
		timestamp: raw?.timestamp ?? "",
		pagination: raw?.pagination ? {
			cursor: raw.pagination.cursor ?? null,
			limit: raw.pagination.limit,
			next_cursor: raw.pagination.next_cursor ?? null,
			prev_cursor: raw.pagination.prev_cursor ?? null
		} : void 0
	};
}
function createRawMediaAdapter(client) {
	return {
		listMedia: async (params) => {
			const response = await media_list(client, {
				"page[cursor]": params?.cursor,
				"page[limit]": params?.limit,
				"filter[title]": params?.["filter[title]"],
				"filter[ownership]": params?.["filter[ownership]"],
				"filter[content_format]": params?.["filter[content_format]"],
				sort: params?.sort,
				language_iso: params?.language_iso
			});
			return {
				media: (response.media ?? []).map(mapMedia),
				meta: mapMediaMeta(response.meta)
			};
		},
		createMedia: async (body) => {
			const response = await media_create(client, { media: body });
			if (!response.media) throw new Error("Media create response missing media");
			return {
				media: mapMedia(response.media),
				meta: mapMediaMeta(response.meta)
			};
		},
		getMedia: async (id, language_iso) => {
			const response = await media_show(client, id, language_iso ? { language_iso } : void 0);
			if (!response.media) throw new Error("Media show response missing media");
			return {
				media: mapMedia(response.media),
				meta: mapMediaMeta(response.meta)
			};
		},
		updateMedia: async (id, body, language_iso) => {
			const response = await media_update(client, id, { media: body }, language_iso ? { language_iso } : void 0);
			if (!response.media) throw new Error("Media update response missing media");
			return {
				media: mapMedia(response.media),
				meta: mapMediaMeta(response.meta)
			};
		},
		deleteMedia: async (id) => {
			const response = await media_destroy(client, id);
			return {
				media: { id: response.media?.id ?? 0 },
				meta: mapMediaMeta(response.meta)
			};
		}
	};
}
/**
* Creates a ContentMediaProductsApi adapter backed by the portal-tenant content BFF.
*/
function createPortalTenantMediaProductsAdapter(client) {
	return {
		listMediaProducts: async (mediumId, params) => {
			const response = await media_products_list(client, mediumId, {
				"page[cursor]": params?.cursor,
				"page[limit]": params?.limit,
				language_iso: params?.language_iso
			});
			return {
				media_products: (response.media_products ?? []).map((p) => ({
					id: p.id ?? 0,
					name: p.name ?? void 0,
					slug: p.slug ?? null,
					image_url: p.image_url ?? null,
					price: p.price ?? null,
					currency: p.currency ?? null,
					added_at: p.added_at ?? null
				})),
				meta: mapMediaMeta(response.meta)
			};
		},
		addMediaProduct: async (mediumId, body) => {
			const response = await media_products_add(client, mediumId, { product: { id: body.id } });
			const p = response.media_product ?? {};
			return {
				media_product: {
					id: p.id ?? 0,
					name: p.name ?? void 0,
					slug: p.slug ?? null,
					image_url: p.image_url ?? null,
					price: p.price ?? null,
					currency: p.currency ?? null,
					added_at: p.added_at ?? null
				},
				meta: {
					request_id: response.meta?.request_id ?? null,
					timestamp: response.meta?.timestamp ?? ""
				}
			};
		},
		removeMediaProduct: async (mediumId, productId) => {
			const response = await media_products_remove(client, mediumId, productId);
			return {
				media_product: { product_id: response.media_product?.product_id ?? 0 },
				meta: {
					request_id: response.meta?.request_id ?? null,
					timestamp: response.meta?.timestamp ?? ""
				}
			};
		}
	};
}
function mediaKindFromType(mediaType) {
	if (mediaType === "video") return "video";
	if (mediaType === "image") return "image";
	if (mediaType === "document" || mediaType === "pdf") return "pdf";
	return null;
}
function toBffMediumResponse(bff) {
	const kind = bff.content_format ?? null;
	const isVideo = kind === "video";
	const isPdf = kind === "pdf";
	const ctaData = bff.cta;
	const seoData = bff.seo;
	return {
		id: bff.id,
		user_id: null,
		owner_type: bff.owner_type ?? null,
		media_type: bff.content_format ?? "image",
		media_format: bff.content_format ?? "image",
		image_url: !isVideo && !isPdf ? bff.url ?? bff.thumbnail_url ?? null : bff.thumbnail_url ?? null,
		video_url: isVideo ? bff.url ?? null : null,
		pdf_url: isPdf ? bff.url ?? null : null,
		title: bff.title,
		description: {
			id: null,
			name: null,
			body: bff.description ?? null,
			record_type: null,
			record_id: null,
			created_at: bff.created_at ?? null,
			updated_at: bff.updated_at ?? null,
			locale: null
		},
		stripped: bff.description ?? null,
		kind,
		active: bff.status === "active",
		visibility: null,
		share_link: null,
		views: 0,
		leads: 0,
		watch: null,
		video_status: null,
		duration: null,
		cta_url: ctaData?.action_url ?? null,
		cta_button_text: ctaData?.button_text ?? null,
		cta_enabled: ctaData?.enabled ?? false,
		cta_action_type: ctaData?.type ?? null,
		video_shopping_enabled: false,
		prompts_enabled: false,
		ranks: [],
		preview_link: null,
		attached_shareables: [],
		created_at: bff.created_at,
		settings: {
			cta: ctaData ? {
				enabled: ctaData.enabled ?? void 0,
				type: ctaData.type ?? void 0,
				url: ctaData.action_url ?? void 0,
				button_text: ctaData.button_text ?? void 0,
				button_color: ctaData.button_color ?? void 0,
				button_description: ctaData.button_description ?? void 0
			} : null,
			seo: seoData ? {
				title: seoData.title ?? void 0,
				description: seoData.description ?? void 0,
				image_url: seoData.image_url ?? void 0,
				block_crawler: seoData.block_crawler ?? void 0
			} : null
		}
	};
}
function createMediaAdapter(client) {
	const portAdapter = createRawMediaAdapter(client);
	const cursorByPage = /* @__PURE__ */ new Map();
	let lastFilterKey = "";
	return {
		list: async (options) => {
			const response = await portAdapter.listMedia({
				cursor: options?.["page[cursor]"],
				limit: options?.["page[limit]"],
				"filter[title]": options?.["filter[title]"],
				"filter[ownership]": options?.["filter[ownership]"],
				"filter[content_format]": options?.["filter[content_format]"],
				sort: options?.sort,
				language_iso: options?.language_iso
			});
			return {
				media: response.media.map(toBffMediumResponse),
				nextCursor: response.meta.pagination?.next_cursor ?? null
			};
		},
		getMedia: async (options) => {
			const pageNumber = options?.page ?? 1;
			const filterKey = `${options?.search_query ?? ""}|${options?.sorted_by ?? ""}|${options?.ownership ?? ""}|${options?.language_iso ?? ""}`;
			if (filterKey !== lastFilterKey) {
				cursorByPage.clear();
				lastFilterKey = filterKey;
			}
			const cursor = pageNumber > 1 ? cursorByPage.get(pageNumber) : void 0;
			const rawSort = options?.sorted_by;
			let bffSort;
			if (rawSort === "title_asc") bffSort = "title_asc";
			else if (rawSort === "title_desc") bffSort = "title_desc";
			const ownership = options?.ownership;
			const bffOwnership = ownership === "all" || ownership === "mine" || ownership === "company" ? ownership : void 0;
			const response = await portAdapter.listMedia({
				cursor,
				limit: options?.per_page,
				"filter[title]": options?.search_query,
				"filter[ownership]": bffOwnership,
				sort: bffSort,
				language_iso: options?.language_iso
			});
			const nextCursor = response.meta.pagination?.next_cursor;
			if (nextCursor) cursorByPage.set(pageNumber + 1, nextCursor);
			const transformedItems = response.media.map(toBffMediumResponse);
			const perPage = options?.per_page ?? 24;
			return {
				data: transformedItems,
				status: "success",
				media: transformedItems,
				meta: {
					total_count: nextCursor ? pageNumber * perPage + 1 : (pageNumber - 1) * perPage + transformedItems.length,
					current: pageNumber,
					per_page: perPage,
					pages: nextCursor ? pageNumber + 1 : pageNumber,
					next: nextCursor ? pageNumber + 1 : null,
					previous: pageNumber > 1 ? pageNumber - 1 : null
				}
			};
		},
		getMediaById: async (id, language_iso) => {
			const medium = toBffMediumResponse((await portAdapter.getMedia(id, language_iso)).media);
			return {
				data: medium,
				status: "success",
				media: medium
			};
		},
		createMedia: async (mediaData) => {
			const contentFormat = mediaData.kind === "image" || mediaData.kind === "video" || mediaData.kind === "pdf" || mediaData.kind === "ppt" ? mediaData.kind : void 0;
			return toBffMediumResponse((await portAdapter.createMedia({
				title: mediaData.title ?? "",
				description: mediaData.description,
				media_type: mediaData.media_type ?? "image",
				url: mediaData.image_url ?? mediaData.video_url ?? mediaData.pdf_url ?? void 0,
				content_format: contentFormat
			})).media);
		},
		updateMedia: async (id, mediaData, language_iso) => {
			const updateBody = {
				title: mediaData.title,
				description: mediaData.description
			};
			if (mediaData.active !== void 0) updateBody.status = mediaData.active ? "active" : "draft";
			const newUrl = mediaData.image_url ?? mediaData.video_url ?? mediaData.pdf_url ?? void 0;
			if (newUrl !== void 0) updateBody.url = newUrl;
			if (mediaData.kind === "image" || mediaData.kind === "video" || mediaData.kind === "pdf" || mediaData.kind === "ppt") updateBody.content_format = mediaData.kind;
			if (mediaData.thumbnail_url !== void 0) updateBody.thumbnail_url = mediaData.thumbnail_url;
			if (mediaData.settings?.cta) {
				const rawType = mediaData.settings.cta.type;
				const ctaType = rawType === "link" || rawType === "cart" || rawType === "email" || rawType === "phone" ? rawType : void 0;
				updateBody.cta = {
					enabled: mediaData.settings.cta.enabled,
					type: ctaType,
					button_text: mediaData.settings.cta.button_text,
					button_color: mediaData.settings.cta.button_color,
					button_description: mediaData.settings.cta.button_description,
					action_url: mediaData.settings.cta.url
				};
			}
			if (mediaData.settings?.seo) updateBody.seo = {
				title: mediaData.settings.seo.title,
				description: mediaData.settings.seo.description,
				image_url: mediaData.settings.seo.image_url,
				block_crawler: mediaData.settings.seo.block_crawler ?? void 0
			};
			return toBffMediumResponse((await portAdapter.updateMedia(id, updateBody, language_iso)).media);
		},
		deleteMedia: async (id) => {
			await portAdapter.deleteMedia(id);
			return { success: true };
		}
	};
}
function mapPlaylist(raw) {
	return {
		id: raw.id ?? 0,
		title: raw.title ?? "",
		description: raw.description ?? null,
		items_count: raw.items_count ?? 0,
		user_id: raw.member_id ?? void 0,
		is_favorited: raw.is_favorited,
		image_url: raw.image_url ?? null,
		created_at: raw.created_at ?? "",
		updated_at: raw.updated_at ?? ""
	};
}
function mapPlaylistItem(raw) {
	return {
		id: raw.id,
		content_type: raw.content_type,
		content_id: raw.content_id,
		position: raw.position,
		created_at: raw.created_at,
		content: raw.content
	};
}
function mapPlaylistsMeta(raw) {
	return {
		request_id: raw?.request_id ?? null,
		timestamp: raw?.timestamp ?? "",
		pagination: raw?.pagination ? {
			cursor: raw.pagination.cursor ?? null,
			limit: raw.pagination.limit,
			next_cursor: raw.pagination.next_cursor ?? null,
			prev_cursor: raw.pagination.prev_cursor ?? null
		} : void 0
	};
}
function createRawPlaylistsAdapter(client) {
	return {
		listPlaylists: async (params) => {
			const response = await playlists_list(client, {
				"page[cursor]": params?.cursor,
				"page[limit]": params?.limit,
				"filter[title]": params?.["filter[title]"],
				"filter[ownership]": params?.["filter[ownership]"],
				sort: params?.sort
			});
			return {
				playlists: (response.playlists ?? []).map(mapPlaylist),
				meta: mapPlaylistsMeta(response.meta)
			};
		},
		createPlaylist: async (body) => {
			const response = await playlists_create(client, { playlist: body });
			return {
				playlist: mapPlaylist(response.playlist ?? {}),
				meta: mapPlaylistsMeta(response.meta)
			};
		},
		getPlaylist: async (id) => {
			const response = await playlists_show(client, id);
			return {
				playlist: mapPlaylist(response.playlist ?? {}),
				meta: mapPlaylistsMeta(response.meta)
			};
		},
		updatePlaylist: async (id, body) => {
			const response = await playlists_update(client, id, { playlist: body });
			return {
				playlist: mapPlaylist(response.playlist ?? {}),
				meta: mapPlaylistsMeta(response.meta)
			};
		},
		deletePlaylist: async (id) => {
			const response = await playlists_destroy(client, id);
			return {
				playlist: { id: response.playlist?.id ?? 0 },
				meta: mapPlaylistsMeta(response.meta)
			};
		},
		listPlaylistItems: async (playlistId, params) => {
			const response = await playlists_items_list(client, playlistId, {
				"page[cursor]": params?.cursor,
				"page[limit]": params?.limit,
				language_iso: params?.language_iso
			});
			return {
				playlist_items: (response.playlist_items ?? []).map(mapPlaylistItem),
				meta: mapPlaylistsMeta(response.meta)
			};
		},
		addPlaylistItem: async (playlistId, body) => {
			const response = await playlists_items_add(client, playlistId, { item: body });
			const rawItem = response.playlist_item;
			if (!rawItem) throw new Error("Playlist item add response missing playlist_item");
			return {
				playlist_item: mapPlaylistItem(rawItem),
				meta: mapPlaylistsMeta(response.meta)
			};
		},
		removePlaylistItem: async (playlistId, itemId) => {
			const response = await playlists_items_remove(client, playlistId, itemId);
			return {
				playlist_item: { id: response.playlist_item?.id ?? 0 },
				meta: mapPlaylistsMeta(response.meta)
			};
		},
		reorderPlaylistItems: async (playlistId, body) => {
			const response = await playlists_items_reorder(client, playlistId, body);
			return {
				playlist_id: response.playlist_id ?? playlistId,
				meta: mapPlaylistsMeta(response.meta)
			};
		}
	};
}
const CONTENT_TYPE_TO_RELATEABLE = {
	media: "Medium",
	page: "Page",
	product: "Product",
	enrollment_pack: "EnrollmentPack"
};
const RELATEABLE_TO_CONTENT_TYPE = {
	Medium: "media",
	Media: "media",
	media: "media",
	Page: "page",
	page: "page",
	Product: "product",
	product: "product",
	EnrollmentPack: "enrollment_pack",
	enrollment_pack: "enrollment_pack"
};
function firstImageUrl(images) {
	return images?.[0]?.url ?? null;
}
function toShareablePlaylistItem(item) {
	const relateableType = CONTENT_TYPE_TO_RELATEABLE[item.content_type];
	const base = {
		id: item.id,
		order: item.position ?? void 0,
		relateable_type: relateableType,
		relateable: { id: item.content_id }
	};
	switch (item.content_type) {
		case "media": {
			const c = item.content;
			const isVideo = c.content_format === "video";
			const isPdf = c.content_format === "pdf";
			base.title = c.title ?? "Untitled";
			base.image_url = isVideo || isPdf ? c.thumbnail_url ?? null : c.url ?? c.thumbnail_url ?? null;
			base.kind = mediaKindFromType(c.content_format ?? "");
			base.video_url = isVideo ? c.url ?? null : null;
			base.duration = null;
			base.media_format = c.content_format ?? null;
			base.relateable = {
				id: c.id,
				title: c.title,
				image_url: base.image_url,
				media_format: c.content_format ?? null,
				video_url: base.video_url,
				kind: base.kind,
				description: {
					id: null,
					name: null,
					body: c.description ?? null,
					record_type: null,
					record_id: null,
					created_at: c.created_at ?? null,
					updated_at: c.updated_at ?? null,
					locale: null
				}
			};
			break;
		}
		case "page": {
			const c = item.content;
			base.title = c.title ?? "Untitled";
			base.image_url = c.image_url ?? null;
			base.relateable = {
				id: c.id,
				title: c.title,
				slug: c.slug ?? null,
				image_url: c.image_url ?? null,
				status: c.status,
				description: {
					id: null,
					name: null,
					body: c.description ?? null,
					record_type: null,
					record_id: null,
					created_at: null,
					updated_at: null,
					locale: null
				}
			};
			break;
		}
		case "product": {
			const c = item.content;
			const image = firstImageUrl(c.images);
			base.title = c.name;
			base.image_url = image;
			base.relateable = {
				id: c.id,
				title: c.name,
				slug: c.slug ?? null,
				price: c.price ?? null,
				display_price: c.price ?? null,
				image_url: image,
				status: c.status ?? null,
				description: {
					id: null,
					name: null,
					body: c.description ?? null,
					record_type: null,
					record_id: null,
					created_at: c.created_at ?? null,
					updated_at: null,
					locale: null
				},
				images: (c.images ?? []).map((img) => ({ image_url: img.url ?? null }))
			};
			break;
		}
		case "enrollment_pack": {
			const c = item.content;
			const image = firstImageUrl(c.images);
			base.title = c.title;
			base.image_url = image;
			base.relateable = {
				id: c.id,
				title: c.title,
				slug: c.slug ?? null,
				canonical_url: c.url ?? null,
				image_url: image,
				description: {
					id: null,
					name: null,
					body: c.description ?? null,
					record_type: null,
					record_id: null,
					created_at: null,
					updated_at: null,
					locale: null
				},
				images: (c.images ?? []).map((img) => ({ image_url: img.url ?? null }))
			};
			break;
		}
		default: {
			const _exhaustive = item.content_type;
			throw new Error(`Unhandled playlist item content_type: ${String(_exhaustive)}`);
		}
	}
	return base;
}
function toBffPlaylist(bff, items) {
	return {
		id: bff.id,
		title: bff.title,
		description: bff.description ?? null,
		image_url: bff.image_url ?? null,
		slug: null,
		active: true,
		user_id: bff.user_id ?? null,
		is_favorited: bff.is_favorited ?? false,
		items: items ?? [],
		items_count: bff.items_count
	};
}
function createPlaylistsAdapter(client) {
	const portAdapter = createRawPlaylistsAdapter(client);
	return {
		getPlaylists: async (options) => {
			const rawSort = options?.sort;
			let bffSort;
			if (rawSort === "title_asc" || rawSort === "title") bffSort = "title_asc";
			else if (rawSort === "title_desc" || rawSort === "-title") bffSort = "title_desc";
			else if (rawSort === "created_at_asc" || rawSort === "created_at") bffSort = "created_at_asc";
			else if (rawSort === "created_at_desc" || rawSort === "-created_at") bffSort = "created_at_desc";
			const response = await portAdapter.listPlaylists({
				cursor: options?.["page[cursor]"],
				limit: options?.["page[limit]"],
				"filter[title]": options?.["filter[title]"],
				"filter[ownership]": options?.["filter[ownership]"],
				sort: bffSort
			});
			return {
				playlists: response.playlists.map((p) => toBffPlaylist(p)),
				meta: {
					request_id: response.meta.request_id ?? "",
					timestamp: response.meta.timestamp ?? "",
					pagination: {
						cursor: response.meta.pagination?.cursor ?? null,
						limit: response.meta.pagination?.limit ?? 12,
						prev_cursor: response.meta.pagination?.prev_cursor ?? null,
						next_cursor: response.meta.pagination?.next_cursor ?? null,
						total_count: 0,
						total_pages: 0
					}
				}
			};
		},
		getPlaylistById: async (id, language_iso) => {
			const response = await portAdapter.getPlaylist(id);
			const allItems = [];
			let cursor;
			const MAX_PAGES = 50;
			for (let i = 0; i < MAX_PAGES; i++) {
				const page = await portAdapter.listPlaylistItems(id, {
					cursor,
					limit: 100,
					language_iso
				});
				allItems.push(...page.playlist_items);
				cursor = page.meta.pagination?.next_cursor ?? void 0;
				if (!cursor) break;
			}
			const items = allItems.map(toShareablePlaylistItem);
			return {
				playlist: toBffPlaylist(response.playlist, items),
				meta: {
					request_id: response.meta.request_id ?? "",
					timestamp: response.meta.timestamp ?? ""
				}
			};
		},
		createPlaylist: async (data) => {
			const response = await portAdapter.createPlaylist({
				title: data.playlist.title,
				description: data.playlist.description
			});
			return {
				playlist: toBffPlaylist(response.playlist),
				meta: {
					request_id: response.meta.request_id ?? "",
					timestamp: response.meta.timestamp ?? ""
				}
			};
		},
		updatePlaylist: async (id, data) => {
			const response = await portAdapter.updatePlaylist(id, {
				title: data.playlist.title,
				description: data.playlist.description
			});
			return {
				playlist: toBffPlaylist(response.playlist),
				meta: {
					request_id: response.meta.request_id ?? "",
					timestamp: response.meta.timestamp ?? ""
				}
			};
		},
		addItemToPlaylist: async (id, data) => {
			for (const item of data.items) {
				const contentType = RELATEABLE_TO_CONTENT_TYPE[item.relateable_type];
				if (!contentType) throw new Error(`Unsupported relateable_type for playlist item: "${item.relateable_type}"`);
				await portAdapter.addPlaylistItem(id, {
					content_type: contentType,
					content_id: item.relateable_id,
					position: typeof item.order === "number" ? item.order : Number(item.order)
				});
			}
			return {
				id,
				title: "",
				description: null,
				image_url: null,
				slug: null,
				active: true,
				user_id: null,
				is_favorited: false,
				items: [],
				items_count: 0
			};
		},
		removeItemsFromPlaylist: async (playlistId, data) => {
			await Promise.all(data.item_ids.map((itemId) => portAdapter.removePlaylistItem(playlistId, itemId)));
			return {
				id: playlistId,
				title: "",
				description: null,
				image_url: null,
				slug: null,
				active: true,
				user_id: null,
				is_favorited: false,
				items: [],
				items_count: 0
			};
		},
		reorderPlaylistItems: async (playlistId, data) => {
			await portAdapter.reorderPlaylistItems(playlistId, { items: data.items });
		}
	};
}
function isShareableType(value) {
	return value === "media" || value === "product" || value === "library" || value === "page";
}
function mapShare(raw) {
	return {
		id: raw.id ?? 0,
		url: raw.url ?? "",
		shareable_type: isShareableType(raw.shareable_type) ? raw.shareable_type : "media",
		shareable_id: raw.shareable_id ?? 0,
		created_at: raw.created_at ?? ""
	};
}
function mapSharesMeta(raw) {
	return {
		request_id: raw?.request_id ?? null,
		timestamp: raw?.timestamp ?? "",
		pagination: raw?.pagination ? {
			cursor: raw.pagination.cursor ?? null,
			limit: raw.pagination.limit,
			next_cursor: raw.pagination.next_cursor ?? null,
			prev_cursor: raw.pagination.prev_cursor ?? null
		} : void 0
	};
}
function createRawSharesAdapter(client) {
	return {
		listShares: async (params) => {
			const response = await shares_list(client, {
				"page[cursor]": params?.cursor,
				"page[limit]": params?.limit
			});
			return {
				shares: (response.shares ?? []).map(mapShare),
				meta: mapSharesMeta(response.meta)
			};
		},
		createShare: async (body) => {
			const response = await shares_create(client, { share: body });
			return {
				share: mapShare(response.share ?? {}),
				meta: mapSharesMeta(response.meta)
			};
		}
	};
}
const SHAREABLE_TYPE_MAP = {
	Medium: "media",
	media: "media",
	Product: "product",
	product: "product",
	Library: "library",
	library: "library",
	Page: "page",
	page: "page"
};
function createShareAdapter(client) {
	const portAdapter = createRawSharesAdapter(client);
	return { createShareLink: async (input) => {
		if (!input.relateableId) throw new Error("Cannot create share link without a relateableId");
		const shareableType = SHAREABLE_TYPE_MAP[input.relateableType];
		if (!shareableType) throw new Error(`Unknown shareable type: "${input.relateableType}"`);
		return (await portAdapter.createShare({
			shareable_type: shareableType,
			shareable_id: input.relateableId
		})).share.url;
	} };
}
function mapPage(raw) {
	return {
		id: raw.id ?? 0,
		title: raw.title ?? null,
		slug: raw.slug ?? null,
		source: raw.source ?? null,
		status: raw.status ?? "unpublished",
		countries: (raw.countries ?? []).map((c) => ({
			code: c.code ?? "",
			name: c.name ?? "",
			currency_code: c.currency_code ?? "",
			states: (c.states ?? []).map((s) => ({
				code: s.code ?? "",
				name: s.name ?? ""
			}))
		})),
		description: raw.description ?? null,
		image_url: raw.image_url ?? null
	};
}
function mapPagesMeta(raw) {
	return {
		request_id: raw?.request_id ?? null,
		timestamp: raw?.timestamp ?? "",
		pagination: raw?.pagination ? {
			cursor: raw.pagination.cursor ?? null,
			limit: raw.pagination.limit,
			next_cursor: raw.pagination.next_cursor ?? null,
			prev_cursor: raw.pagination.prev_cursor ?? null
		} : void 0
	};
}
function createRawPagesAdapter(client) {
	return {
		listPages: async (params) => {
			const response = await pages_list(client, {
				"page[cursor]": params?.cursor,
				"page[limit]": params?.limit,
				"filter[title]": params?.["filter[title]"],
				sort: params?.sort,
				language_iso: params?.language_iso
			});
			return {
				pages: (response.pages ?? []).map(mapPage),
				meta: mapPagesMeta(response.meta)
			};
		},
		getPage: async (id, language_iso) => {
			const response = await pages_show(client, id, language_iso ? { language_iso } : void 0);
			if (!response.page) throw new Error(`Page ${id} not found`);
			return {
				page: mapPage(response.page),
				share_link: response.share_link ?? null,
				meta: mapPagesMeta(response.meta)
			};
		}
	};
}
function mapEnrollmentPack(raw) {
	return {
		id: raw.id ?? 0,
		title: raw.title ?? "",
		slug: raw.slug ?? null,
		description: raw.description ?? null,
		url: raw.url ?? null,
		canonical_url: raw.canonical_url ?? null,
		images: (raw.images ?? []).map((img) => ({
			url: img.url ?? null,
			alt: img.alt ?? null
		}))
	};
}
function mapEnrollmentPacksMeta(raw) {
	return {
		request_id: raw?.request_id ?? null,
		timestamp: raw?.timestamp ?? "",
		pagination: raw?.pagination ? {
			cursor: raw.pagination.cursor ?? null,
			limit: raw.pagination.limit,
			next_cursor: raw.pagination.next_cursor ?? null,
			prev_cursor: raw.pagination.prev_cursor ?? null
		} : void 0
	};
}
function createRawEnrollmentPacksAdapter(client) {
	return {
		listEnrollmentPacks: async (params) => {
			const response = await enrollment_packs_list(client, {
				"page[cursor]": params?.cursor,
				"page[limit]": params?.limit
			});
			return {
				enrollment_packs: (response.enrollment_packs ?? []).filter((p) => typeof p.id === "number").map(mapEnrollmentPack),
				meta: mapEnrollmentPacksMeta(response.meta)
			};
		},
		getEnrollmentPack: async (id) => {
			const response = await enrollment_packs_show(client, id);
			if (!response.enrollment_pack) throw new Error(`EnrollmentPack ${id} not found`);
			return {
				enrollment_pack: mapEnrollmentPack(response.enrollment_pack),
				meta: mapEnrollmentPacksMeta(response.meta)
			};
		}
	};
}
function mapDamAsset(raw) {
	return {
		id: raw.id ?? 0,
		code: raw.code ?? "",
		name: raw.name ?? "",
		description: raw.description ?? null,
		category: raw.category ?? null,
		company: raw.company ?? null,
		default_variant_id: raw.default_variant_id ?? null,
		default_variant_url: raw.default_variant_url ?? null,
		canonical_path: raw.canonical_path ?? null,
		created_at: raw.created_at ?? "",
		updated_at: raw.updated_at ?? ""
	};
}
function mapDamAssetPath(raw) {
	return {
		id: raw.id ?? 0,
		asset_code: raw.asset_code ?? "",
		path: raw.path ?? "",
		created_at: raw.created_at ?? ""
	};
}
function mapDamAssetsMeta(raw) {
	return {
		request_id: raw?.request_id ?? null,
		timestamp: raw?.timestamp ?? "",
		pagination: raw?.pagination ? {
			cursor: raw.pagination.cursor ?? null,
			limit: raw.pagination.limit,
			next_cursor: raw.pagination.next_cursor ?? null,
			prev_cursor: raw.pagination.prev_cursor ?? null
		} : void 0
	};
}
function createRawDamAssetsAdapter(client) {
	return {
		listAssets: async (params) => {
			const response = await dam_assets_list(client, {
				"page[cursor]": params?.cursor,
				"page[limit]": params?.limit
			});
			return {
				assets: (response.assets ?? []).map(mapDamAsset),
				meta: mapDamAssetsMeta(response.meta)
			};
		},
		createAsset: async (body) => {
			const response = await dam_assets_create(client, { asset: body });
			return {
				asset: mapDamAsset(response.asset ?? {}),
				meta: mapDamAssetsMeta(response.meta)
			};
		},
		listAssetPaths: async (assetCode, params) => {
			const response = await dam_asset_paths_list(client, assetCode, {
				"page[cursor]": params?.cursor,
				"page[limit]": params?.limit
			});
			return {
				asset_paths: (response.asset_paths ?? []).map(mapDamAssetPath),
				meta: mapDamAssetsMeta(response.meta)
			};
		},
		createAssetPath: async (assetCode, body) => {
			const response = await dam_asset_paths_create(client, assetCode, { asset_path: body });
			return {
				asset_path: mapDamAssetPath(response.asset_path ?? {}),
				meta: mapDamAssetsMeta(response.meta)
			};
		}
	};
}
function createFileResourcesAdapter(client) {
	const portAdapter = createRawDamAssetsAdapter(client);
	const cursorByPage = /* @__PURE__ */ new Map();
	return { getFileResources: async (params) => {
		const pageNumber = params?.pageParam ? Number(params.pageParam) : 1;
		const pageSize = params?.pageSize ? Number(params.pageSize) : 25;
		const cursor = pageNumber > 1 ? cursorByPage.get(pageNumber) : void 0;
		const response = await portAdapter.listAssets({
			cursor,
			limit: pageSize
		});
		const nextCursor = response.meta.pagination?.next_cursor;
		if (nextCursor) cursorByPage.set(pageNumber + 1, nextCursor);
		const fileResources = response.assets.map((asset) => ({
			id: asset.id,
			alt_text: asset.name,
			url: asset.default_variant_url ?? "",
			filename: asset.name,
			content_type: "application/octet-stream",
			content_size: 0,
			handle: asset.code,
			dam_asset_code: asset.code,
			preview_image_url: asset.default_variant_url ?? "",
			created_at: asset.created_at,
			updated_at: asset.updated_at ?? "",
			relateable_type: null,
			relateable_id: null,
			content: null
		}));
		const hasNextPage = !!nextCursor;
		return {
			file_resources: fileResources,
			meta: {
				total_count: fileResources.length,
				per_page: pageSize,
				current_page: pageNumber,
				total_pages: hasNextPage ? pageNumber + 1 : pageNumber
			}
		};
	} };
}
function mapMetricsMeta(raw) {
	if (!raw) return void 0;
	return {
		request_id: raw.request_id ?? null,
		timestamp: raw.timestamp ?? "",
		pagination: raw.pagination ? {
			cursor: raw.pagination.cursor ?? null,
			limit: raw.pagination.limit,
			next_cursor: raw.pagination.next_cursor ?? null,
			prev_cursor: raw.pagination.prev_cursor ?? null
		} : void 0
	};
}
function createMetricsAdapter(client) {
	return {
		listMediaVisited: async (params) => {
			const response = await content_media_by_visits(client, {
				period: params?.period,
				limit: params?.limit,
				language_iso: params?.language_iso
			});
			return {
				resources: response.resources ?? [],
				meta: mapMetricsMeta(response.meta)
			};
		},
		listMediaShareVisited: async (params) => {
			const response = await content_media_by_shares(client, {
				period: params?.period,
				limit: params?.limit,
				language_iso: params?.language_iso
			});
			return {
				resources: response.resources ?? [],
				meta: mapMetricsMeta(response.meta)
			};
		},
		listPlaylistsVisited: async (params) => {
			const response = await content_playlists_by_visits(client, {
				period: params?.period,
				limit: params?.limit
			});
			return {
				resources: response.resources ?? [],
				meta: mapMetricsMeta(response.meta)
			};
		},
		listPlaylistsShareVisited: async (params) => {
			const response = await content_playlists_by_shares(client, {
				period: params?.period,
				limit: params?.limit
			});
			return {
				resources: response.resources ?? [],
				meta: mapMetricsMeta(response.meta)
			};
		},
		listPagesVisited: async (params) => {
			const response = await content_pages_by_visits(client, {
				period: params?.period,
				limit: params?.limit,
				language_iso: params?.language_iso
			});
			return {
				resources: response.resources ?? [],
				meta: mapMetricsMeta(response.meta)
			};
		},
		listPagesShareVisited: async (params) => {
			const response = await content_pages_by_shares(client, {
				period: params?.period,
				limit: params?.limit,
				language_iso: params?.language_iso
			});
			return {
				resources: response.resources ?? [],
				meta: mapMetricsMeta(response.meta)
			};
		}
	};
}
function mapProductMedia(raw) {
	const isVideo = raw.media_type === "video";
	const isPdf = raw.media_type === "pdf" || raw.media_type === "document";
	return {
		id: raw.id ?? 0,
		slug: null,
		title: raw.title ?? "",
		kind: isVideo ? "video" : isPdf ? "pdf" : "image",
		media_type: raw.media_type ?? "image",
		media_format: raw.media_type ?? "image",
		image_url: !isVideo && !isPdf ? raw.url ?? null : null,
		video_url: isVideo ? raw.url ?? null : null,
		pdf_url: isPdf ? raw.url ?? null : null,
		powerpoint_url: null,
		duration: 0,
		description: null,
		subtitles: {},
		comments_count: 0
	};
}
function createProductMediaAdapter(source) {
	return { getProductMedia: async (productId) => {
		return { media: ((await source.getProductMedia(productId)).media ?? []).map(mapProductMedia) };
	} };
}
/**
* Creates a composite ContentDomainApi backed by the portal-tenant Content
* BFF endpoints. Follows the same pattern as
* `createPortalContactsDomainApiAdapter`.
*/
function createPortalContentDomainApiAdapter(client, productsApi) {
	return {
		media: createMediaAdapter(client),
		playlists: createPlaylistsAdapter(client),
		fileResources: createFileResourcesAdapter(client),
		share: createShareAdapter(client),
		productMedia: createProductMediaAdapter(productsApi),
		metrics: createMetricsAdapter(client),
		pages: createRawPagesAdapter(client)
	};
}
/**
* Creates a ContentPlaylistsApi (the port-level playlists adapter) for
* operations that aren't part of the shareables PlaylistsApi — e.g.
* `deletePlaylist`. Exposed separately because ContentDomainApi.playlists
* is the higher-level shareables PlaylistsApi.
*/
function createPortalContentPlaylistsAdapter(client) {
	return createRawPlaylistsAdapter(client);
}
/**
* Creates a ContentPagesApi (the port-level pages adapter) for screens that
* need to list/show pages outside of ShareablesApiProvider — e.g. the
* playlist editor's content picker. Mirrors createPortalContentPlaylistsAdapter.
*/
function createPortalContentPagesAdapter(client) {
	return createRawPagesAdapter(client);
}
/**
* Creates a ContentEnrollmentPacksApi adapter for screens that need to
* list/show enrollment packs outside of ShareablesApiProvider — e.g. the
* playlist editor's content picker. Backed by the portal-tenant
* `/api/enrollment_packs` endpoint.
*/
function createPortalContentEnrollmentPacksAdapter(client) {
	return createRawEnrollmentPacksAdapter(client);
}
/**
* Toggles a favorite entry on a given shareable (Medium / Playlist /
* Product / etc.) via the portal-tenant BFF's /favorites/toggle endpoint.
* Returns the new is_favorited state reported by the backend.
*/
async function toggleFavorite(client, favoriteableId, favoriteableType) {
	return { is_favorited: (await client.post("/api/content/favorites/toggle", {
		favoriteable_id: favoriteableId,
		favoriteable_type: favoriteableType
	})).favorite?.is_favorited ?? false };
}
//#endregion
//#region src/content/PortalContentApiProvider.tsx
const ContentContext = createContext(null);
function usePortalContentContext() {
	const ctx = use(ContentContext);
	if (!ctx) throw new Error("usePortalContentContext must be used within a <PortalContentApiProvider>");
	return ctx;
}
/**
* Provides all content-domain adapters (media, playlists, shares,
* fileResources, productMedia) via ShareablesApiProvider, plus extra
* context values available through usePortalContentContext().
*
* **Required ancestor:** `<PortalProductsApiProvider>` must appear above
* this in the tree — it supplies the `PortalProductsApi` consumed via
* `usePortalProductsApi()` for product-media bridging.
*/
function PortalContentApiProvider({ children }) {
	const client = usePortalTenantClient();
	const productsApi = usePortalProductsApi();
	const contentApi = useMemo(() => createPortalContentDomainApiAdapter(client, productsApi), [client, productsApi]);
	const playlistsAdapter = useMemo(() => createPortalContentPlaylistsAdapter(client), [client]);
	const pagesAdapter = useMemo(() => createPortalContentPagesAdapter(client), [client]);
	const enrollmentPacksAdapter = useMemo(() => createPortalContentEnrollmentPacksAdapter(client), [client]);
	const mediaProductsAdapter = useMemo(() => createPortalTenantMediaProductsAdapter(client), [client]);
	const filePickerApi = useMemo(() => createFilePickerApiAdapter(client), [client]);
	const ctx = useMemo(() => ({
		productsApi,
		playlistsAdapter,
		pagesAdapter,
		enrollmentPacksAdapter,
		mediaProductsAdapter
	}), [
		productsApi,
		playlistsAdapter,
		pagesAdapter,
		enrollmentPacksAdapter,
		mediaProductsAdapter
	]);
	return /* @__PURE__ */ jsx(ContentContext.Provider, {
		value: ctx,
		children: /* @__PURE__ */ jsx(ShareablesApiProvider, {
			value: contentApi,
			children: /* @__PURE__ */ jsx(FilePickerApiProvider, {
				value: filePickerApi,
				children
			})
		})
	});
}
//#endregion
//#region ../../shareables/core/src/translation-adapter.ts
const shareablesDomain = createDomainTranslations({
	fallback: {
		common_save: "Save",
		common_cancel: "Cancel",
		common_delete: "Delete",
		common_deleting: "Deleting...",
		common_edit: "Edit",
		common_done: "Done",
		common_on: "On",
		common_off: "Off",
		common_replace: "Replace",
		common_remove: "Remove",
		common_removing: "Removing...",
		common_add: "Add",
		common_adding: "Adding...",
		common_added: "Added",
		common_untitled: "Untitled",
		common_loading: "Loading...",
		common_na: "N/A",
		common_all: "All",
		common_mine: "Mine",
		common_company: "Company",
		common_product: "Product",
		common_enrollment: "Enrollment",
		common_enrollment_pack: "Enrollment Pack",
		enrollment_pack_fallback_name: "Enrollment Pack #{{id}}",
		common_page: "Page",
		common_unknown: "Unknown",
		common_title_label: "Title",
		common_description_label: "Description",
		common_start_writing_placeholder: "Start writing...",
		common_read_more: "Read more",
		common_read_less: "Read less",
		common_not_found_default: "Not found or failed to load.",
		common_load_error_default: "Failed to load. Please try again.",
		common_error_prefix: "Error: ",
		common_fill_required_fields: "Please fill out all required fields",
		common_select_all: "Select All",
		common_deselect_all: "Deselect All",
		common_selected_count: "{{count}} selected",
		common_favorite: "Favorite",
		common_unfavorite: "Unfavorite",
		common_cancel_selection_aria: "Cancel selection",
		common_more_options_aria: "More options",
		common_list_view: "List view",
		common_grid_view: "Grid view",
		common_site_hostname_fallback: "your-site.com",
		sort_newest: "Newest",
		sort_oldest: "Oldest",
		sort_newest_first: "Newest first",
		sort_name_asc: "Name (A-Z)",
		sort_name_desc: "Name (Z-A)",
		sort_title_asc: "Title (A-Z)",
		sort_title_desc: "Title (Z-A)",
		sort_date_newest: "Date Created (Newest)",
		sort_date_oldest: "Date Created (Oldest)",
		sort_price_asc: "Price: Low to High",
		sort_price_desc: "Price: High to Low",
		media_breadcrumb: "Media",
		media_heading: "Media",
		media_new_title: "New Media",
		media_create_breadcrumb: "New Media",
		media_type_image: "Image",
		media_type_video: "Video",
		media_type_pdf: "PDF",
		media_type_default: "Media",
		media_create_success: "Media created successfully",
		media_create_error: "Failed to create media: {{message}}",
		media_save_success: "Media saved successfully",
		media_save_error: "Failed to save: {{message}}",
		media_delete_success: "Media deleted",
		media_delete_error: "Failed to delete: {{message}}",
		media_title_required: "Title is required",
		media_file_required: "Please select a file",
		media_not_found: "Media not found or failed to load.",
		media_select_button: "Select Media",
		media_replace_button: "Replace Media",
		media_add_button: "Add Media",
		media_upload_placeholder: "No media uploaded. Click to upload an image, video, or PDF.",
		media_details_heading: "Media Details",
		media_title_placeholder: "Enter media title",
		media_cta_button_label: "CTA Button: ",
		media_thumbnail_label: "Thumbnail",
		media_thumbnail_alt: "Thumbnail",
		media_video_thumbnail_alt: "Video thumbnail",
		media_no_thumbnail: "No thumbnail set",
		media_pending_save: "Pending — save to apply",
		media_select_new_image: "Select New Image",
		media_thumbnail_capture_unavailable: "Thumbnail capture is not available in this context",
		media_thumbnail_upload_error: "Failed to upload thumbnail",
		media_no_media_available: "No media available",
		media_actions_aria: "Media actions",
		media_my_media_tab: "My Media",
		media_my_media_badge: "My Media",
		media_search_placeholder: "Search media...",
		media_filter_all_types: "All types",
		media_filter_images: "Images",
		media_filter_videos: "Videos",
		media_filter_pdfs: "PDFs",
		media_empty_default: "No media available.",
		media_delete_dialog_title: "Delete Media",
		media_delete_dialog_description: "Are you sure you want to delete {{title}}? This action cannot be undone.",
		media_delete_confirm_title: "Delete this media?",
		media_delete_confirm_description: "This removes the item from your media library. Shared links that point to it will stop working.",
		media_frame_capture_error: "Couldn't capture the video frame. Please try again.",
		media_select_from_video_frame: "Select from video frame",
		media_select_video_frame: "Select Video Frame",
		media_select_video_frame_title: "Select Video Frame",
		media_capture_frame: "Capture Frame",
		media_tagged_products_heading: "Tagged Products",
		media_no_products_tagged: "No products tagged yet.",
		media_add_product_button: "Add Product",
		media_add_products_button: "Add Products",
		media_products_selected_count: "{{current}} of {{max}} products selected",
		media_products_country_note: "Products will only display in available countries.",
		media_product_fallback_name: "Product #{{id}}",
		media_max_products_reached: "Maximum {{max}} products reached",
		media_select_products_title: "Select Products to Tag",
		media_products_selected_ratio: "({{current}}/{{max}} selected)",
		media_max_products_warning: "You have reached the maximum limit of {{max}} products.",
		media_limit_reached: "Limit reached",
		cta_dialog_title: "CTA Button",
		cta_dialog_description: "Configure the call-to-action button that appears with your media.",
		cta_enable_toggle_label: "Enable call-to-action button",
		cta_action_type_label: "Action Type",
		cta_type_placeholder: "Select type",
		cta_type_page: "Page",
		cta_type_cart: "Cart",
		cta_type_email: "Email",
		cta_type_phone: "Phone",
		cta_button_label: "Button Label",
		cta_default_button_text: "Learn More",
		cta_url_label: "URL",
		cta_url_placeholder: "https://example.com",
		seo_heading: "SEO And Link Sharing",
		seo_title_label: "SEO Title",
		seo_title_placeholder: "Page title for search engines",
		seo_description_label: "SEO Description",
		seo_description_placeholder: "Description for search engines",
		seo_block_crawlers_label: "Block Crawlers",
		seo_block_crawlers_description: "Prevent search engines from indexing",
		seo_block_crawlers_aria: "Block search engine crawlers",
		seo_preview_title_fallback: "Your page title",
		seo_preview_url_fallback: "yoursite.com/media/...",
		playlist_breadcrumb: "Playlists",
		playlist_breadcrumb_fallback: "Playlist",
		playlist_create_breadcrumb: "New Playlist",
		playlist_edit_breadcrumb: "Edit Playlist",
		playlist_badge_label: "Playlist",
		playlist_create_success: "Playlist created successfully",
		playlist_create_error: "Failed to create playlist",
		playlist_update_success: "Playlist updated successfully",
		playlist_update_error: "Failed to update playlist",
		playlist_delete_success: "Playlist deleted",
		playlist_delete_success_full: "Playlist deleted successfully",
		playlist_delete_error: "Failed to delete playlist",
		playlist_not_found: "Playlist not found or failed to load.",
		playlist_create_items_partial_error: "Playlist created but some items failed to add",
		playlist_favorite_error: "Failed to update favorite",
		playlist_favorite_added: "Added to favorites",
		playlist_favorite_removed: "Removed from favorites",
		playlist_my_playlists_tab: "My Playlists",
		playlist_search_placeholder: "Search playlists...",
		playlist_create_button: "Create Playlist",
		playlist_empty_default: "There are no playlists available at the moment.",
		playlist_untitled: "Untitled Playlist",
		playlist_item_count_one: "{{count}} item",
		playlist_item_count_other: "{{count}} items",
		playlist_select_aria: "Select {{title}}",
		playlist_actions_aria: "Playlist actions",
		playlist_delete_confirm_title: "Delete this playlist?",
		playlist_delete_confirm_description: "This removes the playlist from your library. Shared links that point to it will stop working.",
		playlist_form_heading: "Playlist",
		playlist_form_description: "Name your playlist and add a short description.",
		playlist_name_label: "Name *",
		playlist_name_placeholder: "Playlist name",
		playlist_description_placeholder: "Describe this playlist...",
		playlist_items_heading: "Playlist Items",
		playlist_items_description: "Manage the media and pages in your playlist. At least one is required.",
		playlist_tagged_products_heading: "Tagged Products",
		playlist_tagged_products_description: "Manage the products and enrollments in your playlist. These items will show as recommended items in the cart.",
		playlist_add_item_button: "Add Item",
		playlist_add_item_success: "Item added to playlist successfully",
		playlist_add_item_error: "Failed to add item to playlist",
		playlist_remove_item_success: "Item removed from playlist successfully",
		playlist_remove_item_error: "Failed to remove item from playlist",
		playlist_reorder_error: "Failed to save new item order",
		playlist_no_items_selected: "No items selected",
		playlist_item_already_exists: "This item is already in the playlist",
		playlist_delete_item: "Delete Item",
		playlist_table_order: "Order",
		playlist_table_item: "Item",
		playlist_table_type: "Type",
		playlist_table_actions: "Actions",
		playlist_preview_heading: "Preview",
		playlist_og_title_fallback: "Playlist title",
		playlist_og_description_fallback: "Description shown when this playlist is shared on social platforms.",
		playlist_no_other_playlists: "No Other Playlists",
		playlist_no_other_playlists_description: "There are no other playlists available",
		playlist_view_link: "View playlist ->",
		playlist_other_playlists_tab: "Other Playlists",
		playlist_no_items: "No Items",
		playlist_no_items_description: "This playlist doesn't have any items yet",
		playlist_items_in_playlist_count: "Items in playlist ({{count}})",
		pages_breadcrumb: "Pages",
		pages_breadcrumb_fallback: "Page",
		pages_badge_label: "Page",
		pages_load_error: "Failed to load pages. Please try again.",
		pages_search_no_results: "No pages match \"{{search}}\". Try a different search term.",
		pages_empty_default: "No pages available.",
		pages_search_placeholder: "Search pages...",
		pages_fallback_name: "Page #{{id}}",
		pages_untitled: "Untitled Page",
		pdf_previous_page_aria: "Previous page",
		pdf_next_page_aria: "Next page",
		pages_status_published: "Published",
		pages_status_unpublished: "Unpublished",
		pages_not_found: "Page not found or failed to load.",
		products_breadcrumb: "Products",
		products_breadcrumb_fallback: "Product",
		products_load_error: "Failed to load products. Please try again.",
		products_load_more_error: "Failed to load more products.",
		products_add_error: "Failed to add product. Please try again.",
		products_remove_error: "Failed to remove product. Please try again.",
		products_search_placeholder: "Search products...",
		products_search_no_results: "No products found matching your search.",
		products_search_start_typing: "Start typing to search for products.",
		products_empty_default: "No products available.",
		products_not_found: "Product not found or failed to load.",
		products_no_image: "No Product Image",
		products_no_media: "This product does not have any associated media",
		products_price_label: "Price",
		products_related_sharables: "Related Sharables",
		products_asset_count: "{{count}} assets",
		files_breadcrumb: "Files",
		files_load_error: "Failed to load files. Please try again.",
		files_search_no_results: "No files match \"{{search}}\". Try a different search term.",
		files_empty_default: "No files available.",
		files_search_placeholder: "Search files...",
		files_untitled: "Untitled File",
		files_type_default: "File",
		files_size_b: "B",
		files_size_kb: "KB",
		files_size_mb: "MB",
		files_size_gb: "GB",
		share_download_asset: "Download Asset",
		share_download_no_asset: "No downloadable asset available",
		share_link_copied: "Share link copied to clipboard!",
		share_link_copy_error: "Failed to copy link to clipboard",
		share_link_not_available: "Share link not available yet. Please wait...",
		share_social_description: "Check out this {{type}}: {{title}}",
		share_mysite_success: "Shared to MySite",
		share_mysite_error: "Failed to share to MySite",
		share_unique_link_heading: "Share Your Unique Link",
		open_image_viewer: "Open image viewer",
		open_image_viewer_for: "Open image viewer: {{title}}",
		close_image_viewer: "Close image viewer",
		image_viewer_description: "Share image viewer",
		image_unavailable: "Image unavailable",
		open_media_preview: "Open media preview",
		close_media_preview: "Close media preview",
		pdf_page_number_aria: "PDF page number",
		share_qr_code_alt: "QR Code for share link",
		share_qr_code_default_alt: "QR Code",
		share_qr_code_load_error: "QR code failed to load",
		share_mysite_button: "MySite",
		share_mysite_preview_title: "MySite Preview",
		share_button: "Share",
		share_generating_link: "Generating link...",
		share_loading_media: "Loading media...",
		share_media_load_error: "Failed to load media",
		share_analytics_coming_soon: "Analytics Coming Soon",
		share_analytics_description: "View engagement metrics and performance data",
		share_type_product: "product",
		share_type_media: "media",
		share_type_enrollment_pack: "enrollment pack",
		share_type_site: "site",
		share_type_library: "library",
		share_no_marketing_assets: "No Marketing Assets",
		share_no_associated_media: "This {{label}} does not have any associated media",
		share_related_sharables_count: "Related Sharables ({{count}})",
		share_no_tab_items_found: "No {{tab}} found",
		share_no_items_to_display: "No items to display",
		share_click_to_find_assets: "Click to find shareable assets",
		share_click_to_share_video: "Click to share this video",
		share_click_to_share_asset: "Click to share this asset",
		share_no_tagged_products: "No Tagged Products",
		share_no_tagged_products_description: "No products are tagged in this playlist",
		share_tagged_products_count: "Tagged Products ({{count}})",
		common_filter_search_no_results: "No {{entityName}} match \"{{searchTerm}}\" with the current filters. Try a different search term or switch to \"All\".",
		common_search_no_results: "No {{entityName}} match \"{{searchTerm}}\". Try a different search term.",
		common_filter_no_results: "No matching {{entityName}} for the current filters.",
		common_empty_default: "Nothing available at the moment.",
		playlist_title_required: "Title is required",
		media_alt_fallback: "Media",
		share_opening_facebook: "Opening Facebook share dialog...",
		share_opening_x: "Opening X share dialog...",
		share_opening_linkedin: "Opening LinkedIn share dialog...",
		share_copied_instagram: "Link copied! Opening Instagram and paste link in bio or post!.",
		share_copied_tiktok: "Link copied! Opening TikTok and paste in your link!",
		share_failed: "Failed to share on {{platform}}. Please try again.",
		pdf_document_title: "PDF document",
		media_edit_add_product_failed: "Failed to add product: {{message}}",
		media_edit_remove_product_failed: "Failed to remove product: {{message}}",
		error_unknown: "Unknown error",
		media_edit_seo_preview_alt: "SEO preview",
		file_type_image_fallback: "image",
		modal_asset_details: "Asset details",
		filter_empty_search_filtered: "No {{entityName}} match \"{{searchTerm}}\" with the current filters. Try a different search term or switch to \"All\".",
		filter_empty_search: "No {{entityName}} match \"{{searchTerm}}\". Try a different search term.",
		filter_empty_filtered: "No matching {{entityName}} for the current filters.",
		filter_empty_default: "Nothing available at the moment.",
		editor_bold: "Bold",
		editor_italic: "Italic",
		editor_underline: "Underline",
		editor_align_left: "Align left",
		editor_align_center: "Align center",
		editor_align_right: "Align right",
		editor_justify: "Justify",
		editor_bullet_list: "Bullet list",
		editor_ordered_list: "Ordered list"
	},
	loaders: {
		de: () => import("./de-DSQosa2J.mjs").then((m) => m.default),
		el: () => import("./el-DP2-BvTi.mjs").then((m) => m.default),
		es: () => import("./es-f3koGNFW.mjs").then((m) => m.default),
		fr: () => import("./fr-C8Yvl5U2.mjs").then((m) => m.default),
		he: () => import("./he-D2g9QwSk.mjs").then((m) => m.default),
		hu: () => import("./hu-CBihtDCE.mjs").then((m) => m.default),
		id: () => import("./id-C_IE7FZA.mjs").then((m) => m.default),
		it: () => import("./it-DUhb3CLe.mjs").then((m) => m.default),
		ja: () => import("./ja-umX_08EW.mjs").then((m) => m.default),
		ko: () => import("./ko-BMWFj2O7.mjs").then((m) => m.default),
		nl: () => import("./nl-Ctqrh1vF.mjs").then((m) => m.default),
		pl: () => import("./pl-CokyX8Mo.mjs").then((m) => m.default),
		pt: () => import("./pt-Bt5NXIVW.mjs").then((m) => m.default),
		ro: () => import("./ro-CYGQD0o2.mjs").then((m) => m.default),
		ru: () => import("./ru-BVE1hWep.mjs").then((m) => m.default),
		th: () => import("./th-B834HIs5.mjs").then((m) => m.default),
		tl: () => import("./tl-Ct6goGvc.mjs").then((m) => m.default),
		tr: () => import("./tr-Un2esIQl.mjs").then((m) => m.default),
		zh_CN: () => import("./zh_CN-CUeN37jF.mjs").then((m) => m.default),
		zh_TW: () => import("./zh_TW-D-hmfWQl.mjs").then((m) => m.default)
	}
});
function createShareablesTranslationAdapter(locale, dict) {
	return createStaticDictAdapter(locale, dict);
}
//#endregion
//#region src/hooks/use-account.ts
/**
* Fetches the current user's account from GET /api/account.
* Replaces the old useCurrentUser (which called non-existent /api/me).
*/
function useAccount() {
	const api = useAccountApi();
	return useQuery({
		queryKey: accountKeys.detail(),
		queryFn: async () => {
			return (await api.fetchAccount()).account;
		},
		staleTime: 300 * 1e3
	});
}
//#endregion
export { subscriptions_retry as $, activities_list as A, product_by_visits as B, content_playlists_by_shares as C, playlists_show as D, pages_show as E, enrollment_pack_by_visits as F, store_show as G, products_media_list as H, enrollment_packs_show as I, subscriptions_cancel as J, subscription_bundles_create as K, orders_list as L, calendar_events_list as M, catch_ups_list as N, account_show as O, enrollment_pack_by_shares as P, subscriptions_resume as Q, orders_show as R, content_pages_by_visits as S, media_show as T, products_search as U, products_list as V, products_show as W, subscriptions_pause as X, subscriptions_list as Y, subscriptions_reactivate as Z, useShareablesClient as _, usePortalContentContext as a, todos_list as at, content_media_by_visits as b, useFilePickerApi as c, useAccountApi as ct, useRemoveItemsFromPlaylistMutation as d, __require as dt, subscriptions_show as et, useReorderPlaylistItemsMutation as f, __toESM as ft, useRepContext as g, ShareablesCoreProvider as h, PortalContentApiProvider as i, todos_destroy as it, app_manifest_show as j, account_update as k, useAddItemToPlaylistMutation as l, __commonJSMin as lt, useCreateMediaMutation as m, createShareablesTranslationAdapter as n, subscriptions_update as nt, toggleFavorite as o, todos_update as ot, useUpdatePlaylistMutation as p, subscription_bundles_list as q, shareablesDomain as r, todos_create as rt, FilePickerApiProvider as s, AccountApiProvider as st, useAccount as t, subscriptions_skip as tt, useCreatePlaylistMutation as u, __exportAll as ut, useShareablesUser as v, content_playlists_by_visits as w, content_pages_by_shares as x, content_media_by_shares as y, product_by_shares as z };

//# sourceMappingURL=use-account-D70N5avv.mjs.map