const API = '/api/dashboard/experiment-links';
        const params = new URLSearchParams(window.location.search);
        const linkId = params.get('id');
        let currentData = null;

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

        async function load() {
            if (!linkId) { document.getElementById('hName').textContent = 'Không tìm thấy'; return; }
            const res = await fetch(`${API}/${linkId}`);
            if (!res.ok) { document.getElementById('hName').textContent = 'Không tìm thấy'; return; }
            currentData = await res.json();
            render();
        }

        function render() {
            const d = currentData;
            document.title = `${d.name} — Canifa AI`;

            // Header
            document.getElementById('hIcon').textContent = d.icon || '';
            document.getElementById('hName').textContent = d.name;
            document.getElementById('hLink').href = d.url;
            document.getElementById('hLink').textContent = d.url;
            document.getElementById('openLink').href = d.url;

            const badge = document.getElementById('hBadge');
            if (d.badge) {
                badge.textContent = d.badge;
                badge.className = 'status-chip ' + badgeCls(d.badge_type);
                badge.style.display = '';
            } else {
                badge.style.display = 'none';
            }

            // Description
            const descEl = document.getElementById('descText');
            if (d.description) {
                descEl.textContent = d.description;
                descEl.classList.remove('empty-hint');
            } else {
                descEl.textContent = 'Chưa có mô tả. Bấm "Sửa" để thêm.';
                descEl.classList.add('empty-hint');
            }
            document.getElementById('descInput').value = d.description || '';

            // Versions
            const versions = d.versions || [];
            document.getElementById('vCount').textContent = `${versions.length} phiên bản`;
            renderVersions(versions);
        }

        function renderVersions(versions) {
            const el = document.getElementById('versionList');
            if (!versions.length) {
                el.innerHTML = '<div class="v-empty">Chưa có phiên bản nào.<br>Thêm phiên bản đầu tiên bên dưới!</div>';
                return;
            }
            el.innerHTML = versions.map((v, i) => `
                <div class="v-entry">
                    <div class="v-timeline"><div class="v-dot"></div><div class="v-line"></div></div>
                    <div class="v-content">
                        <div class="v-top">
                            <span class="v-version">${v.version}</span>
                            <span class="v-date">${v.date}</span>
                            <span class="v-author">@${v.author}</span>
                        </div>
                        <div class="v-note">${v.note}</div>
                    </div>
                    <button class="v-delete" onclick="deleteVersion(${i})" title="Xóa">Xóa</button>
                </div>
            `).join('');
        }

        // ─── Description ───
        function toggleDescEdit() {
            const view = document.getElementById('descView');
            const editor = document.getElementById('descEditor');
            const btn = document.getElementById('descEditBtn');
            if (editor.style.display === 'none') {
                editor.style.display = 'block';
                view.style.display = 'none';
                btn.style.display = 'none';
                document.getElementById('descInput').focus();
            } else {
                editor.style.display = 'none';
                view.style.display = 'block';
                btn.style.display = '';
            }
        }

        async function saveDesc() {
            const desc = document.getElementById('descInput').value.trim();
            await fetch(`${API}/${linkId}`, {
                method: 'PUT',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({ description: desc })
            });
            toggleDescEdit();
            await load();
        }

        // ─── Header Edit (Name/URL/Icon) ───
        function toggleHeaderEdit() {
            const form = document.getElementById('headerEditForm');
            const btn = document.getElementById('headerEditBtn');
            if (form.classList.contains('show')) {
                form.classList.remove('show');
                btn.style.display = '';
            } else {
                document.getElementById('editName').value = currentData.name || '';
                document.getElementById('editUrl').value = currentData.url || '';
                document.getElementById('editIcon').value = currentData.icon || '';
                form.classList.add('show');
                btn.style.display = 'none';
                document.getElementById('editName').focus();
            }
        }

        async function saveHeaderEdit() {
            const name = document.getElementById('editName').value.trim();
            const url = document.getElementById('editUrl').value.trim();
            const icon = document.getElementById('editIcon').value.trim();
            if (!name) return alert('Tên không được để trống!');
            await fetch(`${API}/${linkId}`, {
                method: 'PUT',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({ name, url, icon })
            });
            toggleHeaderEdit();
            await load();
        }

        // ─── Versions ───
        async function addVersion() {
            const version = document.getElementById('vVersion').value.trim();
            const author = document.getElementById('vAuthor').value.trim();
            const note = document.getElementById('vNote').value.trim();
            if (!version || !author || !note) return alert('Cần nhập đủ: version, tên, mô tả!');

            await fetch(`${API}/${linkId}/versions`, {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({ version, author, note })
            });
            document.getElementById('vVersion').value = '';
            document.getElementById('vNote').value = '';
            await load();
        }

        async function deleteVersion(idx) {
            if (!confirm('Xóa phiên bản này?')) return;
            await fetch(`${API}/${linkId}/versions/${idx}`, { method: 'DELETE' });
            await load();
        }

        load();