/*
 * c8-cirrus: Cirrus, an app for Bluesky the Metro way. A panorama (home.c):
 * the name across the top, a post with a picture as its hero, Following
 * and the notifications as columns, the pinned feeds as tiles, and you.
 * A section's header opens it as a page beside the hub; a post opens
 * its thread, a face its profile, a picture the viewer. The nav bar
 * along the top goes between Home, Notifications, Search, Feeds, your
 * profile and the accounts; the app bar does things to a post and
 * writes a new one. Every view is built once for both widths: narrow,
 * c8ui makes the hub a pivot and a trail one column. The live
 * tile is tile.c's job; c8-cirrus-tile keeps it fresh while this isn't
 * open.
 */
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gio/gio.h>
#include <xkbcommon/xkbcommon-keysyms.h>
#include "stealth.h"
#include "app.h"

#define MINUTE_S 60
#define SECTIONS_MAX 8 // narrow pages: more feeds are on the Feeds page

struct app g;

enum { PLACE_HOME, PLACE_NOTICES, PLACE_SEARCH, PLACE_FEEDS, PLACE_PROFILE,
	PLACE_ACCOUNTS };

static struct c8ui_widget *cmd_reply, *cmd_repost, *cmd_quote, *cmd_like,
	*cmd_browser, *cmd_copy, *cmd_delete, *cmd_new, *cmd_refresh;
static guint minute_timer;

/* Small things */

double ui_width(void) {
	return g.root ? c8ui_root_width(g.root) : 1180;
}

void ui_error(const char *message) {
	if (message) {
		c8ui_dialog_message(g.root, "Cirrus", message);
	}
}

/* A box's paddings, wide and narrow (the box switches by itself); one
 * beside the reading column has its wide right edge follow the width,
 * so those are kept to be told */

struct pad {
	struct c8ui_widget *box;
	double l, t, b;
};

static GPtrArray *pads; // the ones beside the column

static void pad_apply(struct pad *p) {
	c8ui_box_set_padding(p->box, p->l, p->t,
		fmax(PAGE_PAD, ui_width() - p->l - PAGE_COLUMN), p->b);
}

static void pad_gone(struct c8ui_widget *w, void *data) {
	g_ptr_array_remove(pads, data);
}

void ui_pad(struct c8ui_widget *box, double left, double top, double right,
		double bottom) {
	c8ui_box_set_narrow_padding(box, fmin(left, NARROW_PAD), fmin(top, 14),
		right == PAD_COLUMN ? NARROW_PAD : fmin(right, NARROW_PAD),
		fmin(bottom, 20));
	if (right != PAD_COLUMN) {
		c8ui_box_set_padding(box, left, top, right, bottom);
		return;
	}
	if (pads == NULL) {
		pads = g_ptr_array_new_with_free_func(g_free);
	}
	struct pad *p = g_new0(struct pad, 1);
	*p = (struct pad){ box, left, top, bottom };
	box->user_data = p;
	box->on_destroy = pad_gone;
	g_ptr_array_add(pads, p);
	pad_apply(p);
}

/* Pages over the main view */

static int page_count(void) {
	if (g.stack == NULL) {
		return 0;
	}
	return g.stack->child_count - 1; // the deck
}

static void update_bar(void);

void ui_push(struct c8ui_widget *page) {
	c8ui_appbar_hide(g.appbar);
	c8ui_navbar_hide(g.navbar);
	c8ui_stack_push(g.stack, page, true);
	update_bar();
}

void ui_close_pages(void) {
	while (page_count() > 0) {
		c8ui_widget_destroy(g.stack->children[g.stack->child_count - 1]);
	}
	c8ui_stack_set(g.stack, 0, false);
}

/* Over the whole window, wide too: a pane beside the hub was tried until
 * 2026-12-01 and the user didn't like it */
void ui_open_page(struct c8ui_widget *page) {
	ui_push(page);
}

void ui_pop(void) {
	if (page_count() > 0) {
		c8ui_stack_pop(g.stack, true);
		ui_set_target(NULL);
	}
}

void ui_back(void) {
	/* A trail steps back a column before the page goes */
	if (compose_may_leave() && !trail_back()) {
		ui_pop();
	}
}

void ui_home(void) {
	bool any = page_count() > 0;
	while (page_count() > 0) {
		c8ui_widget_destroy(g.stack->children[g.stack->child_count - 1]);
	}
	if (any && g.main) {
		c8ui_stack_set(g.stack, 0, true);
	}
	ui_set_target(NULL);
}

/* The app bar */

void ui_set_target(struct sky_post *post) {
	if (post != g.target) {
		sky_post_unref(g.target);
		g.target = sky_post_ref(post);
	}
	update_bar();
}

static void update_bar(void) {
	if (g.appbar == NULL) {
		return;
	}
	struct sky_post *p = g.target && !g.target->partial ? g.target : NULL;
	bool mine = p && sky_me && g_strcmp0(p->did, sky_me->did) == 0;
	c8ui_widget_set_hidden(cmd_reply, p == NULL);
	c8ui_widget_set_hidden(cmd_repost, p == NULL);
	c8ui_widget_set_hidden(cmd_quote, p == NULL);
	c8ui_widget_set_hidden(cmd_like, p == NULL);
	c8ui_widget_set_hidden(cmd_browser, p == NULL);
	c8ui_widget_set_hidden(cmd_copy, p == NULL);
	c8ui_widget_set_hidden(cmd_delete, !mine);
	c8ui_widget_set_hidden(cmd_new, sky_me == NULL);
	c8ui_widget_set_hidden(cmd_refresh, sky_me == NULL);
	if (g.navbar) {
		c8ui_navbar_set_current(g.navbar, page_count() == 0 ? PLACE_HOME : -1);
	}
}

void ui_show_bars(void) {
	update_bar();
	c8ui_appbar_show(g.appbar);
	c8ui_navbar_show(g.navbar);
}

static void toggle_bars(void) {
	if (c8ui_navbar_is_shown(g.navbar) || c8ui_appbar_is_shown(g.appbar)) {
		c8ui_navbar_hide(g.navbar);
		c8ui_appbar_hide(g.appbar);
	} else {
		ui_show_bars();
	}
}

/* Likes, reposts, follows: a record of ours each, made or deleted */

struct record_call {
	struct sky_post *post;
	bool like, making;
	char *did; // follows
};

static GString *record_body(const char *collection) {
	GString *body = g_string_new("{\"repo\":");
	sky_json_str(body, sky_me->did);
	g_string_append_printf(body, ",\"collection\":\"%s\"", collection);
	return body;
}

void ui_delete_record(const char *collection, const char *uri, sky_fn fn,
		void *data) {
	GString *body = record_body(collection);
	char *rkey = sky_rkey(uri);
	g_string_append(body, ",\"rkey\":");
	sky_json_str(body, rkey);
	g_string_append_c(body, '}');
	sky_post("com.atproto.repo.deleteRecord", body->str, fn, data);
	g_string_free(body, TRUE);
	g_free(rkey);
}

void ui_create_record(const char *collection, const char *fields, sky_fn fn,
		void *data) {
	GString *body = record_body(collection);
	char *now = sky_now_iso();
	g_string_append_printf(body, ",\"record\":{\"$type\":\"%s\","
		"\"createdAt\":\"%s\"%s}}", collection, now, fields);
	sky_post("com.atproto.repo.createRecord", body->str, fn, data);
	g_string_free(body, TRUE);
	g_free(now);
}

static void toggled(int status, struct json *json, const char *error,
		void *data) {
	struct record_call *rc = data;
	struct sky_post *p = rc->post;
	char **slot = rc->like ? &p->like_uri : &p->repost_uri;
	int *n = rc->like ? &p->likes : &p->reposts;
	if (status == 200 && rc->making) {
		g_free(*slot);
		*slot = g_strdup(json_str(json_get(json, "uri"), "at://unknown"));
	} else if (status != 200 && (status != 0 || error)) {
		/* Back to how it was */
		if (rc->making) {
			g_clear_pointer(slot, g_free);
			*n -= 1;
		} else {
			*n += 1;
			/* Its address is lost; another load brings it back */
			*slot = g_strdup("at://unknown");
		}
		ui_error(error);
	}
	p->rev++;
	views_redraw();
	sky_post_unref(p);
	g_free(rc);
}

static void toggle(struct sky_post *p, bool like) {
	char **slot = like ? &p->like_uri : &p->repost_uri;
	int *n = like ? &p->likes : &p->reposts;
	const char *collection = like ? "app.bsky.feed.like" :
		"app.bsky.feed.repost";
	if (sky_me == NULL || p->partial || g_strcmp0(*slot, "pending") == 0) {
		return;
	}
	struct record_call *rc = g_new0(struct record_call, 1);
	rc->post = sky_post_ref(p);
	rc->like = like;
	if (*slot) {
		ui_delete_record(collection, *slot, toggled, rc);
		g_clear_pointer(slot, g_free);
		*n -= *n > 0;
	} else {
		rc->making = true;
		GString *fields = g_string_new(",\"subject\":{\"uri\":");
		sky_json_str(fields, p->uri);
		g_string_append(fields, ",\"cid\":");
		sky_json_str(fields, p->cid);
		g_string_append_c(fields, '}');
		ui_create_record(collection, fields->str, toggled, rc);
		g_string_free(fields, TRUE);
		*slot = g_strdup("pending");
		*n += 1;
	}
	p->rev++;
	views_redraw();
}

void ui_like(struct sky_post *post) {
	toggle(post, true);
}

void ui_repost(struct sky_post *post) {
	toggle(post, false);
}

static void followed(int status, struct json *json, const char *error,
		void *data) {
	struct record_call *rc = data;
	if (status == 200) {
		const char *uri = rc->making ? json_str(json_get(json, "uri"), NULL) :
			NULL;
		views_set_follow(rc->did, uri);
		profile_set_follow(rc->did, uri);
	} else {
		ui_error(error);
	}
	g_free(rc->did);
	g_free(rc);
}

void ui_follow(const char *did, const char *follow_uri) {
	if (sky_me == NULL || did == NULL) {
		return;
	}
	struct record_call *rc = g_new0(struct record_call, 1);
	rc->did = g_strdup(did);
	if (follow_uri) {
		ui_delete_record("app.bsky.graph.follow", follow_uri, followed, rc);
		return;
	}
	rc->making = true;
	GString *fields = g_string_new(",\"subject\":");
	sky_json_str(fields, did);
	ui_create_record("app.bsky.graph.follow", fields->str, followed, rc);
	g_string_free(fields, TRUE);
}

/* Opening things */

void ui_play(struct sky_post *post) {
	if (post->video == NULL || g.win == NULL) {
		return;
	}
	/* The video player takes the address; without one, the post's page */
	GAppInfo *player = g_app_info_get_default_for_type("video/mp4", TRUE);
	if (player && g_app_info_get_id(player)) {
		const char *uris[] = { post->video, NULL };
		c8ui_window_launch(g.win, g_app_info_get_id(player), uris);
	} else {
		char *web = sky_post_web(post);
		c8ui_window_open_uri(g.win, web);
		g_free(web);
	}
	g_clear_object(&player);
}

/* at://who/collection/key, or bsky.app's pages, open here; the rest of
 * the web in the browser */
void ui_open_uri(const char *uri) {
	if (uri == NULL || g.win == NULL) {
		return;
	}
	char *at = NULL;
	if (g_str_has_prefix(uri, "https://bsky.app/profile/")) {
		char **parts = g_strsplit(uri + strlen("https://bsky.app/profile/"),
			"/", 4);
		int n = (int)g_strv_length(parts);
		/* Nothing after ? or # */
		for (int i = 0; i < n; i++) {
			parts[i][strcspn(parts[i], "?#")] = '\0';
		}
		if (n >= 3 && strcmp(parts[1], "post") == 0) {
			at = g_strdup_printf("at://%s/app.bsky.feed.post/%s", parts[0],
				parts[2]);
		} else if (n >= 3 && strcmp(parts[1], "feed") == 0) {
			at = g_strdup_printf("at://%s/app.bsky.feed.generator/%s", parts[0],
				parts[2]);
		} else if (n >= 3 && strcmp(parts[1], "lists") == 0) {
			at = g_strdup_printf("at://%s/app.bsky.graph.list/%s", parts[0],
				parts[2]);
		} else if (n >= 1 && parts[0][0]) {
			at = g_strdup_printf("at://%s", parts[0]);
		}
		g_strfreev(parts);
	} else if (g_str_has_prefix(uri, "at://")) {
		at = g_strdup(uri);
	}
	if (at == NULL) {
		if (g_str_has_prefix(uri, "https://") || g_str_has_prefix(uri,
				"http://")) {
			c8ui_window_open_uri(g.win, uri);
		}
		return;
	}
	if (sky_me == NULL) {
		g_free(at);
		return;
	}
	if (strstr(at, "/app.bsky.feed.post/")) {
		open_thread(at);
	} else if (strstr(at, "/app.bsky.feed.generator/")) {
		open_feed(VIEW_FEED, at, NULL, "Feed");
	} else if (strstr(at, "/app.bsky.graph.list/")) {
		open_feed(VIEW_LIST, at, NULL, "List");
	} else {
		char *who = g_strdup(at + 5);
		who[strcspn(who, "/")] = '\0';
		open_profile(who);
		g_free(who);
	}
	g_free(at);
}

void ui_activate(struct feedview *fv, struct sky_item *it,
		enum card_part part, int sub) {
	struct sky_post *p = it->post;
	bool notice = it->kind == SKY_ITEM_NOTICE && !(it->whole && p);
	switch (part) {
	case PART_AUTHOR:
		open_profile(p && !notice ? p->did : it->did);
		break;
	case PART_REPLY:
		open_compose(p, NULL, NULL);
		break;
	case PART_REPOST:
		ui_repost(p);
		break;
	case PART_LIKE:
		ui_like(p);
		break;
	case PART_MEDIA:
		open_viewer(p, sub);
		break;
	case PART_VIDEO:
		ui_play(p);
		break;
	case PART_EXTERNAL:
		ui_open_uri(p->ext_uri);
		break;
	case PART_QUOTE:
		if (!trail_open_thread(fv, p->quote->uri)) {
			open_thread(p->quote->uri);
		}
		break;
	case PART_LINK:
		if (sub >= 0 && sub < (int)p->links->len) {
			struct sky_link *link = p->links->pdata[sub];
			if (link->kind == SKY_LINK_WEB) {
				ui_open_uri(link->target);
			} else if (link->kind == SKY_LINK_MENTION) {
				open_profile(link->target);
			} else {
				char *tag = g_strconcat("#", link->target, NULL);
				open_search(tag);
				g_free(tag);
			}
		}
		break;
	case PART_FOLLOW:
		ui_follow(it->did, it->follow_uri);
		break;
	case PART_BODY:
		if (it->kind == SKY_ITEM_ACTOR || (notice && p == NULL)) {
			open_profile(it->did);
		} else if (p && !it->focus && !trail_open_thread(fv, p->uri)) {
			open_thread(p->uri);
		}
		break;
	case PART_NONE:
		break;
	}
}

/* Following, the notifications, the pinned feeds: the hub's columns
 * (home.c) and the narrow pivot's pages */

static struct feedview *section_find(enum view_kind kind, const char *param) {
	for (guint i = 0; g.sections && i < g.sections->len; i++) {
		struct feedview *fv = g.sections->pdata[i];
		if (fv->kind == kind && g_strcmp0(fv->param, param) == 0) {
			return fv;
		}
	}
	return NULL;
}

/* The timeline's newest posts go to the tile too */
static void timeline_loaded(struct feedview *fv, void *data) {
	home_timeline_loaded(); // the hero
	if (fv->items->len) {
		sky_tile_update(APP_ID, fv->items, g.unread);
		sky_tile_update(TILE_WIDGET_ID, fv->items, g.unread);
	}
}

/* A section's list: the one there was, if any, so it keeps its posts */
static void take(GPtrArray *old, enum view_kind kind, const char *param,
		const char *name) {
	struct feedview *have = NULL;
	for (guint k = 0; old && k < old->len && have == NULL; k++) {
		struct feedview *o = old->pdata[k];
		if (o->kind == kind && g_strcmp0(o->param, param) == 0) {
			have = view_ref(o);
		}
	}
	if (have == NULL) {
		have = view_new(kind, param, NULL, name);
	} else {
		g_free(have->name);
		have->name = g_strdup(name);
	}
	g_ptr_array_add(g.sections, have);
}

static void sections_make(void) {
	GPtrArray *old = g.sections;
	g.sections = g_ptr_array_new_with_free_func((GDestroyNotify)view_unref);
	struct feedview *notices = NULL;
	bool timeline = false;
	for (guint i = 0; g.saved && i < g.saved->len &&
			g.sections->len < SECTIONS_MAX; i++) {
		struct sky_saved *s = g.saved->pdata[i];
		if (!s->pinned) {
			continue;
		}
		if (strcmp(s->uri, "following") == 0) {
			if (timeline) {
				continue;
			}
			timeline = true;
			take(old, VIEW_TIMELINE, NULL, "Following");
		} else if (section_find(s->list ? VIEW_LIST : VIEW_FEED, s->uri) ==
				NULL) {
			take(old, s->list ? VIEW_LIST : VIEW_FEED, s->uri, s->name);
		}
		if (g.sections->len == 1) {
			/* What happened to you, right after the first column */
			take(old, VIEW_NOTICES, NULL, "Notifications");
			notices = g.sections->pdata[1];
		}
	}
	if (g.sections->len == 0) {
		take(old, VIEW_TIMELINE, NULL, "Following");
		take(old, VIEW_NOTICES, NULL, "Notifications");
		notices = g.sections->pdata[1];
	}
	if (notices) {
		notices->mark_seen = true;
	}
	struct feedview *tl = section_find(VIEW_TIMELINE, NULL);
	if (tl) {
		tl->on_loaded = timeline_loaded;
	}
	if (old) {
		g_ptr_array_unref(old);
	}
}

void ui_rebuild(void) {
	if (g.stack == NULL) {
		return;
	}
	if (g.main) {
		c8ui_widget_destroy(g.main);
		g.main = NULL;
	}
	if (sky_me == NULL || sky_me->expired) {
		g.main = welcome_new();
	} else {
		sections_make();
		g.main = home_new(section_find(VIEW_TIMELINE, NULL),
			section_find(VIEW_NOTICES, NULL));
		/* Only Following and the notifications are on the hub */
		for (guint i = 0; i < g.sections->len; i++) {
			struct feedview *fv = g.sections->pdata[i];
			if (fv->kind == VIEW_TIMELINE || fv->kind == VIEW_NOTICES) {
				view_ensure(fv);
			}
		}
	}
	g.main->fill = true;
	g.main->expand = true;
	c8ui_widget_insert(g.deck, 0, g.main);
	update_bar();
}

/* The account's own things: who it is, and its saved feeds */

static void got_names(int status, struct json *json, const char *error,
		void *data) {
	if (status != 200 || g.saved == NULL) {
		return;
	}
	for (struct json *f = json_get(json, "feeds") ?
			json_get(json, "feeds")->child : NULL; f; f = f->next) {
		const char *uri = json_str(json_get(f, "uri"), "");
		for (guint i = 0; i < g.saved->len; i++) {
			struct sky_saved *s = g.saved->pdata[i];
			if (strcmp(s->uri, uri) == 0) {
				g_free(s->name);
				s->name = g_utf8_make_valid(json_str(json_get(f, "displayName"),
					"Feed"), -1);
				g_free(s->avatar);
				s->avatar = g_strdup(json_str(json_get(f, "avatar"), NULL));
				g_free(s->by);
				s->by = g_strdup(json_str(json_get(json_get(f, "creator"),
					"handle"), NULL));
			}
		}
	}
	ui_rebuild();
}

static void got_list_name(int status, struct json *json, const char *error,
		void *data) {
	const struct json *list = json_get(json, "list");
	const char *uri = json_str(json_get(list, "uri"), "");
	for (guint i = 0; status == 200 && g.saved && i < g.saved->len; i++) {
		struct sky_saved *s = g.saved->pdata[i];
		if (strcmp(s->uri, uri) == 0) {
			g_free(s->name);
			s->name = g_utf8_make_valid(json_str(json_get(list, "name"),
				"List"), -1);
			g_free(s->avatar);
			s->avatar = g_strdup(json_str(json_get(list, "avatar"), NULL));
			ui_rebuild();
		}
	}
}

static void got_saved(int status, struct json *json, const char *error,
		void *data) {
	if (status != 200) {
		return; // the two columns there are will do
	}
	if (g.saved) {
		g_ptr_array_unref(g.saved);
	}
	g.saved = sky_parse_saved(json);
	GString *call = g_string_new("app.bsky.feed.getFeedGenerators");
	bool feeds = false;
	for (guint i = 0; i < g.saved->len; i++) {
		struct sky_saved *s = g.saved->pdata[i];
		if (s->list) {
			GString *one = g_string_new("app.bsky.graph.getList?limit=1");
			sky_query(one, "list", s->uri);
			sky_get(one->str, got_list_name, NULL);
			g_string_free(one, TRUE);
		} else if (strcmp(s->uri, "following") != 0) {
			sky_query(call, "feeds", s->uri);
			feeds = true;
		}
	}
	if (feeds) {
		sky_get(call->str, got_names, NULL);
	}
	g_string_free(call, TRUE);
	ui_rebuild();
}

static void got_me(int status, struct json *json, const char *error,
		void *data) {
	if (status != 200 || sky_me == NULL) {
		return;
	}
	sky_profile_free(g.me);
	g.me = sky_profile_parse(json);
	if (g.me && (g_strcmp0(sky_me->name, g.me->name) != 0 ||
			g_strcmp0(sky_me->avatar, g.me->avatar) != 0 ||
			g_strcmp0(sky_me->handle, g.me->handle) != 0)) {
		g_free(sky_me->name);
		sky_me->name = g_strdup(g.me->name);
		g_free(sky_me->avatar);
		sky_me->avatar = sky_avatar_small(g.me->avatar);
		g_free(sky_me->handle);
		sky_me->handle = g_strdup(g.me->handle);
		sky_save();
	}
	home_redraw(); // You
}

static void load_account(void) {
	if (sky_me == NULL || sky_me->expired) {
		return;
	}
	sky_get("app.bsky.actor.getPreferences", got_saved, NULL);
	GString *call = g_string_new("app.bsky.actor.getProfile");
	sky_query(call, "actor", sky_me->did);
	sky_get(call->str, got_me, NULL);
	g_string_free(call, TRUE);
}

void ui_signed_in(void) {
	views_forget_account();
	g_clear_pointer(&g.sections, g_ptr_array_unref);
	g_clear_pointer(&g.saved, g_ptr_array_unref);
	g_clear_pointer(&g.me, sky_profile_free);
	g.unread = 0;
	ui_set_target(NULL);
	if (g.stack) {
		while (page_count() > 0) {
			c8ui_widget_destroy(g.stack->children[g.stack->child_count - 1]);
		}
	}
	if (sky_me == NULL) {
		sky_tile_clear(APP_ID);
		sky_tile_clear(TILE_WIDGET_ID);
	}
	ui_rebuild();
	load_account();
	if (g.charms) {
		c8ui_charms_changed(g.charms, NULL);
	}
}

static void expired(void *data) {
	ui_signed_in(); // which shows the sign-in form again
}

/* Commands */

static void cmd_reply_fn(struct c8ui_widget *w, void *data) {
	if (g.target) {
		open_compose(g.target, NULL, NULL);
	}
}

static void cmd_repost_fn(struct c8ui_widget *w, void *data) {
	if (g.target) {
		ui_repost(g.target);
	}
}

static void cmd_quote_fn(struct c8ui_widget *w, void *data) {
	if (g.target) {
		open_compose(NULL, g.target, NULL);
	}
}

static void cmd_like_fn(struct c8ui_widget *w, void *data) {
	if (g.target) {
		ui_like(g.target);
	}
}

static void cmd_browser_fn(struct c8ui_widget *w, void *data) {
	if (g.target && g.win) {
		char *web = sky_post_web(g.target);
		c8ui_window_open_uri(g.win, web);
		g_free(web);
	}
}

static void cmd_copy_fn(struct c8ui_widget *w, void *data) {
	if (g.target) {
		char *web = sky_post_web(g.target);
		c8ui_root_set_clipboard(g.root, web);
		g_free(web);
	}
}

static void deleted(int status, struct json *json, const char *error,
		void *data) {
	char *uri = data;
	if (status == 200) {
		views_remove_post(uri);
	} else {
		ui_error(error);
	}
	g_free(uri);
}

static void delete_answer(int choice, void *data) {
	char *uri = data;
	if (choice == 0 && sky_me) {
		ui_delete_record("app.bsky.feed.post", uri, deleted, uri);
	} else {
		g_free(uri);
	}
}

static void cmd_delete_fn(struct c8ui_widget *w, void *data) {
	static const char *const buttons[] = { "Delete", "Cancel" };
	if (g.target) {
		c8ui_dialog_show(g.root, "Delete this post?",
			"It goes from Bluesky for everyone. This can't be undone.",
			buttons, 2, delete_answer, g_strdup(g.target->uri));
	}
}

static void cmd_new_fn(struct c8ui_widget *w, void *data) {
	open_compose(NULL, NULL, NULL);
}

static void refresh(void) {
	for (guint i = 0; g.sections && i < g.sections->len; i++) {
		struct feedview *fv = g.sections->pdata[i];
		fv->mark_seen = fv->kind == VIEW_NOTICES;
	}
	views_reload(-1);
	load_account();
}

static void cmd_refresh_fn(struct c8ui_widget *w, void *data) {
	refresh();
}

static void nav_chosen(struct c8ui_widget *bar, int index, void *data) {
	c8ui_appbar_hide(g.appbar);
	if ((sky_me == NULL && index != PLACE_ACCOUNTS) || !compose_may_leave()) {
		return;
	}
	ui_home();
	switch (index) {
	case PLACE_NOTICES:
		open_notifications();
		break;
	case PLACE_SEARCH:
		open_search(NULL);
		break;
	case PLACE_FEEDS:
		open_feeds();
		break;
	case PLACE_PROFILE:
		open_profile(sky_me->did);
		break;
	case PLACE_ACCOUNTS:
		open_accounts();
		break;
	default:
		break;
	}
}

static bool keys(const struct c8ui_event *ev, void *data) {
	bool ctrl = ev->mods & C8UI_MOD_CTRL;
	if (ev->sym == XKB_KEY_Escape && page_count()) {
		ui_back();
		return true;
	}
	if (ev->sym == XKB_KEY_Menu) {
		toggle_bars();
		return true;
	}
	if (sky_me == NULL) {
		return false;
	}
	if (ev->sym == XKB_KEY_F5 || (ctrl && ev->base_sym == XKB_KEY_r)) {
		refresh();
		return true;
	}
	if (ctrl && ev->base_sym == XKB_KEY_n) {
		open_compose(NULL, NULL, NULL);
		return true;
	}
	if (ctrl && ev->base_sym == XKB_KEY_f) {
		open_search(NULL);
		return true;
	}
	/* Letters only reach here when no box took them: on a chosen post */
	if (!ctrl && !(ev->mods & C8UI_MOD_ALT) && g.target &&
			!g.target->partial) {
		switch (ev->base_sym) {
		case XKB_KEY_l:
			ui_like(g.target);
			return true;
		case XKB_KEY_t:
			ui_repost(g.target);
			return true;
		case XKB_KEY_r:
			open_compose(g.target, NULL, NULL);
			return true;
		case XKB_KEY_q:
			open_compose(NULL, g.target, NULL);
			return true;
		default:
			break;
		}
	}
	return false;
}

/* The minute: ages move on, and has anything happened? */

static void got_unread(int status, struct json *json, const char *error,
		void *data) {
	if (status != 200) {
		return;
	}
	int count = (int)json_num(json_get(json, "count"), 0);
	if (count > g.unread) {
		struct feedview *notices = section_find(VIEW_NOTICES, NULL);
		if (notices) {
			/* Shown, but not said to be seen: the window may be behind
			 * others, and the tile's badge and the toasts tell of them */
			notices->mark_seen = false;
			view_reload(notices);
		}
	}
	g.unread = count;
}

static gboolean minute(gpointer data) {
	if (g.win == NULL) {
		return G_SOURCE_CONTINUE;
	}
	views_redraw();
	home_redraw(); // the hero's age
	if (sky_me && !sky_me->expired) {
		sky_get("app.bsky.notification.getUnreadCount", got_unread, NULL);
	}
	return G_SOURCE_CONTINUE;
}

static void image_ready(const char *url, void *data) {
	views_pictures();
	home_redraw();
	if (g.stack && page_count() > 0) {
		/* A profile's banner, the viewer's picture */
		c8ui_widget_queue_draw(g.stack->children[g.stack->child_count - 1]);
	}
}

/* Charms */

static void people_found(int status, struct json *json, const char *error,
		void *data) {
	struct c8ui_search *s = data;
	for (struct json *a = status == 200 && json_get(json, "actors") ?
			json_get(json, "actors")->child : NULL; a; a = a->next) {
		const char *did = json_str(json_get(a, "did"), "");
		const char *handle = json_str(json_get(a, "handle"), "");
		char *at = g_strconcat("@", handle, NULL);
		char *small = sky_avatar_small(json_str(json_get(a, "avatar"), NULL));
		const char *icon = sky_image_path(small);
		if (small && icon == NULL) {
			sky_image_fetch(small);
		}
		c8ui_search_add(s, did, json_str(json_get(a, "displayName"), handle),
			at, icon ? icon : "avatar-default");
		g_free(small);
		g_free(at);
	}
	c8ui_search_done(s);
}

static void search(struct c8ui_search *s, const char *query, void *data) {
	if (query[0] == '\0' || sky_me == NULL) {
		return;
	}
	char *posts = g_strdup_printf("Posts with “%s”", query);
	c8ui_search_add(s, "posts", posts, "Search Bluesky", "edit-find");
	g_free(posts);
	GString *call = g_string_new(
		"app.bsky.actor.searchActorsTypeahead?limit=8");
	sky_query(call, "q", query);
	c8ui_search_hold(s);
	sky_get(call->str, people_found, s);
	g_string_free(call, TRUE);
}

static void search_open(const char *id, const char *query, void *data) {
	if (g.win == NULL || sky_me == NULL) {
		return;
	}
	if (g_str_has_prefix(id, "did:")) {
		open_profile(id);
	} else {
		open_search(query);
	}
}

static void search_submit(const char *query, void *data) {
	if (g.win && sky_me) {
		open_search(query);
	}
}

static void option_changed(struct c8ui_setting *s, void *data) {
	const char *id = c8ui_setting_id(s);
	if (strcmp(id, "images") == 0) {
		sky_settings.images = c8ui_setting_get_bool(s);
	} else if (strcmp(id, "sensitive") == 0) {
		sky_settings.sensitive = c8ui_setting_get_bool(s);
	} else if (strcmp(id, "notifications") == 0) {
		sky_settings.toasts = c8ui_setting_get_bool(s);
	} else if (strcmp(id, "text") == 0) {
		sky_settings.text_size = c8ui_setting_get_int(s);
	}
	sky_save();
	views_redraw();
}

static void options_page(struct c8ui_settings_page *page, void *data) {
	static const char *const sizes[] = { "Small", "Medium", "Large" };
	c8ui_page_toggle(page, "images", "Show pictures", sky_settings.images,
		option_changed, NULL);
	struct c8ui_setting *s = c8ui_page_toggle(page, "sensitive",
		"Show sensitive pictures", sky_settings.sensitive, option_changed,
		NULL);
	c8ui_setting_set_description(s, "Ones labelled as adult or graphic are "
		"behind a line of words otherwise");
	c8ui_page_buttons(page, "text", "Text size", sizes, 3,
		sky_settings.text_size, option_changed, NULL);
	s = c8ui_page_toggle(page, "notifications", "Tell me what happens",
		sky_settings.toasts, option_changed, NULL);
	c8ui_setting_set_description(s, "Likes, replies and follows as "
		"notifications, while the tile is on Start");
}

static void accounts_action(void *data) {
	if (g.win) {
		ui_home();
		open_accounts();
	}
}

/* The window */

static void window_gone(struct c8ui_widget *w, void *data) {
	g.win = NULL;
	g.root = NULL;
	g.stack = g.main = g.deck = NULL;
	g.appbar = g.navbar = NULL;
	sky_post_unref(g.target);
	g.target = NULL;
}

/* Nothing is built again here: c8ui's widgets follow the window (the
 * hub becomes a pivot, a trail one column, headers smaller), and this
 * only gives what is measured from the width its new numbers */
static void resized(struct c8ui_root *root, double width, double height,
		void *data) {
	g.narrow = c8ui_root_is_narrow(root);
	for (guint i = 0; pads && i < pads->len; i++) {
		pad_apply(pads->pdata[i]); // the reading column's
	}
	home_resized();
	views_resized(); // the lists' cells
}

static struct c8ui_widget *command(const char *icon, const char *label,
		bool right, c8ui_action_fn fn) {
	return c8ui_appbar_add(g.appbar, icon, label, right, fn, NULL);
}

static void make_window(void) {
	g.win = c8ui_window_new(g.app, "Cirrus", 1280, 760);
	g.root = c8ui_window_root(g.win);
	g.narrow = c8ui_root_is_narrow(g.root);
	g.column_w = COLUMN_W;
	c8ui_window_set_background(g.win, BACKGROUND, 1);

	g.stack = c8ui_stack_new();
	g.stack->fill = true;
	g.stack->on_destroy = window_gone;
	c8ui_widget_set_scheme(g.stack, C8UI_SCHEME_LIGHT);
	c8ui_widget_set_background(g.stack, BACKGROUND);
	c8ui_root_set_child(g.root, g.stack);
	g.deck = c8ui_box_new(C8UI_HORIZONTAL, 0);
	g.deck->fill = true;
	c8ui_widget_add(g.stack, g.deck);
	c8ui_root_set_key_handler(g.root, keys, NULL);
	c8ui_root_on_resize(g.root, resized, NULL);

	g.navbar = c8ui_navbar_new(g.root, nav_chosen, NULL);
	c8ui_navbar_set_colors(g.navbar, BAR, BAR_TILE);
	c8ui_navbar_add(g.navbar, SKY_GLYPHS "/home.svg", "Home");
	c8ui_navbar_add(g.navbar, SKY_GLYPHS "/notifications.svg",
		"Notifications");
	c8ui_navbar_add(g.navbar, SKY_GLYPHS "/search.svg", "Search");
	c8ui_navbar_add(g.navbar, SKY_GLYPHS "/feeds.svg", "Feeds");
	c8ui_navbar_add(g.navbar, SKY_GLYPHS "/profile.svg", "Profile");
	c8ui_navbar_add(g.navbar, SKY_GLYPHS "/accounts.svg", "Accounts");

	g.appbar = c8ui_appbar_new(g.root);
	cmd_reply = command(SKY_GLYPHS "/reply.svg", "Reply", false, cmd_reply_fn);
	cmd_repost = command(SKY_GLYPHS "/repost.svg", "Repost", false,
		cmd_repost_fn);
	cmd_quote = command(SKY_GLYPHS "/quote.svg", "Quote", false, cmd_quote_fn);
	cmd_like = command(SKY_GLYPHS "/like.svg", "Like", false, cmd_like_fn);
	cmd_browser = command("web-browser", "Open in browser", false,
		cmd_browser_fn);
	cmd_copy = command("edit-copy", "Copy link", false, cmd_copy_fn);
	cmd_delete = command("edit-delete", "Delete", false, cmd_delete_fn);
	cmd_new = command(SKY_GLYPHS "/compose.svg", "New post", true, cmd_new_fn);
	cmd_refresh = command("view-refresh", "Refresh", true, cmd_refresh_fn);

	g.main = NULL;
	ui_rebuild();
	load_account();
}

/* Stealth mode went on or off (c8-base's stealth.h): everything that
 * shows us is drawn again, and the tile sent again */
static void stealth_changed(void *data) {
	views_redraw();
	home_redraw();
	pages_stealth_changed();
	struct feedview *tl = section_find(VIEW_TIMELINE, NULL);
	if (tl && sky_me) {
		timeline_loaded(tl, NULL);
	}
}

static void startup(struct c8ui_app *app, void *data) {
	g.app = app;
	sky_load();
	sky_image_on_ready(image_ready, NULL);
	sky_on_expired(expired, NULL);
	g.charms = c8ui_charms_new(app);
	if (g.charms) {
		c8ui_charms_on_search(g.charms, search, search_open, search_submit,
			NULL);
		c8ui_charms_add_page(g.charms, "options", "Options", options_page,
			NULL);
		c8ui_charms_add_action(g.charms, "accounts", "Accounts",
			accounts_action, NULL);
	}
	minute_timer = g_timeout_add_seconds(MINUTE_S, minute, NULL);
	c8_stealth_watch(stealth_changed, NULL);
}

/* Every launch: the first, and each one handed over later (a post's or
 * a profile's address) */
static void open(struct c8ui_app *app, char **uris, void *data) {
	if (g.win == NULL) {
		make_window();
	}
	for (int i = 0; uris[i]; i++) {
		if (g_str_has_prefix(uris[i], "at://") ||
				g_str_has_prefix(uris[i], "https://bsky.app/")) {
			ui_open_uri(uris[i]);
		}
	}
	c8ui_window_present(g.win);
}

static void shutdown(struct c8ui_app *app, void *data) {
	if (minute_timer) {
		g_source_remove(minute_timer);
	}
	c8ui_charms_destroy(g.charms);
}

int main(int argc, char **argv) {
	static const struct c8ui_app_info info = {
		.id = APP_ID,
		.startup = startup,
		.open = open,
		.shutdown = shutdown,
	};
	return c8ui_app_main(&info, argc, argv);
}
