/**
 * Media Folder Pro — Media Grid Filter + Drag & Drop + Bulk Assign
 * Integrates with WP media grid via wp.media backbone props.
 */
( function () {
	'use strict';

	const { ajaxUrl, nonce, i18n } = window.mfpData || {};
	if ( ! ajaxUrl ) return;

	let currentFolderId = null;

	function toast( msg, type ) {
		if ( window.mfpToast ) window.mfpToast( msg, type );
	}

	// ─── AJAX helper ──────────────────────────────────────────
	function ajax( action, data ) {
		data = data || {};
		const body = new URLSearchParams();
		body.append( 'action', action );
		body.append( 'nonce', nonce );
		for ( const [ k, v ] of Object.entries( data ) ) {
			if ( Array.isArray( v ) ) {
				v.forEach( function ( item ) { body.append( k + '[]', item ); } );
			} else {
				body.append( k, v );
			}
		}
		return fetch( ajaxUrl, {
			method: 'POST',
			credentials: 'same-origin',
			body: body,
		} ).then( function ( r ) { return r.json(); } );
	}

	// ─── Media Grid Filter ───────────────────────────────────
	function getMediaCollection() {
		if ( ! window.wp || ! wp.media || ! wp.media.frame ) {
			return null;
		}
		var library = wp.media.frame.state &&
			wp.media.frame.state() &&
			wp.media.frame.state().get( 'library' );
		return library || null;
	}

	function filterByFolder( folderId ) {
		currentFolderId = folderId;
		var library = getMediaCollection();
		if ( library ) {
			if ( folderId ) {
				library.props.set( { media_folder: folderId } );
			} else {
				library.props.set( { media_folder: 0 } );
			}
		}
	}

	// Listen for folder selection from tree
	document.addEventListener( 'mfp-folder-selected', function ( e ) {
		filterByFolder( e.detail.folderId );
	} );

	// Listen for media dropped on folder (from folder-tree.js)
	document.addEventListener( 'mfp-media-dropped', function ( e ) {
		assignMedia( e.detail.attachmentIds, e.detail.folderId );
	} );

	// ─── Drag & Drop (media) ─────────────────────────────────
	function enableDraggable( attachment ) {
		if ( attachment.getAttribute( 'data-mfp-draggable' ) ) return;
		attachment.setAttribute( 'data-mfp-draggable', '1' );
		attachment.setAttribute( 'draggable', 'true' );

		attachment.addEventListener( 'dragstart', function ( e ) {
			var id = attachment.getAttribute( 'data-id' );
			if ( ! id ) {
				e.preventDefault();
				return;
			}
			e.dataTransfer.setData( 'text/plain', id );
			e.dataTransfer.effectAllowed = 'move';
			document.body.classList.add( 'mfp-dragging' );
		} );

		attachment.addEventListener( 'dragend', function () {
			document.body.classList.remove( 'mfp-dragging' );
		} );
	}

	function scanAttachments() {
		document.querySelectorAll( '.attachments .attachment' ).forEach( enableDraggable );
	}

	function observeAttachments() {
		var container = document.querySelector( '.attachments' );
		if ( ! container ) return;

		scanAttachments();

		var observer = new MutationObserver( function () {
			scanAttachments();
		} );
		observer.observe( container, { childList: true, subtree: true } );
	}

	// Drop handlers on folder rows — delegated from tree root
	function initDropTargets() {
		var root = document.getElementById( 'mfp-folder-root' );
		if ( ! root ) return;

		// "All Media" drop = unassign
		var allMedia = root.querySelector( '.mfp-all-media' );
		if ( allMedia ) {
			allMedia.addEventListener( 'dragover', function ( e ) {
				if ( e.dataTransfer.types.includes( 'application/mfp-folder' ) ) return;
				e.preventDefault();
				e.dataTransfer.dropEffect = 'move';
				allMedia.classList.add( 'mfp-drop-target' );
			} );
			allMedia.addEventListener( 'dragleave', function () {
				allMedia.classList.remove( 'mfp-drop-target' );
			} );
			allMedia.addEventListener( 'drop', function ( e ) {
				e.preventDefault();
				allMedia.classList.remove( 'mfp-drop-target' );
				var attachmentId = e.dataTransfer.getData( 'text/plain' );
				if ( attachmentId ) assignMedia( [ attachmentId ], 0 );
			} );
		}
	}

	function assignMedia( attachmentIds, folderId ) {
		ajax( 'mfp_assign_media', {
			attachment_ids: attachmentIds,
			folder_id: folderId,
		} ).then( function ( res ) {
			if ( res.success ) {
				if ( window.mfpRefreshTree ) window.mfpRefreshTree();

				var count = res.data.count || attachmentIds.length;
				toast(
					( i18n.assignSuccess || 'Media przypisane' ) +
					( count > 1 ? ' (' + count + ')' : '' )
				);

				// Refresh grid if viewing a different folder
				if ( currentFolderId && String( currentFolderId ) !== String( folderId ) ) {
					filterByFolder( currentFolderId );
				}
			} else {
				toast( ( res.data && res.data.message ) || i18n.assignError || 'Error', 'error' );
			}
		} ).catch( function () {
			toast( i18n.error || 'Error', 'error' );
		} );
	}

	// ─── Bulk Assign ─────────────────────────────────────────
	function initBulkAssign() {
		// Inject bulk button into WP media toolbar
		var observer = new MutationObserver( function () {
			var toolbar = document.querySelector( '.media-toolbar-secondary' );
			if ( toolbar && ! toolbar.querySelector( '.mfp-bulk-btn' ) ) {
				createBulkButton( toolbar );
			}
		} );
		observer.observe( document.body, { childList: true, subtree: true } );

		// Also check immediately
		var toolbar = document.querySelector( '.media-toolbar-secondary' );
		if ( toolbar && ! toolbar.querySelector( '.mfp-bulk-btn' ) ) {
			createBulkButton( toolbar );
		}
	}

	function createBulkButton( toolbar ) {
		var btn = document.createElement( 'button' );
		btn.className = 'button mfp-bulk-btn';
		btn.textContent = i18n.moveToFolder || 'Przenieś do folderu';
		btn.type = 'button';

		btn.addEventListener( 'click', function () {
			showBulkDropdown( btn );
		} );

		toolbar.appendChild( btn );
	}

	function showBulkDropdown( anchor ) {
		// Remove existing dropdown
		var existing = document.querySelector( '.mfp-bulk-dropdown' );
		if ( existing ) { existing.remove(); return; }

		// Get selected attachments
		var selected = document.querySelectorAll( '.attachment.selected, .attachment.details' );
		if ( selected.length === 0 ) {
			toast( i18n.noSelection || 'Zaznacz media do przeniesienia', 'info' );
			return;
		}

		var ids = [];
		selected.forEach( function ( el ) {
			var id = el.getAttribute( 'data-id' );
			if ( id ) ids.push( id );
		} );

		if ( ids.length === 0 ) return;

		// Load folders and build dropdown
		ajax( 'mfp_get_folders' ).then( function ( res ) {
			if ( ! res.success ) return;

			var dropdown = document.createElement( 'div' );
			dropdown.className = 'mfp-bulk-dropdown';

			// "Remove from folder" option
			var removeOpt = document.createElement( 'button' );
			removeOpt.className = 'mfp-bulk-dropdown__item mfp-bulk-dropdown__item--remove';
			removeOpt.textContent = i18n.removeFromFolder || 'Usuń z folderu';
			removeOpt.addEventListener( 'click', function () {
				dropdown.remove();
				assignMedia( ids, 0 );
			} );
			dropdown.appendChild( removeOpt );

			var sep = document.createElement( 'div' );
			sep.className = 'mfp-context-menu__separator';
			dropdown.appendChild( sep );

			// Folder options (flat)
			flattenAndAddOptions( dropdown, res.data.folders, 0, ids );

			// Position
			var rect = anchor.getBoundingClientRect();
			dropdown.style.position = 'fixed';
			dropdown.style.left = rect.left + 'px';
			dropdown.style.top = ( rect.bottom + 4 ) + 'px';

			document.body.appendChild( dropdown );

			// Close on outside click
			function closeDropdown( e ) {
				if ( ! dropdown.contains( e.target ) && e.target !== anchor ) {
					dropdown.remove();
					document.removeEventListener( 'click', closeDropdown );
				}
			}
			setTimeout( function () {
				document.addEventListener( 'click', closeDropdown );
			}, 0 );
		} );
	}

	function flattenAndAddOptions( container, folders, depth, ids ) {
		for ( var i = 0; i < folders.length; i++ ) {
			var folder = folders[ i ];
			var prefix = depth > 0 ? '\u2003'.repeat( depth ) + '\u2014 ' : '';

			var opt = document.createElement( 'button' );
			opt.className = 'mfp-bulk-dropdown__item';
			opt.textContent = prefix + folder.name;
			opt.setAttribute( 'data-folder-id', folder.id );

			( function ( fId ) {
				opt.addEventListener( 'click', function () {
					container.remove();
					assignMedia( ids, fId );
				} );
			} )( folder.id );

			container.appendChild( opt );

			if ( folder.children && folder.children.length > 0 ) {
				flattenAndAddOptions( container, folder.children, depth + 1, ids );
			}
		}
	}

	// ─── Init ─────────────────────────────────────────────────
	function init() {
		observeAttachments();
		initDropTargets();
		initBulkAssign();
	}

	if ( document.readyState === 'loading' ) {
		document.addEventListener( 'DOMContentLoaded', init );
	} else {
		init();
	}
} )();
