/**
 * Password Protect Master — Admin JS
 *
 * @package PasswordProtectMaster
 */

(function () {
	'use strict';

	document.addEventListener('DOMContentLoaded', function () {

		/* ----- Password Visibility Toggles ----- */
		var toggleButtons = document.querySelectorAll('.ppmstr-toggle-visibility');
		toggleButtons.forEach(function (btn) {
			btn.addEventListener('click', function () {
				var target = btn.getAttribute('data-target');
				var input;

				if (target) {
					input = document.getElementById(target);
				} else {
					input = btn.closest('.ppmstr-input-group').querySelector('input');
				}

				if (!input) return;

				var icon = btn.querySelector('.dashicons');
				if ('password' === input.type) {
					input.type = 'text';
					if (icon) { icon.classList.replace('dashicons-visibility', 'dashicons-hidden'); }
				} else {
					input.type = 'password';
					if (icon) { icon.classList.replace('dashicons-hidden', 'dashicons-visibility'); }
				}
			});
		});

		/* ----- Cookie Type → Duration Visibility ----- */
		var cookieType = document.getElementById('ppmstr-cookie-type');
		var durationRow = document.getElementById('ppmstr-duration-row');

		if (cookieType && durationRow) {
			function ppmstrToggleDuration() {
				durationRow.style.display = (cookieType.value === 'session') ? 'none' : '';
			}
			ppmstrToggleDuration();
			cookieType.addEventListener('change', ppmstrToggleDuration);
		}

		/* ----- Metabox: Toggle password field visibility ----- */
		var protectedToggle = document.getElementById('ppmstr-protected-toggle');
		var passwordWrap = document.getElementById('ppmstr-password-wrap');

		if (protectedToggle && passwordWrap) {
			function ppmstrTogglePasswordField() {
				passwordWrap.style.display = protectedToggle.checked ? '' : 'none';
			}
			ppmstrTogglePasswordField();
			protectedToggle.addEventListener('change', ppmstrTogglePasswordField);
		}

		/* ----- Metabox: Eye toggle ----- */
		var metaboxEye = document.getElementById('ppmstr-toggle-pass');
		if (metaboxEye) {
			metaboxEye.addEventListener('click', function () {
				var input = document.getElementById('ppmstr-password-input');
				if (!input) return;
				var icon = metaboxEye.querySelector('.dashicons');
				if ('password' === input.type) {
					input.type = 'text';
					if (icon) { icon.classList.replace('dashicons-visibility', 'dashicons-hidden'); }
				} else {
					input.type = 'password';
					if (icon) { icon.classList.replace('dashicons-hidden', 'dashicons-visibility'); }
				}
			});
		}

		/* ----- Success notice auto-dismiss ----- */
		var notices = document.querySelectorAll('.ppmstr-notice--success');
		notices.forEach(function (notice) {
			setTimeout(function () {
				notice.style.transition = 'opacity 0.4s ease, transform 0.4s ease';
				notice.style.opacity = '0';
				notice.style.transform = 'translateY(-8px)';
				setTimeout(function () { notice.remove(); }, 400);
			}, 4000);
		});

		/* ----- Metabox: Collapsible sections ----- */
		document.querySelectorAll('.ppmstr-metabox-section-header').forEach(function (header) {
			var section = header.closest('.ppmstr-metabox-section');
			if (section) {
				// Start collapsed.
				section.classList.add('ppmstr-collapsed');
				header.addEventListener('click', function () {
					section.classList.toggle('ppmstr-collapsed');
				});
			}
		});
		/* ================================================================
		 * Phase 5: Template Customizer Live Preview
		 * ================================================================ */

		var lpPreview  = document.getElementById('ppmstr-live-preview');
		var lpCard     = document.getElementById('ppmstr-lp-card');
		var lpIcon     = document.getElementById('ppmstr-lp-icon');
		var lpDesc     = document.getElementById('ppmstr-lp-desc');
		var lpInput    = document.getElementById('ppmstr-lp-input');
		var lpBtn      = document.getElementById('ppmstr-lp-btn');

		if (lpPreview && lpCard) {
			// Color pickers.
			document.querySelectorAll('.ppmstr-color-input').forEach(function (input) {
				input.addEventListener('input', function () {
					var target = input.getAttribute('data-preview');
					if (target === 'bg')     lpPreview.style.background = input.value;
					if (target === 'card')   lpCard.style.background = input.value;
					if (target === 'accent') {
						if (lpIcon) lpIcon.style.color = input.value;
						if (lpBtn)  lpBtn.style.background = input.value;
					}
					if (target === 'text') {
						lpCard.querySelector('h3').style.color = input.value;
						if (lpDesc) lpDesc.style.color = input.value;
					}
				});
			});

			// Range sliders.
			document.querySelectorAll('.ppmstr-range-input').forEach(function (input) {
				input.addEventListener('input', function () {
					var val    = input.value;
					var target = input.getAttribute('data-preview');
					var label  = input.parentElement.querySelector('.ppmstr-range-val');
					if (label) label.textContent = val + 'px';
					if (target === 'cardRadius')  lpCard.style.borderRadius = val + 'px';
					if (target === 'inputRadius' && lpInput) lpInput.style.borderRadius = val + 'px';
					if (target === 'btnRadius' && lpBtn)     lpBtn.style.borderRadius = val + 'px';
				});
			});

			// Toggles.
			document.querySelectorAll('[data-preview="showIcon"]').forEach(function (cb) {
				cb.addEventListener('change', function () {
					if (lpIcon) lpIcon.style.display = cb.checked ? '' : 'none';
				});
			});
			document.querySelectorAll('[data-preview="showDesc"]').forEach(function (cb) {
				cb.addEventListener('change', function () {
					if (lpDesc) lpDesc.style.display = cb.checked ? '' : 'none';
				});
			});
			document.querySelectorAll('[data-preview="cardShadow"]').forEach(function (cb) {
				cb.addEventListener('change', function () {
					lpCard.style.boxShadow = cb.checked ? '0 4px 24px rgba(0,0,0,0.08)' : 'none';
				});
			});
		}

		// Template selection — update active card.
		document.querySelectorAll('.ppmstr-tpl-radio').forEach(function (radio) {
			radio.addEventListener('change', function () {
				document.querySelectorAll('.ppmstr-tpl-card').forEach(function (c) {
					c.classList.remove('ppmstr-tpl-active');
				});
				if (radio.checked) {
					radio.closest('.ppmstr-tpl-card').classList.add('ppmstr-tpl-active');
				}
			});
		});

		// Activate template (preset or custom).
		document.querySelectorAll('.ppmstr-activate-tpl').forEach(function (btn) {
			btn.addEventListener('click', function (e) {
				e.preventDefault();
				var tplId = btn.getAttribute('data-id');
				if (typeof ppmstrAdmin === 'undefined') return;

				btn.disabled = true;
				btn.textContent = 'Activating…';

				var body = new URLSearchParams();
				body.append('action', 'ppmstr_activate_template');
				body.append('nonce', ppmstrAdmin.nonce);
				body.append('template_id', tplId);

				fetch(ppmstrAdmin.ajaxUrl, {
					method: 'POST', credentials: 'same-origin',
					headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
					body: body.toString()
				})
				.then(function (r) { return r.json(); })
				.then(function (resp) {
					if (resp.success) {
						var notice = document.getElementById('ppmstr-tpl-notice');
						if (notice) {
							notice.textContent = resp.data.message || 'Template activated!';
							notice.style.display = 'block';
						}
						setTimeout(function () { location.reload(); }, 600);
					} else {
						btn.disabled = false;
						btn.textContent = 'Activate';
						alert(resp.data || 'Error activating template.');
					}
				});
			});
		});

		// Delete custom template.
		document.querySelectorAll('.ppmstr-delete-custom-tpl').forEach(function (btn) {
			btn.addEventListener('click', function (e) {
				e.preventDefault();
				e.stopPropagation();
				if (!confirm('Delete this custom template?')) return;
				var tplId = btn.getAttribute('data-id');
				if (typeof ppmstrAdmin === 'undefined') return;

				var body = new URLSearchParams();
				body.append('action', 'ppmstr_delete_template');
				body.append('nonce', ppmstrAdmin.nonce);
				body.append('template_id', tplId);

				fetch(ppmstrAdmin.ajaxUrl, {
					method: 'POST', credentials: 'same-origin',
					headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
					body: body.toString()
				})
				.then(function (r) { return r.json(); })
				.then(function (resp) {
					if (resp.success) { location.reload(); }
					else { alert(resp.data || 'Error.'); }
				});
			});
		});

		/* ================================================================
		 * Phase 3: Passwords Page AJAX
		 * ================================================================ */

		if (typeof ppmstrAdmin === 'undefined') return;

		function ppmstrAjax(action, data, callback) {
			data.action = action;
			data.nonce  = ppmstrAdmin.nonce;

			var body = new URLSearchParams();
			for (var key in data) {
				body.append(key, data[key]);
			}

			fetch(ppmstrAdmin.ajaxUrl, {
				method: 'POST',
				credentials: 'same-origin',
				headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
				body: body.toString()
			})
			.then(function (r) { return r.json(); })
			.then(callback)
			.catch(function (err) {
				console.error('PPMSTR AJAX error', err);
			});
		}

		/* ----- Generate random password ----- */
		var genBtn = document.getElementById('ppmstr-pw-generate');
		if (genBtn) {
			genBtn.addEventListener('click', function () {
				var input = document.getElementById('ppmstr-pw-password');
				if (!input) return;
				var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%';
				var pw = '';
				for (var i = 0; i < 12; i++) {
					pw += chars.charAt(Math.floor(Math.random() * chars.length));
				}
				input.value = pw;
				input.type = 'text';
			});
		}

		/* ----- Add password ----- */
		var addBtn = document.getElementById('ppmstr-add-pw-btn');
		if (addBtn) {
			addBtn.addEventListener('click', function () {
				var postId   = document.getElementById('ppmstr-pw-post').value;
				var password = document.getElementById('ppmstr-pw-password').value;
				var label    = document.getElementById('ppmstr-pw-label').value;
				var expires  = document.getElementById('ppmstr-pw-expires').value;
				var maxUses  = document.getElementById('ppmstr-pw-maxuses').value;
				var status   = document.getElementById('ppmstr-add-status');

				if (!postId || !password) {
					status.textContent = 'Please select content and enter a password.';
					status.className = 'ppmstr-ajax-status ppmstr-ajax-status--error';
					return;
				}

				addBtn.disabled = true;
				status.textContent = 'Saving…';
				status.className = 'ppmstr-ajax-status';

				ppmstrAjax('ppmstr_add_password', {
					post_id: postId,
					password: password,
					label: label,
					expires_at: expires,
					max_uses: maxUses
				}, function (resp) {
					addBtn.disabled = false;
					if (resp.success) {
						status.textContent = resp.data.message || 'Added!';
						document.getElementById('ppmstr-pw-password').value = '';
						document.getElementById('ppmstr-pw-label').value = '';
						setTimeout(function () { location.reload(); }, 800);
					} else {
						status.innerHTML = resp.data || 'Error.';
						status.className = 'ppmstr-ajax-status ppmstr-ajax-status--error';
					}
				});
			});
		}

		/* ----- Delete password ----- */
		document.querySelectorAll('.ppmstr-delete-pw').forEach(function (btn) {
			btn.addEventListener('click', function () {
				if (!confirm('Delete this password?')) return;
				var row    = btn.closest('tr');
				var pwId   = btn.getAttribute('data-id');
				var postId = btn.getAttribute('data-post');

				row.style.opacity = '0.5';

				ppmstrAjax('ppmstr_delete_password', {
					post_id: postId,
					password_id: pwId
				}, function (resp) {
					if (resp.success) {
						row.remove();
					} else {
						row.style.opacity = '1';
						alert(resp.data || 'Error deleting password.');
					}
				});
			});
		});

		/* ----- Bulk generate ----- */
		var bulkBtn = document.getElementById('ppmstr-bulk-btn');
		if (bulkBtn) {
			bulkBtn.addEventListener('click', function () {
				var postId  = document.getElementById('ppmstr-bulk-post').value;
				var count   = document.getElementById('ppmstr-bulk-count').value;
				var length  = document.getElementById('ppmstr-bulk-length').value;
				var status  = document.getElementById('ppmstr-bulk-status');
				var output  = document.getElementById('ppmstr-generated-output');
				var listing = document.getElementById('ppmstr-generated-list');

				if (!postId) {
					status.textContent = 'Please select content.';
					status.className = 'ppmstr-ajax-status ppmstr-ajax-status--error';
					return;
				}

				bulkBtn.disabled = true;
				status.textContent = 'Generating…';
				status.className = 'ppmstr-ajax-status';

				ppmstrAjax('ppmstr_bulk_generate', {
					post_id: postId,
					count: count,
					length: length
				}, function (resp) {
					bulkBtn.disabled = false;
					if (resp.success) {
						status.textContent = resp.data.message || 'Done!';
						if (resp.data.passwords && listing) {
							var text = resp.data.passwords.map(function (p) {
								return p.label + ': ' + p.password;
							}).join('\n');
							listing.value = text;
							output.style.display = 'block';
						}
					} else {
						status.textContent = resp.data || 'Error.';
						status.className = 'ppmstr-ajax-status ppmstr-ajax-status--error';
					}
				});
			});
		}

		/* ----- Export CSV ----- */
		var exportBtn = document.getElementById('ppmstr-export-btn');
		if (exportBtn) {
			exportBtn.addEventListener('click', function () {
				ppmstrAjax('ppmstr_export_csv', {}, function (resp) {
					if (resp.success && resp.data.csv) {
						var csvContent = resp.data.csv.map(function (row) {
							return row.map(function (cell) {
								return '"' + String(cell).replace(/"/g, '""') + '"';
							}).join(',');
						}).join('\n');

						var blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
						var url  = URL.createObjectURL(blob);
						var a    = document.createElement('a');
						a.href     = url;
						a.download = 'ppmstr-passwords-' + new Date().toISOString().slice(0, 10) + '.csv';
						a.click();
						URL.revokeObjectURL(url);
					}
				});
			});
		}

	});
})();
