document.addEventListener( "DOMContentLoaded", function( event ) {

    function api( data, result_fn, error_fn ) {
        const formData = new FormData();
        buildFormData( formData, data );
        const ajax = new XMLHttpRequest();
        ajax.addEventListener( "load", function( event ) {
            let responseData = {};
            try {
                responseData = JSON.parse( event.target.responseText );
            } catch (e) {
                console.error("Failed to parse server response:", e, event.target.responseText);
                if ( error_fn ) {
                    error_fn( event );
                }
                return;
            }
            if ( result_fn ) {
                result_fn( responseData );
            }
        } );
        ajax.addEventListener( "error", function( event ) {
            console.error("API request failed");
            if ( error_fn ) {
                error_fn( event );
            }
        } );
        ajax.open( "POST", url_api, true );
        ajax.send( formData );
    }
    
    function buildFormData( formData, data, parentKey ) {
        if ( data && typeof data === "object" && ! ( data instanceof Date ) && ! ( data instanceof File ) ) {
            Object.keys( data ).forEach( key => {
                buildFormData( formData, data[key], parentKey ? `${parentKey}[${key}]` : key );
            } );
        } else {
            const value = data == null ? "" : data;
            formData.append( parentKey, value );
        }
    }

    const allLinks = Array.from(document.querySelectorAll('link[rel="stylesheet/less"]'));
    const mixinLinks = allLinks.filter(el => el.href.includes('.mixin.less'));
    const regularLinks = allLinks.filter(el => !el.href.includes('.mixin.less'));

	if ( regularLinks.length > 0 ) {
		console.log( `Found ${regularLinks.length} LESS files and ${mixinLinks.length} mixin files to compile.` );
		
		// Убедимся, что less.js загружен
		if ( typeof less === "undefined" ) {
			console.error( "less.js is not loaded. Cannot compile styles." );
			return;
		}

        const mixinPromises = mixinLinks.map(el => 
            fetch(el.href).then(response => {
                if (!response.ok) {
                    throw new Error(`Failed to load ${el.href}`);
                }
                return response.text();
            })
        );

        Promise.all(mixinPromises)
            .then(mixinContents => {
                const mixinCss = mixinContents.join('\n');

                const compilationPromises = regularLinks.map( function ( el ) {
                    const href = el.href;
                    const name = href.replace(/.*\//, "").replace(/\.[^.]+$/, "");
                    return fetch( href )
                        .then( function ( response ) {
                            if ( ! response.ok ) {
                                throw new Error( `Failed to load ${href} (status: ${response.status})` );
                            }
                            return response.text();
                        } )
                        .then( function ( lessContent ) {
                            const fullContent = (mixinCss + '\n' + lessContent).replace(/\/\*[\s\S]*?\*\//g, '').replace(/\s\s+/g, ' ');
                            return less.render( fullContent )
                                .then( function ( output ) {
                                    // Успешная компиляция
                                    return { name: name, css: output.css };
                                } );
                        } )
                        .catch( function ( err ) {
                            // Пробрасываем ошибку дальше, чтобы Promise.all ее поймал
                            console.error( `Error processing file ${href}:`, err.message || err );
                            throw { href: href, error: err };
                        } );
                } );

                return Promise.all(compilationPromises);
            })
			.then( function ( results ) {
				// Этот блок выполнится, только если ВСЕ промисы завершились успешно
				const compiledStyles = {};
				results.forEach( function ( result ) {
					// ключ - имя файла без расширения, значение - скомпилированный css
					compiledStyles[result.name] = result.css;
				} );

				console.log( 'All LESS files compiled successfully. Sending to server...' );

				api( {
						fn: "template_save_css", // Имя серверной функции
                        tpl: tpl,
						styles: compiledStyles, // JSON-объект со стилями
					},
					function ( answer ) {
						console.log( 'Server response:', answer );
						if ( answer.result ) {
							console.log( 'Server saved CSS. Reloading page.' );
                            setTimeout( function() {
							    window.location.reload();
                            }, 1000 );
						} else {
							console.error( 'Server error on saving CSS:', answer.error || 'Unknown error' );
						}
					},
					function ( error ) {
						console.error( 'API call to save CSS failed:', error );
					}
				);
			} )
			.catch( function ( error ) {
				// Этот блок поймает ПЕРВУЮ ошибку из любого промиса
				console.error( 'An error occurred during the LESS compilation process. Aborting.', error );
			} );

	} else {
		console.log( 'No regular LESS files found to compile.' );
	}
} );