/**
 * homeSectionsUpload.js
 * Instant AJAX image upload for home sections (hero slides + ads).
 * - Uploads immediately on file pick → shows spinner → shows preview
 * - Writes returned server path into the hidden URL input
 * - Validates before submit (no waiting for server at save time)
 */

(function () {
    'use strict';

    /* ── Config ────────────────────────────────────────────────────────── */
    const UPLOAD_URL  = '/admin/assets/ajax/upload_home_image.php';
    const CSRF_TOKEN  = document.querySelector('meta[name="csrf-token"]')?.content
                      || document.querySelector('input[name="_csrf"]')?.value
                      || '';

    /* ── Spinner HTML ───────────────────────────────────────────────────── */
    const SPINNER_HTML = `
        <div class="upload-spinner d-flex align-items-center gap-2 text-muted small py-1">
            <div class="spinner-border spinner-border-sm" role="status"></div>
            <span>جاري الرفع…</span>
        </div>`;

    /* ── Core: upload one file, update UI ──────────────────────────────── */
    function uploadImage(file, dir, fileInput, urlInput, previewWrap, previewImg) {

        // Show spinner, hide old preview
        previewWrap.style.display = '';
        previewImg.style.display  = 'none';
        previewWrap.insertAdjacentHTML('afterbegin', SPINNER_HTML);
        fileInput.disabled = true;

        const fd = new FormData();
        fd.append('image',  file);
        fd.append('dir',    dir);
        fd.append('_csrf',  CSRF_TOKEN);

        fetch(UPLOAD_URL, { method: 'POST', body: fd })
            .then(function (res) { return res.json(); })
            .then(function (data) {
                // Remove spinner
                previewWrap.querySelector('.upload-spinner')?.remove();
                fileInput.disabled = false;

                if (data.success) {
                    // Update hidden URL input with real path
                    urlInput.value = data.path;

                    // Show preview
                    previewImg.src          = data.path;
                    previewImg.style.display = '';
                    previewWrap.style.display = '';

                    // Clear the file input so the form won't re-upload
                    fileInput.value = '';

                    markSuccess(fileInput);
                } else {
                    markError(fileInput, data.message || 'فشل الرفع');
                    previewWrap.style.display = 'none';
                }
            })
            .catch(function (err) {
                previewWrap.querySelector('.upload-spinner')?.remove();
                fileInput.disabled = false;
                markError(fileInput, 'خطأ في الاتصال');
                console.error('Upload error:', err);
            });
    }

    /* ── Visual feedback ────────────────────────────────────────────────── */
    function markSuccess(input) {
        input.classList.remove('is-invalid');
        input.classList.add('is-valid');
        setTimeout(function () { input.classList.remove('is-valid'); }, 2500);
    }

    function markError(input, msg) {
        input.classList.add('is-invalid');
        let fb = input.nextElementSibling;
        if (!fb || !fb.classList.contains('invalid-feedback')) {
            fb = document.createElement('div');
            fb.className = 'invalid-feedback';
            input.after(fb);
        }
        fb.textContent = msg;
    }

    /* ── Bind one image block ───────────────────────────────────────────── */
    function bindBlock(container, dir) {
        const fileInput  = container.querySelector('.hs-file-input');
        const urlInput   = container.querySelector('.hs-url-input');
        const previewWrap = container.querySelector('.hs-preview-wrap');
        const previewImg  = container.querySelector('.hs-preview-img');

        if (!fileInput || !urlInput || !previewWrap || !previewImg) return;

        // Show existing URL preview on load
        if (urlInput.value.trim()) {
            previewImg.src           = urlInput.value.trim();
            previewImg.style.display = '';
            previewWrap.style.display = '';
        }

        fileInput.addEventListener('change', function () {
            const file = this.files && this.files[0];
            if (!file) return;

            // Instant local preview first
            const reader = new FileReader();
            reader.onload = function (e) {
                previewImg.src           = e.target.result;
                previewImg.style.display = '';
                previewWrap.style.display = '';
            };
            reader.readAsDataURL(file);

            // Then upload
            uploadImage(file, dir, fileInput, urlInput, previewWrap, previewImg);
        });

        // Manual URL input
        urlInput.addEventListener('input', function () {
            if (!fileInput.files || !fileInput.files[0]) {
                const v = this.value.trim();
                if (v) {
                    previewImg.src           = v;
                    previewImg.style.display = '';
                    previewWrap.style.display = '';
                } else {
                    previewImg.style.display  = 'none';
                    previewWrap.style.display = 'none';
                }
            }
        });
    }

    /* ── Public: bind all blocks inside a wrapper ──────────────────────── */
    window.HS_Upload = {

        bindSlides: function (slidesWrapper) {
            if (!slidesWrapper) return;
            slidesWrapper.querySelectorAll('.slide-item').forEach(function (slide) {
                bindBlock(slide, 'hero');
            });
        },

        bindSlide: function (slide) {
            bindBlock(slide, 'hero');
        },

        bindAds: function (container) {
            if (!container) return;
            container.querySelectorAll('.ad-block').forEach(function (ad) {
                bindBlock(ad, 'ads');
            });
        },

        bindAd: function (ad) {
            bindBlock(ad, 'ads');
        },

        /* Validate: at least one slide has an image path */
        hasSlideImages: function (slidesWrapper) {
            if (!slidesWrapper) return false;
            for (const ui of slidesWrapper.querySelectorAll('.hs-url-input')) {
                if (ui.value.trim()) return true;
            }
            return false;
        },

        /* Validate: at least one ad has an image path */
        hasAdImage: function (container) {
            if (!container) return false;
            const first = container.querySelector('.ad-block .hs-url-input');
            return !!(first && first.value.trim());
        }
    };

})();
