/**
 * Workspace Layout Types — defines panel arrangement for the spatial canvas.
 *
 * Tre lag:
 * 1. Personlig — brukerens eget arrangement (lagret i edge metadata)
 * 2. Node-default — samlingens traits foreslår layout
 * 3. Plattform-default — Synops sine standarder (fallback)
 *
 * Ref: docs/retninger/arbeidsflaten.md § "Tre lag"
 */

/** Height of the BlockShell header — used as minimized panel height */
export const PANEL_HEADER_HEIGHT = 36;

/** Position and size of a single panel on the canvas */
export interface PanelLayout {
	/** Trait name this panel represents */
	trait: string;
	/** X position in world coordinates */
	x: number;
	/** Y position in world coordinates */
	y: number;
	/** Panel width */
	width: number;
	/** Panel height */
	height: number;
	/** Whether panel is minimized (collapsed to header only) */
	minimized?: boolean;
}

/** Full workspace layout state */
export interface WorkspaceLayout {
	panels: PanelLayout[];
}

/** Panel metadata: icon and display name per trait */
export interface TraitPanelInfo {
	title: string;
	icon: string;
	defaultWidth: number;
	defaultHeight: number;
}

/** Known trait panel configurations */
export const TRAIT_PANEL_INFO: Record<string, TraitPanelInfo> = {
	chat:          { title: 'Chat',          icon: '💬', defaultWidth: 400, defaultHeight: 500 },
	editor:        { title: 'Artikkelverktøy', icon: '📝', defaultWidth: 600, defaultHeight: 500 },
	kanban:        { title: 'Kanban',        icon: '📋', defaultWidth: 500, defaultHeight: 450 },
	calendar:      { title: 'Kalender',      icon: '📅', defaultWidth: 500, defaultHeight: 400 },
	podcast:       { title: 'Podcast',       icon: '🎙️', defaultWidth: 450, defaultHeight: 400 },
	publishing:    { title: 'Publisering',   icon: '📤', defaultWidth: 400, defaultHeight: 350 },
	rss:           { title: 'RSS',           icon: '📡', defaultWidth: 400, defaultHeight: 350 },
	recording:     { title: 'Opptak',        icon: '🔴', defaultWidth: 450, defaultHeight: 400 },
	transcription: { title: 'Transkripsjon', icon: '📄', defaultWidth: 500, defaultHeight: 450 },
	studio:        { title: 'Studio',        icon: '🎛️', defaultWidth: 550, defaultHeight: 450 },
	mixer:         { title: 'Mikser',        icon: '🎚️', defaultWidth: 450, defaultHeight: 400 },
	orchestration: { title: 'Orkestrering', icon: '⚡', defaultWidth: 550, defaultHeight: 500 },
	mindmap:       { title: 'Tankekart',    icon: '🧠', defaultWidth: 600, defaultHeight: 500 },
	ai:            { title: 'AI-verktøy',  icon: '🤖', defaultWidth: 420, defaultHeight: 500 },
	node_explorer: { title: 'Nodeutforsker', icon: '🔍', defaultWidth: 600, defaultHeight: 500 },
	web:           { title: 'Nettleser',     icon: '🌐', defaultWidth: 700, defaultHeight: 500 },
	usage:         { title: 'Ressursforbruk', icon: '📊', defaultWidth: 380, defaultHeight: 350 },
	storyboard:    { title: 'Storyboard',    icon: '🎬', defaultWidth: 500, defaultHeight: 450 },
};

/** Default info for unknown traits */
const DEFAULT_PANEL_INFO: TraitPanelInfo = {
	title: 'Verktøy',
	icon: '🔧',
	defaultWidth: 400,
	defaultHeight: 350,
};

/** Get panel info for a trait, falling back to defaults */
export function getPanelInfo(trait: string): TraitPanelInfo {
	return TRAIT_PANEL_INFO[trait] ?? { ...DEFAULT_PANEL_INFO, title: trait };
}

/**
 * Generate a default layout from trait names.
 * Arranges panels in a grid, spaced evenly.
 * This is the "plattform-default" layer.
 */
export function generateDefaultLayout(traitNames: string[]): WorkspaceLayout {
	if (traitNames.length === 0) return { panels: [] };

	const GAP = 30;
	const panels: PanelLayout[] = [];

	// Calculate grid: aim for roughly 2-3 columns
	const cols = traitNames.length <= 2 ? traitNames.length : Math.min(3, Math.ceil(Math.sqrt(traitNames.length)));

	let currentX = GAP;
	let currentY = GAP;
	let rowMaxHeight = 0;

	for (let i = 0; i < traitNames.length; i++) {
		const col = i % cols;
		if (col === 0 && i > 0) {
			// New row
			currentX = GAP;
			currentY += rowMaxHeight + GAP;
			rowMaxHeight = 0;
		}

		const info = getPanelInfo(traitNames[i]);
		panels.push({
			trait: traitNames[i],
			x: currentX,
			y: currentY,
			width: info.defaultWidth,
			height: info.defaultHeight,
		});

		currentX += info.defaultWidth + GAP;
		rowMaxHeight = Math.max(rowMaxHeight, info.defaultHeight);
	}

	return { panels };
}

/**
 * Resolve layout using the three-layer model:
 * 1. Personal (from edge metadata) — highest priority
 * 2. Node-default (from traits) — if no personal layout
 * 3. Platform-default (generated) — fallback
 */
export function resolveLayout(
	traitNames: string[],
	savedLayout: WorkspaceLayout | null,
): WorkspaceLayout {
	if (savedLayout && savedLayout.panels.length > 0) {
		// Personal layout exists — use it, but add any new traits not in saved layout
		const savedTraits = new Set(savedLayout.panels.map(p => p.trait));
		const newTraits = traitNames.filter(t => !savedTraits.has(t));

		if (newTraits.length === 0) {
			// Filter out panels for traits that no longer exist
			const activeTraits = new Set(traitNames);
			return {
				panels: savedLayout.panels.filter(p => activeTraits.has(p.trait)),
			};
		}

		// Append new traits at the end
		const existingPanels = savedLayout.panels.filter(p => new Set(traitNames).has(p.trait));
		const maxY = Math.max(0, ...existingPanels.map(p => p.y + p.height));
		const newLayout = generateDefaultLayout(newTraits);
		// Offset new panels below existing ones
		const offsetPanels = newLayout.panels.map(p => ({
			...p,
			y: p.y + maxY + 30,
		}));

		return { panels: [...existingPanels, ...offsetPanels] };
	}

	// No saved layout — generate from traits (platform default)
	return generateDefaultLayout(traitNames);
}
