/**
 * Media Picker — Shared Popup Component
 * เรียกใช้จากหน้าไหนก็ได้ ผ่าน mediaPickerOpen(callback)
 *
 * Usage:
 *   <script src="assets/js/media_picker.js"></script>
 *   <link rel="stylesheet" href="assets/css/media_picker.css">
 *
 *   mediaPickerOpen({ multiple: false, onSelect: function(items) { ... } });
 *     items = [{ id, url, filename, original_name, file_size_text, width, height }]
 */

const MEDIA_PICKER_API = 'api/media_handler.php';
let _mpCallback = null;
let _mpMultiple = false;
let _mpSelectedItems = {};
let _mpCurrentPage = 1;
let _mpInitialized = false;

function mediaPickerOpen(options = {}) {
    _mpCallback = options.onSelect || null;
    _mpMultiple = options.multiple || false;
    _mpSelectedItems = {};
    _mpCurrentPage = 1;

    _mpEnsureDOM();
    document.getElementById('mpOverlay').style.display = 'flex';
    document.getElementById('mpSearchInput').value = '';
    document.getElementById('mpSelectedBar').style.display = 'none';
    _mpLoadImages(1);
}

function mediaPickerClose() {
    document.getElementById('mpOverlay').style.display = 'none';
    _mpCallback = null;
}

function _mpEnsureDOM() {
    if (_mpInitialized) return;
    _mpInitialized = true;

    const overlay = document.createElement('div');
    overlay.id = 'mpOverlay';
    overlay.className = 'mp-overlay';
    overlay.style.display = 'none';
    overlay.innerHTML = `
        <div class="mp-dialog">
            <div class="mp-header">
                <h3><i class="fas fa-images"></i> เลือกรูปจากคลัง</h3>
                <button class="mp-close" onclick="mediaPickerClose()">&times;</button>
            </div>
            <div class="mp-toolbar">
                <div class="mp-search">
                    <i class="fas fa-search"></i>
                    <input type="text" id="mpSearchInput" placeholder="ค้นหา..." oninput="_mpDebounce()">
                </div>
                <select id="mpCatFilter" class="form-control" style="max-width:140px;" onchange="_mpLoadImages(1)">
                    <option value="all">ทั้งหมด</option>
                </select>
            </div>
            <div class="mp-grid" id="mpGrid">
                <div class="mp-loading"><i class="fas fa-spinner fa-spin"></i> กำลังโหลด...</div>
            </div>
            <div class="mp-pagination" id="mpPagination"></div>
            <div class="mp-selected-bar" id="mpSelectedBar" style="display:none;">
                <span>เลือก <strong id="mpSelCount">0</strong> รูป</span>
                <button class="btn btn-primary" onclick="_mpConfirm()">
                    <i class="fas fa-check"></i> ใช้รูปที่เลือก
                </button>
            </div>
        </div>`;
    document.body.appendChild(overlay);
}

let _mpSearchTimer = null;
function _mpDebounce() {
    clearTimeout(_mpSearchTimer);
    _mpSearchTimer = setTimeout(() => _mpLoadImages(1), 400);
}

function _mpLoadImages(page) {
    _mpCurrentPage = page;
    const grid = document.getElementById('mpGrid');
    const search = document.getElementById('mpSearchInput').value.trim();
    const cat = document.getElementById('mpCatFilter').value;

    grid.innerHTML = '<div class="mp-loading"><i class="fas fa-spinner fa-spin"></i> กำลังโหลด...</div>';

    let url = `${MEDIA_PICKER_API}?action=list&page=${page}&category=${encodeURIComponent(cat)}`;
    if (search) url += `&search=${encodeURIComponent(search)}`;

    fetch(url)
        .then(r => r.json())
        .then(data => {
            if (!data.success) return;

            // Update category filter
            const catSel = document.getElementById('mpCatFilter');
            const curCat = catSel.value;
            catSel.innerHTML = '<option value="all">ทั้งหมด</option>' +
                (data.categories || []).map(c =>
                    `<option value="${_mpEsc(c)}" ${c === curCat ? 'selected' : ''}>${_mpEsc(c)}</option>`
                ).join('');

            if (!data.data || data.data.length === 0) {
                grid.innerHTML = '<div class="mp-empty"><i class="fas fa-images"></i><p>ไม่พบรูปภาพ</p></div>';
                document.getElementById('mpPagination').innerHTML = '';
                return;
            }

            grid.innerHTML = data.data.map(item => {
                const thumbSrc = item.thumb_url || item.url;
                return `
                <div class="mp-item ${_mpSelectedItems[item.id] ? 'selected' : ''}"
                     onclick="_mpToggle(${item.id}, '${item.url}', '${_mpEsc(item.filename)}', '${_mpEsc(item.original_name)}', '${item.file_size_text}', ${item.width||0}, ${item.height||0})">
                    <img src="${thumbSrc}" alt="" loading="lazy">
                    <div class="mp-check ${_mpSelectedItems[item.id] ? 'checked' : ''}"><i class="fas fa-check"></i></div>
                    <div class="mp-item-label">${_mpEsc(item.original_name)}</div>
                </div>`;
            }).join('');

            // Pagination
            _mpRenderPagination(data.page, data.total_pages);
        })
        .catch(() => {
            grid.innerHTML = '<div class="mp-empty"><i class="fas fa-exclamation-triangle"></i><p>โหลดไม่สำเร็จ</p></div>';
        });
}

function _mpToggle(id, url, filename, originalName, sizeText, width, height) {
    if (_mpMultiple) {
        if (_mpSelectedItems[id]) {
            delete _mpSelectedItems[id];
        } else {
            _mpSelectedItems[id] = { id, url, filename, original_name: originalName, file_size_text: sizeText, width, height };
        }
    } else {
        // Single select → confirm immediately
        _mpCallback && _mpCallback([{ id, url, filename, original_name: originalName, file_size_text: sizeText, width, height }]);
        mediaPickerClose();
        return;
    }

    // Update UI
    document.querySelectorAll('#mpGrid .mp-item').forEach(el => {
        const itemId = parseInt(el.getAttribute('onclick').match(/_mpToggle\((\d+)/)[1]);
        el.classList.toggle('selected', !!_mpSelectedItems[itemId]);
        el.querySelector('.mp-check').classList.toggle('checked', !!_mpSelectedItems[itemId]);
    });

    const count = Object.keys(_mpSelectedItems).length;
    const bar = document.getElementById('mpSelectedBar');
    bar.style.display = count > 0 ? 'flex' : 'none';
    document.getElementById('mpSelCount').textContent = count;
}

function _mpConfirm() {
    const items = Object.values(_mpSelectedItems);
    _mpCallback && _mpCallback(items);
    mediaPickerClose();
}

function _mpRenderPagination(current, totalPages) {
    const el = document.getElementById('mpPagination');
    if (totalPages <= 1) { el.innerHTML = ''; return; }
    let html = '';
    if (current > 1) html += `<button class="btn btn-sm" onclick="_mpLoadImages(${current-1})"><i class="fas fa-chevron-left"></i></button>`;
    for (let p = 1; p <= totalPages; p++) {
        if (p === current) html += `<button class="btn btn-sm btn-primary">${p}</button>`;
        else if (p <= 2 || p >= totalPages - 1 || Math.abs(p - current) <= 1) html += `<button class="btn btn-sm" onclick="_mpLoadImages(${p})">${p}</button>`;
        else if (Math.abs(p - current) === 2) html += '<span>...</span>';
    }
    if (current < totalPages) html += `<button class="btn btn-sm" onclick="_mpLoadImages(${current+1})"><i class="fas fa-chevron-right"></i></button>`;
    el.innerHTML = html;
}

function _mpEsc(str) {
    if (!str) return '';
    return str.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;');
}
