/**
 * Shared HTML template, CDN URL resolution, and BigCommerce region/schema helpers
 * for CB AI Product Assistant widget APIs (v1 + v2).
 */

export const PRODUCT_TEMPLATE_FILE = 'pages/product';
export const CUSTOM_PRODUCT_TEMPLATE_PREFIX = 'pages/custom/product/';

export const DEFAULT_TITLE = 'Looking for specific info?';
export const DEFAULT_PLACEHOLDER = 'Ask a question about this product...';

export const DEFAULT_WIDGET_SETTINGS = {
	title: DEFAULT_TITLE,
	mainColor: '#3C64F4',
	fontSize: '28px',
	footerHtml: '',
	headerIcon:
		'<svg class="cb-ai-assis-icon" width="28" height="28" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z" fill="{{mainColor}}"/><path d="M12 6c-3.31 0-6 2.69-6 6s2.69 6 6 6 6-2.69 6-6-2.69-6-6-6zm0 10c-2.21 0-4-1.79-4-4s1.79-4 4-4 4 1.79 4 4-1.79 4-4 4z" fill="{{mainColor}}" opacity="0.6"/><circle cx="12" cy="12" r="2" fill="{{mainColor}}"/></svg>',
	addToCartSelector: '#form-action-addToCart, .add-to-cart-button, [data-action="add-to-cart"]',
	addToCartQtySelector: '#qty\\[\\], .form-input--incrementTotal, input[name="qty[]"]',
};

export type ProductAssistantCdnUrls = {
	scriptUrl: string;
	markedUrl: string;
	apiUrl: string;
};

/**
 * @param scriptBasename e.g. cb-ai-product-assistant.js or cb-ai-product-assistant-v2.js
 * @param logLabel optional log prefix
 * @param useV2ApiUrl if true, prefer PRODUCT_WIDGET_V2_API_URL over PRODUCT_WIDGET_API_URL
 */
export function getProductAssistantCdnUrls(
	scriptBasename: string,
	logLabel = '[ProductAssistantWidget]',
	useV2ApiUrl = false
): ProductAssistantCdnUrls {
	const cdnUrl = process.env.CDN_URL || '';
	const apiUrl =
		useV2ApiUrl && process.env.PRODUCT_WIDGET_V2_API_URL
			? process.env.PRODUCT_WIDGET_V2_API_URL
			: process.env.PRODUCT_WIDGET_API_URL || '';

	console.log(`${logLabel} URLs:`, { cdnUrl, apiUrl, scriptBasename, useV2ApiUrl });

	return {
		scriptUrl: `${cdnUrl}/${scriptBasename}`,
		markedUrl: 'https://cdn.jsdelivr.net/npm/marked/marked.min.js',
		apiUrl: apiUrl || '',
	};
}

/**
 * Generate widget template HTML — script injection + skeleton (same markup for v1 and v2; script URL differs).
 */
export function generateProductAssistantWidgetHtml(
	uniqueId: string,
	_storeHash: string,
	widgetSettings: any,
	urls: ProductAssistantCdnUrls
): string {
	const { scriptUrl, markedUrl, apiUrl } = urls;

	const escapedScriptUrl = scriptUrl.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
	const escapedMarkedUrl = markedUrl.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
	const escapedApiUrl = apiUrl.replace(/\\/g, '\\\\').replace(/'/g, "\\'");

	const escapedTitle = (widgetSettings.title || DEFAULT_WIDGET_SETTINGS.title)
		.replace(/\\/g, '\\\\')
		.replace(/'/g, "\\'")
		.replace(/"/g, '\\"');
	const escapedMainColor = (widgetSettings.mainColor || DEFAULT_WIDGET_SETTINGS.mainColor)
		.replace(/\\/g, '\\\\')
		.replace(/'/g, "\\'")
		.replace(/"/g, '\\"');
	const escapedFontSize = (widgetSettings.fontSize || DEFAULT_WIDGET_SETTINGS.fontSize)
		.replace(/\\/g, '\\\\')
		.replace(/'/g, "\\'")
		.replace(/"/g, '\\"');
	const escapedFooterHtml = (widgetSettings.footerHtml || DEFAULT_WIDGET_SETTINGS.footerHtml)
		.replace(/\\/g, '\\\\')
		.replace(/'/g, "\\'")
		.replace(/"/g, '\\"')
		.replace(/\n/g, '\\n')
		.replace(/\r/g, '\\r');

	let headerIconHtml = widgetSettings.headerIcon || DEFAULT_WIDGET_SETTINGS.headerIcon;
	headerIconHtml = headerIconHtml.replace(/\{\{mainColor\}\}/g, widgetSettings.mainColor || DEFAULT_WIDGET_SETTINGS.mainColor);
	const escapedHeaderIcon = headerIconHtml
		.replace(/\\/g, '\\\\')
		.replace(/'/g, "\\'")
		.replace(/"/g, '\\"')
		.replace(/\n/g, '\\n')
		.replace(/\r/g, '\\r');

	const escapedAddToCartSelector = (widgetSettings.addToCartSelector || DEFAULT_WIDGET_SETTINGS.addToCartSelector)
		.replace(/\\/g, '\\\\')
		.replace(/'/g, "\\'")
		.replace(/"/g, '\\"');
	const escapedAddToCartQtySelector = (widgetSettings.addToCartQtySelector || DEFAULT_WIDGET_SETTINGS.addToCartQtySelector)
		.replace(/\\/g, '\\\\')
		.replace(/'/g, "\\'")
		.replace(/"/g, '\\"');

	return `<!-- CB AI Product Assistant Styles -->
<style>
#cb-product-questions {
max-width: 700px;
width: 100%;
max-height: 600px;
display: flex;
flex-direction: column;
background: white;
border-radius: 12px;
padding: 30px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
margin-bottom:30px;
margin-top: 30px;
}
.cb-ai-skeleton {
background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
background-size: 200% 100%;
animation: cb-ai-shimmer 1.5s infinite;
border-radius: 4px;
}
@keyframes cb-ai-shimmer {
0% { background-position: 200% 0; }
100% { background-position: -200% 0; }
}
.cb-ai-skeleton-title {
height: 32px;
width: 60%;
margin-bottom: 30px;
}
.cb-ai-skeleton-input {
height: 50px;
width: 100%;
margin-bottom: 20px;
border-radius: 8px;
}
.cb-ai-skeleton-buttons {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
.cb-ai-skeleton-button {
height: 45px;
width: 200px;
border-radius: 25px;
}
</style>
<!-- Widget Container with Skeleton Loader -->
<div id="cb-product-questions" data-unique-id="${uniqueId}" data-api-url="${escapedApiUrl}">
<div id="cb-ai-skeleton">
<div class="cb-ai-skeleton cb-ai-skeleton-title"></div>
<div class="cb-ai-skeleton cb-ai-skeleton-input"></div>
<div class="cb-ai-skeleton-buttons">
<div class="cb-ai-skeleton cb-ai-skeleton-button"></div>
<div class="cb-ai-skeleton cb-ai-skeleton-button"></div>
<div class="cb-ai-skeleton cb-ai-skeleton-button"></div>
<div class="cb-ai-skeleton cb-ai-skeleton-button"></div>
</div>
</div>
</div>
<!-- CB AI Product Assistant - Script Injection -->
<script>
(function() {
var marked = document.createElement('script');
marked.src = '${escapedMarkedUrl}';
marked.defer = true;
document.head.appendChild(marked);
var s = document.createElement('script');
s.src = '${escapedScriptUrl}';
s.defer = true;
s.dataset.uuid = '${uniqueId}';
s.dataset.apiUrl = '${escapedApiUrl}';
s.dataset.target = '#cb-product-questions';
s.dataset.addToCartSelector = '${escapedAddToCartSelector}';
s.dataset.qtyInputSelector = '${escapedAddToCartQtySelector}';
s.dataset.title = '${escapedTitle}';
s.dataset.placeholder = '{{placeholder}}';
s.dataset.mainColor = '${escapedMainColor}';
s.dataset.fontSize = '${escapedFontSize}';
s.dataset.footerHtml = "${escapedFooterHtml}";
s.dataset.headerIcon = "${escapedHeaderIcon}";
document.head.appendChild(s);
})();
</script>`;
}

/**
 * Normalize a product / custom product template path for the Widgets API.
 * Accepts: custom-product, custom-product.html, pages/custom/product/custom-product
 * Returns null for non-product paths (pages/home, pages/category, etc.).
 */
export function toProductWidgetTemplateFile(fileName: string): string | null {
	if (!fileName || typeof fileName !== 'string') return null;
	let cleaned = fileName.trim().replace(/^\/+/, '').replace(/^templates\//, '');
	if (!cleaned) return null;

	const lower = cleaned.toLowerCase();
	if (
		lower === 'pages/product' ||
		lower === 'pages/product.html' ||
		lower === 'product.html' ||
		lower === 'product'
	) {
		return PRODUCT_TEMPLATE_FILE;
	}

	if (cleaned.startsWith('custom/product/')) {
		cleaned = `pages/${cleaned}`;
	} else if (cleaned.startsWith('pages/custom/product/')) {
		// already normalized
	} else if (cleaned.startsWith('pages/')) {
		return null;
	} else {
		cleaned = `${CUSTOM_PRODUCT_TEMPLATE_PREFIX}${cleaned.replace(/^\/+/, '')}`;
	}

	cleaned = cleaned.replace(/\.html$/i, '');

	if (cleaned.startsWith(CUSTOM_PRODUCT_TEMPLATE_PREFIX)) {
		const rest = cleaned.slice(CUSTOM_PRODUCT_TEMPLATE_PREFIX.length);
		if (!rest || rest.includes('/') || rest.startsWith('pages')) {
			return null;
		}
	}

	return cleaned;
}

/**
 * Build placement template_file list from API body.
 * Always includes pages/product; adds any valid custom templates from templateFile / customTemplate.
 */
export function resolveProductPlacementTemplateFiles(
	templateFile?: string | string[] | null,
	customTemplate?: string | string[] | null
): string[] {
	const files = new Set<string>([PRODUCT_TEMPLATE_FILE]);
	const rawInputs = [
		...(Array.isArray(templateFile) ? templateFile : templateFile ? [templateFile] : []),
		...(Array.isArray(customTemplate) ? customTemplate : customTemplate ? [customTemplate] : []),
	];

	for (const raw of rawInputs) {
		const normalized = toProductWidgetTemplateFile(String(raw));
		if (normalized) {
			files.add(normalized);
		}
	}

	return Array.from(files);
}

export async function getProductBelowContentRegion(
	bigCommerce: any,
	templateFile: string = PRODUCT_TEMPLATE_FILE
): Promise<string | null> {
	try {
		try {
			const regionsResponse = await bigCommerce.get('/content/regions');
			if (regionsResponse?.data) {
				const productRegions = regionsResponse.data.filter(
					(r: any) =>
						r.template_file === templateFile ||
						r.template_file === 'pages/product' ||
						r.template_file?.includes('product')
				);
				const targetRegion = productRegions.find((r: any) => {
					const regionName = (r.name || r.region || '').toLowerCase();
					return regionName.includes('below') && regionName.includes('content');
				});
				if (targetRegion) {
					const regionName = targetRegion.region || targetRegion.name;
					console.log('[ProductAssistantWidget] Found region from regions API:', regionName);
					return regionName;
				}
			}
		} catch (regionsError) {
			console.log('[ProductAssistantWidget] Regions API not available, trying placements API');
		}

		const placementsResponse = await bigCommerce.get('/content/placements');
		if (placementsResponse?.data) {
			const productPlacements = placementsResponse.data.filter(
				(p: any) => p.template_file === templateFile || p.template_file === 'pages/product'
			);
			const targetPlacement = productPlacements.find((p: any) => {
				const regionName = (p.region || '').toLowerCase();
				return regionName.includes('below') && regionName.includes('content');
			});
			if (targetPlacement) {
				console.log('[ProductAssistantWidget] Found region from placements:', targetPlacement.region);
				return targetPlacement.region;
			}
			const commonRegions = [
				'cb_pdp_widget',
				'product_below_content',
				'product-below-content',
				'product_below_content_area',
				'product_below_description',
				'product_below_details',
			];
			for (const commonRegion of commonRegions) {
				const exists = productPlacements.some((p: any) => p.region === commonRegion);
				if (exists) {
					console.log('[ProductAssistantWidget] Found common region:', commonRegion);
					return commonRegion;
				}
			}
		}

		console.log('[ProductAssistantWidget] Using default region: product_below_content');
		return 'product_below_content';
	} catch (error) {
		console.error('[ProductAssistantWidget] Error fetching regions:', error);
		return 'product_below_content';
	}
}

export function generateProductAssistantPageBuilderSchema() {
	return [
		{
			type: 'tab',
			label: 'Content',
			sections: [
				{
					label: 'Widget Settings',
					settings: [
						{
							type: 'input',
							id: 'placeholder',
							label: 'Input Placeholder',
							default: DEFAULT_PLACEHOLDER,
							placeholder: 'Enter placeholder text',
						},
					],
				},
			],
		},
	];
}
