/*
 * The hub: Metro's panorama, a magazine's cover more than a deck of
 * columns (narrow, c8ui makes it a pivot of the named sections, the
 * hero left out). The app's name across the top, then a hero (a carousel of the
 * newest posts with pictures from Following, large), Following and the
 * notifications
 * as columns of a reading width, the pinned feeds and lists as tiles, and
 * you. Sections keep their own widths, so the next one always shows at
 * the right edge: that is what says the hub goes on sideways.
 */
#include <math.h>
#include <string.h>
#include <xkbcommon/xkbcommon-keysyms.h>
#include "app.h"

#define HEAD_H 46 // a section's header, over its content
#define TILE 150 // a feed's tile, square
#define TILE_GAP 10 // what a c8ui list puts between cells
#define TILES_W (2 * TILE + TILE_GAP)
#define YOU_W 300
#define HERO_MIN 420
#define HERO_MAX 900
#define HERO_PAD 28 // the words' margin over the picture
#define SLIDES_MAX 6
#define SLIDE_S 7 // each one shows this long
#define SLIDE_MS 450 // the next sliding in
#define ARROW 44 // the buttons at its sides, under the pointer

struct tile {
	char *uri, *name, *avatar; // uri NULL: "All feeds"
	bool list;
};

static struct {
	struct c8ui_widget *hub, *hero, *tiles, *you;
	/* The carousel: slides (struct sky_post) and the one shown; while
	 * one slides in (slide_start >= 0) from dir's side, from is the
	 * one going. kept[cur] is the one shown, the other the one going. */
	GPtrArray *slides;
	int at, from, dir, cur;
	int64_t slide_start;
	double slid; // 0 to 1: how far in the new one is
	guint timer;
	double pointer_x;
	struct c8ui_kept *kept[2];
	struct feedview *timeline;
	GPtrArray *rows; // struct tile
} home;

double home_hero_width(void) {
	return floor(fmax(fmin(ui_width() * 0.45, HERO_MAX), HERO_MIN));
}

/* A section's header that opens its page: "Following ›" */

struct head {
	char *name;
	void (*open)(void);
};

static void head_draw(struct c8ui_widget *w, cairo_t *cr, void *data) {
	struct head *h = data;
	struct c8ui_colors c = c8ui_widget_colors(w);
	char *text = h->open ? g_strdup_printf("%s  ›", h->name) :
		g_strdup(h->name);
	c8ui_set_source(cr, c.fg, w->hovered ? 0.7 : 1);
	struct c8ui_font font = c8ui_text_font(C8UI_TEXT_SUBHEADER);
	c8ui_text_draw(cr, c8ui_widget_font(w), font, text, w->rect.x, w->rect.y,
		w->rect.width, 1);
	if (c8ui_widget_shows_focus(w)) {
		double tw, th;
		c8ui_text_size(c8ui_widget_font(w), font, text, w->rect.width, 1, &tw,
			&th);
		c8ui_set_source(cr, c.fg, 1);
		cairo_set_line_width(cr, 1);
		cairo_rectangle(cr, w->rect.x - 3.5, w->rect.y - 1.5, tw + 7, th + 5);
		cairo_stroke(cr);
	}
	g_free(text);
}

static bool head_event(struct c8ui_widget *w, const struct c8ui_event *ev,
		void *data) {
	struct head *h = data;
	if (h->open == NULL) {
		return false;
	}
	if (ev->type == C8UI_EVENT_RELEASE && ev->button == C8UI_BUTTON_LEFT &&
			c8ui_rect_contains(&w->rect, ev->x, ev->y)) {
		h->open();
		return true;
	}
	if (ev->type == C8UI_EVENT_KEY && (ev->sym == XKB_KEY_Return ||
			ev->sym == XKB_KEY_KP_Enter || ev->sym == XKB_KEY_space)) {
		h->open();
		return true;
	}
	return ev->type == C8UI_EVENT_PRESS && ev->button == C8UI_BUTTON_LEFT;
}

static void head_gone(struct c8ui_widget *w, void *data) {
	struct head *h = data;
	g_free(h->name);
	g_free(h);
}

/* A section: the header over its content. Its header hides while the
 * window is narrow, where a pivot's headers name it (a hub's), unless
 * kept (a trail's column, which has none over it) */

struct section {
	bool scrolls, keep_head;
};

static void section_narrow(struct c8ui_widget *w, bool narrow) {
	struct section *s = w->data;
	c8ui_widget_set_hidden(w->children[0], narrow && !s->keep_head);
}

static void section_destroy(struct c8ui_widget *w) {
	g_free(w->data);
}

static void section_measure(struct c8ui_widget *w, double avail,
		double *width, double *height) {
	*width = avail;
	*height = 0;
}

static void section_layout(struct c8ui_widget *w) {
	struct c8ui_rect r = w->rect;
	double head = w->children[0]->hidden ? 0 : HEAD_H;
	c8ui_widget_layout(w->children[0], (struct c8ui_rect){ r.x, r.y, r.width,
		HEAD_H });
	c8ui_widget_layout(w->children[1], (struct c8ui_rect){ r.x, r.y + head,
		r.width, fmax(r.height - head, 0) });
}

/* A wheel over a list that is at its end mustn't turn the panorama
 * instead (it takes a wheel either way): only Shift does, and fingers
 * going sideways */
static bool section_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	return ev->type == C8UI_EVENT_SCROLL &&
		((struct section *)w->data)->scrolls &&
		!(ev->mods & (C8UI_MOD_SHIFT | C8UI_MOD_CTRL)) &&
		fabs(ev->dy) >= fabs(ev->dx);
}

static const struct c8ui_widget_impl section_impl = {
	.name = "sky-section",
	.measure = section_measure,
	.layout = section_layout,
	.event = section_event,
	.destroy = section_destroy,
	.narrow = section_narrow,
};

struct c8ui_widget *hub_section_new(const char *name, void (*open)(void),
		struct c8ui_widget *content, bool scrolls) {
	struct section *s = g_new0(struct section, 1);
	s->scrolls = scrolls;
	struct c8ui_widget *sec = c8ui_widget_new(&section_impl, s);
	struct head *h = g_new0(struct head, 1);
	h->name = g_strdup(name);
	h->open = open;
	struct c8ui_widget *head = c8ui_canvas_new(0, HEAD_H, head_draw,
		head_event, h);
	head->cursor = open ? C8UI_CURSOR_POINTER : C8UI_CURSOR_DEFAULT;
	head->focusable = open != NULL;
	head->on_destroy = head_gone;
	head->user_data = h;
	c8ui_widget_add(sec, head);
	if (scrolls) {
		struct c8ui_widget *body = c8ui_box_new(C8UI_VERTICAL, 0);
		body->fill = true;
		c8ui_box_set_padding(body, 0, 0, 0, 30);
		c8ui_box_set_narrow_padding(body, 0, 4, NARROW_PAD, 30);
		c8ui_widget_add(body, content);
		content = c8ui_scroll_new(body);
	}
	c8ui_widget_add(sec, content);
	return sec;
}

void hub_section_keep_head(struct c8ui_widget *sec) {
	((struct section *)sec->data)->keep_head = true;
	c8ui_widget_set_hidden(sec->children[0], false);
}

static void open_following(void) {
	open_feed(VIEW_TIMELINE, NULL, NULL, "Following");
}

static void open_me(void) {
	if (sky_me) {
		open_profile(sky_me->did);
	}
}

/* The hero: a carousel of posts from Following, each as big as the cover
 * of a magazine and drawn as News draws a story's tile with a picture */

static bool shows_picture(struct sky_post *p) {
	return p->n_images > 0 && sky_settings.images &&
		(!p->sensitive || sky_settings.sensitive);
}

static struct sky_post *slide(int i) {
	if (home.slides == NULL || home.slides->len == 0) {
		return NULL;
	}
	return home.slides->pdata[((i % (int)home.slides->len) +
		(int)home.slides->len) % (int)home.slides->len];
}

static const char *slide_url(struct sky_post *p) {
	return p->images[0].full ? p->images[0].full : p->images[0].thumb;
}

/* The newest posts with pictures, the one shown kept in its place; the
 * newest post without one when none has */
static void hero_pick(void) {
	struct sky_post *shown = slide(home.at);
	GPtrArray *slides = g_ptr_array_new_with_free_func(
		(GDestroyNotify)sky_post_unref);
	struct sky_post *first = NULL;
	for (guint i = 0; home.timeline && i < home.timeline->items->len &&
			slides->len < SLIDES_MAX; i++) {
		struct sky_item *it = home.timeline->items->pdata[i];
		struct sky_post *p = it->kind == SKY_ITEM_POST ? it->post : NULL;
		if (p == NULL || p->partial) {
			continue;
		}
		first = first ? first : p;
		bool have = false; // reposted again further down
		for (guint j = 0; j < slides->len; j++) {
			have = have || slides->pdata[j] == p;
		}
		if (!have && shows_picture(p)) {
			g_ptr_array_add(slides, sky_post_ref(p));
		}
	}
	if (slides->len == 0 && first) {
		g_ptr_array_add(slides, sky_post_ref(first));
	}
	int at = 0;
	for (guint j = 0; shown && j < slides->len; j++) {
		if (slides->pdata[j] == shown) {
			at = (int)j;
		}
	}
	if (home.slides) {
		g_ptr_array_unref(home.slides);
	}
	home.slides = slides;
	home.at = at;
	home.slide_start = -1;
	home.slid = 1;
	if (home.hero) {
		c8ui_widget_queue_draw(home.hero);
	}
}

/* Darker towards the bottom, where the words are */
static void shade(cairo_t *cr, struct c8ui_rect r, double from, double alpha) {
	cairo_pattern_t *p = cairo_pattern_create_linear(0, r.y + r.height * from,
		0, r.y + r.height);
	cairo_pattern_add_color_stop_rgba(p, 0, 0, 0, 0, 0);
	cairo_pattern_add_color_stop_rgba(p, 1, 0, 0, 0, alpha);
	cairo_set_source(cr, p);
	cairo_rectangle(cr, r.x, r.y, r.width, r.height);
	cairo_fill(cr);
	cairo_pattern_destroy(p);
}

/* A face, or its first letter on blue */
static void face(cairo_t *cr, const char *family, const char *url,
		const char *name, struct c8ui_rect r) {
	cairo_surface_t *s = url ? sky_image(url) : NULL;
	if (s) {
		c8ui_draw_surface_cover(cr, s, r.x, r.y, r.width, r.height);
		return;
	}
	c8ui_set_source(cr, 0x3a8fd9, 1);
	cairo_rectangle(cr, r.x, r.y, r.width, r.height);
	cairo_fill(cr);
	if (name && name[0]) {
		char letter[8] = "";
		g_unichar_to_utf8(g_unichar_toupper(g_utf8_get_char(name)), letter);
		struct c8ui_font font = { r.height * 0.5, C8UI_WEIGHT_LIGHT };
		double w, h;
		c8ui_text_size(family, font, letter, 0, 1, &w, &h);
		cairo_set_source_rgb(cr, 1, 1, 1);
		c8ui_text_draw(cr, family, font, letter, r.x + (r.width - w) / 2,
			r.y + (r.height - h) / 2, 0, 1);
	}
}

/* Replies, reposts, likes: white glyphs and counts along y; ours filled */
static void counts_row(cairo_t *cr, const char *family, struct sky_post *p,
		double x, double y) {
	const struct { const char *glyph; int n; bool ours; } c[] = {
		{ "reply", p->replies, false },
		{ "repost", p->reposts, p->repost_uri != NULL },
		{ "like", p->likes, p->like_uri != NULL },
	};
	struct c8ui_font font = c8ui_text_font(C8UI_TEXT_BODY_STRONG);
	for (size_t i = 0; i < G_N_ELEMENTS(c); i++) {
		char n[24];
		card_count(c[i].n, n, sizeof(n));
		cairo_set_source_rgb(cr, 1, 1, 1);
		card_glyph(cr, c[i].glyph, x, y + 2, 16, c[i].ours);
		double tw, th;
		c8ui_text_size(family, font, n, 0, 1, &tw, &th);
		c8ui_text_draw(cr, family, font, n, x + 24, y + 10 - th / 2, 0, 1);
		x += 24 + fmax(tw, 18) + 28;
	}
}

/* Who wrote it: a face, the name over "@handle · 4h"; height 40 */
static void byline(cairo_t *cr, const char *family, struct sky_post *p,
		double x, double y, double width) {
	const char *name = sky_shown_name(p->did, p->name && p->name[0] ? p->name :
		p->handle);
	char *age = sky_age(p->date);
	char *by = g_strdup_printf("@%s · %s", sky_shown_handle(p->did, p->handle),
		age);
	char *small_face = sky_avatar_small(sky_shown_avatar(p->did, p->avatar));
	face(cr, family, small_face, name, (struct c8ui_rect){ x, y, 40, 40 });
	g_free(small_face);
	struct c8ui_font strong = c8ui_text_font(C8UI_TEXT_BODY_STRONG);
	struct c8ui_font small = c8ui_text_font(C8UI_TEXT_CAPTION);
	cairo_set_source_rgb(cr, 1, 1, 1);
	c8ui_text_draw(cr, family, strong, name, x + 52, y + 1, width - 52, 1);
	cairo_set_source_rgba(cr, 1, 1, 1, 0.8);
	c8ui_text_draw(cr, family, small, by, x + 52, y + 22, width - 52, 1);
	g_free(by);
	g_free(age);
}

struct paint {
	struct c8ui_widget *w;
	struct sky_post *p;
};

static bool slide_paint(cairo_t *cr, struct c8ui_rect r, void *data) {
	struct paint *a = data;
	const char *family = c8ui_widget_font(a->w);
	struct sky_post *p = a->p;
	sky_image_missed = false;
	cairo_surface_t *img = p && shows_picture(p) ?
		sky_image_large(slide_url(p)) : NULL;
	cairo_save(cr);
	cairo_rectangle(cr, r.x, r.y, r.width, r.height);
	cairo_clip(cr);
	if (img) {
		c8ui_draw_surface_cover(cr, img, r.x, r.y, r.width, r.height);
	} else {
		c8ui_set_source(cr, p && shows_picture(p) ? BAR : BLUE, 1);
		cairo_paint(cr);
	}
	double x = r.x + HERO_PAD, width = r.width - 2 * HERO_PAD;
	if (p == NULL) {
		struct c8ui_font big = { 34, C8UI_WEIGHT_LIGHT };
		cairo_set_source_rgb(cr, 1, 1, 1);
		c8ui_text_draw(cr, family, big, home.timeline &&
			home.timeline->loading ? "Loading…" : "Nothing here yet", x,
			r.y + r.height - 90, width, 1);
		cairo_restore(cr);
		return true;
	}
	/* From the bottom up, as News's tiles: the counts, the whole post
	 * (as much as the lower part holds), who wrote it over the words.
	 * Without a picture the words are the picture: large, from the top. */
	bool words = p->text && p->text[0];
	const char *text = words ? sky_shown_text(p->text) : "";
	double counts_y = r.y + r.height - HERO_PAD - 20;
	double bottom = counts_y - 18; // the words end here
	double tw, th = 0, line;
	if (words && shows_picture(p)) {
		struct c8ui_font font = { r.width > 600 ? 22 : 19,
			C8UI_WEIGHT_SEMILIGHT };
		c8ui_text_size(family, font, "Ag", 0, 1, &tw, &line);
		int lines = (int)floor((r.height * 0.6 - 60) / line);
		lines = lines > 2 ? lines : 2;
		c8ui_text_size(family, font, text, width, lines, &tw, &th);
		/* Dark enough under all the words, however long, over any
		 * picture: clear above them, nearly black at the bottom */
		double top = bottom - th - 56;
		cairo_pattern_t *g = cairo_pattern_create_linear(0, top - 90, 0,
			r.y + r.height);
		cairo_pattern_add_color_stop_rgba(g, 0, 0, 0, 0, 0);
		cairo_pattern_add_color_stop_rgba(g, 90 / (r.y + r.height - top + 90),
			0, 0, 0, 0.7);
		cairo_pattern_add_color_stop_rgba(g, 1, 0, 0, 0, 0.9);
		cairo_set_source(cr, g);
		cairo_paint(cr);
		cairo_pattern_destroy(g);
		cairo_set_source_rgb(cr, 1, 1, 1);
		c8ui_text_draw(cr, family, font, text, x, bottom - th, width, lines);
		byline(cr, family, p, x, bottom - th - 56, width);
	} else {
		if (words) {
			struct c8ui_font font = { r.width > 600 ? 40 : 32,
				C8UI_WEIGHT_LIGHT };
			c8ui_text_size(family, font, "Ag", 0, 1, &tw, &line);
			int lines = (int)floor((bottom - 70 - r.y - HERO_PAD) / line);
			cairo_set_source_rgb(cr, 1, 1, 1);
			c8ui_text_draw(cr, family, font, text, x, r.y + HERO_PAD - 6,
				width, lines > 1 ? lines : 1);
		}
		if (img) {
			shade(cr, r, 0.6, 0.85); // a picture with no words
		}
		byline(cr, family, p, x, bottom - 40, width);
	}
	counts_row(cr, family, p, x, counts_y);
	cairo_restore(cr);
	return !sky_image_missed;
}

static void slide_draw(struct c8ui_widget *w, cairo_t *cr, int slot,
		struct sky_post *p, double dx) {
	char *age = p ? sky_age(p->date) : NULL;
	char *key = g_strdup_printf("%s %s %u %s %d %d %d %d %d %d %d",
		c8ui_widget_font(w), p ? p->uri : "-", p ? p->rev : 0,
		age ? age : "", home.timeline && home.timeline->loading,
		sky_settings.images, sky_settings.sensitive,
		p ? p->replies : 0, p ? p->reposts : 0, p ? p->likes : 0,
		p ? (p->like_uri != NULL) * 2 + (p->repost_uri != NULL) : 0);
	struct c8ui_rect r = w->rect;
	r.x += round(dx);
	struct paint a = { w, p };
	c8ui_kept_draw(&home.kept[slot], cr, r, g_str_hash(key), slide_paint, &a);
	g_free(key);
	g_free(age);
}

static int slide_count(void) {
	return home.slides ? (int)home.slides->len : 0;
}

/* A square button at a side, with a chevron pointing out */
static void arrow_draw(cairo_t *cr, struct c8ui_rect r, int side,
		bool lit) {
	double x = side < 0 ? r.x : r.x + r.width - ARROW;
	double y = r.y + (r.height - ARROW) / 2;
	cairo_set_source_rgba(cr, 0, 0, 0, lit ? 0.7 : 0.45);
	cairo_rectangle(cr, x, y, ARROW, ARROW);
	cairo_fill(cr);
	double cx = x + ARROW / 2, cy = y + ARROW / 2;
	cairo_set_source_rgb(cr, 1, 1, 1);
	cairo_set_line_width(cr, 2);
	cairo_move_to(cr, cx - side * 4, cy - 8);
	cairo_line_to(cr, cx + side * 4, cy);
	cairo_line_to(cr, cx - side * 4, cy + 8);
	cairo_stroke(cr);
}

/* Which arrow x is over: -1, 1, or 0 */
static int arrow_at(struct c8ui_widget *w, double x) {
	if (slide_count() < 2 || !w->hovered) {
		return 0;
	}
	if (x < w->rect.x + ARROW) {
		return -1;
	}
	return x >= w->rect.x + w->rect.width - ARROW ? 1 : 0;
}

static void hero_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct c8ui_rect r = w->rect;
	cairo_save(cr);
	cairo_rectangle(cr, r.x, r.y, r.width, r.height);
	cairo_clip(cr);
	if (home.slide_start >= 0 || home.slid < 1) {
		/* The new one comes in from dir's side, pushing the old out */
		double ease = 1 - pow(1 - home.slid, 3);
		double dx = home.dir * r.width * (1 - ease);
		slide_draw(w, cr, home.cur ^ 1, slide(home.from), dx - home.dir *
			r.width);
		slide_draw(w, cr, home.cur, slide(home.at), dx);
	} else {
		slide_draw(w, cr, home.cur, slide(home.at), 0);
	}
	/* The next one's picture on its way before it is needed */
	struct sky_post *next = slide(home.at + 1);
	if (next && shows_picture(next)) {
		sky_image_large(slide_url(next));
	}
	int n = slide_count();
	if (n > 1) {
		/* Pips at the top right: which of them this is */
		for (int i = 0; i < n; i++) {
			double px = r.x + r.width - HERO_PAD - (n - i) * 14 + 4;
			cairo_rectangle(cr, px, r.y + HERO_PAD - 4, 8, 8);
			cairo_set_source_rgba(cr, 1, 1, 1, i == home.at ? 1 : 0.5);
			cairo_fill_preserve(cr);
			cairo_set_source_rgba(cr, 0, 0, 0, 0.35); // seen on white
			cairo_set_line_width(cr, 1);
			cairo_stroke(cr);
		}
	}
	if (w->hovered && n > 1) {
		int lit = arrow_at(w, home.pointer_x);
		arrow_draw(cr, r, -1, lit < 0);
		arrow_draw(cr, r, 1, lit > 0);
	}
	if (w->pressed && arrow_at(w, home.pointer_x) == 0) {
		c8ui_set_source(cr, 0x000000, 0.15);
		cairo_paint(cr);
	}
	cairo_restore(cr);
	if (c8ui_widget_shows_focus(w)) {
		cairo_set_source_rgb(cr, 1, 1, 1);
		cairo_set_line_width(cr, 2);
		cairo_rectangle(cr, r.x + 5, r.y + 5, r.width - 10, r.height - 10);
		cairo_stroke(cr);
	}
}

static void hero_step(int dir) {
	int n = slide_count();
	if (n < 2 || home.hero == NULL) {
		return;
	}
	home.from = home.at;
	home.at = ((home.at + dir) % n + n) % n;
	home.dir = dir;
	home.cur ^= 1;
	home.slid = 0;
	home.slide_start = -1;
	c8ui_widget_animate(home.hero);
	c8ui_widget_queue_draw(home.hero);
}

static bool hero_tick(struct c8ui_widget *w, int64_t now) {
	if (home.slid >= 1) {
		return false;
	}
	if (home.slide_start < 0) {
		home.slide_start = now;
	}
	home.slid = fmin((double)(now - home.slide_start) / SLIDE_MS, 1);
	if (home.slid >= 1) {
		home.slide_start = -1;
	}
	c8ui_widget_queue_draw(w);
	return home.slid < 1;
}

/* On to the next by itself, but not under the pointer or the keyboard,
 * nor behind a page */
static gboolean hero_turn(gpointer data) {
	struct c8ui_widget *w = home.hero;
	if (w && !w->hovered && !w->focused && g.stack &&
			g.stack->child_count == 1) {
		hero_step(1);
	}
	return G_SOURCE_CONTINUE;
}

static void hero_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	*width = avail;
	*height = 0;
}

static bool hero_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	struct sky_post *p = slide(home.at);
	switch (ev->type) {
	case C8UI_EVENT_MOTION:
		home.pointer_x = ev->x;
		c8ui_widget_queue_draw(w); // the arrows light
		return false;
	case C8UI_EVENT_LEAVE:
		c8ui_widget_queue_draw(w);
		return false;
	case C8UI_EVENT_PRESS:
		home.pointer_x = ev->x;
		if (ev->button == C8UI_BUTTON_RIGHT && p) {
			ui_set_target(p);
			ui_show_bars();
			return true;
		}
		return ev->button == C8UI_BUTTON_LEFT;
	case C8UI_EVENT_RELEASE:
		if (ev->button != C8UI_BUTTON_LEFT ||
				!c8ui_rect_contains(&w->rect, ev->x, ev->y)) {
			return true;
		}
		if (arrow_at(w, ev->x)) {
			hero_step(arrow_at(w, ev->x));
		} else if (p) {
			open_thread(p->uri);
		}
		return true;
	case C8UI_EVENT_KEY:
		if (ev->sym == XKB_KEY_Left || ev->sym == XKB_KEY_Right) {
			if (slide_count() < 2) {
				return false;
			}
			hero_step(ev->sym == XKB_KEY_Left ? -1 : 1);
			return true;
		}
		if (p && (ev->sym == XKB_KEY_Return || ev->sym == XKB_KEY_KP_Enter ||
				ev->sym == XKB_KEY_space)) {
			open_thread(p->uri);
			return true;
		}
		return false;
	default:
		return false;
	}
}

static void hero_destroy(struct c8ui_widget *w) {
	if (home.hero == w) {
		home.hero = NULL;
		c8ui_kept_drop(&home.kept[0]);
		c8ui_kept_drop(&home.kept[1]);
		if (home.timer) {
			g_source_remove(home.timer);
			home.timer = 0;
		}
	}
}

static const struct c8ui_widget_impl hero_impl = {
	.name = "sky-hero",
	.measure = hero_measure,
	.draw = hero_draw,
	.event = hero_event,
	.tick = hero_tick,
	.destroy = hero_destroy,
};

/* Feeds: the pinned ones and lists as tiles, and one for all of them */

static void tile_free(gpointer data) {
	struct tile *t = data;
	g_free(t->uri);
	g_free(t->name);
	g_free(t->avatar);
	g_free(t);
}

static void tile_draw(struct c8ui_widget *list, cairo_t *cr,
		const struct c8ui_list_item *item, void *data) {
	if (home.rows == NULL || item->index >= (int)home.rows->len) {
		return;
	}
	struct tile *t = home.rows->pdata[item->index];
	struct c8ui_rect r = item->rect;
	const char *family = c8ui_widget_font(list);
	cairo_surface_t *s = t->avatar ? sky_image(t->avatar) : NULL;
	cairo_save(cr);
	cairo_rectangle(cr, r.x, r.y, r.width, r.height);
	cairo_clip(cr);
	if (s) {
		c8ui_draw_surface_cover(cr, s, r.x, r.y, r.width, r.height);
		shade(cr, r, 0.4, 0.75);
	} else {
		c8ui_set_source(cr, t->uri == NULL ? BAR : t->list ? BAR_TILE : BLUE,
			1);
		cairo_paint(cr);
	}
	if (item->hovered || item->selected) {
		c8ui_set_source(cr, 0xffffff, item->selected ? 0.25 : 0.12);
		cairo_paint(cr);
	}
	struct c8ui_font font = c8ui_text_font(C8UI_TEXT_BODY_STRONG);
	double tw, th;
	c8ui_text_size(family, font, t->name, r.width - 20, 2, &tw, &th);
	cairo_set_source_rgb(cr, 1, 1, 1);
	c8ui_text_draw(cr, family, font, t->name, r.x + 10,
		r.y + r.height - 10 - th, r.width - 20, 2);
	if (t->list || t->uri == NULL) {
		c8ui_set_source(cr, 0xffffff, 0.75);
		c8ui_text_draw(cr, family, c8ui_text_font(C8UI_TEXT_CAPTION),
			t->uri ? "List" : "Saved and yours", r.x + 10, r.y + 8,
			r.width - 20, 1);
	}
	cairo_restore(cr);
}

static void tile_opened(struct c8ui_widget *list, int index, void *data) {
	if (home.rows == NULL || index < 0 || index >= (int)home.rows->len) {
		return;
	}
	struct tile *t = home.rows->pdata[index];
	c8ui_list_select(list, -1);
	if (t->uri == NULL) {
		open_feeds();
	} else {
		open_feed(t->list ? VIEW_LIST : VIEW_FEED, t->uri, NULL, t->name);
	}
}

static void tiles_make(void) {
	if (home.rows) {
		g_ptr_array_unref(home.rows);
	}
	home.rows = g_ptr_array_new_with_free_func(tile_free);
	for (guint i = 0; g.saved && i < g.saved->len; i++) {
		struct sky_saved *s = g.saved->pdata[i];
		if (!s->pinned || strcmp(s->uri, "following") == 0) {
			continue;
		}
		struct tile *t = g_new0(struct tile, 1);
		t->uri = g_strdup(s->uri);
		t->name = g_strdup(s->name ? s->name : s->list ? "List" : "Feed");
		t->avatar = g_strdup(s->avatar);
		t->list = s->list;
		g_ptr_array_add(home.rows, t);
	}
	struct tile *all = g_new0(struct tile, 1);
	all->name = g_strdup("All feeds");
	g_ptr_array_add(home.rows, all);
}

/* You: who is signed in, and what to do next */

static void you_draw(struct c8ui_widget *w, cairo_t *cr, void *data) {
	if (sky_me == NULL) {
		return;
	}
	struct c8ui_colors c = c8ui_widget_colors(w);
	const char *family = c8ui_widget_font(w);
	struct sky_profile *me = g.me;
	const char *did = sky_me->did;
	const char *name = sky_shown_name(did, me && me->name && me->name[0] ?
		me->name : sky_me->name && sky_me->name[0] ? sky_me->name :
		sky_me->handle);
	const char *handle = sky_shown_handle(did, me ? me->handle :
		sky_me->handle);
	struct c8ui_rect r = w->rect;
	face(cr, family, sky_shown_avatar(did, me ? me->avatar : sky_me->avatar),
		name, (struct c8ui_rect){ r.x, r.y, 120, 120 });
	double y = r.y + 136;
	c8ui_set_source(cr, c.fg, 1);
	c8ui_text_draw(cr, family, c8ui_text_font(C8UI_TEXT_TITLE), name, r.x, y,
		r.width, 1);
	y += 30;
	char *at = g_strconcat("@", handle, NULL);
	c8ui_set_source(cr, c.fg, 0.6);
	c8ui_text_draw(cr, family, c8ui_text_font(C8UI_TEXT_BODY), at, r.x, y,
		r.width, 1);
	g_free(at);
	if (me) {
		y += 32;
		struct c8ui_font big = { 26, C8UI_WEIGHT_LIGHT };
		struct c8ui_font cap = c8ui_text_font(C8UI_TEXT_CAPTION);
		const struct { int n; const char *what; } counts[] = {
			{ me->followers, "followers" }, { me->follows, "following" },
			{ me->posts, "posts" },
		};
		for (int i = 0; i < 3; i++) {
			char n[24];
			card_count(counts[i].n, n, sizeof(n));
			double x = r.x + i * 96;
			c8ui_set_source(cr, c.fg, 1);
			c8ui_text_draw(cr, family, big, n, x, y, 92, 1);
			c8ui_set_source(cr, c.fg, 0.6);
			c8ui_text_draw(cr, family, cap, counts[i].what, x, y + 34, 92, 1);
		}
	}
}

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

static void you_profile(struct c8ui_widget *w, void *data) {
	open_me();
}

static void you_search(struct c8ui_widget *w, void *data) {
	open_search(NULL);
}

static void you_accounts(struct c8ui_widget *w, void *data) {
	ui_home();
	open_accounts();
}

static struct c8ui_widget *you_new(void) {
	struct c8ui_widget *box = c8ui_box_new(C8UI_VERTICAL, 12);
	home.you = c8ui_canvas_new(YOU_W, 262, you_draw, NULL, NULL);
	c8ui_widget_track(home.you, &home.you);
	c8ui_widget_add(box, home.you);
	static const struct { const char *label; c8ui_action_fn fn; } acts[] = {
		{ "New post", you_new_post }, { "Your profile", you_profile },
		{ "Search", you_search }, { "Accounts", you_accounts },
	};
	for (size_t i = 0; i < G_N_ELEMENTS(acts); i++) {
		struct c8ui_widget *b = c8ui_button_new(acts[i].label, acts[i].fn,
			NULL);
		b->fixed_width = 180; // one column of them, alike
		c8ui_button_set_primary(b, i == 0);
		c8ui_widget_add(box, b);
	}
	return box;
}

/* The hub */

static void hub_gone(struct c8ui_widget *w, void *data) {
	if (home.hub == w) {
		home.hub = NULL;
		home.tiles = NULL;
		/* Its list may go with the account (ui_signed_in) */
		home.timeline = NULL;
		g_clear_pointer(&home.slides, g_ptr_array_unref);
	}
}

struct c8ui_widget *home_new(struct feedview *timeline,
		struct feedview *notices) {
	home.timeline = timeline;
	struct c8ui_widget *hub = c8ui_hub_new("Cirrus");
	home.hub = hub;
	hub->on_destroy = hub_gone;

	home.hero = c8ui_widget_new(&hero_impl, NULL);
	home.hero->focusable = true;
	home.hero->cursor = C8UI_CURSOR_POINTER;
	c8ui_hub_add(hub, NULL, home.hero, home_hero_width());
	home.slid = 1;
	home.slide_start = -1;
	hero_pick();
	home.timer = g_timeout_add_seconds(SLIDE_S, hero_turn, NULL);

	/* Following isn't there when the account unpinned it. Narrow, the
	 * pivot calls each section by its name (the hero has none, so it
	 * is left out there). */
	int n = 1;
	if (timeline) {
		c8ui_hub_add(hub, NULL, hub_section_new("Following", open_following,
			view_widget(timeline, SHAPE_COLUMN), true), g.column_w);
		c8ui_hub_set_name(hub, n++, "Following");
	}
	if (notices) {
		c8ui_hub_add(hub, NULL, hub_section_new("Notifications",
			open_notifications, view_widget(notices, SHAPE_COLUMN), true),
			g.column_w);
		c8ui_hub_set_name(hub, n++, "Notifications");
	}

	tiles_make();
	home.tiles = c8ui_list_new(C8UI_LIST_GRID, TILE, TILE, tile_draw, NULL);
	home.tiles->fill = false;
	home.tiles->fixed_width = TILES_W;
	c8ui_list_set_click_opens(home.tiles, true);
	c8ui_list_on_open(home.tiles, tile_opened, NULL);
	c8ui_list_set_count(home.tiles, (int)home.rows->len);
	c8ui_hub_add(hub, NULL, hub_section_new("Feeds", open_feeds, home.tiles, true),
		TILES_W);
	c8ui_hub_set_name(hub, n++, "Feeds");

	c8ui_hub_add(hub, NULL, hub_section_new("You", open_me, you_new(), false),
		YOU_W);
	c8ui_hub_set_name(hub, n++, "You");
	return hub;
}

void home_resized(void) {
	if (home.hub) {
		c8ui_hub_set_width(home.hub, 0, home_hero_width());
	}
}

void home_timeline_loaded(void) {
	hero_pick();
}

/* Pictures came, the minute went by, our profile or stealth changed */
void home_redraw(void) {
	if (home.hero) {
		c8ui_widget_queue_draw(home.hero);
	}
	if (home.tiles) {
		c8ui_widget_queue_draw(home.tiles);
	}
	if (home.you) {
		c8ui_widget_queue_draw(home.you);
	}
}
