<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( ! function_exists( 'wp_powersuite_is_license_valid' ) || ! wp_powersuite_is_license_valid() ) {
	$license_page_url = admin_url( 'admin.php?page=powersuite-license' );
	?>
	<div class="wp-powersuite-module-settings wpps-settings-panel" data-module-id="<?php echo esc_attr( $module_id ?? 'bulk-page-creator' ); ?>">
		<div class="notice notice-warning inline" style="margin:0;">
			<p>
				<?php esc_html_e( 'Bulk Page Creator requires an active license. Activate your license to generate pages from CSV or spreadsheet templates.', 'wppowersuite-lite' ); ?>
				<a href="<?php echo esc_url( $license_page_url ); ?>"><?php esc_html_e( 'Activate license', 'wppowersuite-lite' ); ?></a>
			</p>
		</div>
	</div>
	<?php
	return;
}

if ( ! \WP_PowerSuite\Core\NetworkScope::canManagePlugin() ) {
	return;
}

use WP_PowerSuite\Core\OptionStoreModuleSettingsRepository;

if ( ! isset( $module_id ) || empty( $module_id ) ) {
	$module_id = 'bulk-page-creator';
}

$settings     = OptionStoreModuleSettingsRepository::forModule( $module_id )->all( [] );
if ( ! is_array( $settings ) ) {
	$settings = [];
}

$defaults = [
	'post_type'   => 'page',
	'parent_page' => 0,
	'author_id'   => 0,
	'post_status' => 'publish',
];
$settings = array_merge( $defaults, $settings );

$post_type   = $settings['post_type'] ?? 'page';
$parent_page = (int) ( $settings['parent_page'] ?? 0 );
$author_id   = (int) ( $settings['author_id'] ?? 0 );
$post_status = $settings['post_status'] ?? 'publish';

$bpc_max_rows = 500;

$nonce    = wp_create_nonce( 'wpps_bulk_page_creator' );
$ajax_url = admin_url( 'admin-ajax.php' );

$xlsx_file = __DIR__ . '/assets/xlsx.full.min.js';
$xlsx_url  = plugins_url( 'assets/xlsx.full.min.js', __FILE__ );
if ( is_readable( $xlsx_file ) ) {
	$xlsx_url = add_query_arg( 'ver', (string) filemtime( $xlsx_file ), $xlsx_url );
}

$authors = get_users(
	[
		'orderby'  => 'display_name',
		'role__in' => [ 'administrator', 'editor', 'author' ],
		'fields'   => [ 'ID', 'display_name' ],
		'number'   => 100,
	]
);

$pages = get_pages(
	[
		'number'      => 200,
		'sort_column' => 'post_title',
		'post_status' => [ 'publish', 'draft', 'private' ],
	]
);
$pages = array_values(
	array_filter(
		$pages,
		static function ( $page ) {
			return $page instanceof \WP_Post && current_user_can( 'edit_post', $page->ID );
		}
	)
);

$posts = get_posts(
	[
		'post_type'   => 'post',
		'numberposts' => 100,
		'orderby'     => 'title',
		'order'       => 'ASC',
		'post_status' => [ 'publish', 'draft', 'private' ],
	]
);
$posts = array_values(
	array_filter(
		$posts,
		static function ( $post ) {
			return $post instanceof \WP_Post && current_user_can( 'edit_post', $post->ID );
		}
	)
);
?>

<div class="wp-powersuite-module-settings wpps-bpc-settings" data-module-id="<?php echo esc_attr( $module_id ); ?>">
	<p class="description">
		<?php esc_html_e( 'Create multiple pages from a template. Use placeholders like {city}, {service}, or {name} in your template. The first row of your CSV defines column names—use those as placeholders.', 'wppowersuite-lite' ); ?>
	</p>

	<form class="wp-powersuite-module-settings-form" data-module-id="<?php echo esc_attr( $module_id ); ?>">
		<?php wp_nonce_field( 'wp_powersuite_save_module_settings_' . $module_id, 'wp_powersuite_nonce' ); ?>

		<h3><?php esc_html_e( 'Default Settings', 'wppowersuite-lite' ); ?></h3>
		<table class="form-table" role="presentation">
			<tbody>
				<tr>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id ); ?>_post_type"><?php esc_html_e( 'Post Type', 'wppowersuite-lite' ); ?></label>
					</th>
					<td>
						<select id="<?php echo esc_attr( $module_id ); ?>_post_type" name="post_type" class="wp-powersuite-advanced-setting" data-setting-key="post_type">
							<option value="page" <?php selected( $post_type, 'page' ); ?>><?php esc_html_e( 'Page', 'wppowersuite-lite' ); ?></option>
							<option value="post" <?php selected( $post_type, 'post' ); ?>><?php esc_html_e( 'Post', 'wppowersuite-lite' ); ?></option>
						</select>
						<p class="description"><?php esc_html_e( 'Post type for newly created pages.', 'wppowersuite-lite' ); ?></p>
					</td>
				</tr>
				<tr id="wpps-bpc-settings-parent-row">
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id ); ?>_parent_page"><?php esc_html_e( 'Parent Page', 'wppowersuite-lite' ); ?></label>
					</th>
					<td>
						<select id="<?php echo esc_attr( $module_id ); ?>_parent_page" name="parent_page" class="wp-powersuite-advanced-setting" data-setting-key="parent_page">
							<option value="0"><?php esc_html_e( '— None —', 'wppowersuite-lite' ); ?></option>
							<?php foreach ( $pages as $p ) : ?>
								<option value="<?php echo (int) $p->ID; ?>" <?php selected( $parent_page, $p->ID ); ?>><?php echo esc_html( $p->post_title ); ?></option>
							<?php endforeach; ?>
						</select>
						<p class="description"><?php esc_html_e( 'Optional parent for hierarchical content (pages only).', 'wppowersuite-lite' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id ); ?>_author_id"><?php esc_html_e( 'Author', 'wppowersuite-lite' ); ?></label>
					</th>
					<td>
						<select id="<?php echo esc_attr( $module_id ); ?>_author_id" name="author_id" class="wp-powersuite-advanced-setting" data-setting-key="author_id">
							<option value="0"><?php esc_html_e( '— Use template author —', 'wppowersuite-lite' ); ?></option>
							<?php foreach ( $authors as $u ) : ?>
								<option value="<?php echo (int) $u->ID; ?>" <?php selected( $author_id, $u->ID ); ?>><?php echo esc_html( $u->display_name ); ?></option>
							<?php endforeach; ?>
						</select>
						<p class="description"><?php esc_html_e( 'Author for new pages. Leave as template author to inherit.', 'wppowersuite-lite' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id ); ?>_post_status"><?php esc_html_e( 'Post Status', 'wppowersuite-lite' ); ?></label>
					</th>
					<td>
						<select id="<?php echo esc_attr( $module_id ); ?>_post_status" name="post_status" class="wp-powersuite-advanced-setting" data-setting-key="post_status">
							<option value="publish" <?php selected( $post_status, 'publish' ); ?>><?php esc_html_e( 'Published', 'wppowersuite-lite' ); ?></option>
							<option value="draft" <?php selected( $post_status, 'draft' ); ?>><?php esc_html_e( 'Draft', 'wppowersuite-lite' ); ?></option>
							<option value="private" <?php selected( $post_status, 'private' ); ?>><?php esc_html_e( 'Private', 'wppowersuite-lite' ); ?></option>
						</select>
						<p class="description"><?php esc_html_e( 'Status for newly created pages.', 'wppowersuite-lite' ); ?></p>
					</td>
				</tr>
			</tbody>
		</table>

		<hr style="margin: 24px 0;" />

		<h3><?php esc_html_e( 'Create Pages', 'wppowersuite-lite' ); ?></h3>
	</form>

	<div class="wpps-bpc-create wpps-bpc-card">
		<p class="description" style="margin-bottom: 12px;">
			<?php esc_html_e( 'Select a template, add data via paste or file upload, then click Create. Each row becomes one page.', 'wppowersuite-lite' ); ?>
		</p>

		<div class="wpps-bpc-field">
			<label for="wpps-bpc-template"><?php esc_html_e( 'Template', 'wppowersuite-lite' ); ?></label>
			<select id="wpps-bpc-template" class="wpps-bpc-input">
				<option value=""><?php esc_html_e( '— Select template —', 'wppowersuite-lite' ); ?></option>
				<?php if ( ! empty( $pages ) ) : ?>
					<optgroup class="wpps-bpc-optgroup-page" label="<?php esc_attr_e( 'Pages', 'wppowersuite-lite' ); ?>">
						<?php foreach ( $pages as $p ) : ?>
							<option value="<?php echo (int) $p->ID; ?>"><?php echo esc_html( $p->post_title ); ?> (ID: <?php echo (int) $p->ID; ?>)</option>
						<?php endforeach; ?>
					</optgroup>
				<?php endif; ?>
				<?php if ( ! empty( $posts ) ) : ?>
					<optgroup class="wpps-bpc-optgroup-post" label="<?php esc_attr_e( 'Posts', 'wppowersuite-lite' ); ?>">
						<?php foreach ( $posts as $p ) : ?>
							<option value="<?php echo (int) $p->ID; ?>"><?php echo esc_html( $p->post_title ); ?> (ID: <?php echo (int) $p->ID; ?>)</option>
						<?php endforeach; ?>
					</optgroup>
				<?php endif; ?>
			</select>
			<p class="description"><?php esc_html_e( 'Page or post to use as template. Use {column_name} placeholders in title and content.', 'wppowersuite-lite' ); ?></p>
		</div>

		<div class="wpps-bpc-field">
			<label><?php esc_html_e( 'Data Source', 'wppowersuite-lite' ); ?></label>
			<h2 class="nav-tab-wrapper wpps-bpc-tabs">
				<a href="#" class="nav-tab nav-tab-active wpps-bpc-tab" data-tab="paste"><?php esc_html_e( 'Paste', 'wppowersuite-lite' ); ?></a>
				<a href="#" class="nav-tab wpps-bpc-tab" data-tab="csv"><?php esc_html_e( 'Upload CSV', 'wppowersuite-lite' ); ?></a>
				<a href="#" class="nav-tab wpps-bpc-tab" data-tab="xlsx"><?php esc_html_e( 'Upload XLSX', 'wppowersuite-lite' ); ?></a>
			</h2>

			<div id="wpps-bpc-tab-paste" class="wpps-bpc-tab-panel active">
				<label for="wpps-bpc-delimiter"><?php esc_html_e( 'Delimiter', 'wppowersuite-lite' ); ?></label>
				<select id="wpps-bpc-delimiter" class="wpps-bpc-input" style="width: auto; margin-bottom: 8px;">
					<option value="comma"><?php esc_html_e( 'Comma (,)', 'wppowersuite-lite' ); ?></option>
					<option value="semicolon"><?php esc_html_e( 'Semicolon (;)', 'wppowersuite-lite' ); ?></option>
					<option value="tab"><?php esc_html_e( 'Tab', 'wppowersuite-lite' ); ?></option>
				</select>
				<textarea id="wpps-bpc-csv" class="wpps-bpc-input wpps-bpc-textarea" rows="8" placeholder="city,service,title
New York,Plumber,Plumber in New York
Boston,Electrician,Electrician in Boston"></textarea>
				<p class="description"><?php esc_html_e( 'First row = headers (use as placeholders: {city}, {service}). One row per page.', 'wppowersuite-lite' ); ?></p>
			</div>

			<div id="wpps-bpc-tab-csv" class="wpps-bpc-tab-panel" style="display: none;">
				<label for="wpps-bpc-csv-delimiter"><?php esc_html_e( 'Delimiter', 'wppowersuite-lite' ); ?></label>
				<select id="wpps-bpc-csv-delimiter" class="wpps-bpc-input" style="width: auto; margin-bottom: 8px;">
					<option value="comma"><?php esc_html_e( 'Comma (,)', 'wppowersuite-lite' ); ?></option>
					<option value="semicolon"><?php esc_html_e( 'Semicolon (;)', 'wppowersuite-lite' ); ?></option>
					<option value="tab"><?php esc_html_e( 'Tab', 'wppowersuite-lite' ); ?></option>
				</select>
				<div class="wpps-bpc-upload-area" id="wpps-bpc-csv-upload">
					<input type="file" id="wpps-bpc-csv-file" accept=".csv" style="display: none;">
					<p class="wpps-bpc-upload-text"><?php esc_html_e( 'Drop CSV file here or click to browse', 'wppowersuite-lite' ); ?></p>
					<p class="wpps-bpc-upload-filename" id="wpps-bpc-csv-filename" style="display: none;"></p>
				</div>
			</div>

			<div id="wpps-bpc-tab-xlsx" class="wpps-bpc-tab-panel" style="display: none;">
				<div class="wpps-bpc-upload-area" id="wpps-bpc-xlsx-upload">
					<input type="file" id="wpps-bpc-xlsx-file" accept=".xlsx,.xls" style="display: none;">
					<p class="wpps-bpc-upload-text"><?php esc_html_e( 'Drop XLSX file here or click to browse', 'wppowersuite-lite' ); ?></p>
					<p class="wpps-bpc-upload-filename" id="wpps-bpc-xlsx-filename" style="display: none;"></p>
				</div>
				<p class="description"><?php esc_html_e( 'First row = headers. Uses SheetJS for parsing in browser.', 'wppowersuite-lite' ); ?></p>
			</div>
		</div>

		<div class="wpps-bpc-row">
			<div class="wpps-bpc-field wpps-bpc-field-half">
				<label for="wpps-bpc-slug-column"><?php esc_html_e( 'Slug Column (optional)', 'wppowersuite-lite' ); ?></label>
				<input type="text" id="wpps-bpc-slug-column" class="wpps-bpc-input" placeholder="e.g. slug">
			</div>
			<div class="wpps-bpc-field wpps-bpc-field-half">
				<label for="wpps-bpc-title-column"><?php esc_html_e( 'Title Column (optional)', 'wppowersuite-lite' ); ?></label>
				<input type="text" id="wpps-bpc-title-column" class="wpps-bpc-input" placeholder="e.g. title">
			</div>
		</div>

		<div class="wpps-bpc-row">
			<div class="wpps-bpc-field wpps-bpc-field-half" id="wpps-bpc-parent-column-field">
				<label for="wpps-bpc-parent-column"><?php esc_html_e( 'Parent Column (optional)', 'wppowersuite-lite' ); ?></label>
				<input type="text" id="wpps-bpc-parent-column" class="wpps-bpc-input" placeholder="e.g. parent_id">
				<p class="description"><?php esc_html_e( 'Column with parent page ID (pages only).', 'wppowersuite-lite' ); ?></p>
			</div>
			<div class="wpps-bpc-field wpps-bpc-field-half">
				<label for="wpps-bpc-existing-action"><?php esc_html_e( 'If slug exists', 'wppowersuite-lite' ); ?></label>
				<select id="wpps-bpc-existing-action" class="wpps-bpc-input">
					<option value="create"><?php esc_html_e( 'Create new (add suffix)', 'wppowersuite-lite' ); ?></option>
					<option value="update"><?php esc_html_e( 'Update existing', 'wppowersuite-lite' ); ?></option>
					<option value="skip"><?php esc_html_e( 'Skip', 'wppowersuite-lite' ); ?></option>
				</select>
				<p class="description"><?php esc_html_e( 'When a page with the same slug already exists.', 'wppowersuite-lite' ); ?></p>
			</div>
		</div>

		<div class="wpps-bpc-field" id="wpps-bpc-taxonomy-wrap">
			<label><?php esc_html_e( 'Categories / Terms (optional)', 'wppowersuite-lite' ); ?></label>
			<div id="wpps-bpc-taxonomy-list"></div>
			<p class="description"><?php esc_html_e( 'Assign taxonomy terms to all created pages.', 'wppowersuite-lite' ); ?></p>
		</div>

		<div class="wpps-bpc-actions">
			<button type="button" class="button button-primary" id="wpps-bpc-start" disabled>
				<?php esc_html_e( 'Create Pages', 'wppowersuite-lite' ); ?>
			</button>
			<button type="button" class="button button-secondary" id="wpps-bpc-stop" style="display: none;">
				<?php esc_html_e( 'Stop', 'wppowersuite-lite' ); ?>
			</button>
		</div>

		<div id="wpps-bpc-progress-wrap" class="wpps-bpc-progress-wrap" style="display: none;">
			<div class="wpps-bpc-progress-bar">
				<div class="wpps-bpc-progress-fill" id="wpps-bpc-progress-fill" style="width: 0%;"></div>
			</div>
			<div class="wpps-bpc-progress-meta">
				<span class="wpps-bpc-counter" id="wpps-bpc-counter">0 / 0</span>
				<span class="wpps-bpc-current" id="wpps-bpc-current"></span>
			</div>
		</div>

		<div id="wpps-bpc-log-wrap" class="wpps-bpc-log-wrap" style="display: none;">
			<h4><?php esc_html_e( 'Activity Log', 'wppowersuite-lite' ); ?></h4>
			<div class="wpps-bpc-log" id="wpps-bpc-log"></div>
		</div>
	</div>

	<div class="wpps-bpc-info-box">
		<p>
			<strong><?php esc_html_e( 'Tips', 'wppowersuite-lite' ); ?></strong><br>
			<?php esc_html_e( '• Add a column "wpps_ignore" with 1 to skip that row.', 'wppowersuite-lite' ); ?><br>
			<?php esc_html_e( '• For pages, use a parent_id column with page IDs for per-row hierarchy.', 'wppowersuite-lite' ); ?><br>
			<?php esc_html_e( '• Page builder layouts (Elementor, Beaver Builder, Bricks, Divi, Breakdance, Oxygen, Brizy) are copied with placeholders substituted safely.', 'wppowersuite-lite' ); ?>
		</p>
	</div>
</div>



<?php ob_start(); ?>
(function() {
	'use strict';
	var container = document.querySelector('.wpps-bpc-settings');
	if (!container) return;

	var templateEl = container.querySelector('#wpps-bpc-template');
	var csvEl = container.querySelector('#wpps-bpc-csv');
	var slugColEl = container.querySelector('#wpps-bpc-slug-column');
	var titleColEl = container.querySelector('#wpps-bpc-title-column');
	var parentColEl = container.querySelector('#wpps-bpc-parent-column');
	var existingActionEl = container.querySelector('#wpps-bpc-existing-action');
	var startBtn = container.querySelector('#wpps-bpc-start');
	var stopBtn = container.querySelector('#wpps-bpc-stop');
	var progressWrap = container.querySelector('#wpps-bpc-progress-wrap');
	var progressFill = container.querySelector('#wpps-bpc-progress-fill');
	var counterEl = container.querySelector('#wpps-bpc-counter');
	var currentEl = container.querySelector('#wpps-bpc-current');
	var logWrap = container.querySelector('#wpps-bpc-log-wrap');
	var logEl = container.querySelector('#wpps-bpc-log');
	var postTypeEl = container.querySelector('#<?php echo esc_js( $module_id ); ?>_post_type');
	var taxonomyListEl = container.querySelector('#wpps-bpc-taxonomy-list');

	var nonce = <?php echo wp_json_encode( $nonce ); ?>;
	var ajaxUrl = <?php echo wp_json_encode( $ajax_url ); ?>;
	var xlsxUrl = <?php echo wp_json_encode( $xlsx_url ); ?>;
	var MAX_ROWS = <?php echo (int) $bpc_max_rows; ?>;
	<?php /* translators: %d: number value. */ ?>
	var tooManyRowsMsg = <?php echo wp_json_encode( sprintf( __( 'Too many rows. Maximum is %d.', 'wppowersuite-lite' ), $bpc_max_rows ) ); ?>;

	var state = { rows: [], processed: 0, failed: 0, skipped: 0, running: false, stopped: false, uploadedRows: null };
	var delimiterMap = { comma: ',', semicolon: ';', tab: '\t' };

	function updateParentHierarchyUI() {
		var pt = (postTypeEl && postTypeEl.value) ? postTypeEl.value : 'page';
		var hierarchical = pt === 'page';
		var row = container.querySelector('#wpps-bpc-settings-parent-row');
		var col = container.querySelector('#wpps-bpc-parent-column-field');
		if (row) row.style.display = hierarchical ? '' : 'none';
		if (col) col.style.display = hierarchical ? '' : 'none';
	}

	function syncTemplateSelectToPostType() {
		var pt = (postTypeEl && postTypeEl.value) ? postTypeEl.value : 'page';
		var ogPage = container.querySelector('.wpps-bpc-optgroup-page');
		var ogPost = container.querySelector('.wpps-bpc-optgroup-post');
		if (ogPage) ogPage.style.display = pt === 'page' ? '' : 'none';
		if (ogPost) ogPost.style.display = pt === 'post' ? '' : 'none';
		if (!templateEl || !templateEl.value) return;
		var opt = templateEl.options[templateEl.selectedIndex];
		var g = opt && opt.parentElement && opt.parentElement.tagName === 'OPTGROUP' ? opt.parentElement : null;
		var isPageTpl = g && g.classList.contains('wpps-bpc-optgroup-page');
		var isPostTpl = g && g.classList.contains('wpps-bpc-optgroup-post');
		if ((pt === 'page' && !isPageTpl) || (pt === 'post' && !isPostTpl)) {
			templateEl.value = '';
		}
	}

	function getActiveTab() {
		var t = container.querySelector('.wpps-bpc-tab.nav-tab-active');
		return t ? t.getAttribute('data-tab') : 'paste';
	}

	function getRows() {
		var tab = getActiveTab();
		if (tab === 'paste') {
			var delim = container.querySelector('#wpps-bpc-delimiter');
			return parseCSV(csvEl ? csvEl.value : '', delim ? delim.value : 'comma');
		}
		if (tab === 'csv' || tab === 'xlsx') {
			return state.uploadedRows ? { headers: state.uploadedRows.headers || [], rows: state.uploadedRows.rows || [] } : { headers: [], rows: [] };
		}
		return { headers: [], rows: [] };
	}

	function parseCSV(text, delim) {
		if (!text || !text.trim()) return { headers: [], rows: [] };
		var d = delimiterMap[delim] || ',';
		var lines = text.trim().split(/\r?\n/);
		if (lines.length < 2) return { headers: [], rows: [] };
		var parseRow = function(line) {
			var out = [], cur = '', inQ = false;
			for (var i = 0; i < line.length; i++) {
				var c = line[i];
				if (c === '"') inQ = !inQ;
				else if ((c === d || c === '\r') && !inQ) { out.push(cur.trim()); cur = ''; if (c === '\r') i++; }
				else cur += c;
			}
			out.push(cur.trim());
			return out;
		};
		var headers = parseRow(lines[0]).map(function(h) { return h.replace(/^["']|["']$/g, ''); });
		var rows = [];
		for (var i = 1; i < lines.length && rows.length < MAX_ROWS; i++) {
			var vals = parseRow(lines[i]);
			var obj = {};
			headers.forEach(function(h, j) { obj[h] = vals[j] !== undefined ? vals[j] : ''; });
			var empty = headers.every(function(h) { return !String(obj[h] || '').trim(); });
			if (empty) continue;
			rows.push(obj);
		}
		return { headers: headers, rows: rows };
	}

	function escapeHtml(s) {
		if (!s) return '';
		var div = document.createElement('div');
		div.textContent = s;
		return div.innerHTML;
	}

	function timeStr() {
		var d = new Date();
		return ('0' + d.getHours()).slice(-2) + ':' + ('0' + d.getMinutes()).slice(-2) + ':' + ('0' + d.getSeconds()).slice(-2);
	}

	function logEntry(ok, msg, skipped) {
		var className = skipped ? 'skipped' : (ok ? 'success' : 'fail');
		var icon = skipped ? '○' : (ok ? '✓' : '✗');
		var div = document.createElement('div');
		div.className = 'wpps-bpc-log-entry ' + className;
		div.textContent = '[' + timeStr() + '] ' + icon + ' ' + msg;
		logEl.appendChild(div);
		logEl.scrollTop = logEl.scrollHeight;
	}

	function updateProgress() {
		var total = state.rows.length;
		var done = state.processed + state.failed + state.skipped;
		var pct = total ? Math.round((done / total) * 100) : 0;
		progressFill.style.width = pct + '%';
		counterEl.textContent = done + ' / ' + total;
	}

	function getSelectedTaxonomyTerms() {
		if (!taxonomyListEl) return [];
		var ids = [];
		taxonomyListEl.querySelectorAll('input[type="checkbox"]:checked').forEach(function(cb) {
			ids.push(parseInt(cb.value, 10));
		});
		return ids;
	}

	function resetUI() {
		state.running = false;
		stopBtn.style.display = 'none';
		stopBtn.disabled = false;
		stopBtn.textContent = '<?php echo esc_js( __( 'Stop', 'wppowersuite-lite' ) ); ?>';
		startBtn.disabled = false;
		window.removeEventListener('beforeunload', beforeUnloadHandler);
	}

	function processNext() {
		if (state.stopped || !state.running) { resetUI(); return; }
		var idx = state.processed + state.failed + state.skipped;
		if (idx >= state.rows.length) {
			resetUI();
			logEntry(true, '<?php echo esc_js( __( 'Done.', 'wppowersuite-lite' ) ); ?>');
			return;
		}
		var row = state.rows[idx];
		currentEl.textContent = '<?php echo esc_js( __( 'Processing row', 'wppowersuite-lite' ) ); ?> ' + (idx + 1) + ' <?php echo esc_js( __( 'of', 'wppowersuite-lite' ) ); ?> ' + state.rows.length + '…';
		var fd = new FormData();
		fd.append('action', 'wpps_bpc_create_page');
		fd.append('nonce', nonce);
		fd.append('post_type', (postTypeEl && postTypeEl.value) ? postTypeEl.value : 'page');
		fd.append('template_id', templateEl.value);
		fd.append('row_data', JSON.stringify(row));
		fd.append('slug_column', slugColEl ? slugColEl.value : '');
		fd.append('title_column', titleColEl ? titleColEl.value : '');
		fd.append('parent_column', parentColEl ? parentColEl.value : '');
		fd.append('existing_action', existingActionEl ? existingActionEl.value : 'create');
		getSelectedTaxonomyTerms().forEach(function(id) { fd.append('taxonomy_terms[]', id); });
		fetch(ajaxUrl, { method: 'POST', body: fd, credentials: 'same-origin' })
			.then(function(r) { return r.json(); })
			.then(function(data) {
				if (state.stopped || !state.running) { resetUI(); return; }
				var label = data.data && data.data.title ? data.data.title : (data.data && data.data.slug ? data.data.slug : '#' + (idx + 1));
				if (data.success) {
					if (data.data && data.data.skipped) {
						state.skipped++;
						var reason = data.data.reason === 'ignore' ? '<?php echo esc_js( __( 'Skipped (ignore)', 'wppowersuite-lite' ) ); ?>' : '<?php echo esc_js( __( 'Skipped (duplicate)', 'wppowersuite-lite' ) ); ?>';
						logEntry(true, label + ' — ' + reason, true);
					} else {
						state.processed++;
						var upd = data.data && data.data.updated ? ' (<?php echo esc_js( __( 'updated', 'wppowersuite-lite' ) ); ?>)' : '';
						logEntry(true, label + upd);
					}
				} else {
					state.failed++;
					var msg = data.data && data.data.message ? data.data.message : '<?php echo esc_js( __( 'Unknown error', 'wppowersuite-lite' ) ); ?>';
					logEntry(false, '<?php echo esc_js( __( 'Failed', 'wppowersuite-lite' ) ); ?>: ' + label + ' — ' + msg);
				}
				updateProgress();
				processNext();
			})
			.catch(function() {
				if (state.stopped || !state.running) { resetUI(); return; }
				state.failed++;
				logEntry(false, '<?php echo esc_js( __( 'Failed', 'wppowersuite-lite' ) ); ?>: row ' + (idx + 1) + ' — <?php echo esc_js( __( 'Request failed', 'wppowersuite-lite' ) ); ?>');
				updateProgress();
				processNext();
			});
	}

	function beforeUnloadHandler(e) {
		if (state.running) { e.preventDefault(); e.returnValue = ''; }
	}

	function updateStartButton() {
		var template = templateEl && templateEl.value;
		var data = getRows();
		startBtn.disabled = !template || !data.rows || data.rows.length === 0;
	}

	container.querySelectorAll('.wpps-bpc-tab').forEach(function(btn) {
		btn.addEventListener('click', function(e) {
			e.preventDefault();
			container.querySelectorAll('.wpps-bpc-tab').forEach(function(b) { b.classList.remove('nav-tab-active'); });
			container.querySelectorAll('.wpps-bpc-tab-panel').forEach(function(p) { p.style.display = 'none'; });
			btn.classList.add('nav-tab-active');
			var panel = container.querySelector('#wpps-bpc-tab-' + btn.getAttribute('data-tab'));
			if (panel) panel.style.display = 'block';
			updateStartButton();
		});
	});

	var csvUploadEl = container.querySelector('#wpps-bpc-csv-upload');
	var csvFileEl = container.querySelector('#wpps-bpc-csv-file');
	var csvFilenameEl = container.querySelector('#wpps-bpc-csv-filename');
	if (csvUploadEl && csvFileEl) {
		csvUploadEl.addEventListener('click', function() { csvFileEl.click(); });
		csvUploadEl.addEventListener('dragover', function(e) { e.preventDefault(); csvUploadEl.style.borderColor = '#2271b1'; });
		csvUploadEl.addEventListener('dragleave', function() { csvUploadEl.style.borderColor = ''; });
		csvUploadEl.addEventListener('drop', function(e) {
			e.preventDefault();
			csvUploadEl.style.borderColor = '';
			var f = e.dataTransfer && e.dataTransfer.files[0];
			if (f && /\.csv$/i.test(f.name)) handleCsvUpload(f);
		});
		csvFileEl.addEventListener('change', function() {
			if (csvFileEl.files && csvFileEl.files[0]) handleCsvUpload(csvFileEl.files[0]);
		});
	}

	function handleCsvUpload(file) {
		var fd = new FormData();
		fd.append('action', 'wpps_bpc_parse_file');
		fd.append('nonce', nonce);
		fd.append('post_type', (postTypeEl && postTypeEl.value) ? postTypeEl.value : 'page');
		fd.append('file', file);
		fd.append('delimiter', (container.querySelector('#wpps-bpc-csv-delimiter') || {}).value || 'comma');
		fetch(ajaxUrl, { method: 'POST', body: fd, credentials: 'same-origin' })
			.then(function(r) { return r.json(); })
			.then(function(data) {
				if (data.success && data.data && data.data.rows) {
					state.uploadedRows = { headers: data.data.headers || [], rows: data.data.rows };
					if (csvFilenameEl) { csvFilenameEl.textContent = file.name; csvFilenameEl.style.display = 'block'; }
					updateStartButton();
				} else {
					alert(data.data && data.data.message ? data.data.message : '<?php echo esc_js( __( 'Failed to parse CSV.', 'wppowersuite-lite' ) ); ?>');
				}
			})
			.catch(function() { alert('<?php echo esc_js( __( 'Upload failed.', 'wppowersuite-lite' ) ); ?>'); });
	}

	var xlsxUploadEl = container.querySelector('#wpps-bpc-xlsx-upload');
	var xlsxFileEl = container.querySelector('#wpps-bpc-xlsx-file');
	var xlsxFilenameEl = container.querySelector('#wpps-bpc-xlsx-filename');
	if (xlsxUploadEl && xlsxFileEl) {
		xlsxUploadEl.addEventListener('click', function() { xlsxFileEl.click(); });
		xlsxUploadEl.addEventListener('dragover', function(e) { e.preventDefault(); xlsxUploadEl.style.borderColor = '#2271b1'; });
		xlsxUploadEl.addEventListener('dragleave', function() { xlsxUploadEl.style.borderColor = ''; });
		xlsxUploadEl.addEventListener('drop', function(e) {
			e.preventDefault();
			xlsxUploadEl.style.borderColor = '';
			var f = e.dataTransfer && e.dataTransfer.files[0];
			if (f && /\.(xlsx|xls)$/i.test(f.name)) handleXlsxUpload(f);
		});
		xlsxFileEl.addEventListener('change', function() {
			if (xlsxFileEl.files && xlsxFileEl.files[0]) handleXlsxUpload(xlsxFileEl.files[0]);
		});
	}

	function handleXlsxUpload(file) {
		var reader = new FileReader();
		reader.onload = function(e) {
			if (typeof XLSX === 'undefined') {
				var s = document.createElement('script');
				s.src = xlsxUrl;
				s.onload = function() { parseXlsxData(e.target.result, file); };
				s.onerror = function() { alert('<?php echo esc_js( __( 'Could not load the spreadsheet parser. Please try a CSV file instead.', 'wppowersuite-lite' ) ); ?>'); };
				document.head.appendChild(s);
			} else {
				parseXlsxData(e.target.result, file);
			}
		};
		reader.readAsArrayBuffer(file);
	}

	function parseXlsxData(arrayBuffer, file) {
		try {
			var wb = XLSX.read(arrayBuffer, { type: 'array' });
			var ws = wb.Sheets[wb.SheetNames[0]];
			var data = XLSX.utils.sheet_to_json(ws, { header: 1, defval: '' });
			if (!data || data.length < 2) { alert('<?php echo esc_js( __( 'XLSX has no data or only headers.', 'wppowersuite-lite' ) ); ?>'); return; }
			var headers = data[0].map(function(h) { return String(h || '').trim(); });
			var rows = [];
			for (var i = 1; i < data.length && rows.length < MAX_ROWS; i++) {
				var obj = {};
				headers.forEach(function(h, j) { obj[h] = data[i][j] !== undefined ? String(data[i][j] || '').trim() : ''; });
				var empty = headers.every(function(h) { return !obj[h]; });
				if (empty) continue;
				rows.push(obj);
			}
			state.uploadedRows = { headers: headers, rows: rows };
			if (xlsxFilenameEl) { xlsxFilenameEl.textContent = file.name; xlsxFilenameEl.style.display = 'block'; }
			updateStartButton();
		} catch (err) {
			alert('<?php echo esc_js( __( 'Failed to parse XLSX.', 'wppowersuite-lite' ) ); ?> ' + (err.message || ''));
		}
	}

	templateEl.addEventListener('change', updateStartButton);
	if (csvEl) csvEl.addEventListener('input', updateStartButton);

	startBtn.addEventListener('click', function() {
		var data = getRows();
		if (!data.rows || data.rows.length === 0) {
			alert('<?php echo esc_js( __( 'Please add data: paste CSV, or upload a CSV/XLSX file.', 'wppowersuite-lite' ) ); ?>');
			return;
		}
		if (data.rows.length > MAX_ROWS) {
			alert(tooManyRowsMsg);
			return;
		}
		var itemLabel = (postTypeEl && postTypeEl.value === 'post') ? '<?php echo esc_js( __( 'posts', 'wppowersuite-lite' ) ); ?>' : '<?php echo esc_js( __( 'pages', 'wppowersuite-lite' ) ); ?>';
		if (!confirm('<?php echo esc_js( __( 'Create', 'wppowersuite-lite' ) ); ?> ' + data.rows.length + ' ' + itemLabel + '?')) return;
		state.rows = data.rows;
		state.running = true;
		state.stopped = false;
		state.processed = 0;
		state.failed = 0;
		state.skipped = 0;
		startBtn.disabled = true;
		stopBtn.style.display = 'inline-block';
		progressWrap.style.display = 'block';
		logWrap.style.display = 'block';
		logEl.innerHTML = '';
		progressFill.style.width = '0%';
		counterEl.textContent = '0 / ' + state.rows.length;
		currentEl.textContent = '';
		window.addEventListener('beforeunload', beforeUnloadHandler);
		processNext();
	});

	stopBtn.addEventListener('click', function() {
		state.stopped = true;
		stopBtn.disabled = true;
		stopBtn.textContent = '<?php echo esc_js( __( 'Stopping…', 'wppowersuite-lite' ) ); ?>';
	});

	var modal = document.getElementById('wp-powersuite-modal');
	if (modal) {
		var closeBtn = modal.querySelector('.wp-powersuite-modal__close');
		var cancelBtn = modal.querySelector('.wp-powersuite-modal__cancel');
		var overlay = modal.querySelector('.wp-powersuite-modal__overlay');
		function maybeWarnClose(e) {
			if (state.running) {
				if (!confirm('<?php echo esc_js( __( 'Creation is in progress. Closing will stop it. Are you sure?', 'wppowersuite-lite' ) ); ?>')) {
					e.preventDefault();
					e.stopPropagation();
					return;
				}
				state.stopped = true;
				window.removeEventListener('beforeunload', beforeUnloadHandler);
			}
		}
		if (closeBtn) closeBtn.addEventListener('click', maybeWarnClose);
		if (cancelBtn) cancelBtn.addEventListener('click', maybeWarnClose);
		if (overlay) overlay.addEventListener('click', maybeWarnClose);
		document.addEventListener('keydown', function(e) {
			if (e.key === 'Escape' && state.running && modal && modal.style.display !== 'none') {
				if (!confirm('<?php echo esc_js( __( 'Creation is in progress. Closing will stop it. Are you sure?', 'wppowersuite-lite' ) ); ?>')) {
					e.preventDefault();
					e.stopImmediatePropagation();
					return;
				}
				state.stopped = true;
				window.removeEventListener('beforeunload', beforeUnloadHandler);
			}
		}, true);
	}

	function loadTaxonomies() {
		var pt = (postTypeEl && postTypeEl.value) ? postTypeEl.value : 'page';
		var fd = new FormData();
		fd.append('action', 'wpps_bpc_get_taxonomies');
		fd.append('nonce', nonce);
		fd.append('post_type', pt);
		fetch(ajaxUrl, { method: 'POST', body: fd, credentials: 'same-origin' })
			.then(function(r) { return r.json(); })
			.then(function(data) {
				if (!taxonomyListEl || !data.success || !data.data.taxonomies) return;
				var html = '';
				for (var tax in data.data.taxonomies) {
					var t = data.data.taxonomies[tax];
					html += '<div style="margin-bottom: 8px;"><strong>' + escapeHtml(t.label || tax) + '</strong><br>';
					(t.terms || []).forEach(function(term) {
						html += '<label style="display: inline-block; margin-right: 12px; font-weight: 400;"><input type="checkbox" value="' + parseInt(term.id, 10) + '"> ' + escapeHtml(term.name) + '</label>';
					});
					html += '</div>';
				}
				taxonomyListEl.innerHTML = html || '<p class="description"><?php echo esc_js( __( 'No taxonomies for this post type.', 'wppowersuite-lite' ) ); ?></p>';
			});
	}

	document.addEventListener('wp-powersuite-modal-loaded', function(ev) {
		if (ev.detail && ev.detail.moduleId === 'bulk-page-creator') {
			postTypeEl = container.querySelector('#<?php echo esc_js( $module_id ); ?>_post_type');
			updateParentHierarchyUI();
			syncTemplateSelectToPostType();
			loadTaxonomies();
			updateStartButton();
		}
	});
	if (postTypeEl) {
		postTypeEl.addEventListener('change', function() {
			updateParentHierarchyUI();
			syncTemplateSelectToPostType();
			loadTaxonomies();
			updateStartButton();
		});
	}

	updateParentHierarchyUI();
	syncTemplateSelectToPostType();
	updateStartButton();
})();
<?php \WP_PowerSuite\Core\InlineAssets::script( 'wpps-ia-modules-bulk-page-creator-admin-php-script-1', (string) ob_get_clean() ); ?>

