function createLoadingIndicator() {
	const loadingIndicator = document.createElement('div');
	loadingIndicator.className = 'bwd-pdf-loading';
	loadingIndicator.innerHTML = `
		<div class="bwd-pdf-loading-overlay">
			<div class="bwd-pdf-loading-content">
				<div class="bwd-pdf-loading-spinner"></div>
				<p>Generating PDF, please wait...</p>
			</div>
		</div>
	`;
	const loadingStyles = document.createElement('style');
	loadingStyles.textContent = `
		.bwd-pdf-loading-overlay {
			position: fixed; top: 0; left: 0; width: 100%; height: 100%;
			background: rgba(0,0,0,0.7); display: flex;
			justify-content: center; align-items: center; z-index: 9999;
		}
		.bwd-pdf-loading-content {
			background: white; padding: 30px; border-radius: 8px;
			text-align: center; box-shadow: 0 4px 12px rgba(0,0,0,0.2);
		}
		.bwd-pdf-loading-spinner {
			width: 50px; height: 50px; border: 5px solid #f3f3f3;
			border-top: 5px solid #3498db; border-radius: 50%;
			margin: 0 auto 20px; animation: bwd-pdf-spin 1s linear infinite;
		}
		@keyframes bwd-pdf-spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
		.pdf-page-break-spacer {
			width: 0 !important; max-width: 0 !important; min-width: 0 !important;
			background: transparent !important; page-break-after: always !important;
			break-after: page !important; margin: 0 !important; padding: 0 !important;
			border: none !important; visibility: hidden !important; opacity: 0 !important;
			overflow: hidden !important; line-height: 0 !important; font-size: 0 !important;
			position: relative !important; float: none !important; clear: both !important;
			pointer-events: none !important;
		}
		.section, [class*="section"], [class*="education"], [class*="experience"],
		[class*="reference"], [class*="skill"], [class*="contact"], [class*="about"],
		[class*="language"], [class*="hobby"] {
			page-break-inside: avoid !important; break-inside: avoid !important;
			orphans: 3 !important; widows: 3 !important;
		}
		/* Full-width capture container for mobile */
		#bwd-pdf-capture-stage {
			position: fixed !important;
			top: 0 !important;
			left: 0 !important;
			width: 794px !important;
			z-index: -9999 !important;
			overflow: visible !important;
			background: transparent !important;
			pointer-events: none !important;
			opacity: 0 !important;
		}
	`;
	document.head.appendChild(loadingStyles);
	return loadingIndicator;
}

document.addEventListener('DOMContentLoaded', function () {
	const downloadButton = document.querySelector('.bwd-download-text');
	if (downloadButton) {
		downloadButton.addEventListener('click', async function (event) {
			event.preventDefault();
			event.stopPropagation();

			let loadingIndicator;
			let captureStage = null;
			let originalParent = null;
			let originalNextSibling = null;

			// Show loading indicator first
			loadingIndicator = createLoadingIndicator();
			document.body.appendChild(loadingIndicator);
			await new Promise(resolve => setTimeout(resolve, 100));

			try {
				const { jsPDF } = window.jspdf;
				const doc = new jsPDF({ orientation: 'portrait', unit: 'pt', format: 'letter', compress: true });
				const pageWidth  = doc.internal.pageSize.getWidth();
				const pageHeight = doc.internal.pageSize.getHeight();

				// The actual CV element
				const element = document.querySelector('.wp-block-bwdcv-wp-cv-builder-sass') || document.body;

				// ================================================================
				// KEY FIX: Instead of cloning (which loses CSS), we move the
				// real element into a fixed full-width stage, capture it,
				// then move it back. All CSS/fonts stay intact.
				// ================================================================
				captureStage        = document.createElement('div');
				captureStage.id     = 'bwd-pdf-capture-stage';
				document.body.appendChild(captureStage);

				// Remember where the element was
				originalParent      = element.parentElement;
				originalNextSibling = element.nextSibling;

				// Save inline styles we're going to change
				const savedTransform       = element.style.transform;
				const savedTransformOrigin = element.style.transformOrigin;
				const savedMaxHeight       = element.style.maxHeight;
				const savedTransition      = element.style.transition;
				const savedWidth           = element.style.width;
				const savedOverflow        = element.style.overflow;
				const savedDisplay         = element.style.display;
				const savedAlignItems      = element.style.alignItems;
				const savedFlexDirection   = element.style.flexDirection;

				// Move element into the capture stage
				captureStage.appendChild(element);

				// Force desktop layout
				element.style.cssText = `
					transform: none !important;
					transform-origin: 0 0 !important;
					max-height: none !important;
					transition: none !important;
					width: 794px !important;
					overflow: visible !important;
					display: block !important;
				`;

				// Also fix inner wrapper
				const innerWrapper = element.querySelector('.bwdcvs-cv-builder-common');
				const innerParent  = innerWrapper?.parentElement;
				let savedInnerParentStyles = {};
				let savedInnerStyles       = {};
				if (innerWrapper) {
					savedInnerStyles = {
						transform:       innerWrapper.style.transform,
						transformOrigin: innerWrapper.style.transformOrigin,
						maxHeight:       innerWrapper.style.maxHeight,
						overflow:        innerWrapper.style.overflow,
					};
					innerWrapper.style.transform       = 'none';
					innerWrapper.style.transformOrigin = '0 0';
					innerWrapper.style.maxHeight       = 'none';
					innerWrapper.style.overflow        = 'visible';
				}
				if (innerParent && innerParent !== element) {
					savedInnerParentStyles = {
						transform:       innerParent.style.transform,
						transformOrigin: innerParent.style.transformOrigin,
						maxHeight:       innerParent.style.maxHeight,
						overflow:        innerParent.style.overflow,
						display:         innerParent.style.display,
						alignItems:      innerParent.style.alignItems,
						flexDirection:   innerParent.style.flexDirection,
					};
					innerParent.style.transform       = 'none';
					innerParent.style.transformOrigin = '0 0';
					innerParent.style.maxHeight       = 'none';
					innerParent.style.overflow        = 'visible';
					innerParent.style.display         = 'block';
				}

				// Wait for layout reflow
				await new Promise(resolve => setTimeout(resolve, 500));

				// ================================================================
				// Watermarks
				// ================================================================
				const watermarkOverlays = element.querySelectorAll('[style*="background-image"][style*="position: absolute"]');
				const watermarkStyles   = [];
				watermarkOverlays.forEach(o => { watermarkStyles.push(o.style.cssText); o.style.display = 'none'; });

				// ================================================================
				// SVG → PNG conversion
				// ================================================================
				const svgs = element.querySelectorAll('svg');
				await Promise.all(Array.from(svgs).map(async (svg) => {
					const svgClone = svg.cloneNode(true);
					const style    = window.getComputedStyle(svg);
					const w = svg.clientWidth  || 24;
					const h = svg.clientHeight || 24;
					svgClone.setAttribute('width',  w);
					svgClone.setAttribute('height', h);
					svgClone.style.color = style.color;
					svgClone.style.fill  = style.fill;
					svgClone.querySelectorAll('*').forEach(el => {
						const s = window.getComputedStyle(el);
						['fill','stroke','opacity'].forEach(p => { if (s[p] && s[p] !== 'none') el.style[p] = s[p]; });
					});
					const blob = new Blob([new XMLSerializer().serializeToString(svgClone)], { type: 'image/svg+xml' });
					const url  = URL.createObjectURL(blob);
					await new Promise(resolve => {
						const img = new Image();
						img.onload = () => {
							const canvas = document.createElement('canvas');
							canvas.width = w; canvas.height = h;
							const ctx = canvas.getContext('2d');
							if (style.backgroundColor !== 'rgba(0, 0, 0, 0)') {
								ctx.fillStyle = style.backgroundColor;
								ctx.fillRect(0, 0, w, h);
							}
							ctx.drawImage(img, 0, 0, w, h);
							const png = new Image();
							png.src = canvas.toDataURL('image/png');
							png.style.cssText = svg.style.cssText;
							svg.parentNode.replaceChild(png, svg);
							URL.revokeObjectURL(url);
							resolve();
						};
						img.src = url;
					});
				}));
				await new Promise(resolve => setTimeout(resolve, 300));

				// ================================================================
				// Scale: based on element's actual rendered width in the stage
				// ================================================================
				const renderedWidth = element.offsetWidth || 794;
				const scale         = pageWidth / renderedWidth;

				// ================================================================
				// Cleanup: dup footers, stray spacers, inline marginTops
				// ================================================================
				const existingFooters = element.querySelectorAll('.footer');
				if (existingFooters.length > 1) {
					for (let i = 0; i < existingFooters.length - 1; i++) existingFooters[i].remove();
				}
				element.querySelectorAll('.pdf-page-break-spacer').forEach(s => s.remove());
				element.querySelectorAll('*').forEach(el => {
					if (el.style.marginTop && (el.style.marginTop.includes('px') || el.style.marginTop.includes('pt')))
						el.style.marginTop = '';
				});

				// ================================================================
				// Page-break helpers
				// ================================================================
				function getScaledPosition(el) {
					const r = el.getBoundingClientRect(), cr = element.getBoundingClientRect();
					const top = (r.top - cr.top) * scale, height = r.height * scale;
					return { top, height, bottom: top + height };
				}

				function createPageBreakSpacer(height) {
					const s = document.createElement('div');
					s.className = 'pdf-page-break-spacer';
					s.style.cssText = `height:${Math.max(height,30)}pt!important;width:0px!important;background:transparent!important;page-break-after:always!important;break-after:page!important;margin:0!important;padding:0!important;border:none!important;visibility:hidden!important;opacity:0!important;overflow:hidden!important;position:relative!important;`;
					return s;
				}

				function findAllSections() {
					const sections = [];
					['SKILLS','EDUCATION','EXPERIENCE','REFERENCE','REFERENCES','LANGUAGES','HOBBIES','ABOUT ME','CONTACT','ABOUT'].forEach(headerText => {
						const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT, null, false);
						let t;
						while (t = walker.nextNode()) {
							const nt = t.textContent.trim().toUpperCase();
							if (nt === headerText || (nt.includes(headerText) && nt.length < headerText.length + 10)) {
								let c = t.parentElement, sc = null;
								while (c && c !== element) {
									if (c.offsetHeight > 30) {
										const ct = c.textContent.toUpperCase();
										if (ct.includes(headerText)) {
											if (headerText === 'HOBBIES') {
												if ((c.querySelector('svg,img,[class*="icon"]') || ct.includes('MUSIC') || ct.includes('MOVIE') || ct.includes('WRITING') || ct.includes('FOOTBALL')) && (c.offsetHeight > 80)) { sc = c; break; }
											} else {
												if (ct.substring(ct.indexOf(headerText) + headerText.length).trim().length > 10) { sc = c; break; }
											}
										}
									}
									c = c.parentElement;
								}
								if (sc && !sections.some(s => s.element === sc || s.element.contains(sc) || sc.contains(s.element)))
									sections.push({ element: sc, type: 'text-based', title: headerText + ' Section', height: sc.offsetHeight, keyword: headerText });
							}
						}
					});
					if (!sections.some(s => s.keyword === 'HOBBIES')) {
						element.querySelectorAll('div,section,[class*="hobby"],[class*="hobbies"]').forEach(el => {
							const t = el.textContent.toUpperCase();
							if ((t.includes('MUSIC')||t.includes('MOVIE')||t.includes('WRITING')||t.includes('FOOTBALL')||t.includes('SPORT')||t.includes('HOBBIES')) && el.offsetHeight > 50 && el.offsetHeight < 500 && el.querySelector('svg,img,[class*="icon"]') && !sections.some(s => s.element === el || s.element.contains(el) || el.contains(s.element)))
								sections.push({ element: el, type: 'hobbies-content', title: 'HOBBIES Section', height: el.offsetHeight, keyword: 'HOBBIES' });
						});
					}
					['.section','[class*="section"]:not([class*="sub"])','[class*="education"]','[class*="experience"]','[class*="skill"]','[class*="reference"]','[class*="contact"]','[class*="about"]','[class*="hobby"]','[class*="language"]'].forEach(sel => {
						element.querySelectorAll(sel).forEach(el => {
							if (el.offsetHeight > 60 && el.offsetWidth > 0 && !sections.some(s => s.element === el || s.element.contains(el) || el.contains(s.element)))
								sections.push({ element: el, type: 'class-based', title: el.querySelector('h1,h2,h3,h4,h5,h6,.section-title,.title')?.textContent || el.className.replace(/[^a-zA-Z0-9]/g,' ').trim() || 'Section', height: el.offsetHeight, selector: sel });
						});
					});
					const u = [];
					sections.forEach(s => { if (!u.some(us => us.element === s.element || us.element.contains(s.element) || s.element.contains(us.element))) u.push(s); });
					u.sort((a,b) => getScaledPosition(a.element).top - getScaledPosition(b.element).top);
					return u;
				}

				findAllSections().forEach(section => {
					const el = section.element;
					el.style.pageBreakInside = 'avoid'; el.style.breakInside = 'avoid';
					el.style.orphans = '4'; el.style.widows = '4';
					const pos = getScaledPosition(el);
					const sp  = Math.floor(pos.top / pageHeight), ep = Math.floor(pos.bottom / pageHeight);
					if (sp !== ep) {
						const spaceLeft = ((sp + 1) * pageHeight) - pos.top;
						const pct       = (spaceLeft / pos.height) * 100;
						let thresh = 30;
						if      (section.keyword === 'HOBBIES' || section.title.toLowerCase().includes('hobbies')) thresh = 95;
						else if (section.keyword === 'LANGUAGES') thresh = 85;
						else if (section.height  < 150)           thresh = 80;
						let move = pct < thresh;
						if (section.keyword === 'HOBBIES') move = move || spaceLeft < (pos.height - 30);
						if (move) el.parentNode.insertBefore(createPageBreakSpacer(spaceLeft + 50), el);
					}
				});

				const footerEl = element.querySelector('.footer') || element.querySelector('[class*="footer"]');
				if (footerEl) {
					const pos = getScaledPosition(footerEl);
					const sp  = Math.floor(pos.top / pageHeight);
					const ep  = Math.floor(pos.bottom / pageHeight);
					if (sp !== ep) {
						const spaceLeft = ((sp + 1) * pageHeight) - pos.top;
						if ((spaceLeft / pos.height) * 100 < 80)
							footerEl.parentNode.insertBefore(createPageBreakSpacer(spaceLeft + 30), footerEl);
					}
				}

				// ================================================================
				// Generate PDF
				// ================================================================
				await doc.html(element, {
					html2canvas: {
						scale,
						windowWidth:     renderedWidth,
						windowHeight:    element.scrollHeight,
						useCORS:         true,
						backgroundColor: '#FFFFFF',
						allowTaint:      true,
						logging:         false,
					},
					callback: async function (doc) {
						try {
							watermarkOverlays.forEach((o, i) => { o.style.cssText = watermarkStyles[i]; });
							// Watermark on all pages
							try {
								if (watermarkOverlays.length > 0) {
									const bg = window.getComputedStyle(watermarkOverlays[0]).backgroundImage;
									if (bg && bg !== 'none') {
										const m = bg.match(/url\(['"]?([^'"]+)['"]?\)/);
										if (m && m[1]) {
											const wImg = new Image(); wImg.crossOrigin = 'Anonymous';
											await new Promise(r => { wImg.onload = r; wImg.src = m[1]; });
											const wc = document.createElement('canvas');
											wc.width = wImg.width; wc.height = wImg.height;
											wc.getContext('2d').drawImage(wImg, 0, 0);
											const id = wc.toDataURL('image/png');
											const tp = doc.internal.getNumberOfPages();
											for (let i = 1; i <= tp; i++) { doc.setPage(i); doc.addImage(id,'PNG',0,0,pageWidth,pageHeight,'watermark','FAST',0.3); }
										}
									}
								}
							} catch(e) { console.warn('Watermark failed:', e); }
							// Clickable links
							try {
								Array.from(element.getElementsByTagName('a')).forEach(link => {
									if (!link.href) return;
									const r = link.getBoundingClientRect(), cr = element.getBoundingClientRect();
									const ox = (r.left - cr.left) * scale, oy = (r.top - cr.top) * scale;
									const pn = Math.floor(oy / pageHeight);
									if (pn < doc.internal.getNumberOfPages()) { doc.setPage(pn+1); doc.link(ox, oy-(pn*pageHeight), r.width*scale, r.height*scale, { url: link.href }); }
								});
							} catch(e) { console.warn('Links failed:', e); }
							doc.save('cv.pdf');
						} catch(e) { console.error('PDF callback failed:', e); alert('PDF generation failed. Please try again.'); }
						finally { doRestore(); }
					},
					x: 0, y: 0, width: pageWidth, autoPaging: 'text', margin: [0,0,0,0],
				});

				// ================================================================
				// Restore function: move element back to its original place
				// ================================================================
				function doRestore() {
					try {
						// Remove stray spacers before moving back
						element.querySelectorAll('.pdf-page-break-spacer').forEach(s => s.remove());

						// Restore element styles
						element.style.transform       = savedTransform;
						element.style.transformOrigin = savedTransformOrigin;
						element.style.maxHeight       = savedMaxHeight;
						element.style.transition      = savedTransition;
						element.style.width           = savedWidth;
						element.style.overflow        = savedOverflow;
						element.style.display         = savedDisplay;
						element.style.alignItems      = savedAlignItems;
						element.style.flexDirection   = savedFlexDirection;

						// Restore inner wrapper styles
						if (innerWrapper) {
							innerWrapper.style.transform       = savedInnerStyles.transform;
							innerWrapper.style.transformOrigin = savedInnerStyles.transformOrigin;
							innerWrapper.style.maxHeight       = savedInnerStyles.maxHeight;
							innerWrapper.style.overflow        = savedInnerStyles.overflow;
						}
						if (innerParent && innerParent !== element) {
							innerParent.style.transform       = savedInnerParentStyles.transform;
							innerParent.style.transformOrigin = savedInnerParentStyles.transformOrigin;
							innerParent.style.maxHeight       = savedInnerParentStyles.maxHeight;
							innerParent.style.overflow        = savedInnerParentStyles.overflow;
							innerParent.style.display         = savedInnerParentStyles.display;
							innerParent.style.alignItems      = savedInnerParentStyles.alignItems;
							innerParent.style.flexDirection   = savedInnerParentStyles.flexDirection;
						}

						// Move element back to original position
						if (originalParent) {
							if (originalNextSibling) {
								originalParent.insertBefore(element, originalNextSibling);
							} else {
								originalParent.appendChild(element);
							}
						}

						// Remove the capture stage
						if (captureStage && captureStage.parentNode) {
							captureStage.parentNode.removeChild(captureStage);
							captureStage = null;
						}

						// Remove loading indicator
						if (loadingIndicator && loadingIndicator.parentNode) {
							loadingIndicator.parentNode.removeChild(loadingIndicator);
						}
					} catch(e) { console.warn('Restore failed:', e); }
				}

			} catch (error) {
				console.error('PDF generation failed:', error);
				alert('PDF generation failed. Please try again.');
				// Restore on error too
				setTimeout(() => {
					try {
						if (captureStage && captureStage.contains(document.querySelector('.wp-block-bwdcv-wp-cv-builder-sass'))) {
							const el = captureStage.querySelector('.wp-block-bwdcv-wp-cv-builder-sass');
							if (el && originalParent) {
								originalNextSibling ? originalParent.insertBefore(el, originalNextSibling) : originalParent.appendChild(el);
							}
						}
						if (captureStage && captureStage.parentNode) captureStage.parentNode.removeChild(captureStage);
						if (loadingIndicator && loadingIndicator.parentNode) loadingIndicator.parentNode.removeChild(loadingIndicator);
					} catch(e2) { console.warn('Error cleanup failed:', e2); }
				}, 500);
			}
		});
	}
});

document.getElementById("generate_password")?.addEventListener("click", function () {
	function generatePassword(length) {
		var charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789@#$&*!";
		var password = "";
		for (var i = 0; i < length; i++) password += charset[Math.floor(Math.random() * charset.length)];
		return password;
	}
	var pw = generatePassword(12);
	document.getElementById("user_password").value = pw;
	document.getElementById("user_password_repeat").value = pw;
});

function togglePassword(fieldId, icon) {
	var f = document.getElementById(fieldId), ic = icon.querySelector("i");
	if (f.type === "password") { f.type = "text"; ic.classList.remove("fa-eye"); ic.classList.add("fa-eye-slash"); }
	else { f.type = "password"; ic.classList.remove("fa-eye-slash"); ic.classList.add("fa-eye"); }
}
