import { getConfig } from './config';

export const SPINNER_SELECTOR = '.PDFDraft-Button-Spinner';

export const DOWNLOAD_ICON_SVG =
	'<svg class="PDFDraft-Button-Icon" xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 15V3" /><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" /><path d="m7 10 5 5 5-5" /></svg>';

/** Stroke spinner — shared by download + delete loaders (avoids WP core `.spinner` clipping in narrow meta boxes). */
export const SPINNER_ICON_SVG =
	'<svg class="pdfdraft-spinner-icon" xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a9 9 0 11-6.219-8.56"/></svg>';

export const SPINNER_SVG =
	'<span class="PDFDraft-Button-Spinner" style="display: none;" aria-hidden="true">' +
	SPINNER_ICON_SVG +
	'</span>';

export function escapeHtml(str: string): string {
	const div = document.createElement('div');
	div.textContent = str;
	return div.innerHTML;
}

export function setSpinner(button: HTMLElement, show: boolean): void {
	const spinner = button.querySelector(SPINNER_SELECTOR) as HTMLElement | null;
	const icon = button.querySelector('.PDFDraft-Button-Icon') as HTMLElement | null;
	const label = button.querySelector('.PDFDraft-Button-Text, .PDFDraft-Invoice-Filename') as HTMLElement | null;
	if (spinner) spinner.style.display = show ? 'inline-flex' : 'none';
	if (icon) icon.style.display = show ? 'none' : '';
	if (label) label.style.display = show ? 'none' : '';
	if (show) {
		button.setAttribute('disabled', 'disabled');
		button.style.pointerEvents = 'none';
	} else {
		button.removeAttribute('disabled');
		button.style.pointerEvents = '';
	}
}

export function replaceButtonWithFilename(button: HTMLElement, filename: string): void {
	const wrap = button.closest('.PDFDraft-Invoice-Wrap') as HTMLElement | null;
	if (!wrap) return;

	const context = button.getAttribute('data-context') ?? '';
	const orderId = button.getAttribute('data-order-id') ?? '';
	const deleteUrl = wrap.getAttribute('data-delete-url') ?? '';

	const attrs = [
		`class="PDFDraft-Invoice-Download-Button PDFDraft-Button-${context} PDFDraft-Button-icon"`,
		`data-order-id="${orderId}"`,
		`data-context="${context}"`,
		`data-tip="Download invoice"`,
	].join(' ');

	const config = getConfig();
	// Some older builds may not have this translation key available.
	const deleteLabel = (config.i18n as any)?.removeStoredInvoiceLabel ?? 'Remove stored invoice';
	const deleteMarkup = deleteUrl
		? `<button
			type="button"
			class="PDFDraft-Invoice-Delete-Button"
			data-order-id="${orderId}"
			data-delete-url="${escapeHtml(deleteUrl)}"
			aria-label="${escapeHtml(deleteLabel)}"
			title="${escapeHtml(deleteLabel)}"
		>
			<span class="screen-reader-text">${escapeHtml(deleteLabel)}</span>
			<svg class="PDFDraft-Invoice-Delete-Icon" xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/></svg>
		</button>`
		: '';

	const newWrap = document.createElement('div');
	newWrap.className = `PDFDraft-Invoice-Wrap PDFDraft-Invoice-Wrap--${context} PDFDraft-Invoice-Wrap--has-invoice`;
	newWrap.innerHTML = `
		<div class="PDFDraft-Invoice-Row">
			<a ${attrs}><span class="PDFDraft-Invoice-Filename">${escapeHtml(filename)}</span>${DOWNLOAD_ICON_SVG}${SPINNER_SVG}<span class="screen-reader-text">Download invoice</span></a>
			${deleteMarkup}
		</div>
	`;

	wrap.replaceWith(newWrap);
}

export function showError(button: HTMLElement, message?: string): void {
	const config = getConfig();
	const text = message || config.i18n?.errorDownloadFailed || 'Download failed. Please try again.';
	if (typeof window.alert === 'function') {
		window.alert(text);
	}
}

export function showUpdateButtonLoader(): HTMLElement | null {
	const btn =
		document.querySelector<HTMLElement>('#publish') ||
		document.querySelector<HTMLElement>('button[name="save"]') ||
		document.querySelector<HTMLElement>('input[name="save"]');
	if (!btn) return null;

	const actionWrap =
		(btn.closest('#publishing-action') as HTMLElement | null) ||
		(btn.parentElement as HTMLElement | null);

	const spinner = document.createElement('span');
	spinner.className = 'spinner is-active';
	spinner.style.cssText = 'float:none;margin:0 0 0 90px;vertical-align:middle;';
	if (actionWrap) {
		actionWrap.insertBefore(spinner, btn);
	} else {
		btn.insertAdjacentElement('beforebegin', spinner);
	}
	btn.setAttribute('disabled', 'true');
	return spinner;
}

export function hideUpdateButtonLoader( spinner: HTMLElement | null ): void {
	if (!spinner) return;
	const btn =
		document.querySelector<HTMLElement>('#publish') ||
		document.querySelector<HTMLElement>('button[name="save"]') ||
		document.querySelector<HTMLElement>('input[name="save"]');
	spinner.remove();
	btn?.removeAttribute('disabled');
}
