/**
 * Admin Columns Customizer JavaScript
 *
 * @package AdminColumnsCustomizer
 * @since 1.0.0
 */

(function($) {
	'use strict';

	const AdminColumns = {
		currentScreenType: '',
		currentScreenId: '',
		currentColumns: [],
		currentLayout: {},
		hasListVisit: false,
		columnTypesCache: {},

		init: function() {
			this.bindEvents();
			this.initLayoutAccordion();
			this.updateSortableRowVisibility();
			this.loadColumns();
		},

		initLayoutAccordion: function() {
			const self = this;
			const storageKey = 'wpps_admin_columns_layout_accordion_open';

			function setOpen(isOpen) {
				const $accordion = $('#wpps-layout-accordion');
				if (!$accordion.length) {
					return;
				}
				$accordion.toggleClass('is-open', isOpen);
				$accordion.find('.wpps-acc-accordion-header').attr('aria-expanded', isOpen ? 'true' : 'false');
			}

			try {
				const stored = localStorage.getItem(storageKey);
				if (stored !== null) {
					setOpen(stored === '1');
				}
			} catch (e) {
			}

			$(document).on('click', '#wpps-layout-accordion .wpps-acc-accordion-header', function(e) {
				e.preventDefault();
				const $accordion = $(this).closest('.wpps-acc-accordion');
				const isOpen = !$accordion.hasClass('is-open');
				setOpen(isOpen);
				try {
					localStorage.setItem(storageKey, isOpen ? '1' : '0');
				} catch (err) {
				}
			});
		},

		syncFreezeColumnsVisibility: function() {
			const disabled = $('#wpps-disable-horizontal-scroll').is(':checked');
			$('.wpps-freeze-columns-row').toggleClass('is-hidden', disabled);
			if (disabled) {
				$('#wpps-freeze-first-columns').val('0');
			}
		},

		layoutHasActiveSettings: function(layout) {
			if (!layout || typeof layout !== 'object') {
				return false;
			}
			return !!(
				layout.disable_horizontal_scroll ||
				layout.freeze_header_row ||
				(parseInt(layout.freeze_first_columns, 10) || 0) > 0 ||
				layout.default_sort_column
			);
		},

		updateSortableRowVisibility: function() {
			const supported = !!(wppsAdminColumns.sortableSupported);
			$('#wpps-column-sortable-row').toggle(supported);
			if (!supported) {
				$('#wpps-column-sortable').prop('checked', false);
			}
		},

		bindEvents: function() {
			const self = this;

			// Screen type tabs
			$('.wpps-tab-button').on('click', function() {
				$('.wpps-tab-button').removeClass('active');
				$(this).addClass('active');

				const screenType = $(this).data('screen-type');
				$('.wpps-screen-list').hide();
				$('.wpps-screen-list[data-screen-type="' + screenType + '"]').show();
			});

			$('.wpps-save-columns').on('click', function() {
				self.saveColumns();
			});

			$(document).on('change', '#wpps-disable-horizontal-scroll', function() {
				self.syncFreezeColumnsVisibility();
			});

			// Restore columns - use event delegation to ensure it works
			$(document).on('click', '.wpps-restore-columns', function(e) {
				e.preventDefault();
				e.stopPropagation();
				if (confirm(wppsAdminColumns.strings.confirmRestore || 'Are you sure you want to restore default columns? This will remove all customizations for this screen.')) {
					self.restoreColumns();
				}
				return false;
			});

			$(document).on('click', '.wpps-reset-all-columns', function(e) {
				e.preventDefault();
				e.stopPropagation();
				if (confirm(wppsAdminColumns.strings.confirmResetAll || 'Are you sure you want to reset ALL column settings for this entire module? This will remove all customizations for all screens.')) {
					self.resetAllColumns();
				}
				return false;
			});

			$('.wpps-add-column').on('click', function() {
				self.openAddColumnModal();
			});

			// Modal close
			$('.wpps-modal-close, .wpps-modal-cancel').on('click', function() {
				self.closeAddColumnModal();
			});

			// Column type change
			$('#wpps-column-type').on('change', function() {
				self.handleColumnTypeChange($(this).val());
			});

			$('#wpps-taxonomy').on('change', function() {
				const slug = $(this).val();
				if (!slug) {
					return;
				}
				const label = $(this).find('option:selected').text();
				if (label) {
					$('#wpps-column-label').val(label);
				}
			});

			// Browse fields
			$('.wpps-browse-fields').on('click', function() {
				self.browseCustomFields();
			});

			$('.wpps-modal-save').on('click', function() {
				self.saveNewColumn();
			});

			// Width value input
			$('#wpps-column-width-value').on('input', function() {
				const value = $(this).val().trim();
				// If user starts typing and auto is selected, switch to px
				if (value !== '' && $('input[name="wpps-width-unit"]:checked').val() === 'auto') {
					$('#wpps-width-unit-px').prop('checked', true);
				}
				self.updateWidthValue();
			});

			$('#wpps-column-width-value').on('blur', function() {
				self.updateWidthValue();
			});

			// Width unit radio buttons
			$('input[name="wpps-width-unit"]').on('change', function() {
				const unit = $(this).val();
				// If auto is selected, clear the input
				if (unit === 'auto') {
					$('#wpps-column-width-value').val('');
				}
				self.updateWidthValue();
			});

			// Quick-add buttons
			$(document).on('click', '.wpps-quick-add-btn:not(.added)', function(e) {
				e.preventDefault();
				const $btn = $(this);
				const type = $btn.data('type');
				const key = $btn.data('key');
				const label = $btn.data('label');
				const taxonomy = $btn.data('taxonomy') || '';

				if (self.currentColumns.some(function(c) { return c.key === key; })) {
					self.showNotice(wppsAdminColumns.quickAdd && wppsAdminColumns.quickAdd.labels ? wppsAdminColumns.quickAdd.labels.columnExists : 'Column already exists', 'error');
					return;
				}

				const columnData = {
					key: key,
					label: label,
					type: type,
					custom: true,
					hidden: false,
					sortable: false,
					width: null,
					force_width: false,
					css_class: ''
				};
				if (type === 'taxonomy' && taxonomy) {
					columnData.taxonomy = taxonomy;
				}

				self.currentColumns.push(columnData);
				self.renderColumns();
				self.updateQuickAddState();
				self.showNotice(wppsAdminColumns.strings.saved ? 'Column added. Save changes to apply.' : 'Column added. Save changes to apply.', 'success');
			});

			$(document).on('click', '.wpps-column-delete', function(e) {
				e.preventDefault();
				if (confirm(wppsAdminColumns.strings.confirmDelete || 'Are you sure you want to delete this column?')) {
					const $item = $(this).closest('.wpps-column-item');
					const key = $item.data('column-key');
					self.currentColumns = self.currentColumns.filter(c => c.key !== key);
					$item.remove();
					self.updateColumnOrder();
				}
			});

			// Edit column
			$(document).on('click', '.wpps-column-edit', function(e) {
				e.preventDefault();
				e.stopPropagation();
				const $item = $(this).closest('.wpps-column-item');
				const key = $item.data('column-key');
				let columnData = null;
				
				// Always get fresh data from currentColumns array first (this has the latest saved data)
				if (key && self.currentColumns && self.currentColumns.length > 0) {
					columnData = self.currentColumns.find(c => c.key === key);
					// Make a deep copy to avoid mutating the original
					if (columnData) {
						columnData = $.extend({}, columnData);
					}
				}
				
				// If not found in currentColumns, try data attribute (fallback)
				if (!columnData) {
					columnData = $item.data('column-data');
					if (columnData) {
						columnData = $.extend({}, columnData);
					}
				}
				
				// If still no column data, create it from the DOM (last resort)
				if (!columnData || !columnData.key) {
					const label = $item.find('.wpps-column-label').text();
					const hidden = !$item.find('.wpps-column-checkbox').is(':checked');
					columnData = {
						key: key,
						label: label,
						hidden: hidden,
						custom: false,
						type: '',
						sortable: false,
						width: null
					};
				}
				
				if (!columnData.label || columnData.label === '') {
					columnData.label = $item.find('.wpps-column-label').text();
				}
				
				if (!columnData.key && key) {
					columnData.key = key;
				}
				
				self.openEditColumnModal(columnData);
			});

			// Checkbox toggle
			$(document).on('change', '.wpps-column-checkbox', function() {
				self.updateColumnOrder();
			});

			this.initSortable();
		},

		initSortable: function() {
			const self = this;
			$('#wpps-columns-sortable .wpps-columns-items').sortable({
				handle: '.wpps-column-handle',
				placeholder: 'wpps-column-item ui-sortable-placeholder',
				axis: 'y',
				update: function() {
					self.updateColumnOrder();
				}
			});
		},

		loadColumns: function() {
			const editor = $('.wpps-columns-editor');
			if (!editor.length) {
				return;
			}

			this.currentScreenType = editor.data('screen-type');
			this.currentScreenId = editor.data('screen-id');

			if (!this.currentScreenType || !this.currentScreenId) {
				return;
			}

			this.fetchColumns();
		},

		fetchColumns: function() {
			const self = this;
			$('.wpps-columns-loading').show();
			$('.wpps-columns-items').empty();

			$.ajax({
				url: wppsAdminColumns.ajaxUrl,
				type: 'GET',
				data: {
					action: 'wpps_get_column_config',
					screen_type: this.currentScreenType,
					screen_id: this.currentScreenId,
					nonce: wppsAdminColumns.nonce
				},
				success: function(response) {
					$('.wpps-columns-loading').hide();
					if (response.success) {
						self.currentColumns = response.data.config.columns || [];
						self.currentLayout = response.data.config.layout || {};
						self.hasListVisit = !!response.data.config.has_list_visit;
						self.applyLayoutSettings(response.data.config);
						self.renderColumns();
						self.prefetchColumnTypes();
					} else {
						self.showNotice(response.data.message || wppsAdminColumns.strings.error, 'error');
					}
				},
				error: function() {
					$('.wpps-columns-loading').hide();
					self.showNotice(wppsAdminColumns.strings.error, 'error');
				}
			});
		},

		applyLayoutSettings: function(config) {
			if (!$('.wpps-layout-settings').length) {
				return;
			}

			const layout = config.layout || {};
			$('#wpps-disable-horizontal-scroll').prop('checked', !!layout.disable_horizontal_scroll);
			$('#wpps-freeze-first-columns').val(String(layout.freeze_first_columns || 0));
			$('#wpps-freeze-header-row').prop('checked', !!layout.freeze_header_row);
			$('#wpps-default-sort-order').val(layout.default_sort_order || 'desc');
			this.syncFreezeColumnsVisibility();

			const $sortColumn = $('#wpps-default-sort-column');
			const currentValue = layout.default_sort_column || '';
			$sortColumn.find('option:not(:first)').remove();
			(this.currentColumns || []).forEach(function(column) {
				if (!column.key || column.key === 'cb') {
					return;
				}
				$sortColumn.append(
					$('<option>', { value: column.key, text: column.label || column.key })
				);
			});
			$sortColumn.val(currentValue);

			$('.wpps-list-visit-note').toggle(!config.has_list_visit);

			try {
				if (localStorage.getItem('wpps_admin_columns_layout_accordion_open') === null && this.layoutHasActiveSettings(layout)) {
					$('#wpps-layout-accordion').addClass('is-open');
					$('#wpps-layout-accordion .wpps-acc-accordion-header').attr('aria-expanded', 'true');
				}
			} catch (e) {
				if (this.layoutHasActiveSettings(layout)) {
					$('#wpps-layout-accordion').addClass('is-open');
					$('#wpps-layout-accordion .wpps-acc-accordion-header').attr('aria-expanded', 'true');
				}
			}
		},

		updateDefaultSortOptions: function() {
			if (!$('#wpps-default-sort-column').length) {
				return;
			}

			const $sortColumn = $('#wpps-default-sort-column');
			const currentValue = $sortColumn.val() || '';
			$sortColumn.find('option:not(:first)').remove();
			(this.currentColumns || []).forEach(function(column) {
				if (!column.key || column.key === 'cb') {
					return;
				}
				$sortColumn.append(
					$('<option>', { value: column.key, text: column.label || column.key })
				);
			});
			$sortColumn.val(currentValue);
		},

		getLayoutPayload: function() {
			if (!wppsAdminColumns.layoutSupported) {
				return null;
			}

			return {
				disable_horizontal_scroll: $('#wpps-disable-horizontal-scroll').is(':checked'),
				freeze_first_columns: parseInt($('#wpps-freeze-first-columns').val(), 10) || 0,
				freeze_header_row: $('#wpps-freeze-header-row').is(':checked'),
				default_sort_column: $('#wpps-default-sort-column').val() || '',
				default_sort_order: $('#wpps-default-sort-order').val() || 'desc'
			};
		},

		renderColumns: function() {
			const container = $('.wpps-columns-items');
			container.empty();

			if (this.currentColumns.length === 0) {
				this.loadDefaultColumns();
				return;
			}

			const self = this;
			this.currentColumns.forEach(function(column, index) {
				const item = self.createColumnItem(column);
				container.append(item);
			});

			this.initSortable();
			this.updateQuickAddState();
			this.updateDefaultSortOptions();
		},

		updateQuickAddState: function() {
			const self = this;
			$('.wpps-quick-add-btn').each(function() {
				const key = $(this).data('key');
				const exists = self.currentColumns && self.currentColumns.some(function(c) { return c.key === key; });
				$(this).toggleClass('added', !!exists);
			});
		},

		loadDefaultColumns: function() {
			const msg = (wppsAdminColumns.strings && wppsAdminColumns.strings.usingDefaults)
				? wppsAdminColumns.strings.usingDefaults
				: 'No custom column configuration for this screen. WordPress default columns are in use.';
			$('.wpps-columns-items').html('<p class="description"></p>');
			$('.wpps-columns-items .description').text(msg);
			this.prefetchColumnTypes();
		},

		createColumnItem: function(column) {
			const checked = column.hidden ? '' : 'checked';
			const typeLabel = column.custom ? (column.type || 'Custom') : (column.plugin ? 'Plugin' : 'Default');
			const settings = [];
			
			if (column.sortable) settings.push('<span class="dashicons dashicons-sort" title="Sortable"></span>');
			if (column.width) settings.push('<span title="Width: ' + column.width + '">' + column.width + '</span>');
			
			const settingsHtml = settings.length > 0 ? '<span class="wpps-column-settings">' + settings.join(' ') + '</span>' : '';
			
			const editButton = '<span class="dashicons dashicons-admin-generic wpps-column-edit" title="Edit Column"></span>';
			
			const completeColumnData = $.extend({
				key: column.key,
				label: column.label || column.key,
				hidden: column.hidden || false,
				custom: column.custom || false,
				type: column.type || '',
				sortable: column.sortable || false,
				width: column.width || null,
				force_width: column.force_width || false,
				css_class: column.css_class || '',
				meta_key: column.meta_key || '',
				field_type: column.field_type || '',
				taxonomy: column.taxonomy || ''
			}, column);
			
			return $('<div>')
				.addClass('wpps-column-item')
				.data('column-key', completeColumnData.key)
				.data('column-data', completeColumnData)
				.html(
					'<span class="dashicons dashicons-move wpps-column-handle"></span>' +
					'<input type="checkbox" class="wpps-column-checkbox" ' + checked + '>' +
					'<span class="wpps-column-label">' + (completeColumnData.label || completeColumnData.key) + '</span>' +
					'<span class="wpps-column-type">' + typeLabel + '</span>' +
					settingsHtml +
					editButton +
					(completeColumnData.custom ? '<span class="dashicons dashicons-trash wpps-column-delete" title="Delete Column"></span>' : '')
				);
		},

		updateColumnOrder: function() {
			const self = this;
			this.currentColumns = [];

			$('.wpps-column-item').each(function() {
				const $item = $(this);
				let columnData = $item.data('column-data');
				const hidden = !$item.find('.wpps-column-checkbox').is(':checked');
				
				if (columnData) {
					columnData.hidden = hidden;
					const displayedLabel = $item.find('.wpps-column-label').text();
					if (displayedLabel && displayedLabel !== columnData.label) {
						columnData.label = displayedLabel;
					}
					// Make a copy to avoid mutating the original
					self.currentColumns.push($.extend({}, columnData));
				} else {
					const key = $item.data('column-key');
					self.currentColumns.push({
						key: key,
						label: $item.find('.wpps-column-label').text(),
						hidden: hidden,
						custom: false
					});
				}
			});
		},

		saveColumns: function() {
			const self = this;
			const saveButton = $('.wpps-save-columns');
			const originalText = saveButton.text();
			
			saveButton.prop('disabled', true).text(wppsAdminColumns.strings.saving);

			this.updateColumnOrder();
			
			let totalPercent = 0;
			const visibleColumns = this.currentColumns.filter(col => !col.hidden);
			visibleColumns.forEach(function(col) {
				if (col.width && typeof col.width === 'string' && col.width.indexOf('%') !== -1) {
					const percentValue = parseInt(col.width.replace('%', '')) || 0;
					totalPercent += percentValue;
				}
			});
			
			if (totalPercent > 100) {
				saveButton.prop('disabled', false).text(originalText);
				self.showNotice('Total width percentage (' + totalPercent + '%) exceeds 100%. Please adjust column widths.', 'error');
				return;
			}

			$.ajax({
				url: wppsAdminColumns.ajaxUrl,
				type: 'POST',
				data: {
					action: 'wpps_save_column_config',
					screen_type: this.currentScreenType,
					screen_id: this.currentScreenId,
					columns: JSON.stringify(this.currentColumns),
					layout: (function() {
						const layout = self.getLayoutPayload();
						return layout ? JSON.stringify(layout) : '';
					})(),
					nonce: wppsAdminColumns.nonce
				},
				success: function(response) {
					saveButton.prop('disabled', false).text(originalText);
					if (response.success) {
						self.showNotice(response.data.message || wppsAdminColumns.strings.saved, 'success');
						const layoutPayload = self.getLayoutPayload();
						if (layoutPayload) {
							self.currentLayout = layoutPayload;
							self.applyLayoutSettings({
								layout: layoutPayload,
								has_list_visit: self.hasListVisit
							});
						}
						if (!response.data.no_changes) {
							self.loadColumns();
						}
					} else {
						self.showNotice(response.data.message || wppsAdminColumns.strings.error, 'error');
					}
				},
				error: function() {
					saveButton.prop('disabled', false).text(originalText);
					self.showNotice(wppsAdminColumns.strings.error, 'error');
				}
			});
		},

		restoreColumns: function() {
			const self = this;
			const restoreButton = $('.wpps-restore-columns');
			const originalText = restoreButton.text();
			
			const editor = $('.wpps-columns-editor');
			if (editor.length) {
				this.currentScreenType = editor.data('screen-type') || this.currentScreenType;
				this.currentScreenId = editor.data('screen-id') || this.currentScreenId;
			}
			
			if (!this.currentScreenType || !this.currentScreenId) {
				alert('Please select a screen first.');
				return;
			}
			
			restoreButton.prop('disabled', true).text(wppsAdminColumns.strings.restoring || 'Restoring...');

			$.ajax({
				url: wppsAdminColumns.ajaxUrl,
				type: 'POST',
				data: {
					action: 'wpps_restore_column_config',
					screen_type: this.currentScreenType,
					screen_id: this.currentScreenId,
					nonce: wppsAdminColumns.nonce
				},
				success: function(response) {
					restoreButton.prop('disabled', false).text(originalText);
					if (response.success) {
						self.showNotice(response.data.message || (wppsAdminColumns.strings.restored || 'Columns restored to defaults successfully!'), 'success');
						// Reload columns from server to show defaults
						setTimeout(function() {
							self.loadColumns();
						}, 100);
					} else {
						self.showNotice(response.data.message || wppsAdminColumns.strings.error, 'error');
					}
				},
				error: function() {
					restoreButton.prop('disabled', false).text(originalText);
					self.showNotice(wppsAdminColumns.strings.error, 'error');
				}
			});
		},

		resetAllColumns: function() {
			const self = this;
			const resetButton = $('.wpps-reset-all-columns');
			const originalText = resetButton.text();
			
			resetButton.prop('disabled', true).text(wppsAdminColumns.strings.resetting || 'Resetting...');

			$.ajax({
				url: wppsAdminColumns.ajaxUrl,
				type: 'POST',
				data: {
					action: 'wpps_reset_all_column_config',
					nonce: wppsAdminColumns.nonce
				},
				success: function(response) {
					resetButton.prop('disabled', false).text(originalText);
					if (response.success) {
						self.showNotice(response.data.message || (wppsAdminColumns.strings.resetAll || 'All column settings reset successfully!'), 'success');
						// Reload columns from server to show defaults
						setTimeout(function() {
							self.loadColumns();
						}, 100);
					} else {
						self.showNotice(response.data.message || wppsAdminColumns.strings.error, 'error');
					}
				},
				error: function() {
					resetButton.prop('disabled', false).text(originalText);
					self.showNotice(wppsAdminColumns.strings.error, 'error');
				}
			});
		},

		openAddColumnModal: function(columnData) {
			const self = this;
			const isEdit = columnData && columnData.key;
			$('#wpps-add-column-modal').show();
			this.updateSortableRowVisibility();
			
			const $modalTitle = $('#wpps-add-column-modal .wpps-modal-title');
			const $saveButton = $('#wpps-add-column-modal .wpps-modal-save');
			
			if (isEdit) {
				$modalTitle.text('Edit Column');
				$saveButton.text('Update Column');
				
				$('#wpps-column-label').val(columnData.label || '');
				$('#wpps-column-key').val(columnData.key || '');
				$('#wpps-column-type').val(columnData.type || '');
				$('#wpps-meta-key').val(columnData.meta_key || '');
				$('#wpps-field-type').val(columnData.field_type || '');
				$('#wpps-taxonomy').val(columnData.taxonomy || '');
				
				let widthValue = columnData.width || null;
				let widthUnit = 'auto';
				let numericValue = '';
				
				if (widthValue && widthValue !== '' && widthValue !== 'auto') {
					if (typeof widthValue === 'string') {
						if (widthValue.includes('%')) {
							widthUnit = '%';
							numericValue = parseInt(widthValue.replace('%', '')) || '';
						} else if (widthValue.includes('px')) {
							widthUnit = 'px';
							numericValue = parseInt(widthValue.replace('px', '')) || '';
						} else if (!isNaN(widthValue)) {
							widthUnit = 'px';
							numericValue = parseInt(widthValue) || '';
						}
					} else if (typeof widthValue === 'number') {
						widthUnit = 'px';
						numericValue = widthValue;
					}
				}
				
				$('#wpps-column-width-value').val(numericValue);
				
				$('input[name="wpps-width-unit"]').prop('checked', false);
				$('#wpps-width-unit-' + (widthUnit === '%' ? 'percent' : widthUnit)).prop('checked', true);
				
				$('#wpps-column-sortable').prop('checked', columnData.sortable || false);
				$('#wpps-column-force-width').prop('checked', columnData.force_width || false);
				$('#wpps-column-css-class').val(columnData.css_class || '');
				$('#wpps-edit-column-key').val(columnData.key || '');
			} else {
				$modalTitle.text('Add Column');
				$saveButton.text('Add Column');
				$('#wpps-add-column-form')[0].reset();
				$('#wpps-meta-key-row, #wpps-taxonomy-row, #wpps-field-type-row').hide();
				$('#wpps-edit-column-key').val('');
				$('#wpps-column-width-value').val('');
				$('input[name="wpps-width-unit"]').prop('checked', false);
				$('#wpps-width-unit-auto').prop('checked', true);
				$('#wpps-column-force-width').prop('checked', false);
				$('#wpps-column-css-class').val('');
				$('#wpps-column-sortable').prop('checked', false);
			}
			
			// Store the label before loading column types (to prevent it from being overwritten)
			const savedLabel = isEdit ? (columnData.label || '') : '';
			const cacheKey = this.getColumnTypesCacheKey();
			const hasCachedTypes = !!this.columnTypesCache[cacheKey];

			if (!hasCachedTypes) {
				const $sel = $('#wpps-column-type');
				$sel.empty().append('<option value="">' + (wppsAdminColumns.strings.loadingTypes || 'Loading...') + '</option>').prop('disabled', true);
			}

			this.loadColumnTypes(function(types) {
				const select = $('#wpps-column-type');
				select.prop('disabled', false).empty().append(
					$('<option>', {
						value: '',
						text: wppsAdminColumns.strings.selectColumnType || 'Select Column Type'
					})
				);

				if (!types || typeof types !== 'object') {
					select.append(
						$('<option>', {
							value: '',
							text: wppsAdminColumns.strings.typesLoadError || 'Could not load column types.'
						})
					);
					self.showNotice(wppsAdminColumns.strings.typesLoadError || 'Could not load column types.', 'error');
					return;
				}

				$.each(types, function(key, label) {
					select.append($('<option>', { value: key, text: label }));
				});

				self.populateTaxonomySelect(isEdit ? (columnData.taxonomy || '') : '');
				if (isEdit) {
					select.val(columnData.type || '');
					if (savedLabel) {
						$('#wpps-column-label').val(savedLabel);
					}
					self.handleColumnTypeChange(columnData.type || '', true);
					if (savedLabel) {
						setTimeout(function() {
							$('#wpps-column-label').val(savedLabel);
						}, 0);
					}
					if (!columnData.type && columnData.key) {
						const typeMap = {
							'title': 'title',
							'author': 'author',
							'date': 'date',
							'categories': 'categories',
							'tags': 'tags',
							'comments': 'comments',
							'comment_count': 'comment_count'
						};
						if (typeMap[columnData.key]) {
							select.val(typeMap[columnData.key]);
							if (savedLabel) {
								$('#wpps-column-label').val(savedLabel);
							}
							self.handleColumnTypeChange(typeMap[columnData.key], true);
						}
					}
				}
			});
		},

		openEditColumnModal: function(columnData) {
			this.openAddColumnModal(columnData);
		},

		closeAddColumnModal: function() {
			$('#wpps-add-column-modal').hide();
			$('#wpps-add-column-form')[0].reset();
			$('#wpps-meta-key-row, #wpps-taxonomy-row, #wpps-field-type-row').hide();
		},

		updateWidthValue: function() {
			const $valueInput = $('#wpps-column-width-value');
			const value = $valueInput.val().trim();
			const unit = $('input[name="wpps-width-unit"]:checked').val() || 'auto';
			
			if (unit === 'auto') {
				// Auto selected - clear width (WordPress default)
				$('#wpps-column-width').val('');
			} else if (value === '') {
				// No value entered but unit is not auto - keep unit but no width
				$('#wpps-column-width').val('');
			} else if (!isNaN(value) && value !== '') {
				// Valid numeric value - save with unit
				const numVal = parseInt(value);
				if (numVal > 0) {
					$('#wpps-column-width').val(numVal + unit);
				} else {
					$('#wpps-column-width').val('');
				}
			} else {
				// Invalid value - clear
				$('#wpps-column-width').val('');
			}
		},

		getColumnTypesCacheKey: function() {
			return (this.currentScreenType || '') + '_' + (this.currentScreenId || '');
		},

		prefetchColumnTypes: function() {
			this.loadColumnTypes(function() {});
		},

		loadColumnTypes: function(callback) {
			const self = this;
			const key = this.getColumnTypesCacheKey();
			if (this.columnTypesCache[key]) {
				if (callback) callback(this.columnTypesCache[key]);
				return;
			}
			$.ajax({
				url: wppsAdminColumns.ajaxUrl,
				type: 'GET',
				data: {
					action: 'wpps_get_column_types',
					screen_type: this.currentScreenType,
					screen_id: this.currentScreenId,
					nonce: wppsAdminColumns.nonce
				},
				success: function(response) {
					if (response.success && response.data && response.data.column_types) {
						self.columnTypesCache[key] = response.data.column_types;
						if (callback) callback(response.data.column_types);
						return;
					}
					if (callback) callback(null);
				},
				error: function() {
					if (callback) callback(null);
				}
			});
		},

		populateTaxonomySelect: function(selectedSlug) {
			const $select = $('#wpps-taxonomy');
			const taxonomies = wppsAdminColumns.screenTaxonomies || [];

			$select.empty().append(
				$('<option>', {
					value: '',
					text: wppsAdminColumns.strings.selectTaxonomy || 'Select Taxonomy'
				})
			);

			taxonomies.forEach(function(tax) {
				$select.append(
					$('<option>', { value: tax.slug, text: tax.label || tax.slug })
				);
			});

			if (selectedSlug) {
				$select.val(selectedSlug);
			}
		},

		handleColumnTypeChange: function(type, preserveLabel) {
			$('#wpps-meta-key-row, #wpps-taxonomy-row, #wpps-field-type-row').hide();

			if (type === 'custom_field') {
				$('#wpps-meta-key-row, #wpps-field-type-row').show();
			} else if (type === 'taxonomy') {
				this.populateTaxonomySelect($('#wpps-taxonomy').val() || '');
				$('#wpps-taxonomy-row').show();
			}

			// Only update label if preserveLabel is not true (i.e., when user manually changes type)
			if (!preserveLabel) {
				if (type === 'custom_field') {
					$('#wpps-column-label').val('Custom Field');
				} else if (type === 'taxonomy') {
					const selectedLabel = $('#wpps-taxonomy option:selected').text();
					$('#wpps-column-label').val(selectedLabel && $('#wpps-taxonomy').val() ? selectedLabel : 'Taxonomy');
				} else if (type) {
					$('#wpps-column-label').val($('#wpps-column-type option:selected').text());
				}
			}
		},

		browseCustomFields: function() {
			const self = this;
			$.ajax({
				url: wppsAdminColumns.ajaxUrl,
				type: 'GET',
				data: {
					action: 'wpps_get_custom_fields',
					screen_type: this.currentScreenType,
					screen_id: this.currentScreenId,
					nonce: wppsAdminColumns.nonce
				},
				success: function(response) {
					if (response.success) {
						const fields = response.data.custom_fields || [];
						if (fields.length === 0) {
							alert(wppsAdminColumns.strings.noCustomFields || 'No custom fields found.');
							return;
						}

						let $picker = $('#wpps-meta-key-picker');
						if (!$picker.length) {
							$picker = $('<select id="wpps-meta-key-picker" class="regular-text" style="margin-top:8px;"></select>');
							$('#wpps-meta-key-row td').append($picker);
						}

						$picker.empty().append(
							$('<option></option>').val('').text(wppsAdminColumns.strings.selectField || 'Select field')
						);
						$.each(fields, function(i, field) {
							$picker.append($('<option></option>').val(field).text(String(field)));
						});
						$picker.off('change.wppsBrowse').on('change.wppsBrowse', function() {
							$('#wpps-meta-key').val($(this).val());
						});
					}
				}
			});
		},

		saveNewColumn: function() {
			const form = $('#wpps-add-column-form');
			const type = $('#wpps-column-type').val();
			const label = $('#wpps-column-label').val().trim();
			const editKey = $('#wpps-edit-column-key').val();

			if (!type || !label) {
				alert(wppsAdminColumns.strings.requiredFields || 'Please fill in all required fields.');
				return;
			}

			if (type === 'custom_field') {
				const metaKey = $('#wpps-meta-key').val().trim();
				if (!metaKey) {
					alert(wppsAdminColumns.strings.metaKeyRequired || 'Please enter or select a custom field key.');
					return;
				}
			}

			if (type === 'taxonomy') {
				const taxonomy = $('#wpps-taxonomy').val();
				if (!taxonomy) {
					alert(wppsAdminColumns.strings.taxonomyRequired || 'Please select a taxonomy.');
					return;
				}
			}

			const isEdit = editKey && editKey !== '';
			const columnKey = isEdit ? editKey : ('wpps_' + type + '_' + Date.now());
			const existingColumn = isEdit ? this.currentColumns.find(c => c.key === editKey) : null;
			
			const widthValue = $('#wpps-column-width').val();
			let width = null;
			if (widthValue && widthValue !== '' && widthValue !== 'auto') {
				width = widthValue; // Already includes unit (e.g., "50%" or "200px")
			} else {
				const selectedUnit = $('input[name="wpps-width-unit"]:checked').val();
				if (selectedUnit === 'auto') {
					width = null; // null means auto (WordPress default)
				}
			}

			const columnData = {
				key: columnKey,
				label: label,
				type: type,
				custom: isEdit ? (existingColumn?.custom || false) : true,
				hidden: isEdit ? (existingColumn?.hidden || false) : false,
				sortable: wppsAdminColumns.sortableSupported && $('#wpps-column-sortable').is(':checked'),
				width: width,
				force_width: $('#wpps-column-force-width').is(':checked'),
				css_class: $('#wpps-column-css-class').val() || ''
			};

			if (type === 'custom_field') {
				columnData.meta_key = $('#wpps-meta-key').val().trim();
				columnData.field_type = $('#wpps-field-type').val() || 'text';
			} else if (type === 'taxonomy') {
				columnData.taxonomy = $('#wpps-taxonomy').val();
			}

			if (isEdit) {
				const index = this.currentColumns.findIndex(c => c.key === editKey);
				if (index !== -1) {
					this.currentColumns[index] = columnData;
				}
				this.showNotice('Column updated successfully. Don\'t forget to save!', 'success');
			} else {
				this.currentColumns.push(columnData);
				this.showNotice('Column added successfully. Don\'t forget to save!', 'success');
			}

			this.renderColumns();
			this.closeAddColumnModal();
		},

		showNotice: function(message, type) {
			type = type || 'info';
			const notice = $('<div>')
				.addClass('wpps-notice ' + type)
				.text(message);

			$('.wpps-columns-header').after(notice);

			setTimeout(function() {
				notice.fadeOut(300, function() {
					$(this).remove();
				});
			}, 3000);
		}
	};

	$(document).ready(function() {
		AdminColumns.init();
	});

})(jQuery);
