/*
 * The split moving: when the two apps sharing the screen swap sides or
 * the split between them moves (and when one is snapped, dropped,
 * left alone or closed), each app's last picture is held still (a
 * frame: a scene buffer of the buffer it last showed, kept locked so
 * its new frames can't draw into it) and stretched from its old box to
 * its new one while the app itself is hidden and redraws at its new
 * size. Once the move is over and the app has drawn at that size (or
 * WAIT_MS), the app is shown again under its frame, which fades out.
 * An app with nothing to hold (no buffer) is cropped to its moving box
 * instead. An app that leaves the layout (another takes all of the
 * screen) stays under the others as a frame until the move is over;
 * one that closed fades out meanwhile.
 * Tried and dropped (2026-12-03): covers of the app's colour and icon,
 * Windows 8's way, felt disorienting; cropping the live apps alone
 * still jumped when they redrew.
 */
#include <math.h>
#include "server.h"

#define MOVE_MS 250 // as the shell's pick moves with it
#define WAIT_MS 400 // after the move, at most, for the apps to catch up
#define FADE_MS 150 // the held picture fading into the new one
#define TICK_MS 8

static double decelerate(double t) {
	t = t < 0 ? 0 : t > 1 ? 1 : t;
	return 1 - (1 - t) * (1 - t) * (1 - t);
}

static int lerp(int a, int b, double t) {
	return a + (int)lround((b - a) * t);
}

static struct wlr_box lerp_box(const struct wlr_box *a,
		const struct wlr_box *b, double t) {
	return (struct wlr_box){
		lerp(a->x, b->x, t), lerp(a->y, b->y, t),
		lerp(a->width, b->width, t), lerp(a->height, b->height, t),
	};
}

static struct wlr_surface *main_surface(struct c8_view *view) {
	return view->toplevel ? view->toplevel->base->surface :
		view->impl->get_surface(view);
}

/* What the app has drawn: its window geometry, in its surface's
 * coordinates */
static struct wlr_box drawn(struct c8_view *view) {
	if (view->toplevel) {
		return view->toplevel->base->geometry;
	}
	struct wlr_surface *s = view->impl->get_surface(view);
	return (struct wlr_box){ 0, 0, s ? s->current.width : 0,
		s ? s->current.height : 0 };
}

static void frame_place(struct wlr_scene_buffer *frame,
		const struct wlr_box *b) {
	wlr_scene_node_set_position(&frame->node, b->x, b->y);
	wlr_scene_buffer_set_dest_size(frame, b->width > 0 ? b->width : 1,
		b->height > 0 ? b->height : 1);
}

/* The app's last picture, its window geometry's part of it, at box */
static struct wlr_scene_buffer *frame_create(struct c8_server *server,
		struct c8_view *view, const struct wlr_box *box) {
	struct wlr_surface *s = main_surface(view);
	if (s == NULL || s->buffer == NULL || s->current.width <= 0 ||
			s->current.height <= 0) {
		return NULL;
	}
	struct wlr_buffer *buffer = &s->buffer->base;
	struct wlr_scene_buffer *frame =
		wlr_scene_buffer_create(server->tween.tree, buffer);
	if (frame == NULL) {
		return NULL;
	}
	struct wlr_box g = drawn(view);
	if (wlr_box_empty(&g)) {
		g = (struct wlr_box){ 0, 0, s->current.width, s->current.height };
	}
	double sx = (double)buffer->width / s->current.width;
	double sy = (double)buffer->height / s->current.height;
	struct wlr_fbox src = { g.x * sx, g.y * sy, g.width * sx,
		g.height * sy };
	wlr_scene_buffer_set_source_box(frame, &src);
	frame_place(frame, box);
	return frame;
}

static void frame_destroy(struct wlr_scene_buffer **frame) {
	if (*frame) {
		wlr_scene_node_destroy(&(*frame)->node);
		*frame = NULL;
	}
}

/* No picture to hold: the live app cropped to b, against the edge that
 * stays put */
static void place_view(struct c8_tween_cover *c, const struct wlr_box *b) {
	struct c8_view *view = c->view;
	if (view == NULL || !view->mapped) {
		return;
	}
	struct wlr_box g = drawn(view);
	int x = c->anchor_right ? b->x + b->width - g.width : b->x;
	int y = b->y;
	wlr_scene_node_set_position(&view->tree->node, x - g.x, y - g.y);
	struct wlr_box clip = { g.x + b->x - x, g.y + b->y - y, b->width,
		b->height };
	wlr_scene_subsurface_tree_set_clip(&view->tree->node, &clip);
}

/* Where everything is at t (0..1 of the move) */
static void place(struct c8_server *server, double t) {
	struct c8_tween *tw = &server->tween;
	for (int i = 0; i < tw->count; i++) {
		struct c8_tween_cover *c = &tw->covers[i];
		if (c->hidden) {
			continue;
		}
		struct wlr_box b = lerp_box(&c->from, &c->to, t);
		if (c->frame) {
			frame_place(c->frame, &b);
			wlr_scene_buffer_set_opacity(c->frame, c->view ? 1 : 1 - t);
		} else {
			place_view(c, &b);
		}
	}
	for (int i = 0; i < tw->leave_count; i++) {
		struct c8_tween_leave *l = &tw->leave[i];
		wlr_scene_buffer_set_opacity(l->frame, l->fade ? 1 - t : 1);
	}
	/* A divider that wasn't there comes once the apps are in place */
	if (!wlr_box_empty(&tw->div_to)) {
		bool from = !wlr_box_empty(&tw->div_from);
		struct wlr_box b = lerp_box(from ? &tw->div_from : &tw->div_to,
			&tw->div_to, t);
		wlr_scene_node_set_position(&server->divider->node, b.x, b.y);
		wlr_scene_node_set_enabled(&server->divider->node, from || t >= 1);
	}
}

/* Each app has drawn at the size it was given */
static bool caught_up(struct c8_tween *tw) {
	for (int i = 0; i < tw->count; i++) {
		struct c8_view *view = tw->covers[i].view;
		if (view == NULL || !view->mapped || tw->covers[i].hidden) {
			continue;
		}
		struct wlr_box g = drawn(view);
		if (g.width != tw->covers[i].to.width ||
				g.height != tw->covers[i].to.height) {
			return false;
		}
	}
	return true;
}

static void drop_leaving(struct c8_tween *tw) {
	for (int i = 0; i < tw->leave_count; i++) {
		frame_destroy(&tw->leave[i].frame);
	}
	tw->leave_count = 0;
}

static void drop_clips(struct c8_tween *tw) {
	for (int i = 0; i < tw->count; i++) {
		struct c8_view *view = tw->covers[i].view;
		if (view && view->mapped && tw->covers[i].frame == NULL) {
			wlr_scene_subsurface_tree_set_clip(&view->tree->node, NULL);
		}
	}
}

/* Everything at once where it goes: no move, no frames */
static void finish(struct c8_server *server) {
	struct c8_tween *tw = &server->tween;
	drop_clips(tw);
	for (int i = 0; i < tw->count; i++) {
		frame_destroy(&tw->covers[i].frame);
	}
	drop_leaving(tw);
	tw->active = false;
	tw->fading = false;
	wl_event_source_timer_update(tw->timer, 0);
}

static double progress(struct c8_tween *tw) {
	return decelerate((double)(c8_now_ms() - tw->start) / MOVE_MS);
}

static int tick(void *data) {
	struct c8_server *server = data;
	struct c8_tween *tw = &server->tween;
	int64_t ms = c8_now_ms() - tw->start;
	if (tw->active) {
		place(server, progress(tw));
		if (ms >= MOVE_MS && (caught_up(tw) || ms >= MOVE_MS + WAIT_MS)) {
			/* The apps come back under their pictures, which fade */
			tw->active = false;
			drop_clips(tw);
			drop_leaving(tw);
			tw->fading = false;
			for (int i = 0; i < tw->count; i++) {
				tw->fading |= tw->covers[i].frame != NULL;
			}
			tw->start = c8_now_ms();
			if (!tw->fading) {
				c8_views_arrange(server); // the border
				return 0;
			}
			c8_views_arrange(server);
		}
	} else if (tw->fading) {
		double t = (double)ms / FADE_MS;
		for (int i = 0; i < tw->count; i++) {
			if (tw->covers[i].frame) {
				wlr_scene_buffer_set_opacity(tw->covers[i].frame,
					t >= 1 ? 0 : 1 - t);
			}
		}
		if (t >= 1) {
			finish(server);
			c8_views_arrange(server); // the border
			return 0;
		}
	} else {
		return 0;
	}
	wl_event_source_timer_update(tw->timer, TICK_MS);
	return 0;
}

void c8_tween_stop(struct c8_server *server) {
	finish(server);
	server->tween.last_count = 0;
}

void c8_tween_view_gone(struct c8_view *view) {
	struct c8_server *server = view->server;
	struct c8_tween *tw = &server->tween;
	bool covered = false;
	for (int i = 0; i < tw->count; i++) {
		if (tw->covers[i].view == view) {
			tw->covers[i].view = NULL; // its frame fades as it goes
			covered = tw->covers[i].frame != NULL;
		}
	}
	for (int i = 0; i < tw->last_count; i++) {
		if (tw->last_view[i] != view) {
			continue;
		}
		tw->last_view[i] = NULL;
		/* Closed while on screen: its picture stays where it was and
		 * fades while the other app takes its place */
		if (!covered && view->tree->node.enabled &&
				!server->start_visible &&
				tw->leave_count < C8_TWEEN_LEAVE_MAX) {
			struct wlr_scene_buffer *frame =
				frame_create(server, view, &tw->last_box[i]);
			if (frame) {
				tw->leave[tw->leave_count++] =
					(struct c8_tween_leave){ frame, true };
			}
		}
	}
}

void c8_tween_drop(struct c8_server *server, struct c8_view *view,
		const struct wlr_box *from) {
	server->tween.drop_view = view;
	server->tween.drop_box = *from;
}

void c8_tween_hide(struct c8_server *server, struct c8_view *view) {
	struct c8_tween *tw = &server->tween;
	for (int i = 0; i < tw->count; i++) {
		if (tw->covers[i].view == view) {
			frame_destroy(&tw->covers[i].frame);
			tw->covers[i].hidden = true;
			wlr_scene_subsurface_tree_set_clip(&view->tree->node, NULL);
		}
	}
}

/* Where a view's box is now, if the move is under way */
static bool shown_box(struct c8_server *server, struct c8_view *view,
		struct wlr_box *out) {
	struct c8_tween *tw = &server->tween;
	if (!tw->active) {
		return false;
	}
	for (int i = 0; i < tw->count; i++) {
		struct c8_tween_cover *c = &tw->covers[i];
		if (c->view == view && !c->hidden) {
			*out = lerp_box(&c->from, &c->to, progress(tw));
			return true;
		}
	}
	return false;
}

static void begin(struct c8_server *server, struct c8_view **views,
		const struct wlr_box *boxes, const struct wlr_box *from,
		int count, const struct wlr_box *divider, struct c8_view *hidden) {
	struct c8_tween *tw = &server->tween;
	struct wlr_box div_from = tw->last_div;
	if (tw->active && !wlr_box_empty(&tw->div_to) &&
			server->divider->node.enabled) {
		div_from = (struct wlr_box){ server->divider->node.x,
			server->divider->node.y, divider->width, divider->height };
	}
	/* Mid-move, an app keeps the picture it is already shown by */
	struct wlr_scene_buffer *kept[2] = { NULL, NULL };
	bool moving = tw->active;
	drop_clips(tw);
	for (int i = 0; i < tw->count; i++) {
		struct c8_tween_cover *c = &tw->covers[i];
		for (int j = 0; j < count && moving && c->frame; j++) {
			if (c->view && c->view == views[j]) {
				kept[j] = c->frame;
				c->frame = NULL;
			}
		}
		if (c->frame && c->view == NULL && moving &&
				tw->leave_count < C8_TWEEN_LEAVE_MAX) {
			tw->leave[tw->leave_count++] =
				(struct c8_tween_leave){ c->frame, true };
			c->frame = NULL;
		}
		frame_destroy(&c->frame);
	}
	/* Apps leaving the layout (another takes the screen) stay behind
	 * as they were till the move is over */
	for (int j = 0; j < tw->last_count; j++) {
		struct c8_view *v = tw->last_view[j];
		bool stays = v == NULL || v == hidden;
		for (int i = 0; i < count && !stays; i++) {
			stays = views[i] == v;
		}
		if (!stays && v->mapped && v->tree->node.enabled &&
				tw->leave_count < C8_TWEEN_LEAVE_MAX) {
			struct wlr_scene_buffer *frame =
				frame_create(server, v, &tw->last_box[j]);
			if (frame) {
				tw->leave[tw->leave_count++] =
					(struct c8_tween_leave){ frame, false };
			}
		}
	}
	struct wlr_box *area = &server->usable;
	for (int i = 0; i < count; i++) {
		struct c8_tween_cover *c = &tw->covers[i];
		*c = (struct c8_tween_cover){
			.view = views[i], .from = from[i], .to = boxes[i],
			.hidden = views[i] == hidden,
		};
		if (c->hidden) {
			frame_destroy(&kept[i]);
			continue;
		}
		if (!wlr_box_equal(&c->from, &c->to)) {
			c->frame = kept[i] ? kept[i] :
				frame_create(server, views[i], &c->from);
			kept[i] = NULL;
		}
		frame_destroy(&kept[i]);
		/* Without a picture: held by the edge that stays; with both
		 * moving (a swap), by the screen edge it ends on */
		int from_right = c->from.x + c->from.width;
		int to_right = c->to.x + c->to.width;
		if (c->from.x == c->to.x) {
			c->anchor_right = false;
		} else if (from_right == to_right) {
			c->anchor_right = true;
		} else {
			c->anchor_right = to_right >= area->x + area->width &&
				c->to.x > area->x;
		}
	}
	tw->count = count;
	tw->div_from = div_from;
	tw->div_to = *divider;
	tw->start = c8_now_ms();
	tw->active = true;
	tw->fading = false;
	place(server, 0);
	wl_event_source_timer_update(tw->timer, TICK_MS);
}

bool c8_tween_layout(struct c8_server *server, struct c8_view **views,
		const struct wlr_box *boxes, int count, const struct wlr_box *divider,
		bool split, struct c8_view *hidden) {
	struct c8_tween *tw = &server->tween;
	if (count > 2) {
		count = 2;
	}
	struct c8_view *drop = tw->drop_view;
	tw->drop_view = NULL;
	/* Only between layouts of the same screen, the apps on view, and
	 * not while the divider follows the pointer: a drag is its own
	 * animation. An app dropped by its title bar always comes from
	 * where it was let go */
	bool on_view = !server->start_visible && !c8_chrome_grabbing(server) &&
		count > 0 && wlr_box_equal(&server->usable, &tw->last_area);
	/* (Going to one app arranges twice: the second, one app to one
	 * app, mustn't stop the move the first started) */
	bool can = on_view && tw->last_count > 0 &&
		(split || tw->last_split || tw->active);
	struct wlr_box from[2];
	/* same: the layout the move (or fade) is already going to */
	bool moved = false, same = (tw->active || tw->fading) &&
		count == tw->count;
	for (int i = 0; i < count; i++) {
		from[i] = boxes[i]; // new here: it appears where it goes
		bool known = false;
		if (drop && views[i] == drop && on_view) {
			from[i] = tw->drop_box;
			known = can = true;
		}
		known = known || shown_box(server, views[i], &from[i]);
		for (int j = 0; j < tw->last_count && !known; j++) {
			if (tw->last_view[j] == views[i]) {
				from[i] = tw->last_box[j];
				known = true;
			}
		}
		if (known && !wlr_box_equal(&from[i], &boxes[i]) &&
				views[i] != hidden) {
			moved = true;
		}
		if (same && (tw->covers[i].view != views[i] ||
				!wlr_box_equal(&tw->covers[i].to, &boxes[i]))) {
			same = false;
		}
	}
	if (can && moved && !same) {
		begin(server, views, boxes, from, count, divider, hidden);
	} else if ((tw->active && !(can && same)) || (tw->fading && !same)) {
		finish(server);
	} else if (tw->active) {
		/* Arranged again mid-move (a commit, focus): arranging put
		 * them at their ends, so back to where the move has them */
		place(server, progress(tw));
	}
	if (!tw->active) {
		drop_leaving(tw); // a closed app's picture with no move to show
	}

	tw->last_count = server->start_visible ? 0 : count;
	for (int i = 0; i < count; i++) {
		tw->last_view[i] = views[i];
		tw->last_box[i] = boxes[i];
	}
	tw->last_div = *divider;
	tw->last_area = server->usable;
	tw->last_split = split;
	return tw->active || tw->fading;
}

void c8_tween_restack(struct c8_server *server) {
	struct c8_tween *tw = &server->tween;
	wlr_scene_node_raise_to_top(&tw->tree->node);
	/* Leaving apps under the moving ones, the focused one on top */
	for (int i = 0; i < tw->leave_count; i++) {
		wlr_scene_node_lower_to_bottom(&tw->leave[i].frame->node);
	}
	for (int i = tw->count - 1; i >= 0; i--) {
		if (tw->covers[i].frame) {
			wlr_scene_node_raise_to_top(&tw->covers[i].frame->node);
		}
	}
	wlr_scene_node_raise_to_top(&server->divider->node);
	if (!tw->active) {
		return;
	}
	/* While its picture moves the app and its dialogs are out of sight */
	struct c8_view *view;
	wl_list_for_each(view, &server->views, link) {
		struct c8_view *root = view->mapped ? c8_view_root(view) : NULL;
		for (int i = 0; i < tw->count && root; i++) {
			if (tw->covers[i].frame && tw->covers[i].view == root) {
				wlr_scene_node_set_enabled(&view->tree->node, false);
			}
		}
	}
}

void c8_tween_init(struct c8_server *server) {
	server->tween.tree = wlr_scene_tree_create(server->layers.views);
	server->tween.timer = wl_event_loop_add_timer(server->loop, tick,
		server);
}
