/* Add custom JS code below */ 
/* FLANTENO | Show color badge on products with options */

(function () {
    function getProductData(card) {
        let product = card.product || card.getAttribute('product');

        if (typeof product === 'string') {
            try {
                product = JSON.parse(product);
            } catch (e) {
                product = null;
            }
        }

        return product;
    }

    function findImageWrapper(card) {
        return card.querySelector(
            '.s-product-card-image, .product-card__image, .product-card-image, .s-product-card-image-wrap, .s-product-card-content-main .image'
        );
    }

    function createBadge() {
        const badge = document.createElement('div');
        badge.className = 'flanteno-color-badge';
        badge.innerHTML = `
            <span class="plus">+</span>
            <span class="sq sq1"></span>
            <span class="sq sq2"></span>
            <span class="sq sq3"></span>
        `;
        return badge;
    }

    function updateBadges() {
        const cards = document.querySelectorAll('salla-product-card, custom-salla-product-card');

        cards.forEach(card => {
            const product = getProductData(card);
            const imageWrapper = findImageWrapper(card);

            if (!product || !imageWrapper) return;

            const hasOptions =
                product.has_options === true ||
                (Array.isArray(product.options) && product.options.length > 0);

            card.classList.toggle('flanteno-multi-options', hasOptions);

            const oldBadge = imageWrapper.querySelector('.flanteno-color-badge');

            if (hasOptions) {
                if (!oldBadge) {
                    imageWrapper.appendChild(createBadge());
                }
            } else {
                if (oldBadge) {
                    oldBadge.remove();
                }
            }
        });
    }

    updateBadges();

    const observer = new MutationObserver(() => {
        updateBadges();
    });

    observer.observe(document.body, {
        childList: true,
        subtree: true
    });
})();

/* FLANTENO SMART SEARCH V1 */

(function () {
    if (window.flantenoSmartSearchV1) return;
    window.flantenoSmartSearchV1 = true;

    const libraries = {};

    function loadLibrary(url) {
        if (!libraries[url]) {
            libraries[url] = new Promise((resolve, reject) => {
                const script = document.createElement('script');
                script.src = url;
                script.onload = resolve;
                script.onerror = () => {
                    delete libraries[url];
                    script.remove();
                    reject(new Error('Library unavailable'));
                };
                document.head.appendChild(script);
            });
        }
        return libraries[url];
    }

    function searchProduct(input, text) {
        if (!text || !input.isConnected) return;

        const setter = Object.getOwnPropertyDescriptor(
            HTMLInputElement.prototype, 'value'
        ).set;

        setter.call(input, text.trim());

        input.dispatchEvent(
            new Event('input', { bubbles: true })
        );

        input.dispatchEvent(
            new Event('change', { bubbles: true })
        );
    }

    function selectImage(camera, callback) {
        const fileInput = document.createElement('input');

        fileInput.type = 'file';
        fileInput.accept = 'image/*';

        if (camera) {
            fileInput.setAttribute('capture', 'environment');
        }

        fileInput.addEventListener('change', () => {
            const file = fileInput.files[0];
            if (file) callback(file);
        });

        fileInput.click();
    }

    async function readBarcode(file) {
        if ('BarcodeDetector' in window) {
            let bitmap;

            try {
                bitmap = await createImageBitmap(file);

                const detector = new BarcodeDetector();
                const codes = await detector.detect(bitmap);

                if (codes.length) {
                    return codes[0].rawValue;
                }
            } catch (error) {
                // Use fallback library
            } finally {
                if (bitmap) bitmap.close();
            }
        }

        await loadLibrary(
            'https://cdn.jsdelivr.net/npm/@zxing/browser@0.1.5/umd/zxing-browser.min.js'
        );

        const reader = new ZXingBrowser.BrowserMultiFormatReader();
        const url = URL.createObjectURL(file);

        try {
            const result = await reader.decodeFromImageUrl(url);
            return result.getText();
        } finally {
            URL.revokeObjectURL(url);
        }
    }

    async function readProductImage(file) {
        await loadLibrary(
            'https://cdn.jsdelivr.net/npm/tesseract.js@5.1.1/dist/tesseract.min.js'
        );

        const worker = await Tesseract.createWorker('eng+ara');

        try {
            const result = await worker.recognize(file);
            return result.data.text
                .replace(/\s+/g, ' ')
                .trim();
        } finally {
            await worker.terminate();
        }
    }

    function addSmartSearch(input) {
        if (!input.parentElement) return;

        const wrapper = input.parentElement;

        if (wrapper.nextElementSibling?.classList.contains(
            'flanteno-smart-search'
        )) return;

        const panel = document.createElement('div');
        panel.className = 'flanteno-smart-search';

        panel.innerHTML = `
            <div class="flanteno-search-heading">
                ✦ البحث الذكي
            </div>

            <div class="flanteno-search-tools">

                <button type="button" data-mode="camera">
                    <svg viewBox="0 0 24 24">
                        <path d="M14 4H10L8 7H4a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-4z"/>
                        <circle cx="12" cy="14" r="4"/>
                    </svg>
                    تصوير المنتج
                </button>

                <button type="button" data-mode="image">
                    <svg viewBox="0 0 24 24">
                        <rect x="3" y="3" width="18" height="18" rx="3"/>
                        <circle cx="8" cy="8" r="2"/>
                        <path d="m3 17 5-5 4 4 4-6 5 7"/>
                    </svg>
                    رفع صورة
                </button>

                <button type="button" data-mode="barcode">
                    <svg viewBox="0 0 24 24">
                        <path d="M3 4v16M6 4v16M10 4v16M12 4v16M16 4v16M19 4v16M21 4v16"/>
                    </svg>
                    مسح الباركود
                </button>

                <button type="button" data-mode="voice">
                    <svg viewBox="0 0 24 24">
                        <rect x="9" y="2" width="6" height="13" rx="3"/>
                        <path d="M5 10v2a7 7 0 0 0 14 0v-2M12 19v3M8 22h8"/>
                    </svg>
                    البحث الصوتي
                </button>

            </div>

            <div class="flanteno-search-status"
                 role="status"></div>
        `;

        wrapper.after(panel);

        const status = panel.querySelector(
            '.flanteno-search-status'
        );

        const buttons = panel.querySelectorAll('button');

        function busy(value) {
            buttons.forEach(button => {
                button.disabled = value;
            });
        }

        buttons.forEach(button => {

            button.addEventListener('click', () => {

                const mode = button.dataset.mode;

                if (mode === 'voice') {

                    const Recognition =
                        window.SpeechRecognition ||
                        window.webkitSpeechRecognition;

                    if (!Recognition) {
                        status.textContent =
                            'البحث الصوتي غير مدعوم في هذا المتصفح';
                        return;
                    }

                    const recognition = new Recognition();

                    recognition.lang = 'ar-SA';
                    recognition.interimResults = false;

                    recognition.onstart = () => {
                        busy(true);
                        status.textContent = 'تحدث الآن...';
                    };

                    recognition.onresult = event => {
                        const text =
                            event.results[0][0].transcript;

                        searchProduct(input, text);
                        status.textContent = 'تم التعرف على الصوت';
                    };

                    recognition.onerror = () => {
                        status.textContent =
                            'تعذر التعرف على الصوت';
                        busy(false);
                    };

                    recognition.onend = () => busy(false);

                    try {
                        recognition.start();
                    } catch (error) {
                        busy(false);
                        status.textContent =
                            'تعذر تشغيل الميكروفون';
                    }

                    return;
                }

                selectImage(mode !== 'image', async file => {

                    busy(true);

                    status.textContent =
                        'جاري تحليل الصورة...';

                    try {
                        if (mode === 'barcode') {

                            const code = await readBarcode(file);

                            searchProduct(input, code);

                            status.textContent =
                                'تم قراءة الباركود: ' + code;

                        } else {

                            const text =
                                await readProductImage(file);

                            if (!text) {
                                status.textContent =
                                    'لم يتم التعرف على اسم المنتج';
                                return;
                            }

                            const query = window.prompt(
                                'تأكد من اسم المنتج قبل البحث',
                                text.slice(0, 160)
                            );

                            if (query && query.trim()) {
                                searchProduct(input, query);
                                status.textContent =
                                    'تم إرسال اسم المنتج للبحث';
                            } else {
                                status.textContent = '';
                            }
                        }

                    } catch (error) {

                        status.textContent =
                            'تعذر القراءة، جرب صورة أوضح أو البحث بالكتابة';

                    } finally {
                        busy(false);
                    }
                });
            });
        });
    }

    function init() {

        const inputs = document.querySelectorAll(
            'salla-search input, ' +
            'input[type="search"], ' +
            'input[placeholder="ابحث"]'
        );

        inputs.forEach(input => {
            if (input.offsetWidth &&
                input.offsetHeight &&
                !input.disabled &&
                !input.readOnly) {
                addSmartSearch(input);
            }
        });
    }

    function start() {
        init();

        let timer;

        const observer = new MutationObserver(() => {
            clearTimeout(timer);
            timer = setTimeout(init, 150);
        });

        observer.observe(document.body, {
            childList: true,
            subtree: true
        });

        document.addEventListener('click', () => {
            setTimeout(init, 300);
        });
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', start);
    } else {
        start();
    }

})();