(function ($) {
	'use strict';

	var state = JSON.parse( JSON.stringify( UNODOCK_DATA.settings ) );
	var activeIconTarget = null;
	var isPremium = !! UNODOCK_DATA.isPremium;
	var previewActiveIndex = 0;
	var defaultGeneral = $.extend( {}, UNODOCK_DATA.settings.general );

	function uid() {
		return 'btn_' + Math.random().toString(36).substr(2, 9);
	}

	function showUpsell( message ) {
		if ( confirm( ( message || UNODOCK_DATA.i18n.proRequired ) + '\n\nOK = ' + 'Go to upgrade page' ) ) {
			window.open( UNODOCK_DATA.upgradeUrl, '_blank' );
		}
	}

	/**
	 * Locks a control (and its wrapping switch, if any) behind a PRO upsell click.
	 */
	function lockControl( $control, message ) {
		$control.prop( 'disabled', true ).addClass( 'udock-locked' );
		var $wrap = $control.closest( '.udock-field, .udock-switch-row' );
		$wrap.addClass( 'udock-locked-wrap' );
		$wrap.off( 'click.udockLock' ).on( 'click.udockLock', function ( e ) {
			e.preventDefault();
			e.stopPropagation();
			showUpsell( message );
		} );
	}

	/**
	 * Applies free-tier locks to every PRO-only control. Runs once on init,
	 * and again whenever the buttons list re-renders.
	 */
	function applyProGating() {
		if ( isPremium ) {
			return;
		}
		lockControl( $( '#g-featured_enabled' ), UNODOCK_DATA.i18n.proRequired );
		lockControl( $( '#g-top_corner_radius' ), UNODOCK_DATA.i18n.proRequired );
		lockControl( $( '#g-visibility' ), UNODOCK_DATA.i18n.proRequired );
		lockControl( $( '#g-vibrate_enabled' ), UNODOCK_DATA.i18n.proRequired );

		$( '.udock-b-click_animation, .udock-b-show_cart_count' ).each( function () {
			lockControl( $( this ), UNODOCK_DATA.i18n.proRequired );
		} );
	}

	/* ---------------------------------------------------------
	 * INIT
	 * ------------------------------------------------------- */
	function init() {
		bindTabs();
		bindGeneralFields();
		bindColorPickers();
		bindRangeSliders();
		bindSizeBar();
		renderButtons();
		bindAddButton();
		bindSortable();
		bindIconModal();
		bindSave();
		bindClearCache();
		renderTemplates();
		populatePageCheckboxList( 'g-show_on_pages-list', 'show_on_pages' );
		populatePageCheckboxList( 'g-show_on_exclude_pages-list', 'show_on_exclude_pages' );
		renderPreview();
		bindPreviewInteractivity();
		applyProGating();
	}

	/* ---------------------------------------------------------
	 * TABS
	 * ------------------------------------------------------- */
	function bindTabs() {
		$( '.udock-tab' ).on( 'click', function () {
			var tab = $( this ).data( 'tab' );
			$( '.udock-tab' ).removeClass( 'active' );
			$( this ).addClass( 'active' );
			$( '.udock-panel' ).removeClass( 'active' );
			$( '.udock-panel[data-panel="' + tab + '"]' ).addClass( 'active' );
			if ( tab === 'preview' ) {
				renderPreview();
			}
		} );
	}

	/* ---------------------------------------------------------
	 * GENERAL FIELDS — value sync (no listeners) + one-time bindings
	 * ------------------------------------------------------- */
	function syncGeneralUI() {
		var g = state.general;

		$( '#g-enabled' ).prop( 'checked', !! g.enabled );
		$( '#g-sticky' ).prop( 'checked', !! g.sticky );
		$( '#g-safe_area' ).prop( 'checked', !! g.safe_area );
		$( '#g-hide_for_admins' ).prop( 'checked', !! g.hide_for_admins );
		$( '#g-uninstall_cleanup' ).prop( 'checked', !! g.uninstall_cleanup );
		$( '#g-visibility' ).val( g.visibility );
		$( '#g-show_on' ).val( g.show_on );
		$( '#g-z_index' ).val( g.z_index );
		$( '#g-featured_enabled' ).prop( 'checked', !! g.featured_enabled );
		$( '#g-featured_button_number' ).val( g.featured_button_number || 1 );
		$( '#g-underline_enabled' ).prop( 'checked', !! g.underline_enabled );
		$( '#g-active_icon_enabled' ).prop( 'checked', !! g.active_icon_enabled );
		$( '#g-vibrate_enabled' ).prop( 'checked', !! g.vibrate_enabled );
		$( 'input[name="bg_type"][value="' + ( g.bg_type || 'color' ) + '"]' ).prop( 'checked', true );
		setSizeBarValue( g.featured_size || 1 );

		[ 'bar_height', 'icon_size', 'font_size', 'top_corner_radius' ].forEach( function ( key ) {
			$( '#g-' + key ).val( g[ key ] );
			$( '#val-' + key ).text( g[ key ] );
		} );

		[ 'icon_color', 'icon_color_active', 'text_color', 'underline_color', 'bg_color', 'bg_gradient_start', 'bg_gradient_end' ].forEach( function ( key ) {
			var $el = $( '#g-' + key );
			if ( $el.hasClass( 'wp-color-picker' ) || $el.next( '.wp-picker-container' ).length ) {
				$el.wpColorPicker( 'color', g[ key ] );
			} else {
				$el.val( g[ key ] );
			}
		} );

		toggleShowOnPages();
		toggleFeaturedNumber();
		toggleBgType();
		toggleUnderline();
		toggleActiveIcon();
	}

	function bindGeneralFields() {
		syncGeneralUI();

		$( '#g-enabled' ).on( 'change', function () { state.general.enabled = this.checked; } );
		$( '#g-sticky' ).on( 'change', function () { state.general.sticky = this.checked; } );
		$( '#g-safe_area' ).on( 'change', function () { state.general.safe_area = this.checked; } );
		$( '#g-hide_for_admins' ).on( 'change', function () { state.general.hide_for_admins = this.checked; } );
		$( '#g-uninstall_cleanup' ).on( 'change', function () { state.general.uninstall_cleanup = this.checked; } );
		$( '#g-visibility' ).on( 'change', function () { state.general.visibility = this.value; } );
		$( '#g-z_index' ).on( 'input', function () { state.general.z_index = parseInt( this.value, 10 ) || 9999; } );

		$( '#g-show_on' ).on( 'change', function () {
			state.general.show_on = this.value;
			toggleShowOnPages();
		} );

		$( '#g-featured_enabled' ).on( 'change', function () {
			state.general.featured_enabled = this.checked;
			toggleFeaturedNumber();
			renderButtonNumbers();
			renderPreview();
		} );

		$( '#g-featured_button_number' ).on( 'change', function () {
			state.general.featured_button_number = parseInt( this.value, 10 ) || 1;
			renderButtonNumbers();
			renderPreview();
		} );

		$( 'input[name="bg_type"]' ).on( 'change', function () {
			state.general.bg_type = this.value;
			toggleBgType();
			renderPreview();
		} );

		$( '#g-underline_enabled' ).on( 'change', function () {
			state.general.underline_enabled = this.checked;
			toggleUnderline();
			renderPreview();
		} );

		$( '#g-active_icon_enabled' ).on( 'change', function () {
			state.general.active_icon_enabled = this.checked;
			toggleActiveIcon();
			renderPreview();
		} );

		$( '#g-vibrate_enabled' ).on( 'change', function () {
			state.general.vibrate_enabled = this.checked;
		} );
	}

	function toggleShowOnPages() {
		$( '#g-show_on_pages-wrap' ).toggle( state.general.show_on === 'specific' );
		$( '#g-show_on_exclude_pages-wrap' ).toggle( state.general.show_on === 'exclude' );
	}

	function toggleFeaturedNumber() {
		$( '#g-featured_number-wrap' ).toggle( !! state.general.featured_enabled );
		$( '#g-featured_size-wrap' ).toggle( !! state.general.featured_enabled );
	}

	/**
	 * Updates the visual state (filled dots) of the 5-position featured-size bar.
	 */
	function setSizeBarValue( value ) {
		value = Math.max( 1, Math.min( 5, parseInt( value, 10 ) || 1 ) );
		var $bar = $( '#g-featured_size-bar' );
		$bar.attr( 'data-value', value );
		$bar.find( '.udock-size-bar-dot' ).each( function () {
			var dotSize = parseInt( $( this ).data( 'size' ), 10 );
			$( this ).toggleClass( 'active', dotSize <= value );
		} );
	}

	function bindSizeBar() {
		$( '#g-featured_size-bar .udock-size-bar-dot' ).on( 'click', function () {
			var size = parseInt( $( this ).data( 'size' ), 10 );
			state.general.featured_size = size;
			setSizeBarValue( size );
			renderPreview();
		} );
	}

	function toggleBgType() {
		var isGradient = state.general.bg_type === 'gradient';
		$( '#g-bg_color-wrap' ).toggle( ! isGradient );
		$( '#g-bg_gradient-wrap' ).toggle( isGradient );
	}

	function toggleUnderline() {
		$( '#g-underline_color-wrap' ).toggle( !! state.general.underline_enabled );
	}

	function toggleActiveIcon() {
		$( '#g-icon_color_active-wrap' ).toggle( !! state.general.active_icon_enabled );
	}

	/**
	 * Builds a checkbox list bound to a general settings array (e.g. show_on_pages).
	 */
	function populatePageCheckboxList( listId, stateKey ) {
		var $list = $( '#' + listId ).empty();

		if ( ! UNODOCK_DATA.pages.length ) {
			$list.append( '<div class="udock-checkbox-list-empty">No pages found.</div>' );
			return;
		}

		UNODOCK_DATA.pages.forEach( function ( p ) {
			var checked = state.general[ stateKey ].indexOf( p.id ) !== -1;
			var $label = $( '<label></label>' );
			var $cb = $( '<input type="checkbox" />' ).val( p.id ).prop( 'checked', checked );

			$cb.on( 'change', function () {
				var id = parseInt( this.value, 10 );
				var idx = state.general[ stateKey ].indexOf( id );
				if ( this.checked && idx === -1 ) {
					state.general[ stateKey ].push( id );
				} else if ( ! this.checked && idx !== -1 ) {
					state.general[ stateKey ].splice( idx, 1 );
				}
			} );

			$label.append( $cb ).append( ' ' + p.title );
			$list.append( $label );
		} );
	}

	/* ---------------------------------------------------------
	 * COLOR PICKERS (general fields — initialized once)
	 * ------------------------------------------------------- */
	function bindColorPickers() {
		var fields = [ 'icon_color', 'icon_color_active', 'text_color', 'underline_color', 'bg_color', 'bg_gradient_start', 'bg_gradient_end' ];
		fields.forEach( function ( key ) {
			$( '#g-' + key ).val( state.general[ key ] ).wpColorPicker( {
				change: function ( event, ui ) {
					state.general[ key ] = ui.color.toString();
					renderPreview();
				},
				clear: function () {
					state.general[ key ] = '';
					renderPreview();
				}
			} );
		} );
	}

	/* ---------------------------------------------------------
	 * RANGE SLIDERS
	 * ------------------------------------------------------- */
	function bindRangeSliders() {
		var fields = [ 'bar_height', 'icon_size', 'font_size', 'top_corner_radius' ];
		fields.forEach( function ( key ) {
			var $range = $( '#g-' + key );
			$range.val( state.general[ key ] );
			$( '#val-' + key ).text( state.general[ key ] );
			$range.on( 'input', function () {
				state.general[ key ] = parseInt( this.value, 10 );
				$( '#val-' + key ).text( this.value );
				renderPreview();
			} );
		} );
	}

	/* ---------------------------------------------------------
	 * BUTTONS LIST
	 * ------------------------------------------------------- */
	function renderButtons() {
		var $list = $( '#udock-buttons-list' ).empty();
		var tpl = $( '#udock-button-template' ).html();

		state.buttons.forEach( function ( btn ) {
			var html = tpl
				.replace( /{{id}}/g, btn.id )
				.replace( /{{icon}}/g, btn.icon )
				.replace( /{{label}}/g, btn.label || '(no text)' );

			var $item = $( html );
			$item.attr( 'data-id', btn.id );
			fillButtonFields( $item, btn );
			bindButtonEvents( $item, btn );
			$list.append( $item );
		} );

		updateAddButtonState();
		renderButtonNumbers();

		if ( ! isPremium ) {
			$( '.udock-b-click_animation, .udock-b-show_cart_count' ).each( function () {
				lockControl( $( this ), UNODOCK_DATA.i18n.proRequired );
			} );
		}
	}

	/**
	 * Updates the position number (1-6) shown next to each button,
	 * and highlights the one currently set as "featured".
	 */
	function renderButtonNumbers() {
		$( '#udock-buttons-list .udock-button-item' ).each( function ( index ) {
			var $numberEl = $( this ).find( '.udock-button-number' );
			var position = index + 1;
			$numberEl.text( position );

			var isFeatured = !! state.general.featured_enabled && ( state.general.featured_button_number === position );
			$numberEl.toggleClass( 'udock-is-featured', isFeatured );
		} );
	}

	function fillButtonFields( $item, btn ) {
		$item.find( '.udock-b-label' ).val( btn.label );
		$item.find( '.udock-b-show_label' ).prop( 'checked', !! btn.show_label );
		$item.find( '.udock-b-label_position' ).val( btn.label_position );
		$item.find( 'input.udock-b-link_type[value="' + btn.link_type + '"]' ).prop( 'checked', true );
		$item.find( '.udock-b-url' ).val( btn.url );

		var $pageSel = $item.find( '.udock-b-page_id' ).empty();
		$pageSel.append( $( '<option>' ).val( 0 ).text( '— Select a page —' ) );
		UNODOCK_DATA.pages.forEach( function ( p ) {
			$pageSel.append( $( '<option>' ).val( p.id ).text( p.title ).prop( 'selected', p.id === btn.page_id ) );
		} );

		$item.find( '.udock-b-click_animation' ).val( btn.click_animation || 'none' );

		$item.find( '.udock-b-icon_bg_enabled' ).prop( 'checked', !! btn.icon_bg_enabled );
		$item.find( 'input.udock-b-icon_bg_type[value="' + ( btn.icon_bg_type || 'color' ) + '"]' ).prop( 'checked', true );

		bindColorPickerOnce( $item.find( '.udock-b-icon_bg_color' ), btn.icon_bg_color || '#D462FF', function ( val ) {
			findButton( btn.id ).icon_bg_color = val;
			renderPreview();
		} );
		bindColorPickerOnce( $item.find( '.udock-b-icon_bg_gradient_start' ), btn.icon_bg_gradient_start || '#16E2F5', function ( val ) {
			findButton( btn.id ).icon_bg_gradient_start = val;
			renderPreview();
		} );
		bindColorPickerOnce( $item.find( '.udock-b-icon_bg_gradient_end' ), btn.icon_bg_gradient_end || '#D462FF', function ( val ) {
			findButton( btn.id ).icon_bg_gradient_end = val;
			renderPreview();
		} );

		$item.find( '.udock-b-show_cart_count' ).prop( 'checked', !! btn.show_cart_count );
		$item.find( '.udock-b-woo-row, .udock-b-woo-divider' ).toggle( !! UNODOCK_DATA.wooCommerceActive );

		toggleIconBgOptions( $item, btn.icon_bg_enabled );
		toggleIconBgTypeFields( $item, btn.icon_bg_type || 'color' );
		toggleLinkTypeFields( $item, btn.link_type );
	}

	/**
	 * Initializes a wp-color-picker on an element only once (avoids re-init on re-render),
	 * or updates its value if it already exists.
	 */
	function bindColorPickerOnce( $input, value, onChange ) {
		if ( $input.hasClass( 'wp-color-picker' ) ) {
			$input.wpColorPicker( 'color', value );
			return;
		}
		$input.val( value );
		$input.wpColorPicker( {
			change: function ( event, ui ) {
				onChange( ui.color.toString() );
			},
			clear: function () {
				onChange( '' );
			}
		} );
	}

	function toggleIconBgOptions( $item, enabled ) {
		$item.find( '.udock-icon-bg-options' ).toggle( !! enabled );
	}

	function toggleIconBgTypeFields( $item, type ) {
		$item.find( '.udock-b-icon_bg_color-wrap' ).toggle( type === 'color' );
		$item.find( '.udock-b-icon_bg_gradient-wrap' ).toggle( type === 'gradient' );
	}

	function toggleLinkTypeFields( $item, type ) {
		$item.find( '.udock-b-url-wrap' ).toggle( type === 'url' );
		$item.find( '.udock-b-page-wrap' ).toggle( type === 'page' );
		$item.find( '.udock-b-search-note-wrap' ).toggle( type === 'search' );
	}

	function findButton( id ) {
		return state.buttons.find( function ( b ) { return b.id === id; } );
	}

	function bindButtonEvents( $item, btn ) {
		var id = btn.id;

		// Accordion: opening a button closes every other open one.
		$item.find( '.udock-button-toggle, .udock-button-item-head .udock-button-item-label' ).on( 'click', function () {
			var willOpen = ! $item.hasClass( 'open' );
			$( '#udock-buttons-list .udock-button-item' ).removeClass( 'open' );
			if ( willOpen ) {
				$item.addClass( 'open' );
			}
		} );

		$item.find( '.udock-button-remove' ).on( 'click', function ( e ) {
			e.stopPropagation();
			if ( ! confirm( UNODOCK_DATA.i18n.confirmDel ) ) {
				return;
			}
			state.buttons = state.buttons.filter( function ( b ) { return b.id !== id; } );
			renderButtons();
			renderPreview();
		} );

		$item.find( '.udock-b-label' ).on( 'input', function () {
			findButton( id ).label = this.value;
			$item.find( '.udock-button-item-label' ).text( this.value || '(no text)' );
			renderPreview();
		} );

		$item.find( '.udock-b-show_label' ).on( 'change', function () {
			findButton( id ).show_label = this.checked;
			renderPreview();
		} );

		$item.find( '.udock-b-label_position' ).on( 'change', function () {
			findButton( id ).label_position = this.value;
			renderPreview();
		} );

		$item.find( '.udock-b-link_type' ).on( 'change', function () {
			findButton( id ).link_type = this.value;
			toggleLinkTypeFields( $item, this.value );
		} );

		$item.find( '.udock-b-url' ).on( 'input', function () {
			findButton( id ).url = this.value;
		} );

		$item.find( '.udock-b-page_id' ).on( 'change', function () {
			findButton( id ).page_id = parseInt( this.value, 10 ) || 0;
		} );

		$item.find( '.udock-b-click_animation' ).on( 'change', function () {
			findButton( id ).click_animation = this.value;
		} );

		$item.find( '.udock-b-icon_bg_enabled' ).on( 'change', function () {
			findButton( id ).icon_bg_enabled = this.checked;
			toggleIconBgOptions( $item, this.checked );
			renderPreview();
		} );

		$item.find( '.udock-b-icon_bg_type' ).on( 'change', function () {
			findButton( id ).icon_bg_type = this.value;
			toggleIconBgTypeFields( $item, this.value );
			renderPreview();
		} );

		$item.find( '.udock-b-show_cart_count' ).on( 'change', function () {
			findButton( id ).show_cart_count = this.checked;
		} );

		$item.find( '.udock-icon-picker-btn' ).on( 'click', function () {
			openIconModal( id, $item );
		} );
	}

	function bindAddButton() {
		$( '#udock-add-button' ).on( 'click', function () {
			if ( state.buttons.length >= UNODOCK_DATA.maxButtons ) {
				alert( isPremium ? UNODOCK_DATA.i18n.maxReachedPro : UNODOCK_DATA.i18n.maxReached );
				return;
			}
			state.buttons.push( newButtonDefaults() );
			renderButtons();
			renderPreview();
		} );
	}

	function newButtonDefaults() {
		return {
			id: uid(),
			icon: 'fa-star',
			label: UNODOCK_DATA.i18n.newButton,
			show_label: true,
			label_position: 'bottom',
			link_type: 'url',
			url: '#',
			page_id: 0,
			click_animation: 'none',
			icon_bg_enabled: false,
			icon_bg_type: 'color',
			icon_bg_color: '#D462FF',
			icon_bg_gradient_start: '#16E2F5',
			icon_bg_gradient_end: '#D462FF',
			show_cart_count: false
		};
	}

	function updateAddButtonState() {
		$( '#udock-add-button' ).prop( 'disabled', state.buttons.length >= UNODOCK_DATA.maxButtons );
	}

	/* ---------------------------------------------------------
	 * SORTABLE (drag & drop reorder)
	 * ------------------------------------------------------- */
	function bindSortable() {
		$( '#udock-buttons-list' ).sortable( {
			handle: '.udock-drag-handle',
			placeholder: 'udock-sorting-placeholder',
			axis: 'y',
			update: function () {
				var order = $( '#udock-buttons-list' ).children().map( function () {
					return $( this ).data( 'id' );
				} ).get();

				state.buttons.sort( function ( a, b ) {
					return order.indexOf( a.id ) - order.indexOf( b.id );
				} );
				renderButtonNumbers();
				renderPreview();
			}
		} );
	}

	/* ---------------------------------------------------------
	 * ICON PICKER MODAL
	 * ------------------------------------------------------- */
	function bindIconModal() {
		var $grid = $( '#udock-icon-grid' );
		var categories = UNODOCK_DATA.iconCategories || {};
		var flatIcons = {};

		Object.keys( categories ).forEach( function ( categoryName ) {
			$.extend( flatIcons, categories[ categoryName ] );
		} );

		Object.keys( flatIcons ).forEach( function ( iconClass ) {
			var label = flatIcons[ iconClass ];
			var $opt = $( '<div class="udock-icon-option" tabindex="0">' )
				.attr( 'data-icon', iconClass )
				.html( '<i class="fa-solid ' + iconClass + '"></i><span>' + label + '</span>' );
			$opt.on( 'click', function () {
				if ( ! activeIconTarget ) return;
				var btn = findButton( activeIconTarget.id );
				btn.icon = iconClass;
				activeIconTarget.$item.find( '.udock-icon-picker-btn i' ).attr( 'class', 'fa-solid ' + iconClass );
				activeIconTarget.$item.find( '.udock-button-icon-preview i' ).attr( 'class', 'fa-solid ' + iconClass );
				closeIconModal();
				renderPreview();
			} );
			$grid.append( $opt );
		} );

		$( '#udock-icon-search' ).on( 'input', function () {
			var q = this.value.toLowerCase();
			$grid.find( '.udock-icon-option' ).each( function () {
				var txt = $( this ).text().toLowerCase();
				$( this ).toggle( txt.indexOf( q ) !== -1 );
			} );
		} );

		$( '.udock-modal-close, #udock-icon-modal' ).on( 'click', function ( e ) {
			if ( e.target === this ) closeIconModal();
		} );
	}

	function openIconModal( id, $item ) {
		activeIconTarget = { id: id, $item: $item };
		$( '#udock-icon-search' ).val( '' ).trigger( 'input' );
		$( '#udock-icon-modal' ).addClass( 'open' );
	}

	function closeIconModal() {
		$( '#udock-icon-modal' ).removeClass( 'open' );
		activeIconTarget = null;
	}

	/* ---------------------------------------------------------
	 * TEMPLATES
	 * ------------------------------------------------------- */
	function renderTemplates() {
		var $grid = $( '#udock-templates-grid' ).empty();
		var templates = UNODOCK_DATA.templates || {};

		Object.keys( templates ).forEach( function ( key ) {
			var tpl = templates[ key ];
			var $card = $( '<div class="udock-template-card"></div>' );
			var $previewFrame = $( '<div class="udock-template-preview"></div>' );
			var mergedGeneral = $.extend( {}, defaultGeneral, tpl.general );
			var $bar = buildPreviewBar( mergedGeneral, tpl.buttons );

			if ( tpl.pro ) {
				$card.addClass( 'udock-template-pro' );
				$previewFrame.append( '<span class="udock-pro-badge">PRO</span>' );
			}

			$previewFrame.append( $bar );
			$card.append( $previewFrame );
			$card.append( '<div class="udock-template-name">' + escapeHtml( tpl.label ) + '</div>' );

			var $applyBtn = $( '<button type="button" class="udock-btn udock-btn-outline udock-template-apply">Use this template</button>' );

			if ( tpl.pro && ! isPremium ) {
				$applyBtn.text( 'Unlock with PRO' );
				$applyBtn.on( 'click', function () {
					showUpsell( UNODOCK_DATA.i18n.proTemplate );
				} );
			} else {
				$applyBtn.on( 'click', function () {
					if ( ! confirm( UNODOCK_DATA.i18n.confirmTemplate ) ) {
						return;
					}
					applyTemplate( tpl );
				} );
			}

			$card.append( $applyBtn );
			$grid.append( $card );
		} );
	}

	function applyTemplate( tpl ) {
		state.general = $.extend( {}, state.general, JSON.parse( JSON.stringify( tpl.general ) ) );
		state.buttons = JSON.parse( JSON.stringify( tpl.buttons ) );

		syncGeneralUI();
		renderButtons();
		renderPreview();

		var $status = $( '#udock-save-status' );
		$status.text( UNODOCK_DATA.i18n.templateApplied ).removeClass( 'error' ).addClass( 'show' );
		setTimeout( function () { $status.removeClass( 'show' ); }, 4000 );

		$( '.udock-tab[data-tab="buttons"]' ).trigger( 'click' );
	}

	/**
	 * Builds a small preview bar element from a given general/buttons config.
	 * Shared between the main live Preview tab and the Templates cards.
	 */
	function featuredScale( size ) {
		var map = { 1: 1.5, 2: 1.65, 3: 1.8, 4: 1.9, 5: 2.0 };
		size = Math.max( 1, Math.min( 5, parseInt( size, 10 ) || 1 ) );
		return map[ size ];
	}

	function buildPreviewBar( g, buttons, options ) {
		options = options || {};
		var activeIndex = typeof options.activeIndex === 'number' ? options.activeIndex : 0;
		var interactive = !! options.interactive;

		var $bar = $( '<div class="udock-preview-bar"></div>' );
		var radiusPx = ( g.top_corner_radius || 0 ) * 2;
		var barBg = g.bg_type === 'gradient'
			? 'linear-gradient(135deg,' + g.bg_gradient_start + ',' + g.bg_gradient_end + ')'
			: g.bg_color;

		$bar.css( {
			height: ( g.bar_height || 60 ) + 'px',
			background: barBg,
			borderTopLeftRadius: radiusPx + 'px',
			borderTopRightRadius: radiusPx + 'px',
			overflow: 'visible',
			position: 'static'
		} );

		buttons.forEach( function ( btn, index ) {
			var position = index + 1;
			var isFeatured = !! g.featured_enabled && ( g.featured_button_number === position );
			var isActive = index === activeIndex;
			var color = ( isActive && g.active_icon_enabled ) ? g.icon_color_active : g.icon_color;
			var textColor = g.text_color;
			var iconSize = g.icon_size || 22;

			var $btn = $( '<div class="udock-preview-btn"></div>' );
			var content = '';
			var iconStyle = '';
			var fScale = featuredScale( g.featured_size || 1 );

			if ( isFeatured ) {
				iconSize = Math.round( iconSize * fScale );
			}

			if ( btn.icon_bg_enabled ) {
				var bgSize = Math.round( ( g.icon_size || 22 ) * ( isFeatured ? ( fScale + 0.7 ) : 1.9 ) );
				var isGradient = btn.icon_bg_type === 'gradient';
				var bgCss = isGradient
					? 'linear-gradient(135deg,' + btn.icon_bg_gradient_start + ',' + btn.icon_bg_gradient_end + ')'
					: btn.icon_bg_color;

				iconStyle = 'display:inline-flex;align-items:center;justify-content:center;box-sizing:border-box;width:' + bgSize + 'px;height:' + bgSize + 'px;border-radius:50%;background:' + bgCss + ';box-shadow:0 4px 12px rgba(0,0,0,.2);';
				if ( isFeatured ) {
					iconStyle += 'margin-top:-16px;';
				}
				color = '#ffffff';
				iconSize = Math.round( iconSize * 0.867 );
			}

			var showUnderline = isActive && g.underline_enabled;
			var labelStyle = 'font-size:' + ( g.font_size || 11 ) + 'px;color:' + textColor + ';';
			var labelClass = 'udock-preview-label' + ( showUnderline ? ' udock-preview-label-active' : '' );
			var underlineVar = showUnderline ? ' --udock-preview-underline:' + ( g.underline_color || '#16E2F5' ) + ';' : '';

			if ( btn.show_label && btn.label_position === 'top' ) {
				content += '<span class="' + labelClass + '" style="' + labelStyle + underlineVar + '">' + escapeHtml( btn.label ) + '</span>';
			}
			content += '<span style="' + iconStyle + '"><i class="fa-solid ' + btn.icon + '" style="font-size:' + iconSize + 'px;color:' + color + ';"></i></span>';
			if ( btn.show_label && btn.label_position !== 'top' ) {
				content += '<span class="' + labelClass + '" style="' + labelStyle + underlineVar + '">' + escapeHtml( btn.label ) + '</span>';
			}
			$btn.html( content );

			if ( interactive ) {
				$btn.addClass( 'udock-preview-btn-clickable' ).attr( 'data-preview-index', index );
			}

			$bar.append( $btn );
		} );

		return $bar;
	}

	/* ---------------------------------------------------------
	 * LIVE PREVIEW (main Preview tab)
	 * ------------------------------------------------------- */
	function renderPreview() {
		var $frame = $( '.udock-preview-frame' ).not( '.udock-template-preview' );
		$frame.find( '#udock-preview-bar' ).remove();

		if ( previewActiveIndex >= state.buttons.length ) {
			previewActiveIndex = 0;
		}

		var $newBar = buildPreviewBar( state.general, state.buttons, {
			activeIndex: previewActiveIndex,
			interactive: true
		} ).attr( 'id', 'udock-preview-bar' );
		$newBar.css( { position: 'absolute', bottom: 0, left: 0, right: 0 } );
		$frame.append( $newBar );
	}

	/**
	 * Lets the user click any button in the main Preview tab to see how the
	 * active state (underline, active icon color, etc.) looks on it.
	 */
	function bindPreviewInteractivity() {
		var $frame = $( '.udock-preview-frame' ).not( '.udock-template-preview' );
		$frame.on( 'click', '.udock-preview-btn-clickable', function () {
			previewActiveIndex = parseInt( $( this ).data( 'preview-index' ), 10 ) || 0;
			renderPreview();
		} );
	}

	function escapeHtml( str ) {
		return $( '<div>' ).text( str || '' ).html();
	}

	/* ---------------------------------------------------------
	 * SAVE
	 * ------------------------------------------------------- */
	function bindSave() {
		function performSave() {
			var $buttons = $( '#udock-save-btn, #udock-floating-save-btn' );
			var $status = $( '#udock-save-status' );

			$buttons.prop( 'disabled', true );

			$.post( UNODOCK_DATA.ajaxUrl, {
				action: 'udock_save_settings',
				nonce: UNODOCK_DATA.nonce,
				payload: JSON.stringify( state )
			} ).done( function ( res ) {
				if ( res.success ) {
					$status.text( UNODOCK_DATA.i18n.saved ).removeClass( 'error' ).addClass( 'show' );
				} else {
					$status.text( UNODOCK_DATA.i18n.error ).addClass( 'error show' );
				}
			} ).fail( function () {
				$status.text( UNODOCK_DATA.i18n.error ).addClass( 'error show' );
			} ).always( function () {
				$buttons.prop( 'disabled', false );
				setTimeout( function () { $status.removeClass( 'show' ); }, 3000 );
			} );
		}

		$( '#udock-save-btn, #udock-floating-save-btn' ).on( 'click', performSave );
	}

	/* ---------------------------------------------------------
	 * CLEAR CACHE
	 * ------------------------------------------------------- */
	function bindClearCache() {
		$( '#udock-clear-cache-btn' ).on( 'click', function () {
			if ( ! confirm( UNODOCK_DATA.i18n.confirmCache ) ) {
				return;
			}
			var $btn = $( this );
			var $status = $( '#udock-save-status' );

			$btn.prop( 'disabled', true );

			$.post( UNODOCK_DATA.ajaxUrl, {
				action: 'udock_clear_cache',
				nonce: UNODOCK_DATA.clearCacheNonce
			} ).done( function ( res ) {
				if ( res.success ) {
					$status.text( UNODOCK_DATA.i18n.cacheCleared ).removeClass( 'error' ).addClass( 'show' );
				} else {
					$status.text( UNODOCK_DATA.i18n.cacheError ).addClass( 'error show' );
				}
			} ).fail( function () {
				$status.text( UNODOCK_DATA.i18n.cacheError ).addClass( 'error show' );
			} ).always( function () {
				$btn.prop( 'disabled', false );
				setTimeout( function () { $status.removeClass( 'show' ); }, 3000 );
			} );
		} );
	}

	$( init );

})( jQuery );
