#ifndef C8UI_PRIVATE_H
#define C8UI_PRIVATE_H

#include <math.h>
#include <string.h>
#include <time.h>
#include <xkbcommon/xkbcommon-keysyms.h>
#include "c8ui.h"

#define C8UI_DEFAULT_FONT "Selawik, sans-serif"
#define C8UI_DEFAULT_ACCENT 0x1ba1e2
#define C8UI_DEFAULT_BACKGROUND 0x180052

struct c8ui_root {
	const struct c8ui_host_impl *impl;
	void *host;
	struct c8ui_theme theme;
	struct c8ui_widget *child;
	struct c8ui_widget **overlays;
	struct c8ui_widget **saved_focus; // per overlay: focus before it
	bool *popups; // per overlay: it left the focus be
	int overlay_count, overlay_cap;
	double width, height;
	bool needs_layout;
	/* What to draw again: all of it, or these rects (logical pixels).
	 * The host takes it with c8ui_root_take_damage. */
	bool damage_all;
	cairo_region_t *damage;
	c8ui_key_fn key_fn;
	void *key_data;
	c8ui_resize_fn resize_fn;
	void *resize_data;

	double px, py;
	uint32_t mods; // held now, for presses: c8ui_root_set_mods
	bool pointer_in;
	struct c8ui_widget *hover, *grab, *focus;
	int grab_buttons;
	/* Fingers taken by a widget, and the one acting as the mouse */
	struct {
		int32_t id;
		struct c8ui_widget *owner; // NULL: a free slot
		double x, y; // where it is now
	} touches[10];
	int32_t touch_mouse; // -1 for none
	double mouse_x, mouse_y; // where that finger is now
	/* Two fingers on the screen pinching: they go to root->pinch as
	 * PINCH_* events, not as touches. A finger left when the other
	 * lifts is ignored until it lifts too. */
	struct {
		bool on;
		int32_t id[2];
		double x[2], y[2];
		double d0, mx, my; // their gap at the start, the last midpoint
		int32_t leftover; // -1 for none
	} tpinch;
	struct c8ui_widget *swipe; // took the touchpad swipe going on
	int swipe_fingers;
	struct c8ui_widget *pinch; // and the pinch
	int pinch_fingers;
	bool focus_visible, keyboard_focused;
	enum c8ui_cursor cursor;

	struct c8ui_widget **ticking;
	int tick_count, tick_cap;
	int64_t now;

	/* Widgets destroyed while events were being handled: freed once
	 * that's over, as code up the stack may still hold them */
	int dispatching;
	struct c8ui_widget **graveyard;
	int grave_count, grave_cap;

	/* Widgets that live as long as the root without being in its tree
	 * all the time (the app bar) */
	struct c8ui_widget **kept;
	int kept_count, kept_cap;

	/* The tooltip of what the pointer rests on: waiting, then shown */
	struct c8ui_widget *tip_owner;
	void *tip_timer;
	bool tip_shown;
	double tip_x, tip_y;

	/* The back button that Alt+Left and the mouse's back button press */
	struct c8ui_widget *back;

	/* A popup closed by a press outside it: the press goes on to what is
	 * under it */
	bool repress;
};

void c8ui_root_show_focus(struct c8ui_root *root, bool visible);
void c8ui_dispatch_begin(struct c8ui_root *root);
void c8ui_dispatch_end(struct c8ui_root *root);
/* A finger dragging along one axis, for widgets that pan (see core.c).
 * Pass every touch event; pass TOUCH_DOWN only when the widget would
 * pan now. Taps become clicks and holds right clicks by themselves. */
enum c8ui_drag_state {
	C8UI_DRAG_IGNORED, // not taken: return false
	C8UI_DRAG_TAKEN, // the finger is ours, nothing to do yet
	C8UI_DRAG_START, // it set off along the axis: delta is how far
	C8UI_DRAG_MOVE,
	C8UI_DRAG_END, // lifted; velocity is its speed (px/ms, 0: stopped)
	C8UI_DRAG_CANCEL,
};

struct c8ui_drag {
	enum c8ui_orientation axis;
	bool down, active, held;
	int32_t id;
	double x0, y0;
	double delta; // along the axis from where it landed; + right or down
	double velocity;
	/* both: pans either way (never handed off); dx, dy and their speeds
	 * are kept whatever the axis */
	bool both;
	double dx, dy, vx, vy;
	double last_x, last_y;
	double last;
	uint32_t last_time;
	void *hold;
	struct c8ui_root *hold_root;
};

enum c8ui_drag_state c8ui_drag_touch(struct c8ui_widget *w,
	struct c8ui_drag *d, const struct c8ui_event *ev);
/* Stops its timer: call from destroy */
void c8ui_drag_finish(struct c8ui_drag *d);

/* Touchpad kinetic scrolling (core.c), for widgets that scroll by SCROLL
 * events: give it every precise one (c8ui_pad_reset for a wheel click), and
 * at SCROLL_STOP c8ui_pad_lift says whether the fingers left at speed and
 * the speed (px/ms, 0 along an axis that is too slow); c8ui_pad_distance is
 * how far to scroll on. */
struct c8ui_pad {
	double vx, vy;
	int64_t last; // ms of the last scroll, 0: none
};
void c8ui_pad_reset(struct c8ui_pad *pad);
void c8ui_pad_sample(struct c8ui_pad *pad, double dx, double dy);
bool c8ui_pad_lift(struct c8ui_pad *pad, double *vx, double *vy);
double c8ui_pad_distance(double v);

/* The back button (forms.c) registers itself; core presses it */
void c8ui_root_set_back(struct c8ui_root *root, struct c8ui_widget *back);
void c8ui_back_activate(struct c8ui_widget *back);

/* An overlay that leaves the keyboard focus where it is (keys go to the
 * overlay first, which passes on what it doesn't use), as for suggestions
 * under an entry. Removed like any overlay. */
void c8ui_root_push_popup(struct c8ui_root *root, struct c8ui_widget *popup);
/* From a popup's PRESS outside it, before it closes: the press is then
 * given again to whatever is under the pointer */
void c8ui_root_repress(struct c8ui_root *root);

void c8ui_root_keep(struct c8ui_root *root, struct c8ui_widget *w);
void c8ui_root_unkeep(struct c8ui_root *root, struct c8ui_widget *w);

/* Small things several widget files want */

static inline int64_t c8ui_now_ms(void) {
	struct timespec ts;
	clock_gettime(CLOCK_MONOTONIC, &ts);
	return (int64_t)ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
}

/* Metro's cubic ease out, t clamped to 0..1 */
static inline double c8ui_ease_out(double t) {
	t = t < 0 ? 0 : t > 1 ? 1 : t;
	return 1 - pow(1 - t, 3);
}

/* A second click this soon after the first is a double click */
#define C8UI_MULTI_CLICK_MS 400

/* The line of text over a control that says what it is */
#define C8UI_HEADER_GAP 6

static inline double c8ui_header_height(struct c8ui_widget *w,
		const char *header, double avail, double *width) {
	double tw = 0, th;
	if (width) {
		*width = 0;
	}
	if (header == NULL || header[0] == '\0') {
		return 0;
	}
	c8ui_text_size(c8ui_widget_font(w), c8ui_text_font(C8UI_TEXT_BODY),
		header, avail, 0, &tw, &th);
	if (width) {
		*width = tw;
	}
	return th + C8UI_HEADER_GAP;
}

static inline void c8ui_header_draw(struct c8ui_widget *w, cairo_t *cr,
		const char *header, double alpha) {
	if (header == NULL || header[0] == '\0') {
		return;
	}
	struct c8ui_colors c = c8ui_widget_colors(w);
	c8ui_set_source(cr, c.fg, alpha);
	c8ui_text_draw(cr, c8ui_widget_font(w), c8ui_text_font(C8UI_TEXT_BODY),
		header, w->rect.x, w->rect.y, w->rect.width + 1, 0);
}

/* Space or Enter: the keys that press what has the focus */
static inline bool c8ui_activates(const struct c8ui_event *ev) {
	return ev->type == C8UI_EVENT_KEY && (ev->mods & ~C8UI_MOD_SHIFT) == 0 &&
		(ev->sym == XKB_KEY_space || ev->sym == XKB_KEY_Return ||
		ev->sym == XKB_KEY_KP_Enter);
}

/* What a push button does with input: a left press takes the pointer, a
 * release over it activates, and so do Space and Enter. Nothing here
 * touches w after activate, which may have destroyed it. Hover and
 * press need no redraw from the widget: the root draws it again when
 * either changes. */
static inline bool c8ui_push_event(struct c8ui_widget *w,
		const struct c8ui_event *ev,
		void (*activate)(struct c8ui_widget *w)) {
	switch (ev->type) {
	case C8UI_EVENT_PRESS:
		return ev->button == C8UI_BUTTON_LEFT;
	case C8UI_EVENT_RELEASE:
		if (c8ui_rect_contains(&w->rect, ev->x, ev->y)) {
			activate(w);
		}
		return true;
	case C8UI_EVENT_KEY:
		if (c8ui_activates(ev)) {
			activate(w);
			return true;
		}
		return false;
	default:
		return false;
	}
}

static inline void c8ui_stroke_rect(cairo_t *cr, double x, double y, double w,
		double h, double line) {
	cairo_set_line_width(cr, line);
	cairo_rectangle(cr, x + line / 2, y + line / 2, w - line, h - line);
	cairo_stroke(cr);
}

/* The keyboard's focus ring: a dotted hairline along the rect, in the
 * colour that is the source */
static inline void c8ui_dotted_rect(cairo_t *cr, double x, double y, double w,
		double h) {
	double dash = 1;
	cairo_set_line_width(cr, 1);
	cairo_set_dash(cr, &dash, 1, 0);
	cairo_rectangle(cr, x, y, w, h);
	cairo_stroke(cr);
	cairo_set_dash(cr, NULL, 0, 0);
}

/* Which of a widget's items the pointer is over (-1: none) */
static inline void c8ui_hover_item(struct c8ui_widget *w, int *hover, int i) {
	if (i != *hover) {
		*hover = i;
		c8ui_widget_queue_draw(w);
	}
}

/* A button's face (no label): the accent when it is the primary one or
 * switched on, inverted while held, else a framed fill. Returns the
 * colour its text takes. */
static inline uint32_t c8ui_button_face(struct c8ui_widget *w, cairo_t *cr,
		bool accent) {
	struct c8ui_colors c = c8ui_widget_colors(w);
	struct c8ui_rect r = w->rect;
	bool down = w->pressed && w->hovered;
	uint32_t text = c.fg;
	if (accent) {
		c8ui_set_source(cr, down ? c8ui_shade(c.accent, 0.8) :
			w->hovered ? c8ui_shade(c.accent, 1.15) : c.accent, 1);
		cairo_rectangle(cr, r.x, r.y, r.width, r.height);
		cairo_fill(cr);
		text = 0xffffff;
	} else if (down) {
		c8ui_set_source(cr, c.fg, 1);
		cairo_rectangle(cr, r.x, r.y, r.width, r.height);
		cairo_fill(cr);
		text = c.bg;
	} else {
		c8ui_set_source(cr, c.fg, w->hovered ? c.fill * 1.6 : c.fill);
		cairo_rectangle(cr, r.x, r.y, r.width, r.height);
		cairo_fill(cr);
		c8ui_set_source(cr, c.fg, w->hovered ? c.border_hover : c.border);
		c8ui_stroke_rect(cr, r.x, r.y, r.width, r.height, 2);
	}
	return text;
}

static inline char *c8ui_dup_or_null(const char *s) {
	return s && s[0] ? strdup(s) : NULL;
}

static inline struct c8ui_widget *c8ui_first_focusable(struct c8ui_widget *w) {
	if (w->hidden || w->disabled) {
		return NULL;
	}
	if (w->focusable) {
		return w;
	}
	for (int i = 0; i < w->child_count; i++) {
		struct c8ui_widget *f = c8ui_first_focusable(w->children[i]);
		if (f) {
			return f;
		}
	}
	return NULL;
}

/* The icon as a glyph: its shape, size px, filled with one colour */
static inline void c8ui_icon_draw_tinted(cairo_t *cr, struct c8ui_icon *icon,
		double cx, double cy, double size, uint32_t color, double alpha) {
	cairo_push_group(cr);
	c8ui_icon_draw_fit(cr, icon, cx, cy, size);
	cairo_pattern_t *mask = cairo_pop_group(cr);
	c8ui_set_source(cr, color, alpha);
	cairo_mask(cr, mask);
	cairo_pattern_destroy(mask);
}

#endif
