import { ConfigService } from "../../configService/index.mjs";
import { LoadingIndicator } from "../../UI/loading/LoadingIndicator/LoadingIndicator.mjs";
import { AmbientAlert } from "../../UI/feedback/AmbientAlert.mjs";
import { exchangeAuthorizationCode, getOutlookRedirectUri } from "./outlookIntegrationClient.mjs";
import { refreshOutlookStatus } from "./outlookIntegrationStatus.mjs";
import { c } from "react-compiler-runtime";
import React, { useEffect, useState } from "react";
import { useLocation } from "react-router-dom";
//#region src/integrations/outlook/OutlookIntegrationCallbackPage.jsx
const OutlookIntegrationCallbackPage = () => {
	const $ = c(32);
	const location = useLocation();
	const [error, setError] = useState(null);
	let t0;
	if ($[0] === Symbol.for("react.memo_cache_sentinel")) {
		t0 = [];
		$[0] = t0;
	} else t0 = $[0];
	const [debugLog, setDebugLog] = useState(t0);
	let t1;
	if ($[1] === Symbol.for("react.memo_cache_sentinel")) {
		t1 = isDebugEnabled();
		$[1] = t1;
	} else t1 = $[1];
	const debugEnabled = t1;
	let t2;
	let t3;
	let t4;
	let t5;
	if ($[2] !== location.search) {
		const params = new URLSearchParams(location.search);
		t2 = params.get("code");
		t3 = params.get("state");
		t4 = params.get("error");
		t5 = params.get("error_description");
		$[2] = location.search;
		$[3] = t2;
		$[4] = t3;
		$[5] = t4;
		$[6] = t5;
	} else {
		t2 = $[3];
		t3 = $[4];
		t4 = $[5];
		t5 = $[6];
	}
	let t6;
	if ($[7] !== t2 || $[8] !== t3 || $[9] !== t4 || $[10] !== t5) {
		t6 = {
			code: t2,
			state: t3,
			errorParam: t4,
			errorDescription: t5
		};
		$[7] = t2;
		$[8] = t3;
		$[9] = t4;
		$[10] = t5;
		$[11] = t6;
	} else t6 = $[11];
	const { code, state, errorParam, errorDescription } = t6;
	let t7;
	if ($[12] === Symbol.for("react.memo_cache_sentinel")) {
		t7 = getOutlookRedirectUri();
		$[12] = t7;
	} else t7 = $[12];
	const redirectUri = t7;
	let t8;
	if ($[13] === Symbol.for("react.memo_cache_sentinel")) {
		t8 = (message) => {
			const timestamp = (/* @__PURE__ */ new Date()).toISOString();
			console.debug(`[OutlookCallback] ${message}`);
			if (!debugEnabled) return;
			setDebugLog((prev) => [...prev, `${timestamp} ${message}`]);
		};
		$[13] = t8;
	} else t8 = $[13];
	const log = t8;
	let t9;
	if ($[14] === Symbol.for("react.memo_cache_sentinel")) {
		t9 = () => {
			if (debugEnabled) {
				log("Debug mode enabled; window will remain open for inspection.");
				return;
			}
			log("Closing Outlook popup after successful authorization.");
			closeWindowSoon();
		};
		$[14] = t9;
	} else t9 = $[14];
	const closePopup = t9;
	let t10;
	let t11;
	if ($[15] !== code || $[16] !== errorDescription || $[17] !== errorParam || $[18] !== location.search || $[19] !== state) {
		t10 = () => {
			log(`Callback page mounted with search: "${location.search || "<empty>"}"`);
			if (errorParam) {
				const message_0 = errorDescription || errorParam || "Outlook authorization failed.";
				log(`Outlook authorization returned error: ${message_0}`);
				setError(message_0);
				notifyParent("outlookConnectFailure", message_0);
				return;
			}
			if (!code || !state) {
				log("Authorization code or state missing in query string.");
				setError("Authorization details missing from Outlook redirect.");
				notifyParent("outlookConnectFailure", "Authorization details missing from Outlook redirect.");
				return;
			}
			log(`Exchanging authorization code via redirect URI: ${redirectUri}`);
			exchangeAuthorizationCode({
				authorizationCode: code,
				state,
				redirectUri
			}).then(() => {
				log("Authorization code exchange succeeded; refreshing Outlook status.");
				return refreshOutlookStatus();
			}).then(() => {
				log("Outlook status refreshed; notifying parent of success.");
				notifyParent("outlookConnectSuccess");
				closePopup();
			}).catch((err) => {
				const message_2 = extractErrorMessage(err, "Failed to finalize the Outlook connection.");
				log(`Outlook connect flow failed: ${message_2}`);
				setError(message_2);
				notifyParent("outlookConnectFailure", message_2);
				log("Leaving callback window open so the error details stay visible.");
			});
		};
		t11 = [
			closePopup,
			code,
			errorDescription,
			errorParam,
			location.search,
			log,
			redirectUri,
			state
		];
		$[15] = code;
		$[16] = errorDescription;
		$[17] = errorParam;
		$[18] = location.search;
		$[19] = state;
		$[20] = t10;
		$[21] = t11;
	} else {
		t10 = $[20];
		t11 = $[21];
	}
	useEffect(t10, t11);
	let t12;
	if ($[22] !== error) {
		t12 = !error && /* @__PURE__ */ React.createElement(LoadingIndicator, null);
		$[22] = error;
		$[23] = t12;
	} else t12 = $[23];
	let t13;
	if ($[24] !== error) {
		t13 = error && /* @__PURE__ */ React.createElement(AmbientAlert, {
			alertSeverity: "error",
			showAlert: true,
			alertMessage: error
		});
		$[24] = error;
		$[25] = t13;
	} else t13 = $[25];
	let t14;
	if ($[26] !== debugLog) {
		t14 = debugEnabled && /* @__PURE__ */ React.createElement("div", { style: {
			marginTop: 16,
			padding: "12px 14px",
			backgroundColor: "#111",
			color: "#eee",
			borderRadius: 4,
			fontFamily: "monospace",
			fontSize: 12,
			maxHeight: "40vh",
			overflowY: "auto"
		} }, /* @__PURE__ */ React.createElement("strong", { style: {
			display: "block",
			marginBottom: 8
		} }, "Outlook callback debug log"), debugLog.length === 0 ? /* @__PURE__ */ React.createElement("div", null, "Waiting for events...") : debugLog.map(_temp), /* @__PURE__ */ React.createElement("div", { style: { marginTop: 12 } }, "This window will stay open in debug mode. Close it manually after reviewing the log."));
		$[26] = debugLog;
		$[27] = t14;
	} else t14 = $[27];
	let t15;
	if ($[28] !== t12 || $[29] !== t13 || $[30] !== t14) {
		t15 = /* @__PURE__ */ React.createElement(React.Fragment, null, t12, t13, t14);
		$[28] = t12;
		$[29] = t13;
		$[30] = t14;
		$[31] = t15;
	} else t15 = $[31];
	return t15;
};
function notifyParent(type, message) {
	try {
		window.opener?.postMessage({
			type,
			message
		}, window.location.origin);
	} catch {}
	try {
		window.opener?.postMessage(type, window.location.origin);
	} catch {}
}
function closeWindowSoon() {
	setTimeout(() => {
		try {
			window.close();
		} catch {}
	}, 750);
}
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;
}
function isDebugEnabled() {
	const raw = ConfigService?.config?.OUTLOOK_POPUP_DEBUG;
	if (typeof raw === "boolean") return raw;
	return String(raw ?? "").toLowerCase() === "true";
}
function _temp(entry, idx) {
	return /* @__PURE__ */ React.createElement("div", { key: idx }, entry);
}
//#endregion
export { OutlookIntegrationCallbackPage as default };

//# sourceMappingURL=OutlookIntegrationCallbackPage.mjs.map