import grapesjs from 'grapesjs';
import 'grapesjs/dist/css/grapes.min.css';
import webpagePreset from 'grapesjs-preset-webpage';
import basicBlocks from 'grapesjs-blocks-basic';
import forms from 'grapesjs-plugin-forms';

// blocks
import ProductSliderList from './grapesjs/block/product-slider-list';


function boot() {
    const root = document.querySelector('#gjs');
    if (!root) {
        console.error('GrapesJS: #gjs not found');
        return;
    }

    const CFG = window.BUILDER_CONFIG || {};

    // Validate critical configuration
    if (!CFG.URL_LOAD || !CFG.URL_STORE) {
        console.error('GrapesJS: Missing required configuration URLs');
        return;
    }

    const headers = { 'X-CSRF-TOKEN': CFG.CSRF };

    try {
        const editor = grapesjs.init({
            container: root,
            height: '100%',
            fromElement: false,

            canvas: {},

            plugins: [webpagePreset, basicBlocks, forms],
            pluginsOpts: {
                'grapesjs-preset-webpage': {
                    navbarOpts: false,
                    countdownOpts: false,
                    formsOpts: false
                }
            },

            storageManager: {
                type: 'remote',
                stepsBeforeSave: 3,
                autosave: true,
                autoload: true,
                options: {
                    remote: {
                        urlLoad: CFG.URL_LOAD,
                        urlStore: CFG.URL_STORE,
                        contentTypeJson: true,
                        headers,
                        credentials: 'same-origin',
                        onStore: (projectData, editor) => {
                            return {
                                gjs_html: editor.getHtml(),
                                gjs_css: editor.getCss(),
                                gjs_js: editor.getJs(),
                                gjs_source: projectData,
                            };
                        },
                        onLoad: (result) => {
                            return JSON.parse(result.data ?? '{}');
                        },
                    }
                }
            },

            assetManager: {
                upload: CFG.URL_UPLOAD,
                uploadName: 'file',
                headers,
                uploadFile: function (e) {
                    var files = e.dataTransfer ? e.dataTransfer.files : e.target.files;
                    console.log(files);

                    var formData = new FormData();

                    // Use Array.from() and forEach instead of for-in loop
                    // for-in loop can iterate over unexpected properties
                    Array.from(files).forEach((file, index) => {
                        formData.append('file-' + index, file);
                    });

                    // Add CSRF token for Laravel protection
                    formData.append('_token', CFG.CSRF);

                    fetch(CFG.URL_UPLOAD, {
                        method: 'POST',
                        body: formData,
                        mode: 'cors',
                        credentials: 'same-origin',
                        // headers: {
                        //     'X-CSRF-TOKEN': '{{ csrf_token() }}',
                        //     'X-Requested-With': 'XMLHttpRequest'
                        // }
                        // Remove headers object - let browser set Content-Type automatically
                    })
                        .then(response => {
                            if (!response.ok) {
                                throw new Error('Network response was not ok');
                            }
                            return response.json();
                        })
                        .then(result => {
                            console.log(result);
                            // You might want to do something with the result here
                            // like adding the images to your editor
                            for (let i = 0; i < result.data.length; i++) {
                                editor.AssetManager.add(result.data[i]);
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                        });
                }
            },
        });

        // Enhanced RTL support
        editor.on('canvas:frame:load', () => {
            const doc = editor.Canvas.getDocument();
            const style = doc.createElement('style');
            style.textContent = `body { direction: rtl; text-align: right; } *[class*="gjs-"] { direction: rtl; }`;
            doc.head.appendChild(style);
            doc.documentElement.setAttribute('dir', 'rtl');
            doc.documentElement.setAttribute('lang', 'fa-IR');
        });

        // Fixed keyboard shortcuts
        editor.Keymaps.add('core:save', 'ctrl+s, cmd+s', () => editor.store());
        editor.Keymaps.add('core:preview', 'ctrl+p, cmd+p', () => editor.runCommand('preview'));

        // Debug
        editor.on('storage:start', e => console.log('Storage start', e));
        editor.on('storage:end', e => console.log('Storage end', e));
        editor.on('storage:error', e => console.error('Storage error', e));


        // start Block
        ProductSliderList(editor);

        // End Block
        window.__editor__ = editor;



    } catch (error) {
        console.error('GrapesJS initialization failed:', error);
    }
}

// DOM ready handling
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', boot);
} else {
    boot();
}
