import { FluentButton } from "../../UI/inputs/buttons/FluentButton.mjs";
import { SideSheet } from "../../UI/surfaces/SideSheet.mjs";
import { AmbientCard } from "../../UI/surfaces/cards/AmbientCard/AmbientCard.mjs";
import { AmbientAlert } from "../../UI/feedback/AmbientAlert.mjs";
import { disconnect, getAuthorizeUrl, getOutlookRedirectUri, sendMail } from "./outlookIntegrationClient.mjs";
import { getOutlookStatus, refreshOutlookStatus, subscribeOutlookStatus } from "./outlookIntegrationStatus.mjs";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { Box, Divider, TextField, Typography, useTheme } from "@material-ui/core";
import { OutlookLogoIcon } from "@fluentui/react-icons";
import { useTranslation } from "react-i18next";
//#region src/integrations/outlook/OutlookIntegrationSideSheet.jsx
const OutlookIntegrationSideSheet = ({ open, onClose, closeOnConnect = false, appName, connectDescription, disclaimerText, footerNote, whyConnectTitle, whyConnectDescription, whyConnectItems, showTestEmail = false, testEmailDefaults, testEmailCopy }) => {
	const { t } = useTranslation();
	const theme = useTheme();
	const resolvedAppName = appName || t("outlook.appName", "this app");
	const [status, setStatus] = useState(() => getOutlookStatus());
	const [initializing, setInitializing] = useState(!status.loaded);
	const [action, setAction] = useState(null);
	const [feedback, setFeedback] = useState(null);
	const [testTo, setTestTo] = useState(testEmailDefaults?.to ?? "");
	const [testSubject, setTestSubject] = useState("");
	const [testBody, setTestBody] = useState("");
	useEffect(() => {
		const unsubscribe = subscribeOutlookStatus(setStatus);
		return () => unsubscribe();
	}, []);
	useEffect(() => {
		if (!open) return;
		setInitializing(true);
		refreshOutlookStatus().catch((err) => {
			setFeedback({
				severity: "error",
				message: extractErrorMessage(err, t("outlook.errors.status", "Unable to load Outlook status."))
			});
		}).finally(() => setInitializing(false));
	}, [open, t]);
	useEffect(() => {
		if (!showTestEmail || !status.connected || !status.mailboxPrincipal) return;
		setTestTo((prev) => prev ? prev : status.mailboxPrincipal);
	}, [
		showTestEmail,
		status.connected,
		status.mailboxPrincipal
	]);
	useEffect(() => {
		const handler = (event) => {
			if (!event || !window || event.origin !== window.location.origin) return;
			const payload = typeof event.data === "string" ? { type: event.data } : event.data || {};
			if (payload.type === "outlookConnectSuccess") refreshOutlookStatus().then(() => {
				setFeedback({
					severity: "success",
					message: t("outlook.connectSuccess", "Outlook connected successfully.")
				});
				if (closeOnConnect) onClose?.();
			});
			else if (payload.type === "outlookConnectFailure") setFeedback({
				severity: "error",
				message: payload.message || t("outlook.connectFailed", "Outlook connection failed. Please try again.")
			});
		};
		window.addEventListener("message", handler);
		return () => window.removeEventListener("message", handler);
	}, [
		closeOnConnect,
		onClose,
		t
	]);
	const openPopup = useCallback((url) => {
		if (typeof window === "undefined") return null;
		const width = 600;
		const height = 600;
		const left = (window.screen.width - width) / 2;
		const features = `width=${width},height=${height},top=${(window.screen.height - height) / 2},left=${left},status=no,toolbar=no,menubar=no,location=no`;
		return window.open(url, "OutlookConnectPopup", features);
	}, []);
	const handleConnect = useCallback(async () => {
		setAction("authorize");
		try {
			const { authorizeUrl } = await getAuthorizeUrl({ redirectUri: getOutlookRedirectUri() });
			if (!openPopup(authorizeUrl)) throw new Error(t("outlook.errors.popupBlocked", "Popup blocked. Please allow popups and try again."));
		} catch (err_0) {
			setFeedback({
				severity: "error",
				message: extractErrorMessage(err_0, t("outlook.errors.connect", "Unable to start the Outlook connection."))
			});
		} finally {
			setAction(null);
		}
	}, [openPopup, t]);
	const handleDisconnect = useCallback(async () => {
		setAction("disconnect");
		try {
			await disconnect();
			await refreshOutlookStatus();
			setFeedback({
				severity: "success",
				message: t("outlook.disconnectSuccess", "Outlook disconnected.")
			});
		} catch (err_1) {
			setFeedback({
				severity: "error",
				message: extractErrorMessage(err_1, t("outlook.errors.disconnect", "Unable to disconnect from Outlook."))
			});
		} finally {
			setAction(null);
		}
	}, [t]);
	const handleSendTest = useCallback(async () => {
		const to = testTo.trim();
		if (!to) {
			setFeedback({
				severity: "error",
				message: testEmailCopy?.missingRecipient || t("outlook.errors.testTo", "Please enter a recipient email.")
			});
			return;
		}
		const fallbackSubject = testEmailDefaults?.subject || t("outlook.sendTest.defaultSubject", `${resolvedAppName} test email`);
		const fallbackBody = testEmailDefaults?.body || t("outlook.sendTest.defaultBody", `This is a test email sent from ${resolvedAppName} via Outlook.`);
		setAction("send-mail");
		try {
			await sendMail({
				to,
				subject: testSubject.trim() || fallbackSubject,
				body: testBody.trim() || fallbackBody
			});
			setFeedback({
				severity: "success",
				message: testEmailCopy?.success || t("outlook.sendTest.success", "Test email sent.")
			});
		} catch (err_2) {
			setFeedback({
				severity: "error",
				message: extractErrorMessage(err_2, testEmailCopy?.error || t("outlook.errors.sendTest", "Unable to send test email."))
			});
		} finally {
			setAction(null);
		}
	}, [
		resolvedAppName,
		t,
		testBody,
		testEmailCopy?.error,
		testEmailCopy?.missingRecipient,
		testEmailCopy?.success,
		testEmailDefaults?.body,
		testEmailDefaults?.subject,
		testSubject,
		testTo
	]);
	const expiresLabel = useMemo(() => formatExpiresAt(status.expiresAt), [status.expiresAt]);
	const connectionDescription = useMemo(() => {
		if (status.connected && status.mailboxPrincipal) return t("outlook.status.connectedAs", "Connected as {{mailbox}}", { mailbox: status.mailboxPrincipal });
		if (status.connected) return t("outlook.status.connectedNoMailbox", "Outlook is connected.");
		return connectDescription || t("outlook.connectDescription", "Link your account to Outlook to manage your emails directly from our app.", { appName: resolvedAppName });
	}, [
		connectDescription,
		resolvedAppName,
		status.connected,
		status.mailboxPrincipal,
		t
	]);
	const connectButtonLabel = useMemo(() => status.connected ? t("outlook.status.connected", "Connected") : t("outlook.connectCta", "Connect To Outlook"), [status.connected, t]);
	const connectButtonDisabled = useMemo(() => status.connected || action === "authorize", [status.connected, action]);
	const disconnectDisabled = useMemo(() => action === "disconnect", [action]);
	const sendTestDisabled = useMemo(() => !status.connected || action === "send-mail", [status.connected, action]);
	const resolvedDisclaimer = disclaimerText || t("outlook.sidesheetDisclaimer", `By signing in you are giving ${resolvedAppName} access to send emails on your behalf using your Outlook Mailbox.`, { appName: resolvedAppName });
	const resolvedWhyConnectTitle = whyConnectTitle || t("outlook.whyConnect.title", "Why connect to Outlook?");
	const resolvedWhyConnectDescription = whyConnectDescription || t("outlook.whyConnect.description", `Certain actions within ${resolvedAppName} that require emailing will be enabled, such as:`, { appName: resolvedAppName });
	const resolvedFooterNote = footerNote || t("outlook.todoNotes", `The ${resolvedAppName} backend securely stores your Mail.Send token and updates this status automatically.`, { appName: resolvedAppName });
	return /* @__PURE__ */ React.createElement(SideSheet, {
		title: t("outlook.title", "Outlook Integration"),
		open,
		onClose,
		width: 560
	}, /* @__PURE__ */ React.createElement(AmbientAlert, {
		alertSeverity: "info",
		showAlert: true,
		alertMessage: resolvedDisclaimer
	}), feedback && /* @__PURE__ */ React.createElement(AmbientAlert, {
		alertSeverity: feedback.severity,
		showAlert: true,
		alertMessage: feedback.message,
		closeAlert: () => setFeedback(null)
	}), status.error && /* @__PURE__ */ React.createElement(AmbientAlert, {
		alertSeverity: "warning",
		showAlert: true,
		alertMessage: status.error
	}), /* @__PURE__ */ React.createElement(Box, {
		display: "flex",
		flexDirection: "column",
		alignItems: "center",
		mt: 2,
		mb: 2,
		textAlign: "center"
	}, /* @__PURE__ */ React.createElement(OutlookLogoIcon, { style: {
		fontSize: 128,
		width: 128,
		height: 128,
		color: theme.palette.info.dark
	} }), /* @__PURE__ */ React.createElement(Typography, {
		variant: "h6",
		gutterBottom: true
	}, status.connected ? t("outlook.status.header.connected", "Connected to Outlook") : t("outlook.connectHeader", "Connect to Outlook")), /* @__PURE__ */ React.createElement(Typography, {
		variant: "body2",
		color: "textSecondary"
	}, connectionDescription), expiresLabel && /* @__PURE__ */ React.createElement(Typography, {
		variant: "caption",
		color: "textSecondary"
	}, t("outlook.status.expiresAt", "Token expires {{date}}", { date: expiresLabel }))), initializing && /* @__PURE__ */ React.createElement(Box, { mb: 2 }, /* @__PURE__ */ React.createElement(Typography, {
		variant: "body2",
		color: "textSecondary"
	}, t("outlook.status.loading", "Checking current Outlook connection..."))), /* @__PURE__ */ React.createElement(Box, { mb: status.connected ? 2 : 4 }, /* @__PURE__ */ React.createElement(FluentButton, {
		variant: "contained",
		color: "primary",
		fullWidth: true,
		onClick: handleConnect,
		disabled: connectButtonDisabled
	}, connectButtonLabel)), status.connected && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(FluentButton, {
		variant: "outlined",
		color: "primary",
		fullWidth: true,
		onClick: handleDisconnect,
		disabled: disconnectDisabled
	}, t("outlook.disconnect", "Disconnect Outlook")), showTestEmail && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Divider, { style: { margin: "24px 0" } }), /* @__PURE__ */ React.createElement(Typography, {
		variant: "subtitle1",
		gutterBottom: true
	}, testEmailCopy?.title || t("outlook.sendTest.title", "Send a Test Email")), /* @__PURE__ */ React.createElement(Box, {
		display: "flex",
		flexDirection: "column",
		gridGap: 12,
		mb: 2
	}, /* @__PURE__ */ React.createElement(TextField, {
		label: testEmailCopy?.toLabel || t("outlook.sendTest.to", "To"),
		variant: "outlined",
		size: "small",
		fullWidth: true,
		value: testTo,
		onChange: (event_0) => setTestTo(event_0.target.value)
	}), /* @__PURE__ */ React.createElement(TextField, {
		label: testEmailCopy?.subjectLabel || t("outlook.sendTest.subject", "Subject"),
		variant: "outlined",
		size: "small",
		fullWidth: true,
		value: testSubject,
		onChange: (event_1) => setTestSubject(event_1.target.value)
	}), /* @__PURE__ */ React.createElement(TextField, {
		label: testEmailCopy?.bodyLabel || t("outlook.sendTest.body", "Body"),
		variant: "outlined",
		size: "small",
		multiline: true,
		minRows: 3,
		fullWidth: true,
		value: testBody,
		onChange: (event_2) => setTestBody(event_2.target.value)
	})), /* @__PURE__ */ React.createElement(FluentButton, {
		variant: "contained",
		color: "primary",
		fullWidth: true,
		onClick: handleSendTest,
		disabled: sendTestDisabled
	}, action === "send-mail" ? testEmailCopy?.sending || t("outlook.sendTest.sending", "Sending...") : testEmailCopy?.cta || t("outlook.sendTest.cta", "Send Test Email"))), /* @__PURE__ */ React.createElement(Divider, { style: { margin: "24px 0" } })), /* @__PURE__ */ React.createElement(AmbientCard, {
		title: resolvedWhyConnectTitle,
		fullWidth: true
	}, /* @__PURE__ */ React.createElement(Box, { ml: 2 }, /* @__PURE__ */ React.createElement(Typography, { variant: "body2" }, resolvedWhyConnectDescription), Array.isArray(whyConnectItems) && whyConnectItems.length > 0 && /* @__PURE__ */ React.createElement("ul", null, whyConnectItems.map((item, index) => /* @__PURE__ */ React.createElement("li", { key: `${index}-${String(item)}` }, /* @__PURE__ */ React.createElement(Typography, { variant: "body2" }, item)))))), /* @__PURE__ */ React.createElement(Box, { mt: 3 }, /* @__PURE__ */ React.createElement(Typography, {
		variant: "caption",
		color: "textSecondary"
	}, resolvedFooterNote)));
};
function formatExpiresAt(expiresAt) {
	if (!expiresAt) return null;
	const date = new Date(expiresAt);
	return Number.isNaN(date.getTime()) ? null : date.toLocaleString();
}
function extractErrorMessage(error, fallback) {
	if (!error) return fallback;
	if (typeof error === "string") return error;
	if (typeof error.message === "string" && error.message.trim()) return error.message;
	const responseMessage = error?.response?.data || error?.response?.statusText || error?.message;
	if (typeof responseMessage === "string" && responseMessage.trim()) return responseMessage;
	return fallback;
}
//#endregion
export { OutlookIntegrationSideSheet as default };

//# sourceMappingURL=OutlookIntegrationSideSheet.mjs.map