(function($) {
	'use strict';

	var cfg = window.wppsContentFolders || {};
	var ajaxUrl = cfg.ajaxUrl || '';
	var nonce = cfg.nonce || '';
	var strings = cfg.strings || {};

	function notice(msg, isError) {
		var cls = isError ? 'wpps-notice-error' : '';
		var n = $('<div class="wpps-notice ' + cls + '"></div>').text(msg);
		$('#wpps-media-folders-sidebar .wpps-sidebar-inner').prepend(n);
		setTimeout(function() { n.fadeOut(function() { n.remove(); }); }, 3000);
	}

	var defaultMenuExpanded = (cfg.adminMenuWidth > 0) ? cfg.adminMenuWidth : 160;
	var defaultMenuFolded = (cfg.adminMenuWidthFolded > 0) ? cfg.adminMenuWidthFolded : 36;

	function getAdminMenuWidth() {
		var folded = document.body.classList.contains('folded');
		var wrap = document.getElementById('adminmenuwrap');
		if (wrap && wrap.offsetWidth > 0) {
			return wrap.offsetWidth;
		}
		return folded ? defaultMenuFolded : defaultMenuExpanded;
	}

	function getContentMargin(hidden) {
		var menu = getAdminMenuWidth();
		if (hidden) return menu;
		var w = parseInt($('#wpps-media-folders-sidebar').css('width'), 10) || 280;
		return menu + w;
	}

	function applyContentMargin() {
		var hidden = $('#wpps-media-folders-sidebar').hasClass('wpps-sidebar-hidden');
		var margin = getContentMargin(hidden);
		var folded = document.body.classList.contains('folded');
		var sel = folded ? 'body.wp-admin.folded.wpps-media-folders-page #wpcontent' : 'body.wp-admin.wpps-media-folders-page #wpcontent';
		var id = 'wpps-folders-dynamic-margin';
		var el = document.getElementById(id);
		if (!el) {
			el = document.createElement('style');
			el.id = id;
			document.head.appendChild(el);
		}
		el.textContent = sel + ' { margin-left: ' + margin + 'px !important; }';
	}

	function setSidebarVisible(visible) {
		var $bar = $('#wpps-media-folders-sidebar');
		if (visible) {
			$bar.removeClass('wpps-sidebar-hidden');
		} else {
			$bar.addClass('wpps-sidebar-hidden');
		}
		applyContentMargin();
	}

	function pinSidebarLeft() {
		var el = document.getElementById('wpps-media-folders-sidebar');
		if (!el) return;
		var menuPx = getAdminMenuWidth();
		el.style.setProperty('left', menuPx + 'px', 'important');
		el.style.setProperty('right', 'auto', 'important');
		var styleId = 'wpps-folders-pin-left';
		var styleEl = document.getElementById(styleId);
		if (!styleEl) {
			styleEl = document.createElement('style');
			styleEl.id = styleId;
			document.head.appendChild(styleEl);
		}
		styleEl.textContent = '#wpps-media-folders-sidebar { left: ' + menuPx + 'px !important; right: auto !important; }';
	}

	function onAdminFoldChange() {
		pinSidebarLeft();
		applyContentMargin();
	}

	$(function() {
		pinSidebarLeft();
		applyContentMargin();

		$('#wpps-media-folders-sidebar').on('dragstart', function(e) {
			e.preventDefault();
			e.stopPropagation();
		});

		var $tree = $('#wpps-media-folders-sidebar .wpps-folder-tree');
		if ($tree.length && $.fn.sortable) {
			$tree.sortable({
				items: '> li.wpps-folder-item',
				axis: 'y',
				handle: '.wpps-folder-drag-handle',
				placeholder: 'wpps-folder-item ui-sortable-placeholder',
				tolerance: 'pointer',
				cancel: 'a, button',
				update: function() {
					var order = [];
					$tree.find('> li.wpps-folder-item').each(function() {
						var id = $(this).data('term-id');
						if (id) order.push(id);
					});
					if (order.length === 0) return;
					$.post(ajaxUrl, {
						action: 'wpps_folders_reorder',
						nonce: nonce,
						order: order
					})
						.done(function(res) {
							if (res.success) notice(strings.saved || 'Saved.');
							else notice((res.data && res.data.message) || (strings.error || 'Error.'), true);
						})
						.fail(function() { notice(strings.error || 'Error.', true); });
				}
			});
		}

		var body = document.body;
		if (body && typeof MutationObserver !== 'undefined') {
			var foldObserver = new MutationObserver(function(mutations) {
				for (var i = 0; i < mutations.length; i++) {
					if (mutations[i].attributeName === 'class') {
						onAdminFoldChange();
						break;
					}
				}
			});
			foldObserver.observe(body, { attributes: true, attributeFilter: ['class'] });
		}
		$(document).on('click', '#collapse-button', function() {
			setTimeout(onAdminFoldChange, 50);
		});
	});
	$(window).on('load', onAdminFoldChange);

	$(document).on('click', '.wpps-sidebar-toggle', function() {
		var $bar = $('#wpps-media-folders-sidebar');
		$bar.toggleClass('wpps-sidebar-hidden');
		var hidden = $bar.hasClass('wpps-sidebar-hidden');
		applyContentMargin();
		$.post(ajaxUrl, {
			action: 'wpps_folders_settings_save',
			nonce: nonce,
			sidebar_visible: hidden ? '0' : '1'
		});
	});

	$(document).on('click', '.wpps-sidebar-show-tab', function() {
		setSidebarVisible(true);
		$.post(ajaxUrl, {
			action: 'wpps_folders_settings_save',
			nonce: nonce,
			sidebar_visible: '1'
		});
	});

	function updateSidebarCount(termId, delta) {
		var $count;
		if (!termId || termId === '0') {
			$count = $('#wpps-media-folders-sidebar .wpps-nav-item').eq(1).find('.wpps-count');
		} else {
			var $item = $('#wpps-media-folders-sidebar .wpps-folder-item[data-term-id="' + termId + '"]');
			$count = $item.find('.wpps-count');
		}
		if ($count.length) {
			var raw = $count.text().replace(/[()]/g, '');
			var n = (parseInt(raw, 10) || 0) + delta;
			$count.text('(' + Math.max(0, n) + ')');
		}
	}

	$(document).on('change', '.wpps-folder-assign-select', function() {
		var $sel = $(this);
		var attachmentId = $sel.data('attachment-id');
		var termId = $sel.val() || '0';
		var prevId = $sel.data('prev') || '0';
		$sel.prop('disabled', true);
		$.post(ajaxUrl, {
			action: 'wpps_folders_assign_media',
			nonce: nonce,
			attachment_id: attachmentId,
			term_id: termId
		})
			.done(function(res) {
				if (res.success) {
					notice(strings.saved || 'Saved.');
					updateSidebarCount(prevId, -1);
					updateSidebarCount(termId, 1);
				} else {
					notice((res.data && res.data.message) || (strings.error || 'Error.'), true);
					$sel.val(prevId);
				}
			})
			.fail(function() {
				notice(strings.error || 'Error.', true);
				$sel.val(prevId);
			})
			.always(function() {
				$sel.prop('disabled', false);
			});
	});
	$(document).on('focus', '.wpps-folder-assign-select', function() {
		$(this).data('prev', $(this).val());
	});

	$(document).on('click', '.wpps-add-folder-btn', function() {
		var name = $('.wpps-new-folder-input').val().trim();
		if (!name) return;
		$.post(ajaxUrl, { action: 'wpps_folders_add', nonce: nonce, name: name, parent_id: 0 })
			.done(function(res) {
				if (res.success && res.data) {
					notice(strings.saved || 'Saved.');
					window.location.reload();
				} else {
					notice((res.data && res.data.message) || (strings.error || 'Error.'), true);
				}
			})
			.fail(function() { notice(strings.error || 'Error.', true); });
		$('.wpps-new-folder-input').val('');
	});

	$(document).on('click', '.wpps-add-subfolder', function(e) {
		e.preventDefault();
		e.stopPropagation();
		var parentId = $(this).data('term-id');
		var $parentLi = $(this).closest('li.wpps-folder-item');
		$('#wpps-media-folders-sidebar .wpps-add-subfolder-form').closest('li').remove();
		var $childrenUl = $parentLi.children('ul.wpps-folder-children').first();
		if (!$childrenUl.length) {
			$childrenUl = $('<ul class="wpps-folder-children" role="group" aria-hidden="true"></ul>').appendTo($parentLi);
		}
		var tpl = document.getElementById('wpps-add-subfolder-form-tpl');
		if (!tpl) return;
		var $form = $(tpl.content.cloneNode(true));
		$form.find('.wpps-add-subfolder-input').data('parent-id', parentId);
		$childrenUl.append($form);
		$parentLi.addClass('wpps-folder-expanded');
		$childrenUl.attr('aria-hidden', 'false');
		$form.find('.wpps-add-subfolder-input').focus();
	});
	$(document).on('click', '.wpps-folder-toggle', function(e) {
		e.preventDefault();
		e.stopPropagation();
		var $li = $(this).closest('li.wpps-folder-item');
		var $ul = $li.children('ul.wpps-folder-children').first();
		$li.toggleClass('wpps-folder-expanded');
		$ul.attr('aria-hidden', $li.hasClass('wpps-folder-expanded') ? 'false' : 'true');
	});
	$(document).on('click', '.wpps-add-subfolder-save', function() {
		var $form = $(this).closest('.wpps-add-subfolder-form');
		var name = $form.find('.wpps-add-subfolder-input').val().trim();
		var parentId = $form.find('.wpps-add-subfolder-input').data('parent-id');
		if (!name) return;
		$(this).prop('disabled', true);
		$.post(ajaxUrl, { action: 'wpps_folders_add', nonce: nonce, name: name, parent_id: parentId })
			.done(function(res) {
				if (res.success && res.data) {
					notice(strings.saved || 'Saved.');
					window.location.reload();
				} else {
					notice((res.data && res.data.message) || (strings.error || 'Error.'), true);
					$form.find('.wpps-add-subfolder-save').prop('disabled', false);
				}
			})
			.fail(function() {
				notice(strings.error || 'Error.', true);
				$form.find('.wpps-add-subfolder-save').prop('disabled', false);
			});
	});
	$(document).on('click', '.wpps-add-subfolder-cancel', function() {
		$(this).closest('.wpps-add-subfolder-form').closest('li').remove();
	});
	$(document).on('keypress', '.wpps-add-subfolder-input', function(e) {
		if (e.which === 13) {
			e.preventDefault();
			$(this).closest('.wpps-add-subfolder-form').find('.wpps-add-subfolder-save').click();
		}
	});

	$('.wpps-new-folder-input').on('keypress', function(e) {
		if (e.which === 13) {
			e.preventDefault();
			$('.wpps-add-folder-btn').click();
		}
	});

	function getDescendantIds(termId, folderList) {
		var ids = [];
		if (!folderList || !folderList.length) return ids;
		function collect(pid) {
			for (var i = 0; i < folderList.length; i++) {
				if (parseInt(folderList[i].parent, 10) === pid) {
					ids.push(parseInt(folderList[i].term_id, 10));
					collect(folderList[i].term_id);
				}
			}
		}
		collect(termId);
		return ids;
	}
	$(document).on('click', '.wpps-folder-edit', function(e) {
		e.preventDefault();
		e.stopPropagation();
		var id = $(this).data('term-id');
		var name = $(this).data('name') || '';
		var parent = $(this).data('parent');
		if (parent === undefined || parent === '') parent = '0';
		$('#wpps-edit-term-id').val(id);
		$('#wpps-edit-folder-name').val(name);
		var folderList = (window.wppsContentFolders && window.wppsContentFolders.folderList) || [];
		var currentId = parseInt(id, 10);
		var descendants = getDescendantIds(currentId, folderList);
		var $sel = $('#wpps-edit-parent-id');
		$sel.empty();
		$sel.append($('<option value="0">').text('— ' + (strings.parentNone || 'None (top level)') + ' —'));
		for (var j = 0; j < folderList.length; j++) {
			var t = folderList[j];
			var tid = parseInt(t.term_id, 10);
			if (tid === currentId || descendants.indexOf(tid) !== -1) continue;
			$sel.append($('<option value="' + tid + '">').text(t.name));
		}
		$sel.val(parent);
		$('#wpps-edit-folder-modal').show();
	});

	$(document).on('click', '.wpps-edit-save', function() {
		var id = $('#wpps-edit-term-id').val();
		var name = $('#wpps-edit-folder-name').val().trim();
		var parentId = $('#wpps-edit-parent-id').val();
		if (!id || !name) return;
		$.post(ajaxUrl, { action: 'wpps_folders_update', nonce: nonce, term_id: id, name: name, parent_id: parentId || '0' })
			.done(function(res) {
				if (res.success) {
					notice(strings.saved || 'Saved.');
					$('#wpps-edit-folder-modal').hide();
					window.location.reload();
				} else {
					notice((res.data && res.data.message) || (strings.error || 'Error.'), true);
				}
			})
			.fail(function() { notice(strings.error || 'Error.', true); });
	});

	$(document).on('click', '.wpps-folder-delete', function(e) {
		e.preventDefault();
		e.stopPropagation();
		if (!confirm(strings.confirmDelete || 'Delete this folder? Items will be unassigned.')) return;
		var id = $(this).data('term-id');
		$.post(ajaxUrl, { action: 'wpps_folders_delete', nonce: nonce, term_id: id })
			.done(function(res) {
				if (res.success) {
					notice(strings.saved || 'Saved.');
					window.location.reload();
				} else {
					notice((res.data && res.data.message) || (strings.error || 'Error.'), true);
				}
			})
			.fail(function() { notice(strings.error || 'Error.', true); });
	});

	var settingsModal = cfg.settings || {};
	$(document).on('click', '.wpps-sidebar-settings', function() {
		var w = parseInt($('#wpps-media-folders-sidebar').css('width'), 10) || settingsModal.sidebar_width || 280;
		$('#wpps-settings-sidebar-width').val(Math.max(200, Math.min(400, w)));
		$('#wpps-settings-default-folder').val(settingsModal.default_folder || '0');
		$('#wpps-folders-settings-modal').show();
	});
	$(document).on('click', '.wpps-settings-save', function() {
		var w = parseInt($('#wpps-settings-sidebar-width').val(), 10) || 280;
		w = Math.max(200, Math.min(400, w));
		var defaultFolder = $('#wpps-settings-default-folder').val() || '0';
		$.post(ajaxUrl, {
			action: 'wpps_folders_settings_save',
			nonce: nonce,
			sidebar_width: w,
			default_folder: defaultFolder
		})
			.done(function(res) {
				if (res.success) {
					notice(strings.saved || 'Saved.');
					$('#wpps-folders-settings-modal').hide();
					$('#wpps-media-folders-sidebar').css('width', w + 'px');
					applyContentMargin();
					settingsModal.sidebar_width = w;
					settingsModal.default_folder = parseInt(defaultFolder, 10) || 0;
				} else {
					notice((res.data && res.data.message) || (strings.error || 'Error.'), true);
				}
			})
			.fail(function() { notice(strings.error || 'Error.', true); });
	});

	$(document).on('click', '.wpps-modal-close, .wpps-modal-cancel, .wpps-modal-backdrop', function(e) {
		e.stopPropagation();
		var $modal = $(this).closest('.wpps-modal');
		if ($modal.length) {
			$modal.hide();
		} else {
			$('#wpps-edit-folder-modal').hide();
			$('#wpps-folders-settings-modal').hide();
		}
	});

	var resizing = false;
	var startX = 0;
	var startW = 0;
	$(document).on('mousedown', '.wpps-sidebar-resize-handle', function(e) {
		e.preventDefault();
		resizing = true;
		startX = e.pageX;
		startW = $('#wpps-media-folders-sidebar').width();
		$(document).on('mousemove.wppsResize', function(ev) {
			if (!resizing) return;
			var dx = ev.pageX - startX;
			var newW = Math.max(200, Math.min(400, startW + dx));
			$('#wpps-media-folders-sidebar').css('width', newW + 'px');
			applyContentMargin();
		});
		$(document).on('mouseup.wppsResize', function() {
			resizing = false;
			$(document).off('mousemove.wppsResize mouseup.wppsResize');
			var w = $('#wpps-media-folders-sidebar').width();
			applyContentMargin();
			$.post(ajaxUrl, { action: 'wpps_folders_settings_save', nonce: nonce, sidebar_width: w });
		});
	});

	/**
	 * Media grid: do not mutate Query.args or call library.fetch().
	 * That aborts the in-flight query-attachments request and leaves the spinner spinning.
	 * Folder filtering is applied server-side via ajax_query_attachments_args + synced cookie.
	 */
	if ($('#wp-media-grid').length && typeof wp !== 'undefined' && wp.media) {
		var uploadPageUrl = cfg.uploadPageUrl || 'upload.php';
		var assignBtnText = strings.assignToFolder || 'Assign to folder';
		var checkFrame = function(tries) {
			tries = tries || 0;
			if (tries > 50) return;
			var frame = wp.media.frames.browse;
			if (!frame || !frame.content || !frame.content.get()) {
				setTimeout(function() { checkFrame(tries + 1); }, 200);
				return;
			}
			var $btn = $('<button type="button" class="button wpps-grid-assign-folder">' + assignBtnText + '</button>');
			$btn.prop('disabled', true);
			$btn.on('click', function() {
				var state = frame.state();
				if (!state) return;
				var selection = state.get('selection');
				if (!selection || !selection.length) return;
				var ids = [];
				selection.each(function(m) { ids.push(m.get('id')); });
				if (ids.length) {
					window.location.href = uploadPageUrl + (uploadPageUrl.indexOf('?') !== -1 ? '&' : '?') + 'wpps_bulk_assign=1&media=' + ids.join(',');
				}
			});
			frame.on('select:activate', function() {
				var content = frame.content.get();
				var toolbar = content && content.toolbar;
				if (!toolbar || !toolbar.$) return;
				var placeButton = function() {
					var $del = toolbar.$('.delete-selected-button');
					if ($del.length && $btn.parent().length === 0) {
						$del.after($btn);
						var sel = frame.state() && frame.state().get('selection');
						$btn.prop('disabled', !sel || !sel.length);
					}
				};
				setTimeout(placeButton, 0);
			});
			frame.on('select:deactivate', function() {
				$btn.detach();
			});
			frame.on('selection:toggle', function() {
				var state = frame.state();
				var sel = state && state.get('selection');
				$btn.prop('disabled', !sel || !sel.length);
			});
		};
		$(function() { checkFrame(0); });
	}
})(jQuery);
