import { o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CIXf7egm.js";
import { c as isRecord } from "./record-coerce-DItp3I4t.js";
import { u as normalizeStringEntries } from "./string-normalization-e_fvmxMf.js";
import { n as normalizeAccountId } from "./account-id-BH0zJUew.js";
import { C as resolveMessagePresentationButtonAction, T as resolveMessagePresentationOptionAction, f as normalizeMessagePresentation, v as renderMessagePresentationFallbackText } from "./payload-C7E4iMOo.js";
import { t as adaptMessagePresentationForChannel } from "./presentation-limits-WuXKq1ZQ.js";
import { t as resolveAccountEntry } from "./account-lookup-CaTe6-6f.js";
import "./string-coerce-runtime-C8jKEm3h.js";
import "./account-resolution-CVTi8Q7c.js";
import { t as createPluginRuntimeStore } from "./runtime-store-CjjjpvHZ.js";
import { i as resolveLineAccount } from "./accounts-D_yUAsP7.js";
import { t as hasLineCredentials } from "./account-helpers-BSUyZwLm.js";
import { a as createAgendaCard, m as truncateLineActionLabel, o as createEventCard, p as postbackAction, u as messageAction } from "./send-retry-C5yY9Hzp.js";
import { t as createActionCard } from "./basic-cards-bNLpKTX0.js";
import { Type } from "typebox";
//#region extensions/line/src/runtime.ts
const { setRuntime: setLineRuntime, getRuntime: getLineRuntime } = createPluginRuntimeStore({
	pluginId: "line",
	errorMessage: "LINE runtime not initialized - plugin not registered"
});
//#endregion
//#region extensions/line/src/group-keys.ts
function resolveLineGroupLookupIds(groupId) {
	const normalized = groupId?.trim();
	if (!normalized) return [];
	if (normalized.startsWith("group:") || normalized.startsWith("room:")) {
		const rawId = normalized.split(":").slice(1).join(":");
		return rawId ? [rawId, normalized] : [normalized];
	}
	return [
		normalized,
		`group:${normalized}`,
		`room:${normalized}`
	];
}
function resolveLineGroupConfigEntry(groups, params) {
	if (!groups) return;
	for (const candidate of resolveLineGroupLookupIds(params.groupId)) {
		const hit = groups[candidate];
		if (hit) return hit;
	}
	for (const candidate of resolveLineGroupLookupIds(params.roomId)) {
		const hit = groups[candidate];
		if (hit) return hit;
	}
	return groups["*"];
}
function resolveLineGroupsConfig(cfg, accountId) {
	const lineConfig = cfg.channels?.line;
	if (!lineConfig) return;
	const normalizedAccountId = normalizeAccountId(accountId);
	return resolveAccountEntry(lineConfig.accounts, normalizedAccountId)?.groups ?? lineConfig.groups;
}
function resolveExactLineGroupConfigKey(params) {
	const { groups } = params;
	if (!groups) return;
	return resolveLineGroupLookupIds(params.groupId).find((candidate) => Object.hasOwn(groups, candidate));
}
//#endregion
//#region extensions/line/src/quick-reply-fallback.ts
function buildLineQuickReplyFallbackText(labels) {
	const normalized = normalizeStringEntries(labels ?? []).slice(0, 13);
	if (normalized.length === 0) return "Choose an option.";
	return `Options:\n${normalized.map((label) => `- ${label}`).join("\n")}`;
}
//#endregion
//#region extensions/line/src/flex-templates/media-control-cards.ts
/**
* Create a media player card for Sonos, Spotify, Apple Music, etc.
*
* Editorial design: Album art hero with gradient overlay for text,
* prominent now-playing indicator, refined playback controls.
*/
function createMediaPlayerCard(params) {
	const { title, subtitle, source, imageUrl, isPlaying, progress, controls, extraActions } = params;
	const trackInfo = [{
		type: "text",
		text: title,
		weight: "bold",
		size: "xl",
		color: "#111111",
		wrap: true
	}];
	if (subtitle) trackInfo.push({
		type: "text",
		text: subtitle,
		size: "md",
		color: "#666666",
		wrap: true,
		margin: "sm"
	});
	const statusItems = [];
	if (isPlaying !== void 0) statusItems.push({
		type: "box",
		layout: "horizontal",
		contents: [{
			type: "box",
			layout: "vertical",
			contents: [],
			width: "8px",
			height: "8px",
			backgroundColor: isPlaying ? "#06C755" : "#CCCCCC",
			cornerRadius: "4px"
		}, {
			type: "text",
			text: isPlaying ? "Now Playing" : "Paused",
			size: "xs",
			color: isPlaying ? "#06C755" : "#888888",
			weight: "bold",
			margin: "sm"
		}],
		alignItems: "center"
	});
	if (source) statusItems.push({
		type: "text",
		text: source,
		size: "xs",
		color: "#AAAAAA",
		margin: statusItems.length > 0 ? "lg" : void 0
	});
	if (progress) statusItems.push({
		type: "text",
		text: progress,
		size: "xs",
		color: "#888888",
		align: "end",
		flex: 1
	});
	const bodyContents = [{
		type: "box",
		layout: "vertical",
		contents: trackInfo
	}];
	if (statusItems.length > 0) bodyContents.push({
		type: "box",
		layout: "horizontal",
		contents: statusItems,
		margin: "lg",
		alignItems: "center"
	});
	const bubble = {
		type: "bubble",
		size: "mega",
		body: {
			type: "box",
			layout: "vertical",
			contents: bodyContents,
			paddingAll: "xl",
			backgroundColor: "#FFFFFF"
		}
	};
	if (imageUrl) bubble.hero = {
		type: "image",
		url: imageUrl,
		size: "full",
		aspectRatio: "1:1",
		aspectMode: "cover"
	};
	if (controls || extraActions?.length) {
		const footerContents = [];
		if (controls) {
			const controlButtons = [];
			if (controls.previous) controlButtons.push({
				type: "button",
				action: postbackAction("⏮", controls.previous.data),
				style: "secondary",
				flex: 1,
				height: "sm"
			});
			if (controls.play) controlButtons.push({
				type: "button",
				action: postbackAction("▶", controls.play.data),
				style: isPlaying ? "secondary" : "primary",
				flex: 1,
				height: "sm",
				margin: controls.previous ? "md" : void 0
			});
			if (controls.pause) controlButtons.push({
				type: "button",
				action: postbackAction("⏸", controls.pause.data),
				style: isPlaying ? "primary" : "secondary",
				flex: 1,
				height: "sm",
				margin: controlButtons.length > 0 ? "md" : void 0
			});
			if (controls.next) controlButtons.push({
				type: "button",
				action: postbackAction("⏭", controls.next.data),
				style: "secondary",
				flex: 1,
				height: "sm",
				margin: controlButtons.length > 0 ? "md" : void 0
			});
			if (controlButtons.length > 0) footerContents.push({
				type: "box",
				layout: "horizontal",
				contents: controlButtons
			});
		}
		if (extraActions?.length) footerContents.push({
			type: "box",
			layout: "horizontal",
			contents: extraActions.slice(0, 2).map((action, index) => ({
				type: "button",
				action: postbackAction(truncateLineActionLabel(action.label, 15), action.data),
				style: "secondary",
				flex: 1,
				height: "sm",
				margin: index > 0 ? "md" : void 0
			})),
			margin: "md"
		});
		if (footerContents.length > 0) bubble.footer = {
			type: "box",
			layout: "vertical",
			contents: footerContents,
			paddingAll: "lg",
			backgroundColor: "#FAFAFA"
		};
	}
	return bubble;
}
/**
* Create an Apple TV remote card with a D-pad and control rows.
*/
function createAppleTvRemoteCard(params) {
	const { deviceName, status, actionData } = params;
	const headerContents = [{
		type: "text",
		text: deviceName,
		weight: "bold",
		size: "xl",
		color: "#111111",
		wrap: true
	}];
	if (status) headerContents.push({
		type: "text",
		text: status,
		size: "sm",
		color: "#666666",
		wrap: true,
		margin: "sm"
	});
	const makeButton = (label, data, style = "secondary") => ({
		type: "button",
		action: postbackAction(label, data),
		style,
		height: "sm",
		flex: 1
	});
	const dpadRows = [
		{
			type: "box",
			layout: "horizontal",
			contents: [
				{ type: "filler" },
				makeButton("↑", actionData.up),
				{ type: "filler" }
			]
		},
		{
			type: "box",
			layout: "horizontal",
			contents: [
				makeButton("←", actionData.left),
				makeButton("OK", actionData.select, "primary"),
				makeButton("→", actionData.right)
			],
			margin: "md"
		},
		{
			type: "box",
			layout: "horizontal",
			contents: [
				{ type: "filler" },
				makeButton("↓", actionData.down),
				{ type: "filler" }
			],
			margin: "md"
		}
	];
	const menuRow = {
		type: "box",
		layout: "horizontal",
		contents: [makeButton("Menu", actionData.menu), makeButton("Home", actionData.home)],
		margin: "lg"
	};
	const playbackRow = {
		type: "box",
		layout: "horizontal",
		contents: [makeButton("Play", actionData.play), makeButton("Pause", actionData.pause)],
		margin: "md"
	};
	const volumeRow = {
		type: "box",
		layout: "horizontal",
		contents: [
			makeButton("Vol +", actionData.volumeUp),
			makeButton("Mute", actionData.mute),
			makeButton("Vol -", actionData.volumeDown)
		],
		margin: "md"
	};
	return {
		type: "bubble",
		size: "mega",
		body: {
			type: "box",
			layout: "vertical",
			contents: [
				{
					type: "box",
					layout: "vertical",
					contents: headerContents
				},
				{
					type: "separator",
					margin: "lg",
					color: "#EEEEEE"
				},
				...dpadRows,
				menuRow,
				playbackRow,
				volumeRow
			],
			paddingAll: "xl",
			backgroundColor: "#FFFFFF"
		}
	};
}
/**
* Create a device control card for Apple TV, smart home devices, etc.
*
* Editorial design: Device-focused header with status indicator,
* clean control grid with clear visual hierarchy.
*/
function createDeviceControlCard(params) {
	const { deviceName, deviceType, status, isOnline, imageUrl, controls } = params;
	const headerContents = [{
		type: "box",
		layout: "horizontal",
		contents: [{
			type: "box",
			layout: "vertical",
			contents: [],
			width: "10px",
			height: "10px",
			backgroundColor: isOnline !== false ? "#06C755" : "#FF5555",
			cornerRadius: "5px"
		}, {
			type: "text",
			text: deviceName,
			weight: "bold",
			size: "xl",
			color: "#111111",
			wrap: true,
			flex: 1,
			margin: "md"
		}],
		alignItems: "center"
	}];
	if (deviceType) headerContents.push({
		type: "text",
		text: deviceType,
		size: "sm",
		color: "#888888",
		margin: "sm"
	});
	if (status) headerContents.push({
		type: "box",
		layout: "vertical",
		contents: [{
			type: "text",
			text: status,
			size: "sm",
			color: "#444444",
			wrap: true
		}],
		margin: "lg",
		paddingAll: "md",
		backgroundColor: "#F8F9FA",
		cornerRadius: "md"
	});
	const bubble = {
		type: "bubble",
		size: "mega",
		body: {
			type: "box",
			layout: "vertical",
			contents: headerContents,
			paddingAll: "xl",
			backgroundColor: "#FFFFFF"
		}
	};
	if (imageUrl) bubble.hero = {
		type: "image",
		url: imageUrl,
		size: "full",
		aspectRatio: "16:9",
		aspectMode: "cover"
	};
	if (controls.length > 0) {
		const rows = [];
		const limitedControls = controls.slice(0, 6);
		for (let i = 0; i < limitedControls.length; i += 2) {
			const rowButtons = [];
			for (const [offset, ctrl] of limitedControls.slice(i, i + 2).entries()) {
				const buttonLabel = ctrl.icon ? `${ctrl.icon} ${ctrl.label}` : ctrl.label;
				rowButtons.push({
					type: "button",
					action: postbackAction(truncateLineActionLabel(buttonLabel, 18), ctrl.data),
					style: ctrl.style ?? "secondary",
					flex: 1,
					height: "sm",
					margin: offset > 0 ? "md" : void 0
				});
			}
			if (rowButtons.length === 1) rowButtons.push({ type: "filler" });
			rows.push({
				type: "box",
				layout: "horizontal",
				contents: rowButtons,
				margin: i > 0 ? "md" : void 0
			});
		}
		bubble.footer = {
			type: "box",
			layout: "vertical",
			contents: rows,
			paddingAll: "lg",
			backgroundColor: "#FAFAFA"
		};
	}
	return bubble;
}
//#endregion
//#region extensions/line/src/rich-messages.ts
const nonempty = () => Type.String({ minLength: 1 });
const closed = (properties) => Type.Object(properties, { additionalProperties: false });
const lineCardSchema = Type.Union([
	closed({
		type: Type.Literal("media_player"),
		title: nonempty(),
		artist: Type.Optional(nonempty()),
		source: Type.Optional(nonempty()),
		imageUrl: Type.Optional(Type.String({ pattern: "^https://" })),
		status: Type.Optional(Type.Union([Type.Literal("playing"), Type.Literal("paused")]))
	}),
	closed({
		type: Type.Literal("event"),
		title: nonempty(),
		date: nonempty(),
		time: Type.Optional(nonempty()),
		location: Type.Optional(nonempty()),
		description: Type.Optional(nonempty())
	}),
	closed({
		type: Type.Literal("agenda"),
		title: nonempty(),
		events: Type.Array(closed({
			title: nonempty(),
			time: Type.Optional(nonempty()),
			location: Type.Optional(nonempty())
		}), {
			minItems: 1,
			maxItems: 6
		})
	}),
	closed({
		type: Type.Literal("device"),
		name: nonempty(),
		deviceType: Type.Optional(nonempty()),
		status: Type.Optional(nonempty()),
		controls: Type.Optional(Type.Array(closed({
			label: nonempty(),
			action: nonempty()
		}), { maxItems: 6 }))
	}),
	closed({
		type: Type.Literal("appletv_remote"),
		name: Type.Optional(nonempty()),
		status: Type.Optional(nonempty())
	})
]);
const lineChannelDataSchema = Type.Optional(closed({ line: closed({
	location: Type.Optional(closed({
		title: nonempty(),
		address: nonempty(),
		latitude: Type.Number({
			minimum: -90,
			maximum: 90
		}),
		longitude: Type.Number({
			minimum: -180,
			maximum: 180
		})
	})),
	card: Type.Optional(lineCardSchema),
	mediaKind: Type.Optional(Type.Union([
		Type.Literal("image"),
		Type.Literal("video"),
		Type.Literal("audio")
	])),
	previewImageUrl: Type.Optional(Type.String({ pattern: "^https://" })),
	durationMs: Type.Optional(Type.Integer({ minimum: 1 })),
	trackingId: Type.Optional(nonempty())
}) }));
const lineMessageActions = {
	describeMessageTool: ({ cfg, accountId }) => {
		const account = resolveLineAccount({
			cfg,
			accountId: accountId ?? void 0
		});
		return account.enabled && hasLineCredentials(account) ? {
			actions: ["send"],
			capabilities: ["presentation"],
			schema: {
				actions: ["send"],
				properties: { channelData: lineChannelDataSchema }
			}
		} : {
			actions: [],
			capabilities: [],
			schema: null
		};
	},
	prepareSendPayload: ({ payload }) => payload
};
const LINE_PRESENTATION_CAPABILITIES = {
	supported: true,
	buttons: true,
	selects: true,
	context: true,
	limits: {
		actions: {
			maxActions: 4,
			maxActionsPerRow: 1,
			maxRows: 4,
			maxLabelLength: 40
		},
		selects: {
			maxOptions: 13,
			maxLabelLength: 20,
			maxValueBytes: 300
		},
		text: { markdownDialect: "plain" }
	}
};
function toLineAction(button) {
	const normalized = resolveMessagePresentationButtonAction(button);
	const { label } = button;
	if (normalized?.type === "command") return {
		type: "message",
		label,
		text: normalized.command
	};
	if (normalized?.type === "callback") return {
		type: "postback",
		label,
		data: normalized.value,
		displayText: label
	};
	if (normalized?.type === "url") return {
		type: "uri",
		label,
		uri: normalized.url
	};
	if (normalized?.type === "web-app" && normalized.url) return {
		type: "uri",
		label,
		uri: normalized.url
	};
}
function renderLinePresentation(payload, presentation) {
	const buttons = presentation.blocks.flatMap((block) => block.type === "buttons" ? block.buttons : []);
	const buttonActions = buttons.map(toLineAction);
	const options = presentation.blocks.flatMap((block) => block.type === "select" ? block.options : []);
	const quickReplyItems = options.flatMap((option) => {
		const action = resolveMessagePresentationOptionAction(option);
		return action?.type === "command" || action?.type === "callback" ? [{
			label: option.label,
			action
		}] : [];
	});
	if (buttons.length > 0 && buttonActions.some((action) => !action) || quickReplyItems.length !== options.length || buttons.length === 0 && options.length === 0) return null;
	const lineData = isRecord(payload.channelData?.line) ? payload.channelData.line : {};
	const text = presentation.blocks.flatMap((block) => block.type === "text" || block.type === "context" ? [block.text] : []).join("\n");
	const title = presentation.title || "Choose an option";
	const flexMessage = buttonActions.length > 0 ? {
		altText: title,
		contents: createActionCard(title, text || "Choose an option.", buttons.map((button, index) => ({
			label: button.label,
			action: buttonActions[index]
		})))
	} : void 0;
	return {
		...payload,
		channelData: {
			...payload.channelData,
			line: {
				...lineData,
				...flexMessage ? { flexMessage } : {},
				quickReplyItems
			}
		}
	};
}
/**
* Resolve a reply's portable presentation into LINE-native controls.
*
* Core runs the presentation renderer inside the outbound send pipeline only, so
* replies the plugin delivers itself reach delivery with the controls still
* portable. Preparing them here keeps both LINE delivery paths on one rendering.
*/
function prepareLineReplyPayload(payload) {
	const presentation = normalizeMessagePresentation(payload.presentation);
	if (!presentation) return payload;
	const { presentation: _presentation, presentationTextMode, ...rest } = payload;
	const usesFallbackText = presentationTextMode === "fallback";
	const rendered = renderLinePresentation(usesFallbackText ? {
		...rest,
		text: void 0
	} : rest, adaptMessagePresentationForChannel({
		presentation,
		capabilities: LINE_PRESENTATION_CAPABILITIES
	}));
	if (rendered) {
		const renderedLine = isRecord(rendered.channelData?.line) ? rendered.channelData.line : {};
		return usesFallbackText && renderedLine.flexMessage === void 0 ? {
			...rendered,
			text: rest.text
		} : rendered;
	}
	return {
		...rest,
		text: usesFallbackText ? rest.text ?? renderMessagePresentationFallbackText({ presentation }) : renderMessagePresentationFallbackText({
			text: rest.text,
			presentation
		})
	};
}
const toSlug = (value) => normalizeLowercaseStringOrEmpty(value).replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "") || "device";
const lineActionData = (action, device) => `line.action=${encodeURIComponent(action)}&line.device=${encodeURIComponent(device)}`;
function renderLineCard(card) {
	if (card.type === "media_player") {
		const device = toSlug(card.source || card.title);
		return {
			altText: `🎵 ${card.title}${card.artist ? ` - ${card.artist}` : ""}`,
			contents: createMediaPlayerCard({
				title: card.title,
				subtitle: card.artist,
				source: card.source,
				imageUrl: card.imageUrl,
				isPlaying: card.status ? card.status === "playing" : void 0,
				controls: Object.fromEntries([
					"previous",
					"play",
					"pause",
					"next"
				].map((action) => [action, { data: lineActionData(action, device) }]))
			})
		};
	}
	if (card.type === "event") return {
		altText: `📅 ${card.title} - ${card.date}${card.time ? ` ${card.time}` : ""}`,
		contents: createEventCard(card)
	};
	if (card.type === "agenda") return {
		altText: `📋 ${card.title} (${card.events.length} events)`,
		contents: createAgendaCard(card)
	};
	const device = toSlug(card.type === "device" ? card.name : card.name || "apple_tv");
	if (card.type === "device") return {
		altText: `📱 ${card.name}${card.status ? `: ${card.status}` : ""}`,
		contents: createDeviceControlCard({
			deviceName: card.name,
			deviceType: card.deviceType,
			status: card.status,
			controls: (card.controls ?? []).map((control) => ({
				label: control.label,
				data: lineActionData(control.action, device)
			}))
		})
	};
	const actionData = {
		up: lineActionData("up", device),
		down: lineActionData("down", device),
		left: lineActionData("left", device),
		right: lineActionData("right", device),
		select: lineActionData("select", device),
		menu: lineActionData("menu", device),
		home: lineActionData("home", device),
		play: lineActionData("play", device),
		pause: lineActionData("pause", device),
		volumeUp: lineActionData("volume_up", device),
		volumeDown: lineActionData("volume_down", device),
		mute: lineActionData("mute", device)
	};
	return {
		altText: `📺 ${card.name || "Apple TV"} Remote`,
		contents: createAppleTvRemoteCard({
			deviceName: card.name || "Apple TV",
			status: card.status,
			actionData
		})
	};
}
function createLineQuickReply(items) {
	return { items: items.slice(0, 13).map((item) => ({
		type: "action",
		action: item.action.type === "command" ? messageAction(item.label, item.action.command) : postbackAction(item.label, item.action.value, item.label)
	})) };
}
//#endregion
export { renderLineCard as a, createDeviceControlCard as c, resolveExactLineGroupConfigKey as d, resolveLineGroupConfigEntry as f, setLineRuntime as g, getLineRuntime as h, prepareLineReplyPayload as i, createMediaPlayerCard as l, resolveLineGroupsConfig as m, createLineQuickReply as n, renderLinePresentation as o, resolveLineGroupLookupIds as p, lineMessageActions as r, createAppleTvRemoteCard as s, LINE_PRESENTATION_CAPABILITIES as t, buildLineQuickReplyFallbackText as u };
