#define _GNU_SOURCE
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <xkbcommon/xkbcommon.h>
#include "c8ui-private.h"

/* The nav bar: the app bar's twin along the top of the window, holding the
 * places of the app (sections, not commands) as squares with a label. Too
 * many for the width and it pages sideways. Like the app bar it is an
 * overlay while shown, so a click anywhere else only closes it. */

#define BAR_HEIGHT 120
#define ITEM_WIDTH 112
#define BOX 56
#define GLYPH 28
#define RING 2
#define EDGE 36 // the paging arrows' width
#define SLIDE_MS 200
#define DRAG_START 8
#define BAR_COLOR 0x1d1d1d
#define TILE 100 // a place as a filled square, with c8ui_navbar_set_colors

struct item {
	char *label;
	struct c8ui_icon *icon;
};

struct navbar {
	struct c8ui_root *root;
	struct item *items;
	int count, cap;
	int current; // the place the app is at
	int cursor; // the keyboard's
	int hover, pressed;
	bool keyboard;
	double offset, target; // sideways scroll
	double press_x, press_offset;
	bool dragging;
	c8ui_navbar_fn fn;
	void *data;
	uint32_t bar_color, tile_color;
	bool tiles; // places as filled squares, the label inside

	bool shown, closing;
	int64_t start;
	double from, shown_frac;
};

static double content_width(struct navbar *n) {
	return n->count * ITEM_WIDTH;
}

static double max_offset(struct c8ui_widget *w) {
	struct navbar *n = w->data;
	double over = content_width(n) - (w->rect.width - 2 * EDGE);
	return over > 0 ? over : 0;
}

/* Where the items start: centred when they all fit */
static double items_x(struct c8ui_widget *w) {
	struct navbar *n = w->data;
	double room = w->rect.width - 2 * EDGE;
	if (content_width(n) <= room) {
		return w->rect.x + EDGE + (room - content_width(n)) / 2;
	}
	return w->rect.x + EDGE - n->offset;
}

static double bar_top(struct c8ui_widget *w) {
	struct navbar *n = w->data;
	return w->rect.y - BAR_HEIGHT * (1 - n->shown_frac);
}

static int item_at(struct c8ui_widget *w, double x, double y) {
	struct navbar *n = w->data;
	double top = bar_top(w);
	if (y < top || y > top + BAR_HEIGHT || x < w->rect.x + EDGE ||
			x > w->rect.x + w->rect.width - EDGE) {
		return -1;
	}
	int i = (int)floor((x - items_x(w)) / ITEM_WIDTH);
	return i >= 0 && i < n->count ? i : -1;
}

static void scroll_to(struct c8ui_widget *w, double offset) {
	struct navbar *n = w->data;
	double max = max_offset(w);
	n->target = offset < 0 ? 0 : offset > max ? max : offset;
	c8ui_widget_animate(w);
}

static void reveal_item(struct c8ui_widget *w, int i) {
	struct navbar *n = w->data;
	double room = w->rect.width - 2 * EDGE;
	if (i * ITEM_WIDTH < n->target) {
		scroll_to(w, i * ITEM_WIDTH);
	} else if ((i + 1) * ITEM_WIDTH > n->target + room) {
		scroll_to(w, (i + 1) * ITEM_WIDTH - room);
	}
}

static void arrow(cairo_t *cr, double x, double y, bool left, bool hot) {
	c8ui_set_source(cr, 0xffffff, hot ? 1 : 0.7);
	cairo_set_line_width(cr, 2);
	double d = left ? -1 : 1;
	cairo_move_to(cr, x - d * 5, y - 10);
	cairo_line_to(cr, x + d * 5, y);
	cairo_line_to(cr, x - d * 5, y + 10);
	cairo_stroke(cr);
}

/* A place as a tile in the app's colours: the current one white, the
 * glyph above and the label in its bottom left corner */
static void draw_tile(struct c8ui_widget *w, cairo_t *cr, struct item *it,
		double x, double y, bool on, bool down, bool hover, bool cursor) {
	struct navbar *n = w->data;
	uint32_t fill = on ? 0xffffff : down ? c8ui_shade(n->tile_color, 0.8) :
		hover ? c8ui_shade(n->tile_color, 1.2) : n->tile_color;
	uint32_t ink = on ? n->bar_color : 0xffffff;
	c8ui_set_source(cr, fill, 1);
	cairo_rectangle(cr, x, y, TILE, TILE);
	cairo_fill(cr);
	const char *family = c8ui_widget_font(w);
	if (it->icon) {
		c8ui_icon_draw_tinted(cr, it->icon, x + TILE / 2.0,
			y + TILE / 2.0 - 10, GLYPH, ink, 1);
	}
	struct c8ui_font font = { 12, C8UI_WEIGHT_SEMIBOLD };
	double tw, th;
	c8ui_text_size(family, font, it->label, TILE - 16, 1, &tw, &th);
	c8ui_set_source(cr, ink, 1);
	c8ui_text_draw(cr, family, font, it->label, x + 8, y + TILE - 8 - th,
		TILE - 16, 1);
	if (cursor) {
		c8ui_set_source(cr, 0xffffff, 1);
		c8ui_dotted_rect(cr, x - 3.5, y - 3.5, TILE + 7, TILE + 7);
	}
}

static void bar_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct navbar *n = w->data;
	double top = bar_top(w);
	struct c8ui_font font = c8ui_text_font(C8UI_TEXT_CAPTION);
	c8ui_set_source(cr, n->bar_color, 1);
	cairo_rectangle(cr, w->rect.x, top, w->rect.width, BAR_HEIGHT);
	cairo_fill(cr);

	cairo_save(cr);
	cairo_rectangle(cr, w->rect.x + EDGE, top, w->rect.width - 2 * EDGE,
		BAR_HEIGHT);
	cairo_clip(cr);
	double x0 = items_x(w);
	for (int i = 0; i < n->count; i++) {
		struct item *it = &n->items[i];
		double x = x0 + i * ITEM_WIDTH;
		if (x + ITEM_WIDTH < w->rect.x || x > w->rect.x + w->rect.width) {
			continue;
		}
		double bx = x + (ITEM_WIDTH - BOX) / 2, by = top + 14;
		bool down = i == n->pressed && i == n->hover;
		bool on = i == n->current;
		if (n->tiles) {
			draw_tile(w, cr, it, x + (ITEM_WIDTH - TILE) / 2.0,
				top + (BAR_HEIGHT - TILE) / 2.0, on, down, i == n->hover,
				n->keyboard && i == n->cursor);
			continue;
		}
		cairo_rectangle(cr, bx, by, BOX, BOX);
		if (on || down) {
			c8ui_set_source(cr, 0xffffff, down && !on ? 0.8 : 1);
			cairo_fill(cr);
		} else if (i == n->hover) {
			c8ui_set_source(cr, 0xffffff, 0.15);
			cairo_fill(cr);
		}
		c8ui_set_source(cr, 0xffffff, 1);
		cairo_set_line_width(cr, RING);
		cairo_rectangle(cr, bx + RING / 2.0, by + RING / 2.0, BOX - RING,
			BOX - RING);
		cairo_stroke(cr);
		uint32_t glyph = on || down ? n->bar_color : 0xffffff;
		if (it->icon) {
			c8ui_icon_draw_tinted(cr, it->icon, bx + BOX / 2.0,
				by + BOX / 2.0, GLYPH, glyph, 1);
		} else if (it->label[0]) {
			char first[8] = { 0 };
			size_t len = 1;
			while (it->label[len] && ((unsigned char)it->label[len] & 0xc0) ==
					0x80) {
				len++;
			}
			memcpy(first, it->label, len < sizeof(first) ? len : 7);
			struct c8ui_font f = c8ui_text_font(C8UI_TEXT_TITLE);
			double tw, th;
			c8ui_text_size(c8ui_widget_font(w), f, first, 0, 0, &tw, &th);
			c8ui_set_source(cr, glyph, 1);
			c8ui_text_draw(cr, c8ui_widget_font(w), f, first,
				bx + (BOX - tw) / 2, by + (BOX - th) / 2, 0, 0);
		}
		double tw, th;
		c8ui_text_size(c8ui_widget_font(w), font, it->label, ITEM_WIDTH - 8, 2,
			&tw, &th);
		c8ui_set_source(cr, 0xffffff, 1);
		c8ui_text_draw(cr, c8ui_widget_font(w), font, it->label,
			x + (ITEM_WIDTH - tw) / 2, by + BOX + 6, ITEM_WIDTH - 8, 2);
		if (n->keyboard && i == n->cursor) {
			c8ui_set_source(cr, 0xffffff, 1);
			c8ui_dotted_rect(cr, bx - 3.5, by - 3.5, BOX + 7, BOX + 7);
		}
	}
	cairo_restore(cr);

	/* Paging arrows, when there is more than shows */
	if (max_offset(w) > 0) {
		if (n->target > 0.5) {
			arrow(cr, w->rect.x + EDGE / 2.0, top + 14 + BOX / 2.0, true,
				n->hover == -2);
		}
		if (n->target < max_offset(w) - 0.5) {
			arrow(cr, w->rect.x + w->rect.width - EDGE / 2.0, top + 14 + BOX / 2.0,
				false, n->hover == -3);
		}
	}
}

static void finish_hide(struct c8ui_widget *w) {
	struct navbar *n = w->data;
	n->shown = n->closing = false;
	c8ui_root_remove_overlay(n->root, w);
}

static bool bar_tick(struct c8ui_widget *w, int64_t now) {
	struct navbar *n = w->data;
	bool more = false;
	if (n->shown) {
		if (n->start == 0) {
			n->start = now;
		}
		double t = (double)(now - n->start) / SLIDE_MS;
		t = t > 1 ? 1 : t;
		double e = c8ui_ease_out(t);
		n->shown_frac = n->from + ((n->closing ? 0 : 1) - n->from) * e;
		if (t >= 1 && n->closing) {
			finish_hide(w);
			return false;
		}
		more = t < 1;
	}
	if (fabs(n->target - n->offset) > 0.5) {
		n->offset += (n->target - n->offset) * 0.3;
		more = true;
	} else {
		n->offset = n->target;
	}
	c8ui_widget_queue_draw(w);
	return more;
}

static void choose(struct c8ui_widget *w, int i) {
	struct navbar *n = w->data;
	if (i < 0 || i >= n->count) {
		return;
	}
	n->current = i;
	c8ui_navbar_fn fn = n->fn;
	void *data = n->data;
	c8ui_navbar_hide(w);
	if (fn) {
		fn(w, i, data);
	}
}

static bool bar_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	struct navbar *n = w->data;
	double top = bar_top(w);
	switch (ev->type) {
	case C8UI_EVENT_MOTION: {
		int i = item_at(w, ev->x, ev->y);
		if (max_offset(w) > 0 && ev->y >= top && ev->y <= top + BAR_HEIGHT) {
			if (ev->x < w->rect.x + EDGE) {
				i = -2;
			} else if (ev->x > w->rect.x + w->rect.width - EDGE) {
				i = -3;
			}
		}
		if (n->pressed >= 0 || n->dragging) {
			if (!n->dragging && fabs(ev->x - n->press_x) > DRAG_START &&
					max_offset(w) > 0) {
				n->dragging = true;
				n->pressed = -1;
			}
			if (n->dragging) {
				n->offset = n->target = fmax(0, fmin(max_offset(w),
					n->press_offset - (ev->x - n->press_x)));
				c8ui_widget_queue_draw(w);
			}
		}
		if (i != n->hover) {
			n->hover = i;
			n->keyboard = false;
			c8ui_widget_queue_draw(w);
		}
		return true;
	}
	case C8UI_EVENT_LEAVE:
		n->hover = -1;
		c8ui_widget_queue_draw(w);
		return false;
	case C8UI_EVENT_PRESS:
		/* Light dismiss: a click below the bar only closes it */
		if (ev->y > top + BAR_HEIGHT || ev->y < top) {
			c8ui_navbar_hide(w);
			return true;
		}
		if (ev->button != C8UI_BUTTON_LEFT) {
			return true;
		}
		n->press_x = ev->x;
		n->press_offset = n->offset;
		n->dragging = false;
		if (max_offset(w) > 0 && ev->x < w->rect.x + EDGE) {
			scroll_to(w, n->target - (w->rect.width - 2 * EDGE));
			return true;
		}
		if (max_offset(w) > 0 && ev->x > w->rect.x + w->rect.width - EDGE) {
			scroll_to(w, n->target + (w->rect.width - 2 * EDGE));
			return true;
		}
		n->pressed = item_at(w, ev->x, ev->y);
		c8ui_widget_queue_draw(w);
		return true;
	case C8UI_EVENT_RELEASE: {
		int i = n->pressed;
		n->pressed = -1;
		bool was_drag = n->dragging;
		n->dragging = false;
		c8ui_widget_queue_draw(w);
		if (!was_drag && i >= 0 && item_at(w, ev->x, ev->y) == i) {
			choose(w, i);
		}
		return true;
	}
	case C8UI_EVENT_TOUCH_DOWN:
		if (ev->y > top + BAR_HEIGHT || ev->y < top) {
			c8ui_navbar_hide(w);
			return true;
		}
		return false; // a finger on the bar acts as the mouse
	case C8UI_EVENT_SCROLL: {
		double d = fabs(ev->dx) > fabs(ev->dy) ? ev->dx : ev->dy;
		if (max_offset(w) > 0) {
			if (ev->precise) {
				n->offset = n->target = fmax(0, fmin(max_offset(w),
					n->offset + d));
				c8ui_widget_queue_draw(w);
			} else {
				scroll_to(w, n->target + (d > 0 ? 1 : -1) * ITEM_WIDTH * 2);
			}
		}
		return true;
	}
	case C8UI_EVENT_KEY:
		if (ev->sym == XKB_KEY_Escape) {
			c8ui_navbar_hide(w);
			return true;
		}
		if (n->count == 0) {
			return false;
		}
		if (n->cursor < 0 || n->cursor >= n->count) {
			n->cursor = n->current >= 0 ? n->current : 0;
		}
		switch (ev->sym) {
		case XKB_KEY_Left:
		case XKB_KEY_Right:
			n->cursor = (n->cursor + n->count +
				(ev->sym == XKB_KEY_Right ? 1 : -1)) % n->count;
			break;
		case XKB_KEY_Home:
			n->cursor = 0;
			break;
		case XKB_KEY_End:
			n->cursor = n->count - 1;
			break;
		case XKB_KEY_Return:
		case XKB_KEY_KP_Enter:
		case XKB_KEY_space:
			choose(w, n->cursor);
			return true;
		default:
			return false;
		}
		n->keyboard = true;
		reveal_item(w, n->cursor);
		c8ui_widget_queue_draw(w);
		return true;
	default:
		return false;
	}
}

static void bar_destroy(struct c8ui_widget *w) {
	struct navbar *n = w->data;
	c8ui_root_unkeep(n->root, w);
	for (int i = 0; i < n->count; i++) {
		free(n->items[i].label);
		c8ui_icon_destroy(n->items[i].icon);
	}
	free(n->items);
	free(n);
}

static const struct c8ui_widget_impl bar_impl = {
	.name = "navbar",
	.draw = bar_draw,
	.event = bar_event,
	.tick = bar_tick,
	.destroy = bar_destroy,
};

struct c8ui_widget *c8ui_navbar_new(struct c8ui_root *root, c8ui_navbar_fn fn,
		void *data) {
	struct navbar *n = calloc(1, sizeof(*n));
	n->root = root;
	n->fn = fn;
	n->data = data;
	n->current = n->cursor = n->hover = n->pressed = -1;
	n->bar_color = BAR_COLOR;
	struct c8ui_widget *w = c8ui_widget_new(&bar_impl, n);
	w->scheme = C8UI_SCHEME_DARK;
	c8ui_root_keep(root, w);
	return w;
}

int c8ui_navbar_add(struct c8ui_widget *w, const char *icon, const char *label) {
	struct navbar *n = w->data;
	if (n->count == n->cap) {
		n->cap = n->cap ? n->cap * 2 : 8;
		n->items = realloc(n->items, sizeof(*n->items) * n->cap);
	}
	n->items[n->count].label = strdup(label ? label : "");
	n->items[n->count].icon = icon ? c8ui_icon_load(NULL, icon) : NULL;
	c8ui_widget_queue_draw(w);
	return n->count++;
}

void c8ui_navbar_set_colors(struct c8ui_widget *w, uint32_t bar,
		uint32_t tile) {
	struct navbar *n = w->data;
	n->bar_color = bar;
	n->tile_color = tile;
	n->tiles = true;
	c8ui_widget_queue_draw(w);
}

void c8ui_navbar_set_current(struct c8ui_widget *w, int index) {
	struct navbar *n = w->data;
	n->current = index >= 0 && index < n->count ? index : -1;
	c8ui_widget_queue_draw(w);
}

int c8ui_navbar_get_current(struct c8ui_widget *w) {
	return ((struct navbar *)w->data)->current;
}

void c8ui_navbar_show(struct c8ui_widget *w) {
	struct navbar *n = w->data;
	if (n->shown && !n->closing) {
		return;
	}
	if (!n->shown) {
		n->shown = true;
		n->shown_frac = 0;
		n->hover = n->pressed = -1;
		n->keyboard = false;
		c8ui_root_push_overlay(n->root, w);
		if (n->current >= 0) {
			n->cursor = n->current;
		}
	}
	n->from = n->shown_frac;
	n->closing = false;
	n->start = 0;
	c8ui_widget_animate(w);
}

void c8ui_navbar_hide(struct c8ui_widget *w) {
	struct navbar *n = w->data;
	if (!n->shown || n->closing) {
		return;
	}
	n->from = n->shown_frac;
	n->closing = true;
	n->start = 0;
	c8ui_widget_animate(w);
}

void c8ui_navbar_toggle(struct c8ui_widget *w) {
	if (c8ui_navbar_is_shown(w)) {
		c8ui_navbar_hide(w);
	} else {
		c8ui_navbar_show(w);
	}
}

bool c8ui_navbar_is_shown(struct c8ui_widget *w) {
	struct navbar *n = w->data;
	return n->shown && !n->closing;
}
