/**
 * CPT Builder admin scripts.
 *
 * Handles tab switching, delete confirmation, the import panel, key
 * auto-suggestion, capability presets, and the Dashicons picker. No data is
 * rendered unescaped; all values come from a localized, sanitized list.
 */
( function ( $ ) {
	'use strict';

	var settings = window.wppsCptb || {};
	var strings = settings.strings || {};
	var maxKeyLength = parseInt( settings.maxKeyLength, 10 ) || 20;

	function initTabs() {
		var $tabs = $( '.cptb-tab' );
		if ( ! $tabs.length ) {
			return;
		}

		function activateTab( target ) {
			target = String( target || '' ).replace( /[^a-z0-9_-]/gi, '' );
			var $tab = $tabs.filter( '[data-tab="' + target + '"]' );
			if ( ! $tab.length ) {
				return;
			}

			$tabs.removeClass( 'is-active' ).attr( 'aria-selected', 'false' );
			$tab.addClass( 'is-active' ).attr( 'aria-selected', 'true' );

			$( '.cptb-panel' ).each( function () {
				var match = this.id === 'cptb-tab-' + target;
				$( this ).prop( 'hidden', ! match );
			} );
		}

		$tabs.on( 'click', function () {
			var target = $( this ).data( 'tab' );
			activateTab( target );
			if ( window.history && window.history.replaceState ) {
				window.history.replaceState( null, '', '#cptb-tab-' + target );
			}
		} );

		$( window ).on( 'hashchange', function () {
			if ( window.location.hash.indexOf( '#cptb-tab-' ) === 0 ) {
				activateTab( window.location.hash.replace( '#cptb-tab-', '' ) );
			}
		} );

		if ( window.location.hash.indexOf( '#cptb-tab-' ) === 0 ) {
			activateTab( window.location.hash.replace( '#cptb-tab-', '' ) );
		}
	}

	function transformLabelValue( value, transform ) {
		if ( transform === 'lower' ) {
			return value.toLowerCase();
		}
		return value;
	}

	function initLabelPlaceholders() {
		var $templated = $( 'input[data-cptb-template]' );
		var $singular = $( '#cptb-singular' );
		var $plural = $( '#cptb-plural' );

		if ( ! $templated.length || ( ! $singular.length && ! $plural.length ) ) {
			return;
		}

		function refresh() {
			var singular = String( $singular.val() || '' ).trim();
			var plural = String( $plural.val() || '' ).trim();

			$templated.each( function () {
				var $input = $( this );
				var source = $input.data( 'cptb-source' ) === 'singular' ? singular : plural;
				if ( source === '' ) {
					$input.attr( 'placeholder', '' );
					return;
				}
				var value = transformLabelValue( source, $input.data( 'cptb-transform' ) );
				$input.attr( 'placeholder', String( $input.data( 'cptb-template' ) ).replace( '%s', value ) );
			} );
		}

		$singular.add( $plural ).on( 'input', refresh );
		refresh();
	}

	function escapeFieldName( name ) {
		return name.replace( /([\[\]])/g, '\\$1' );
	}

	function initKeyPlaceholders() {
		var $targets = $( 'input[data-cptb-key-placeholder]' );
		var $key = $( '#cptb-key' );

		if ( ! $targets.length || ! $key.length ) {
			return;
		}

		var fallbacks = [];
		$targets.each( function () {
			fallbacks.push( $( this ).attr( 'placeholder' ) || '' );
		} );

		$key.on( 'input', function () {
			var key = String( $key.val() || '' ).trim();
			$targets.each( function ( index ) {
				$( this ).attr( 'placeholder', key !== '' ? key : fallbacks[ index ] );
			} );
		} );
	}

	function initDependentFields() {
		var map = {
			'args[rewrite]': [
				'args[rewrite_slug]',
				'args[rewrite_with_front]',
				'args[rewrite_feeds]',
				'args[rewrite_pages]',
				'args[rewrite_hierarchical]',
			],
			'args[has_archive]': [ 'args[has_archive_slug]' ],
			'args[query_var]': [ 'args[query_var_slug]' ],
			'args[show_in_rest]': [
				'args[rest_base]',
				'args[rest_namespace]',
				'args[rest_controller_class]',
			],
			'args[show_in_menu]': [ 'args[show_in_menu_parent]' ],
		};

		$.each( map, function ( parentName, dependentNames ) {
			var $parent = $( 'input[name="' + escapeFieldName( parentName ) + '"]' );
			if ( ! $parent.length ) {
				return;
			}

			function refresh() {
				var enabled = $parent.prop( 'checked' );
				dependentNames.forEach( function ( name ) {
					$( 'input[name="' + escapeFieldName( name ) + '"]' )
						.closest( 'tr' )
						.toggleClass( 'cptb-row-disabled', ! enabled );
				} );
			}

			$parent.on( 'change', refresh );
			refresh();
		} );
	}

	function initPublicMasterSwitch() {
		var $public = $( 'input[name="args[public]"]' );
		if ( ! $public.length ) {
			return;
		}

		var dependents = [
			'args[publicly_queryable]',
			'args[show_ui]',
			'args[show_in_menu]',
			'args[show_in_nav_menus]',
			'args[show_in_admin_bar]',
			'args[show_tagcloud]',
			'args[show_in_quick_edit]',
		];
		var saved = null;

		$public.on( 'change', function () {
			var checked = $( this ).prop( 'checked' );

			if ( ! checked ) {
				saved = {};
				dependents.forEach( function ( name ) {
					var $el = $( 'input[name="' + escapeFieldName( name ) + '"]' );
					if ( ! $el.length ) {
						return;
					}
					saved[ name ] = $el.prop( 'checked' );
					$el.prop( 'checked', false ).trigger( 'change' );
				} );
				return;
			}

			if ( saved ) {
				dependents.forEach( function ( name ) {
					var $el = $( 'input[name="' + escapeFieldName( name ) + '"]' );
					if ( ! $el.length || typeof saved[ name ] === 'undefined' ) {
						return;
					}
					$el.prop( 'checked', saved[ name ] ).trigger( 'change' );
				} );
				saved = null;
				return;
			}

			dependents.forEach( function ( name ) {
				$( 'input[name="' + escapeFieldName( name ) + '"]' )
					.prop( 'checked', true )
					.trigger( 'change' );
			} );
		} );
	}

	function initDeleteConfirm() {
		$( document ).on( 'click', '.cptb-delete', function ( e ) {
			var isTaxonomy = $( this ).closest( '#cptb-taxonomies-list-form' ).length > 0;
			var message = isTaxonomy
				? ( strings.confirmTaxDelete || strings.confirmDelete || 'Are you sure?' )
				: ( strings.confirmDelete || 'Are you sure?' );
			if ( ! window.confirm( message ) ) {
				e.preventDefault();
			}
		} );
	}

	function initImportPanel() {
		$( '#cptb-import-toggle' ).on( 'click', function () {
			var $panel = $( '#cptb-import-panel' );
			$panel.prop( 'hidden', ! $panel.prop( 'hidden' ) );
		} );
	}

	function slugify( value ) {
		return String( value || '' )
			.toLowerCase()
			.replace( /[^a-z0-9_\s-]/g, '' )
			.replace( /[\s-]+/g, '_' )
			.replace( /^_+|_+$/g, '' )
			.replace( /^[0-9_]+/, '' )
			.substring( 0, maxKeyLength );
	}

	function initKeyAutosuggest() {
		var $source = $( '[data-cptb-autoslug]' );
		var $key = $( '#cptb-key' );
		if ( ! $source.length || ! $key.length ) {
			return;
		}

		var manuallyEdited = $key.val() !== '';
		$key.on( 'input', function () {
			manuallyEdited = true;
		} );

		$source.on( 'input', function () {
			if ( manuallyEdited ) {
				return;
			}
			$key.val( slugify( $( this ).val() ) ).trigger( 'input' );
		} );
	}

	function capabilityPreview( singular, plural ) {
		singular = String( singular || '' ).toLowerCase().replace( /[^a-z0-9_]/g, '' );
		plural = String( plural || '' ).toLowerCase().replace( /[^a-z0-9_]/g, '' );
		if ( ! singular ) {
			return [];
		}
		if ( ! plural ) {
			plural = singular + 's';
		}
		return [
			'edit_' + singular,
			'read_' + singular,
			'delete_' + singular,
			'edit_' + plural,
			'edit_others_' + plural,
			'publish_' + plural,
			'read_private_' + plural,
			'delete_' + plural,
			'delete_private_' + plural,
			'delete_published_' + plural,
			'delete_others_' + plural,
			'edit_private_' + plural,
			'edit_published_' + plural,
			'create_' + plural,
		];
	}

	function initCapabilityModes() {
		var $modes = $( 'input[data-cptb-cap-mode]' );
		if ( ! $modes.length ) {
			return;
		}

		var $custom = $( '[data-cptb-cap-custom]' );
		var $list = $( '[data-cptb-cap-list]' );
		var $singular = $( '[data-cptb-cap-singular]' );
		var $plural = $( '[data-cptb-cap-plural]' );
		var $key = $( '#cptb-key' );
		var $cards = $( '.cptb-cap-mode' );

		function currentMode() {
			return String( $modes.filter( ':checked' ).val() || 'post' );
		}

		function refreshPreview() {
			var mode = currentMode();
			var singular = mode === 'custom'
				? String( $singular.val() || $key.val() || 'item' )
				: mode;
			var plural = mode === 'custom' ? String( $plural.val() || '' ) : '';
			var caps = capabilityPreview( singular, plural );

			$list.empty();
			caps.forEach( function ( cap ) {
				$list.append( $( '<li/>' ).append( $( '<code/>' ).text( cap ) ) );
			} );
		}

		function refreshModeUi() {
			var mode = currentMode();
			$cards.removeClass( 'is-selected' );
			$modes.filter( ':checked' ).closest( '.cptb-cap-mode' ).addClass( 'is-selected' );
			$custom.prop( 'hidden', mode !== 'custom' );
			refreshPreview();
		}

		$modes.on( 'change', refreshModeUi );
		$singular.add( $plural ).on( 'input', refreshPreview );
		$key.on( 'input', function () {
			if ( currentMode() !== 'custom' ) {
				return;
			}
			if ( ! $singular.val() ) {
				refreshPreview();
			}
		} );

		refreshModeUi();
	}

	function initIconPicker() {
		var $current = $( '#cptb-icon-current' );
		var $input = $( '#cptb-menu-icon' );
		var $grid = $( '#cptb-icon-grid' );
		var $list = $( '#cptb-icon-list' );
		var $search = $( '#cptb-icon-search' );

		if ( ! $current.length || ! $list.length ) {
			return;
		}

		var icons = Array.isArray( settings.dashicons ) ? settings.dashicons : [];

		icons.forEach( function ( icon ) {
			var $btn = $( '<button type="button" class="cptb-icon-option" />' )
				.attr( 'data-icon', icon )
				.attr( 'title', icon );
			$( '<span class="dashicons" />' ).addClass( icon ).appendTo( $btn );
			$list.append( $btn );
		} );

		$current.on( 'click', function () {
			$grid.prop( 'hidden', ! $grid.prop( 'hidden' ) );
		} );

		$list.on( 'click', '.cptb-icon-option', function () {
			var icon = $( this ).data( 'icon' );
			$input.val( icon );
			$current.find( '.dashicons' ).attr( 'class', 'dashicons ' + icon );
			$grid.prop( 'hidden', true );
		} );

		$input.on( 'input', function () {
			var value = String( $( this ).val() || '' );
			if ( value.indexOf( 'dashicons-' ) === 0 ) {
				$current.find( '.dashicons' ).attr( 'class', 'dashicons ' + value.replace( /[^a-z0-9-]/g, '' ) );
			}
		} );

		$search.on( 'input', function () {
			var term = String( $( this ).val() || '' ).toLowerCase();
			$list.find( '.cptb-icon-option' ).each( function () {
				var icon = String( $( this ).data( 'icon' ) || '' );
				$( this ).toggle( icon.indexOf( term ) !== -1 );
			} );
		} );

		$( document ).on( 'click', function ( e ) {
			if ( ! $( e.target ).closest( '.cptb-icon-picker' ).length ) {
				$grid.prop( 'hidden', true );
			}
		} );
	}

	$( function () {
		initTabs();
		initDeleteConfirm();
		initImportPanel();
		initKeyAutosuggest();
		initIconPicker();
		initLabelPlaceholders();
		initKeyPlaceholders();
		initDependentFields();
		initPublicMasterSwitch();
		initCapabilityModes();
	} );
} )( jQuery );
