/**
 * WP PowerSuite - Customizer Reset
 * Standalone admin page (no Customizer dependency).
 */
(function ($) {
	'use strict';

	var config = typeof wppsCr !== 'undefined' ? wppsCr : {};
	var nonce = config.nonce || {};

	function notify(type, msg, duration) {
		var $n = $('#wpps-cr-notice');
		if ($n.length) {
			$n.removeClass('notice-info notice-success notice-error').addClass('notice-' + (type === 'error' ? 'error' : type === 'success' ? 'success' : 'info'));
			$n.text(msg).show();
			if (duration) setTimeout(function () { $n.fadeOut(); }, duration);
		} else {
			alert(msg);
		}
	}

	function getStylesheet() {
		return 'theme';
	}

	function doExport() {
		var fmt = $('input[name="wpps-cr-format"]:checked').val() || 'json';
		notify('info', 'Exporting...');
		$.post(ajaxurl, { action: 'wpps_cr_export', nonce: nonce.export, format: fmt })
			.done(function (r) {
				if (r.success) {
					var ext = fmt === 'dat' ? 'dat' : 'json';
					var mime = fmt === 'dat' ? 'application/octet-stream' : 'application/json';
					var blob = new Blob([fmt === 'dat' ? r.data : JSON.stringify(r.data, null, 2)], { type: mime });
					var a = document.createElement('a');
					a.href = URL.createObjectURL(blob);
					a.download = 'customizer-' + (r.data.stylesheet || getStylesheet()) + '-' + Date.now() + '.' + ext;
					document.body.appendChild(a);
					a.click();
					document.body.removeChild(a);
					URL.revokeObjectURL(a.href);
					notify('success', 'Settings exported successfully!', 3000);
				} else {
					notify('error', 'Export failed: ' + (r.data || 'Unknown error'));
				}
			})
			.fail(function () { notify('error', 'Export failed: Network error'); });
	}

	function parseImportMeta(raw, fmt) {
		var meta = { theme: 'Unknown', exported: 'Unknown', template: '', payload: raw, format: fmt };
		if (fmt === 'dat') {
			meta.payload = raw;
			return meta;
		}
		try {
			var parsed = JSON.parse(raw);
			if (parsed && typeof parsed === 'object') {
				meta.theme = parsed.theme || parsed.stylesheet || parsed.template || 'Unknown';
				meta.exported = parsed.exported || parsed.created || 'Unknown';
				meta.template = parsed.template || '';
				meta.payload = JSON.stringify(parsed);
			}
		} catch (err) {
			return null;
		}
		return meta;
	}

	function doImport(file) {
		if (!file || !file.name.match(/\.(json|dat)$/i)) {
			notify('error', 'Please select a JSON or DAT file');
			return;
		}
		var fmt = file.name.match(/\.dat$/i) ? 'dat' : 'json';
		var reader = new FileReader();
		reader.onload = function (e) {
			var raw = e.target.result;
			var meta = parseImportMeta(raw, fmt);
			if (!meta) {
				notify('error', 'Invalid JSON file');
				return;
			}
			var warn = '';
			if (meta.template && typeof wppsCr !== 'undefined' && wppsCr.currentTemplate && meta.template !== wppsCr.currentTemplate) {
				warn = '\n\nThis file is for parent theme "' + meta.template + '". Your site uses "' + wppsCr.currentTemplate + '". Import will be rejected unless strict checking is disabled.';
				if (!confirm('Import settings from "' + meta.theme + '"?' + warn)) return;
			} else if (!confirm('Import settings from "' + meta.theme + '"?\n\nThis will replace your current customizer settings.\nExported: ' + meta.exported)) {
				return;
			}
			notify('info', 'Importing...');
			$.post(ajaxurl, {
				action: 'wpps_cr_import',
				nonce: nonce.import,
				import_data: meta.payload,
				format: meta.format,
				import_images: $('#wpps-cr-import-images').is(':checked') ? '1' : '0'
			})
				.done(function (r) {
					if (r.success) {
						notify('success', 'Settings imported! Reloading...');
						setTimeout(function () { location.reload(); }, 1000);
					} else {
						var err = (r.data && r.data.message) ? r.data.message : (r.data || 'Unknown error');
						notify('error', 'Import failed: ' + err);
					}
				})
				.fail(function () { notify('error', 'Import failed: Network error'); });
		};
		reader.readAsText(file);
	}

	function doBackupReset() {
		if (!confirm(config.confirm || 'This will remove all customizations. Continue?')) return;
		notify('info', 'Creating backup...');
		$.post(ajaxurl, { action: 'wpps_cr_backup', nonce: nonce.backup })
			.done(function (r) {
				if (r.success) {
					notify('info', 'Resetting...');
					$.post(ajaxurl, {
						action: 'wpps_cr_reset',
						nonce: nonce.reset,
						reset_css: $('#wpps-cr-reset-css').is(':checked') ? '1' : '0'
					})
						.done(function (r2) {
							if (r2.success) {
								notify('success', 'Backup created! Resetting...');
								setTimeout(function () { location.reload(); }, 1000);
							} else notify('error', 'Reset failed: ' + (r2.data || 'Unknown error'));
						})
						.fail(function () { notify('error', 'Reset failed: Network error'); });
				} else notify('error', 'Backup failed: ' + (r.data || 'Unknown error'));
			})
			.fail(function () { notify('error', 'Backup failed: Network error'); });
	}

	function doReset() {
		var msg = config.confirm || 'This will remove all customizations. Continue?';
		if (!config.hasBackup) msg += '\n\nWARNING: No backup exists. Consider using "Backup & Reset" instead.';
		if (!confirm(msg)) return;
		notify('info', config.resetting || 'Resetting...');
		$.post(ajaxurl, {
			action: 'wpps_cr_reset',
			nonce: nonce.reset,
			reset_css: $('#wpps-cr-reset-css').is(':checked') ? '1' : '0'
		})
			.done(function (r) {
				if (r.success) {
					notify('success', 'Customizer reset successfully!');
					setTimeout(function () { location.reload(); }, 1000);
				} else notify('error', 'Reset failed: ' + (r.data || 'Unknown error'));
			})
			.fail(function () { notify('error', 'Reset failed: Network error'); });
	}

	function doCreateBackup() {
		notify('info', 'Creating backup...');
		$.post(ajaxurl, { action: 'wpps_cr_backup', nonce: nonce.backup })
			.done(function (r) {
				if (r.success) {
					notify('success', 'Backup created! Reloading...', 2000);
					setTimeout(function () { location.reload(); }, 1000);
				} else notify('error', 'Backup failed: ' + (r.data || 'Unknown error'));
			})
			.fail(function () { notify('error', 'Backup failed: Network error'); });
	}

	function doDownloadBackup(key) {
		notify('info', 'Preparing download...');
		$.post(ajaxurl, { action: 'wpps_cr_download_backup', nonce: nonce.download, backup_key: key })
			.done(function (r) {
				if (r.success) {
					var blob = new Blob([JSON.stringify(r.data, null, 2)], { type: 'application/json' });
					var a = document.createElement('a');
					a.href = URL.createObjectURL(blob);
					a.download = 'customizer-backup-' + (r.data.stylesheet || 'theme') + '-' + Date.now() + '.json';
					document.body.appendChild(a);
					a.click();
					document.body.removeChild(a);
					URL.revokeObjectURL(a.href);
					notify('success', 'Backup downloaded!', 2000);
				} else notify('error', 'Download failed: ' + (r.data || 'Unknown error'));
			})
			.fail(function () { notify('error', 'Download failed: Network error'); });
	}

	function doRestore(key) {
		if (!confirm('Restore this backup?\n\nThis will replace your current customizer settings.')) return;
		notify('info', config.restoring || 'Restoring...');
		$.post(ajaxurl, { action: 'wpps_cr_restore', nonce: nonce.restore, backup_key: key })
			.done(function (r) {
				if (r.success) {
					notify('success', 'Backup restored!');
					setTimeout(function () { location.reload(); }, 1000);
				} else notify('error', 'Restore failed: ' + (r.data || 'Unknown error'));
			})
			.fail(function () { notify('error', 'Restore failed: Network error'); });
	}

	function doDeleteBackup(key) {
		if (!confirm('Delete this backup?\n\nThis action cannot be undone.')) return;
		$.post(ajaxurl, { action: 'wpps_cr_delete_backup', nonce: nonce.delete, backup_key: key })
			.done(function (r) {
				if (r.success) {
					notify('success', 'Backup deleted!', 3000);
					$('.wpps-cr-backup-item[data-backup-key="' + key + '"]').fadeOut(300, function () {
						$(this).remove();
						var n = $('.wpps-cr-backup-item').length;
						$('.wpps-cr-count').text('(' + n + ')');
						if (n === 0) {
							$('.wpps-cr-backup-list').remove();
							$('.wpps-cr-backup-actions').remove();
							$('.wpps-cr-backups-panel').append('<p class="wpps-cr-empty-desc">No backups found. Use "Backup & Reset" to create a backup before resetting.</p>');
						}
					});
				} else notify('error', 'Delete failed: ' + (r.data || 'Unknown error'));
			})
			.fail(function () { notify('error', 'Delete failed: Network error'); });
	}

	function doDeleteAll() {
		if (!confirm('Delete ALL backups?\n\nThis will permanently delete all your backup history.')) return;
		$.post(ajaxurl, { action: 'wpps_cr_delete_all', nonce: nonce.deleteAll })
			.done(function (r) {
				if (r.success) {
					notify('success', r.data && r.data.message ? r.data.message : 'All backups deleted!', 3000);
					$('.wpps-cr-backup-list').fadeOut(300, function () {
						$(this).remove();
						$('.wpps-cr-backup-actions').remove();
						$('.wpps-cr-count').text('(0)');
						$('.wpps-cr-backups-panel').append('<p class="wpps-cr-empty-desc">No backups found. Use "Backup & Reset" to create a backup before resetting.</p>');
					});
				} else notify('error', 'Delete failed: ' + (r.data || 'Unknown error'));
			})
			.fail(function () { notify('error', 'Delete failed: Network error'); });
	}

	$(function () {
		var $file = $('#wpps-cr-import-file');

		$(document).on('click', '.wpps-cr-action[data-action]', function (e) {
			e.preventDefault();
			var a = $(this).data('action');
			if (a === 'export') doExport();
			else if (a === 'import') $file.val('').trigger('click');
			else if (a === 'backup-reset') doBackupReset();
			else if (a === 'reset') doReset();
		});

		$file.on('change', function () {
			if (this.files && this.files[0]) doImport(this.files[0]);
		});

		$(document).on('click', '.wpps-cr-download', function (e) {
			e.preventDefault();
			doDownloadBackup($(this).data('backup-key'));
		});
		$(document).on('click', '.wpps-cr-restore', function (e) {
			e.preventDefault();
			doRestore($(this).data('backup-key'));
		});
		$(document).on('click', '.wpps-cr-delete', function (e) {
			e.preventDefault();
			doDeleteBackup($(this).data('backup-key'));
		});
		$(document).on('click', '.wpps-cr-delete-all', function (e) {
			e.preventDefault();
			doDeleteAll();
		});
		$(document).on('click', '.wpps-cr-create-backup', function (e) {
			e.preventDefault();
			doCreateBackup();
		});

		$(document).on('click', '.wpps-cr-dropzone', function (e) {
			if ($(e.target).hasClass('wpps-cr-confirm') || $(e.target).hasClass('wpps-cr-cancel')) return;
			e.preventDefault();
			$file.val('').trigger('click');
		});

		$(document).on('dragover dragenter', '.wpps-cr-dropzone', function (e) {
			e.preventDefault();
			e.stopPropagation();
			$(this).addClass('drag-over');
		});
		$(document).on('dragleave', '.wpps-cr-dropzone', function (e) {
			e.preventDefault();
			e.stopPropagation();
			$(this).removeClass('drag-over');
		});
		$(document).on('drop', '.wpps-cr-dropzone', function (e) {
			e.preventDefault();
			e.stopPropagation();
			$(this).removeClass('drag-over');
			var files = e.originalEvent.dataTransfer.files;
			if (files && files[0]) {
				if (!files[0].name.match(/\.(json|dat)$/i)) {
					notify('error', 'Please drop a JSON or DAT file');
					return;
				}
				doImport(files[0]);
			}
		});
	});
})(jQuery);
