/**
 * sidebar-experiments.js
 * Dynamic "Thử nghiệm" sidebar — add, edit mode, load more (>5)
 */
(function () {
    const API = '/api/dashboard/experiment-links';
    const MAX_VISIBLE = 5;
    const ICONS = ['🔗','🧪','⚡','🛠️','📊','🤖','🔍','📦','🗄️','📝','🎯','💡'];
    const BADGES = [
        { value: '',     label: 'Không',  cls: '' },
        { value: 'dev',  label: 'DEV',    cls: 'badge-dev' },
        { value: 'beta', label: 'BETA',   cls: 'badge-beta' },
        { value: 'new',  label: 'NEW',    cls: 'badge-new' },
    ];
    let allLinks = [];
    let expanded = false;

    // ─── Helpers ───
    function getGroup() { return document.getElementById('nav-group-experiments'); }

    function badgeCls(type) {
        if (type === 'beta') return 'badge-beta';
        if (type === 'new')  return 'badge-new';
        if (type === 'dev')  return 'badge-dev';
        return 'badge-count';
    }

    // ─── Render sidebar links ───
    function render() {
        const group = getGroup();
        if (!group) return;

        const label = group.querySelector('.exp-label-row');
        // Remove everything except label
        Array.from(group.children).forEach(c => { if (c !== label) c.remove(); });

        const sidebarLinks = allLinks.filter(l => l.section !== 'main');
        const visible = expanded ? sidebarLinks : sidebarLinks.slice(0, MAX_VISIBLE);

        visible.forEach(link => {
            const detailUrl = `/static/experiment_detail.html?id=${link.id}`;
            const a = document.createElement('a');
            a.href = detailUrl;
            const currentId = new URLSearchParams(window.location.search).get('id');
            a.className = 'nav-item' + (currentId === link.id ? ' active' : '');

            let html = `<span class="nav-icon">${link.icon || '🔗'}</span><span>${link.name}</span>`;
            if (link.badge) {                       
                html += `<span class="nav-badge ${badgeCls(link.badge_type)}">${link.badge}</span>`;
            }

            // Edit mode btn (click to change badge)
            html += `<span class="exp-edit" data-id="${link.id}" title="Đổi trạng thái">✎</span>`;

            // Delete btn
            html += `<span class="exp-delete" data-id="${link.id}" title="Xóa">×</span>`;

            a.innerHTML = html;
            group.appendChild(a);
        });

        // Load more / collapse
        if (!expanded && allLinks.length > MAX_VISIBLE) {
            const btn = document.createElement('button');
            btn.className = 'nav-item exp-load-more';
            btn.innerHTML = `<span class="nav-icon">🔽</span><span>Xem thêm (${allLinks.length - MAX_VISIBLE})</span>`;
            btn.onclick = () => { expanded = true; render(); };
            group.appendChild(btn);
        } else if (expanded && allLinks.length > MAX_VISIBLE) {
            const btn = document.createElement('button');
            btn.className = 'nav-item exp-load-more';
            btn.innerHTML = `<span class="nav-icon">🔼</span><span>Thu gọn</span>`;
            btn.onclick = () => { expanded = false; render(); };
            group.appendChild(btn);
        }

        // Wire events
        group.querySelectorAll('.exp-delete').forEach(btn => {
            btn.onclick = async (e) => {
                e.preventDefault(); e.stopPropagation();
                if (!confirm('Xóa link này?')) return;
                await fetch(`${API}/${btn.dataset.id}`, { method: 'DELETE' });
                await load();
            };
        });
        group.querySelectorAll('.exp-edit').forEach(btn => {
            btn.onclick = (e) => {
                e.preventDefault(); e.stopPropagation();
                const link = allLinks.find(l => l.id === btn.dataset.id);
                if (link) showEditModal(link);
            };
        });
    }

    // ─── Load from API ───
    async function load() {
        try {
            const res = await fetch(API);
            allLinks = await res.json();
            render();
        } catch (e) { console.error('Experiment links load failed:', e); }
    }

    // ─── Remove existing modal ───
    function closeModal() {
        const m = document.getElementById('exp-modal');
        if (m) m.remove();
    }

    // ─── ADD modal ───
    function showAddModal() {
        closeModal();
        const modal = document.createElement('div');
        modal.id = 'exp-modal';
        modal.innerHTML = `
            <div class="exp-overlay" onclick="document.getElementById('exp-modal').remove()"></div>
            <div class="exp-box">
                <h3>➕ Thêm link thử nghiệm</h3>

                <label>Tên <span class="exp-req">*</span></label>
                <input type="text" id="exp-name" placeholder="VD: Monitoring Dashboard" />

                <label>URL <span class="exp-req">*</span></label>
                <input type="text" id="exp-url" placeholder="VD: http://localhost:3000" />

                <label>Icon</label>
                <div class="exp-icon-grid" id="exp-icon-grid">
                    ${ICONS.map(ic => `<button class="exp-icon-btn${ic === '🔗' ? ' selected' : ''}" data-icon="${ic}">${ic}</button>`).join('')}
                </div>

                <label>Trạng thái</label>
                <div class="exp-badge-row" id="exp-badge-row">
                    ${BADGES.map(b => `<button class="exp-badge-btn${b.value === '' ? ' selected' : ''}" data-value="${b.value}" data-label="${b.label}">${b.label}</button>`).join('')}
                </div>

                <div class="exp-actions">
                    <button class="exp-btn-cancel" onclick="document.getElementById('exp-modal').remove()">Hủy</button>
                    <button class="exp-btn-save" id="exp-save">Thêm</button>
                </div>
            </div>
        `;
        document.body.appendChild(modal);
        wireModalEvents(modal, 'add');
    }

    // ─── EDIT modal (change badge/mode) ───
    function showEditModal(link) {
        closeModal();
        const modal = document.createElement('div');
        modal.id = 'exp-modal';
        modal.innerHTML = `
            <div class="exp-overlay" onclick="document.getElementById('exp-modal').remove()"></div>
            <div class="exp-box">
                <h3>✎ Đổi trạng thái — ${link.name}</h3>

                <label>Icon</label>
                <div class="exp-icon-grid" id="exp-icon-grid">
                    ${ICONS.map(ic => `<button class="exp-icon-btn${ic === (link.icon || '🔗') ? ' selected' : ''}" data-icon="${ic}">${ic}</button>`).join('')}
                </div>

                <label>Trạng thái</label>
                <div class="exp-badge-row" id="exp-badge-row">
                    ${BADGES.map(b => `<button class="exp-badge-btn${b.value === (link.badge_type || '') ? ' selected' : ''}" data-value="${b.value}" data-label="${b.label}">${b.label}</button>`).join('')}
                </div>

                <div class="exp-status-hint" id="exp-hint"></div>

                <div class="exp-actions">
                    <button class="exp-btn-cancel" onclick="document.getElementById('exp-modal').remove()">Hủy</button>
                    <button class="exp-btn-save" id="exp-save">Lưu</button>
                </div>
            </div>
        `;
        document.body.appendChild(modal);
        wireModalEvents(modal, 'edit', link);
        updateHint(link.badge_type || '');
    }

    // ─── Hint text for each badge ───
    function updateHint(val) {
        const hint = document.getElementById('exp-hint');
        if (!hint) return;
        const hints = {
            '':     '⚪ <b>Stable</b> — Dùng hàng ngày, không cần nhấn mạnh',
            'dev':  '🟣 <b>DEV</b> — Dev mới code xong, chưa test',
            'beta': '🟡 <b>BETA</b> — Dev test OK, đợi BA test',
            'new':  '🔵 <b>NEW</b> — BA test OK, release cho team dùng',
        };
        hint.innerHTML = hints[val] || '';
    }

    // ─── Wire modal events ───
    function wireModalEvents(modal, mode, link) {
        let selectedIcon = mode === 'edit' ? (link.icon || '🔗') : '🔗';
        let selectedBadge = mode === 'edit' ? (link.badge_type || '') : '';

        // Icon picker
        modal.querySelectorAll('.exp-icon-btn').forEach(btn => {
            btn.onclick = () => {
                modal.querySelectorAll('.exp-icon-btn').forEach(b => b.classList.remove('selected'));
                btn.classList.add('selected');
                selectedIcon = btn.dataset.icon;
            };
        });

        // Badge toggle
        modal.querySelectorAll('.exp-badge-btn').forEach(btn => {
            btn.onclick = () => {
                modal.querySelectorAll('.exp-badge-btn').forEach(b => b.classList.remove('selected'));
                btn.classList.add('selected');
                selectedBadge = btn.dataset.value;
                updateHint(selectedBadge);
            };
        });

        // Save
        document.getElementById('exp-save').onclick = async () => {
            const badgeMap = { dev: 'DEV', beta: 'BETA', 'new': 'NEW' };

            if (mode === 'add') {
                const name = document.getElementById('exp-name').value.trim();
                const url = document.getElementById('exp-url').value.trim();
                if (!name || !url) return alert('Cần nhập tên và URL!');

                await fetch(API, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        name, url, icon: selectedIcon,
                        badge: badgeMap[selectedBadge] || null,
                        badge_type: selectedBadge || null,
                    }),
                });
            } else {
                await fetch(`${API}/${link.id}`, {
                    method: 'PUT',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        icon: selectedIcon,
                        badge: badgeMap[selectedBadge] || null,
                        badge_type: selectedBadge || null,
                    }),
                });
            }

            closeModal();
            await load();
        };
    }

    // ─── Styles ───
    const style = document.createElement('style');
    style.textContent = `
        .exp-label-row { display: flex; justify-content: space-between; align-items: center; }
        .exp-add-btn { background: none; border: none; color: #484f58; cursor: pointer; font-size: 1em; padding: 2px 6px; border-radius: 4px; transition: all 0.2s; line-height: 1; }
        .exp-add-btn:hover { color: #a78bfa; background: rgba(167,139,250,0.1); }

        .exp-edit, .exp-delete { display: none; margin-left: 4px; color: #484f58; font-size: 0.9em; cursor: pointer; padding: 0 3px; line-height: 1; transition: color 0.15s; }
        .nav-item:hover .exp-edit, .nav-item:hover .exp-delete { display: inline; }
        .exp-edit:hover { color: #58a6ff; }
        .exp-delete:hover { color: #f85149; }

        .exp-load-more { background: none; border: none; width: 100%; text-align: left; cursor: pointer; }
        .exp-load-more span { color: #484f58; }
        .exp-load-more:hover span { color: #8b949e; }

        .badge-dev { background: rgba(167,139,250,0.15); color: #a78bfa; border: 1px solid rgba(167,139,250,0.25); }

        /* ═══ Modal ═══ */
        .exp-overlay { position: fixed; inset: 0; background: rgba(0,0,0,0.6); z-index: 9998; backdrop-filter: blur(2px); }
        .exp-box { position: fixed; top: 50%; left: 50%; transform: translate(-50%,-50%); z-index: 9999; background: #161b22; border: 1px solid #30363d; border-radius: 16px; padding: 28px; width: 400px; box-shadow: 0 20px 60px rgba(0,0,0,0.5); }
        .exp-box h3 { font-size: 1.05em; font-weight: 700; color: #e6edf3; margin-bottom: 20px; }
        .exp-box label { display: block; font-size: 0.75em; font-weight: 600; color: #8b949e; margin: 14px 0 6px; letter-spacing: 0.5px; }
        .exp-req { color: #f85149; }
        .exp-box input { width: 100%; padding: 10px 14px; background: #0d1117; border: 1px solid #21262d; border-radius: 10px; color: #e6edf3; font-size: 0.88em; outline: none; transition: border-color 0.2s; }
        .exp-box input:focus { border-color: #667eea; box-shadow: 0 0 0 3px rgba(102,126,234,0.1); }
        .exp-box input::placeholder { color: #484f58; }

        /* Icon picker */
        .exp-icon-grid { display: flex; flex-wrap: wrap; gap: 6px; }
        .exp-icon-btn { width: 38px; height: 38px; border: 1px solid #21262d; border-radius: 8px; background: #0d1117; font-size: 1.15em; cursor: pointer; transition: all 0.15s; display: flex; align-items: center; justify-content: center; }
        .exp-icon-btn:hover { border-color: #30363d; background: #161b22; transform: scale(1.1); }
        .exp-icon-btn.selected { border-color: #667eea; background: rgba(102,126,234,0.12); box-shadow: 0 0 0 2px rgba(102,126,234,0.2); }

        /* Badge toggle chips */
        .exp-badge-row { display: flex; gap: 8px; }
        .exp-badge-btn { padding: 6px 16px; border: 1px solid #21262d; border-radius: 20px; background: #0d1117; color: #8b949e; font-size: 0.78em; font-weight: 600; cursor: pointer; transition: all 0.15s; letter-spacing: 0.5px; }
        .exp-badge-btn:hover { border-color: #30363d; color: #c9d1d9; }
        .exp-badge-btn.selected { border-color: #667eea; background: rgba(102,126,234,0.12); color: #a78bfa; }

        /* Hint */
        .exp-status-hint { margin-top: 10px; padding: 8px 12px; background: rgba(22,27,34,0.8); border-radius: 8px; font-size: 0.78em; color: #8b949e; line-height: 1.5; min-height: 32px; }
        .exp-status-hint b { color: #e6edf3; }

        /* Actions */
        .exp-actions { display: flex; gap: 10px; justify-content: flex-end; margin-top: 22px; padding-top: 16px; border-top: 1px solid #21262d; }
        .exp-btn-cancel { background: none; border: 1px solid #30363d; color: #8b949e; padding: 8px 18px; border-radius: 10px; cursor: pointer; font-size: 0.82em; font-weight: 500; transition: all 0.15s; }
        .exp-btn-cancel:hover { color: #e6edf3; border-color: #484f58; }
        .exp-btn-save { background: linear-gradient(135deg, #667eea, #764ba2); border: none; color: #fff; padding: 8px 24px; border-radius: 10px; cursor: pointer; font-size: 0.82em; font-weight: 600; transition: all 0.15s; }
        .exp-btn-save:hover { opacity: 0.9; transform: translateY(-1px); box-shadow: 0 4px 12px rgba(102,126,234,0.3); }
    `;
    document.head.appendChild(style);

    // ─── Init ───
    function init() {
        const labels = document.querySelectorAll('.nav-group-label');
        let group = null;
        labels.forEach(lbl => {
            if (lbl.textContent.trim() === 'Thử nghiệm') {
                group = lbl.parentElement;
            }
        });
        if (!group) return;

        group.id = 'nav-group-experiments';

        // Replace label → label + add btn
        const lbl = group.querySelector('.nav-group-label');
        const wrapper = document.createElement('div');
        wrapper.className = 'nav-group-label exp-label-row';
        wrapper.innerHTML = `<span>Thử nghiệm</span><button class="exp-add-btn" title="Thêm link">＋</button>`;
        wrapper.querySelector('.exp-add-btn').onclick = showAddModal;
        lbl.replaceWith(wrapper);

        // Remove static items
        group.querySelectorAll('.nav-item').forEach(item => item.remove());

        load();
    }

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