// SF Extension — Notification Widget
// Always-on ambient widget rendered belowEditor showing unread count and
// the most recent notification message. Refreshes every 30 seconds.
// Widget key: "sf-notifications", placement: "belowEditor"
import {
	getUnreadCount,
	onNotificationStoreChange,
} from "./notification-store.js";
import { formattedShortcutPair } from "./shortcut-defs.js";
import { safeSetWidget } from "./widget-safe.js";
// ─── Pure rendering ─────────────────────────────────────────────────────
/**
 * Build the notification widget UI lines. Returns empty array if no unread
 * notifications; otherwise shows unread count and keyboard shortcut hint.
 */
export function buildNotificationWidgetLines() {
	const unread = getUnreadCount();
	if (unread === 0) return [];
	return [
		`  🔔 Notifications: ${unread} unread  (${formattedShortcutPair("notifications")})`,
	];
}
// ─── Widget init ────────────────────────────────────────────────────────
const REFRESH_INTERVAL_MS = 30_000;

/**
 * Initialize the always-on notification widget (belowEditor).
 * Call once from session_start after the notification store is initialized.
 */
export function initNotificationWidget(ctx) {
	if (!ctx.hasUI) return;

	// String-array fallback for RPC mode.
	// The factory call below overwrites this when the host supports factories.
	safeSetWidget(ctx, "sf-notifications", buildNotificationWidgetLines(), {
		placement: "belowEditor",
	});

	// Factory-based widget for TUI mode
	safeSetWidget(
		ctx,
		"sf-notifications",
		(_tui, _theme) => {
			let cachedLines;
			const refresh = () => {
				cachedLines = undefined;
				_tui.requestRender();
			};
			const unsubscribe = onNotificationStoreChange(refresh);
			const refreshTimer = setInterval(refresh, REFRESH_INTERVAL_MS);
			return {
				render(_width) {
					if (!cachedLines) cachedLines = buildNotificationWidgetLines();
					return cachedLines;
				},
				invalidate() {
					cachedLines = undefined;
				},
				dispose() {
					unsubscribe();
					clearInterval(refreshTimer);
				},
			};
		},
		{ placement: "belowEditor" },
	);
}
