// @unaiverse/gui-kit. Copyright 2024-2026 UNaIVERSE S.r.l.
// Licensed under the Apache License, Version 2.0, in LICENSE.
//
// Types of the GUI kit: the node a world's (or agent's) GUI gets from the
// UNaIVERSE webapp, and the fake network to build it with no account.

/**
 * A file to send: a browser `File` or `Blob` (from a file field or a drop), or its name, type and
 * base64 data URI.
 */
export type FileToSend = File | Blob | { name?: string; type?: string; url: string };

/** What `send` takes: text, an image with text, a file with text (up to 20 MB), or a question with a form. */
export type SendValue = string | { text?: string; image?: string; file?: FileToSend; form?: FormSpec };

/** A file of a message, with the same shape as a file in `data`. */
export interface GuiFile {
	/** The file's name, or null when the sender gave none (an agent's files arrive without a name). */
	name: string | null;
	/** Its MIME type, e.g. 'application/pdf'. */
	type: string | null;
	/** A data URI to show or download it; null when only its name was kept (a file the person sent, after a reload). */
	url: string | null;
}

/** A video, a sound, a PDF or a link that a message shows. */
export interface GuiMedia {
	/** The address (always `https:`). */
	url: string;
	/**
	 * Its MIME type: 'image/*', 'video/*', 'audio/*', 'application/pdf', 'video/youtube', 'video/vimeo';
	 * any other type: show it as a link.
	 */
	type: string;
	/** A caption, or null. */
	title: string | null;
	/** A preview picture (`https:`), or null. */
	poster: string | null;
	/** A sentence that says what it is. */
	alt: string;
}

/** A chart that a message shows. */
export interface GuiChart {
	/** The kind of chart. */
	kind: 'bar' | 'line' | 'pie';
	/** The series, each with its `[x, y]` points (x a label or a number, y a number). */
	series: Array<{ label: string; points: Array<[string | number, number]> }>;
	/** A sentence that says what it shows. */
	alt: string;
}

/** How a send ended: delivered, failed (it can be retried), or not allowed now. */
export type SendResult = 'sent' | 'failed' | 'not-allowed';

/**
 * A form: fields to fill. When you write one, options can be plain strings; in a message they always
 * arrive as `{ value, label }`. A form with no `id` gets one of its own, so each answer finds its question.
 */
export interface FormSpec {
	/** The form's id; the answer names it. */
	id?: string;
	/** A short name for the form. */
	name?: string;
	/** The fields: each with a `name`, a `type` ('select', 'text', 'number', ...) and, for a choice, its `options`. */
	fields: Array<{ name: string; type: string; label?: string; options?: Array<string | { value: string; label: string }>; [key: string]: unknown }>;
	[key: string]: unknown;
}

/** One message of the world's (or agent's) conversation with the person. */
export interface GuiMessage {
	/** Stable id. */
	id: string;
	/** The words only, or null: a form, a media or a chart is in its own field, not here. */
	text: string | null;
	/** The first picture (data URI), or null. */
	image: string | null;
	/** Every picture, in order (missing with a webapp older than 2026-11). */
	images?: string[];
	/** The files attached (missing with an older webapp). */
	files?: GuiFile[];
	/** The videos, sounds, PDFs and links it shows (missing with an older webapp). */
	media?: GuiMedia[];
	/** The charts it shows (missing with an older webapp). */
	charts?: GuiChart[];
	/** The sender's name. For the person's own messages use `fromMe`: `from` is only a placeholder there. */
	from: string | null;
	/**
	 * Who wrote it: a member's id (as in `members`), the node's own id for its words and notes, null for
	 * the person's own messages (missing with an older webapp).
	 * @example const author = world.members?.find((member) => member.id === message.fromId);
	 */
	fromId?: string | null;
	/** When it was said (Unix ms). */
	time: number;
	/** True for what the person sent. */
	fromMe: boolean;
	/** True for the notes of the world's rules. */
	isSystem: boolean;
	/** The person's messages only: the delivery. */
	status?: 'sending' | 'sent' | 'failed';
	/** The person's messages only: send it again when it failed. */
	retry?(): Promise<SendResult>;
	/** A question: its form. */
	form?: FormSpec;
	/** A question: true once it is answered. */
	isAnswered?: boolean;
	/** A question: answer it, by field name. */
	answer?(values: Record<string, unknown>): Promise<SendResult>;
	/** An answer: its values, by field name. */
	values?: Record<string, unknown>;
	/** An answer: the id of the question's message (missing with an older webapp). */
	answers?: string;
}

/**
 * The browser's features a GUI gets only after the person says yes to it in
 * the webapp (the browser would otherwise keep one yes for every GUI).
 * Everything else the browser offers (fullscreen, writing the clipboard,
 * screen sharing, payments, sensors, popups, downloads, ...) is always on.
 */
export type BrowserFeature =
	| 'camera' | 'microphone' | 'geolocation' | 'clipboard-read' | 'midi'
	| 'usb' | 'serial' | 'hid' | 'bluetooth' | 'idle-detection' | 'local-fonts';

/** What the webapp tells the GUI about itself; `subscribe` runs again when it changes. */
export interface GuiWebapp {
	/** The webapp's theme: draw the GUI to match. */
	theme: 'light' | 'dark';
	/** The webapp's language, e.g. 'it' or 'en'. */
	language: string;
	/** The screen's safe areas (notch, rounded corners, home bar), in pixels, on the sides where the GUI touches the screen's edge. */
	insets: { top: number; right: number; bottom: number; left: number };
	/** The height of the on-screen keyboard over the GUI, in pixels; 0 when closed (always 0 on a desktop). */
	keyboard: number;
	/** The features of `BrowserFeature` the person allowed this GUI. */
	allowed: BrowserFeature[];
}

/**
 * The person who looks at the GUI, as they chose to share themselves with it when they accepted it in the
 * webapp. The nickname is always there. Each other field is there only when the person ticked it and their
 * profile has it. These are public fields of the profile: the GUI never gets the email, the exact position,
 * the nodes of the person or any credential.
 */
export interface GuiMe {
	/** The nickname of the person on UNaIVERSE. It can change, and a freed nickname can go to someone else. */
	nickname: string;
	/** Their name. */
	name?: string;
	/** Their surname. */
	surname?: string;
	/** Their title, as written in their profile (e.g. 'Dr.'). */
	title?: string;
	/** The organization they work for or belong to. */
	organization?: string;
	/** Their city. */
	city?: string;
	/** Their country. */
	country?: string;
}

/** A member of the world. */
export interface GuiMember {
	id: string;
	name: string | null;
	type: 'agent' | 'person' | 'world' | 'unknown';
	/** Its role in the world. */
	role: string | null;
	/** True for one of the world's masters. */
	isMaster: boolean;
	/** Whether the member is reachable now. */
	status: 'online' | 'connecting' | 'offline';
	data: Record<string, unknown>;
}

/**
 * The node a GUI gets: its world (or agent), as the person sees it.
 *
 * Error codes, on the `code` of a failed call: 'failed' (an action), 'too-big' (a file over 20 MB),
 * 'declined' and 'unavailable' (askFor, identity), and 'not-allowed-verb' (a webapp older than the kit).
 * The person's own messages have `fromMe: true`, and their `from` is only a placeholder. The person's
 * nickname is in `me`.
 */
export interface GuiNode {
	id: string;
	name: string | null;
	type: 'agent' | 'person' | 'world' | 'unknown';
	address: string | null;
	profile: { description: string | null; owner: string | null; place: string | null; isVerified: boolean; since: number | null };
	/** 'online' while the person is in; 'ended' when the world finished. */
	status: 'connecting' | 'online' | 'offline' | 'unreachable' | 'not-found' | 'ended';
	isOnline: boolean;
	/** What the node shows, by name, ready to use: image sources, numbers, grids, files. */
	data: Record<string, unknown>;
	/** The conversation with the person, oldest first. */
	messages: GuiMessage[];
	/** What is happening now by the rules, what can come next, and the actions the person may choose. */
	now: {
		text: string | null;
		next: string[];
		actions: Array<{ name: string; to: string; text: string | null; args: Record<string, unknown>; canChoose: boolean | null; isRequested: boolean }>;
	} | null;
	/** True when the person may send now (the world's rules). */
	canSend: boolean;
	/**
	 * The person, with the nickname and only the fields of their profile they chose to share with this GUI
	 * (missing with a webapp from before 2026-11-06).
	 * @example greeting.textContent = `Welcome, ${world.me?.nickname ?? 'guest'}`;
	 */
	me?: GuiMe;
	/**
	 * False when the world asks not to show who wrote each message: show no names or pictures next to
	 * messages (missing with an older webapp).
	 */
	showsSenders?: boolean;
	/** The webapp's theme, language, screen and the features the person allowed this GUI. */
	webapp: GuiWebapp;
	/** Worlds: the members, the roles, and the person's role. */
	members?: GuiMember[];
	roles?: Array<{ name: string; description: string | null; diagram: Record<string, unknown> | null }>;
	myRole?: string | null;
	/** Calls `listener` at once and after every change; returns a function that stops it. */
	subscribe(listener: (node: GuiNode) => void): () => void;
	/** The newest node. */
	get(): GuiNode;
	/**
	 * Sends as the person: text, `{ image, text }`, `{ file, text }` or `{ text, form }`. Fails with the code
	 * 'too-big' (a file over 20 MB, before anything leaves), 'not-allowed-verb' (a file, with a webapp older
	 * than files) or 'failed'. Only the world's agents whose code takes files read a file.
	 * @example await world.send({ file: input.files[0], text: 'My CV' });
	 */
	send(value: SendValue): Promise<SendResult>;
	/**
	 * Asks the rules to do one of `now.actions` for the person: 'requested', 'refused' or 'not-allowed'. Fails with
	 * the code 'failed'.
	 */
	act(name: string, args?: Record<string, unknown>): Promise<'requested' | 'refused' | 'not-allowed'>;
	/** The recent values of one name of `data`, oldest first (await it). */
	dataHistory(name: string): Promise<Array<{ value: unknown; time: number }>> | Array<{ value: unknown; time: number }>;
	/** Adds older messages at the start of `messages`; how many were added. */
	loadMore(): Promise<number>;
	/** Calls `listener` with each new value of one name of `data`; returns a function that stops it. */
	onData(name: string, listener: (value: unknown) => void): () => void;
	/**
	 * Writes the GUI's path into the webapp's address (`?gui=/rooms/3`), so that the link opens the GUI there.
	 * Only a path of the GUI's own site; false when it was ignored. No new step in the history.
	 * @example world.setPath('/rooms/3');
	 */
	setPath(path: string): Promise<boolean>;
	/**
	 * Takes the back button first: `handler` runs when the person presses back (the newest handler first) and
	 * returns true when it handled it (it closed a panel); otherwise, or after half a second, the webapp goes back.
	 * Returns a function that gives the button back.
	 * @example const stop = world.onBack(() => (panel.open ? (panel.close(), true) : false));
	 */
	onBack(handler: () => boolean | Promise<boolean>): () => void;
	/**
	 * Asks the person, in the webapp, to let this GUI use these features. Resolves with true at once when they are
	 * allowed already; with a yes the webapp loads the GUI again with them (find them in `webapp.allowed`); with a
	 * no it fails with the code 'declined'. Unknown names are ignored.
	 * @example if (!world.webapp.allowed.includes('camera')) await world.askFor(['camera']);
	 */
	askFor(features: BrowserFeature[]): Promise<true>;
	/**
	 * Gives `me` at once, with no question to the person and no signature. Kept for GUIs written for the earlier
	 * kit, which got a signed token here. Fails with 'unavailable' when the webapp gives no `me`.
	 * @example const { nickname } = await world.identity();
	 */
	identity(): Promise<GuiMe>;
	/**
	 * Shows the webapp's own profile card of a member (or of the world or agent itself), over the GUI: true
	 * when shown, false for an id that is not the node's or a member's, and for a member known only by its
	 * role (`type` 'unknown', with no profile yet and therefore no card). The GUI gets nothing from the card.
	 * @example avatar.onclick = () => world.openProfile(member.id);
	 */
	openProfile(id: string): Promise<boolean>;
}

/**
 * What a fake node answers: text, or a message with words, pictures, files, videos and charts, a
 * question with a form, and (a fake world) the member who says it.
 */
export type FakeAnswer = string | {
	text?: string;
	image?: string;
	images?: string[];
	/** Files, as `{ name, type, url }` with a data URI; in a message their name does not travel, as with a real agent. */
	files?: Array<{ name?: string; type?: string; url: string }>;
	media?: Array<{ url: string; type: string; title?: string; poster?: string; alt?: string }>;
	charts?: GuiChart[];
	form?: FormSpec;
	/** A fake world: the name of the member who says it (a plain message with its pictures and files, not a note). */
	from?: string;
};

/** A fake node, to build the GUI with no account and no network. */
export interface FakeNode {
	name: string;
	owner?: string;
	profile?: { description?: string; place?: string; isVerified?: boolean };
	/** Values, functions of time (a new value every second), or `{ every: ms, value: (time) => value }`. */
	data?: Record<string, unknown | ((time: number) => unknown) | { every?: number; value: (time: number) => unknown }>;
	now?: { text?: string; next?: string[]; actions?: Array<{ name: string; text?: string; to?: string }> };
	/**
	 * Answers what the person sends: a `FakeAnswer`, or nothing. The message has `text`, `image`, `files`
	 * (the file they sent, with its name), `from`, `time`, and `values` when it answers a form. A fake
	 * world's own answer is a note of its rules: words, media, charts and forms, no pictures or files.
	 */
	onMessage?: (message: GuiMessage, node: { name: string; address: string }, sender: { name: string; address: string }) => FakeAnswer | null | undefined | Promise<FakeAnswer | null | undefined>;
	/** True: the next message sent to it fails. */
	failNext?: boolean;
	/** Answers the person's choice of one of `now.actions`. */
	onAction?: (name: string, args: Record<string, unknown>, sender: { name: string; address: string }) => FakeAnswer | null | undefined | Promise<FakeAnswer | null | undefined>;
	/**
	 * Only on the world or the agent that the GUI is for (not on its members): the person the GUI gets as `me`,
	 * as the webapp would give them. The nickname is 'you' when missing.
	 */
	me?: Partial<GuiMe>;
}

/** A fake world: a fake node with members and roles. */
export interface FakeWorld extends FakeNode {
	members?: Array<FakeNode & { role?: string; isMaster?: boolean }>;
	roles?: Array<{ name: string; description?: string }>;
	myRole?: string;
	/** False: the world asks not to show who wrote each message (`showsSenders`). */
	showsSenders?: boolean;
}

/** The webapp's origins accepted by default: unaiverse.io and localhost:5173. */
export const DEFAULT_HOST_ORIGINS: ReadonlyArray<string>;

/**
 * Gives the node the GUI is for: inside the webapp, its world (or agent); with `fake`, a fake one.
 * Fails with the code 'no-host' outside the webapp (or with no answer) and 'unsupported' when the
 * webapp does not speak this version of the kit. With `fake`, `me` comes from the fake world (or
 * agent), `webapp` follows the page (or the `webapp` given), `setPath`, `onBack` and `askFor` are
 * accepted, `openProfile` shows nothing (true for the node's or a member's id), and `identity()`
 * gives `me`.
 * @example const world = await connectToHost({ fake: { world: { name: 'Arena', me: { nickname: 'ada' } } } }); // while building
 * @example const world = await connectToHost(); // in the webapp
 */
export function connectToHost(options?: {
	fake?: { world: FakeWorld } | { agent: FakeNode };
	/** With `fake`: the webapp's look to use instead of the page's. */
	webapp?: Partial<GuiWebapp>;
	hostOrigins?: string[];
	timeoutMs?: number;
}): Promise<GuiNode>;
