// 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 type { ExtensionContext } from "@singularity-forge/pi-coding-agent";

import {
	getUnreadCount,
	onNotificationStoreChange,
} from "./notification-store.js";
import { formattedShortcutPair } from "./shortcut-defs.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(): string[] {
	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: ExtensionContext): void {
	if (!ctx.hasUI) return;

	// String-array fallback for RPC mode
	ctx.ui.setWidget("sf-notifications", buildNotificationWidgetLines(), {
		placement: "belowEditor",
	});

	// Factory-based widget for TUI mode
	ctx.ui.setWidget(
		"sf-notifications",
		(_tui, _theme) => {
			let cachedLines: string[] | undefined;

			const refresh = () => {
				cachedLines = undefined;
				_tui.requestRender();
			};

			const unsubscribe = onNotificationStoreChange(refresh);
			const refreshTimer = setInterval(refresh, REFRESH_INTERVAL_MS);

			return {
				render(_width: number): string[] {
					if (!cachedLines) cachedLines = buildNotificationWidgetLines();
					return cachedLines;
				},
				invalidate(): void {
					cachedLines = undefined;
				},
				dispose(): void {
					unsubscribe();
					clearInterval(refreshTimer);
				},
			};
		},
		{ placement: "belowEditor" },
	);
}
