import { getCsrfToken } from './helpers.js';


/**
 * Creates an image upload zone with drag-and-drop support.
 * Uploads immediately on file selection via AJAX and stores the resulting URL.
 *
 * @param {jQuery} $container  - Element to render the uploader into
 * @param {string} uploadUrl   - POST endpoint (multipart/form-data, field name "file")
 * @returns {{ getUrl, setUrl, reset }}
 */
export function createImageUploader($container, uploadUrl) {
    let currentUrl = null;

    $container.html(`
        <div class="img-uploader">
            <div class="img-uploader__zone">
                <div class="img-uploader__placeholder">
                    <i class="bi bi-cloud-arrow-up"></i>
                    <div class="mt-1 fw-semibold" style="color:#6c757d">Перетащите фото или нажмите для выбора</div>
                    <small class="text-muted">JPG, PNG, WebP · до 10 МБ</small>
                </div>
                <img class="img-uploader__preview d-none" alt="preview">
                <div class="img-uploader__loading d-none">
                    <div class="spinner-border text-light" role="status"></div>
                </div>
            </div>
            <button type="button" class="img-uploader__remove d-none" title="Удалить фото">
                <i class="bi bi-x-lg"></i>
            </button>
            <input type="file" class="img-uploader__input" accept="image/*" style="display:none">
        </div>
    `);

    const $zone     = $container.find('.img-uploader__zone');
    const $ph       = $container.find('.img-uploader__placeholder');
    const $preview  = $container.find('.img-uploader__preview');
    const $loading  = $container.find('.img-uploader__loading');
    const $removeBtn= $container.find('.img-uploader__remove');
    const $fileInput= $container.find('.img-uploader__input');

    // url must already be the full absolute URL (CDN-prefixed)
    function setUrl(url) {
        currentUrl = url || null;
        if (currentUrl) {
            $preview.attr('src', currentUrl).removeClass('d-none');
            $ph.addClass('d-none');
            $removeBtn.removeClass('d-none');
        } else {
            $preview.attr('src', '').addClass('d-none');
            $ph.removeClass('d-none');
            $removeBtn.addClass('d-none');
        }
    }

    function uploadFile(file) {
        if (!file) return;
        if (!file.type.startsWith('image/')) {
            alert('Пожалуйста, выберите изображение (JPG, PNG, WebP)');
            return;
        }
        if (file.size > 10 * 1024 * 1024) {
            alert('Файл слишком большой. Максимальный размер — 10 МБ');
            return;
        }

        $loading.removeClass('d-none');
        $zone.addClass('uploading');

        const formData = new FormData();
        formData.append('file', file);

        $.ajax({
            url: uploadUrl,
            type: 'POST',
            data: formData,
            contentType: false,
            processData: false,
            beforeSend: xhr => xhr.setRequestHeader('X-XSRF-TOKEN', getCsrfToken()),
            success: resp => setUrl((window.cdn || '') + resp.url),
            error: () => alert('Ошибка загрузки изображения. Проверьте настройки хранилища.'),
            complete: () => {
                $loading.addClass('d-none');
                $zone.removeClass('uploading');
            }
        });
    }

    // Click zone → open file dialog
    $zone.on('click', () => $fileInput.trigger('click'));

    // File input change
    $fileInput.on('change', function () {
        uploadFile(this.files[0]);
        this.value = '';
    });

    // Drag-and-drop
    $zone.on('dragover', e => {
        e.preventDefault();
        $zone.addClass('dragover');
    }).on('dragleave dragend', () => {
        $zone.removeClass('dragover');
    }).on('drop', e => {
        e.preventDefault();
        $zone.removeClass('dragover');
        uploadFile(e.originalEvent.dataTransfer.files[0]);
    });

    // Remove button
    $removeBtn.on('click', e => {
        e.stopPropagation();
        setUrl(null);
    });

    return {
        getUrl: () => currentUrl,
        setUrl,
        reset: () => setUrl(null)
    };
}
