// publish.js — 发行管理页面逻辑
(function() {
const form = document.getElementById('publish-form');
const accSelect = document.getElementById('account-select');
const worksArea = document.getElementById('works-area');
const submitBtn = document.getElementById('submit-btn');
const reloadBtn = document.getElementById('reload-btn');
const WORKS_URL = form.dataset.worksUrl;

const LS_KEY = 'publish_last_account_id';
const CACHE_TTL = 5 * 60 * 1000; // 5 minutes
const PAGE_SIZE = 10;

let currentWorks = [];
let currentPage = 1;
let currentWorkType = 1;

function escapeHtml(s) {
    return String(s ?? '').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
}

function cacheKey(accId, workType) {
    return 'publish_works_' + accId + '_' + workType;
}

function getCache(accId, workType) {
    try {
        const raw = sessionStorage.getItem(cacheKey(accId, workType));
        if (!raw) return null;
        const obj = JSON.parse(raw);
        if (Date.now() - obj.timestamp > CACHE_TTL) return null;
        return obj.data;
    } catch { return null; }
}

function setCache(accId, workType, data) {
    try {
        sessionStorage.setItem(cacheKey(accId, workType), JSON.stringify({
            timestamp: Date.now(),
            data: data,
        }));
    } catch {}
}

function renderToolbar(count) {
    return `
    <div style="margin-bottom:10px; padding:8px 14px; background:#f0f7ff; border-radius:6px; border:1px solid #d0e3ff; font-size:14px;">
        <strong style="color:#1890ff;">${count}</strong> 首待发行
    </div>
    <div class="toolbar">
        <div class="group">
            <input type="checkbox" id="select-all">
            <label for="select-all">全选</label>
        </div>
        <div class="group"><label>已选 <strong id="selected-count">0</strong> / ${count} 首</label></div>
        <div class="group" style="margin-left: auto;">
            <label>批量默认:</label>
            <select id="bulk-auth-type">
                <option value="exclusive">独家授权</option>
                <option value="exclusive_agent">独家代理授权</option>
            </select>
            <select id="bulk-auth-region" disabled>
                <option value="1">全球</option>
                <option value="2">中国（含港澳台）</option>
                <option value="3">仅中国大陆</option>
            </select>
            <button type="button" id="apply-bulk" class="btn btn-sm">应用到选中</button>
        </div>
    </div>`;
}

function renderRow(w, idx) {
    const cover = w.cover ? `<img class="cover" src="${escapeHtml(w.cover)}" alt="">` : `<div class="cover"></div>`;
    return `
    <tr data-idx="${idx}">
        <td><input type="checkbox" class="row-check"></td>
        <td>${cover}</td>
        <td>${escapeHtml(w.title || '(无标题)')}</td>
        <td>
            <select class="row-auth-type" disabled>
                <option value="exclusive">独家授权</option>
                <option value="exclusive_agent">独家代理授权</option>
            </select>
        </td>
        <td>
            <select class="row-auth-region" disabled>
                <option value="1">全球</option>
                <option value="2">中国（含港澳台）</option>
                <option value="3">仅中国大陆</option>
            </select>
        </td>
        <td style="display:none;">
            <input type="hidden" class="h-issue" value="${escapeHtml(w.issue_id)}" disabled>
            <input type="hidden" class="h-task"  value="${escapeHtml(w.task_id)}"  disabled>
            <input type="hidden" class="h-work"  value="${escapeHtml(w.work_id)}"  disabled>
            <input type="hidden" class="h-title" value="${escapeHtml(w.title)}"   disabled>
        </td>
    </tr>`;
}

function renderWorks(works) {
    currentWorks = works;
    currentPage = 1;
    if (!works.length) {
        worksArea.innerHTML = '<p style="color:#999;">无可发行作品。</p>';
        updateSubmit();
        return;
    }
    worksArea.innerHTML = `
        ${renderToolbar(works.length)}
        <table class="works-table">
            <thead>
                <tr>
                    <th style="width:36px;"></th>
                    <th style="width:50px;">封面</th>
                    <th>标题</th>
                    <th style="width:140px;">授权类型</th>
                    <th style="width:160px;">发行范围</th>
                </tr>
            </thead>
            <tbody>${works.map((w, i) => renderRow(w, i)).join('')}</tbody>
        </table>
        <div id="pagination-area"></div>
    `;
    applyPagination();
    bindEvents();
    updateSubmit();
}

function totalPages() {
    return Math.max(1, Math.ceil(currentWorks.length / PAGE_SIZE));
}

function applyPagination() {
    const tp = totalPages();
    if (currentPage > tp) currentPage = tp;
    const start = (currentPage - 1) * PAGE_SIZE;
    const end = start + PAGE_SIZE;
    // Toggle row visibility — keep all rows in DOM so selection state persists.
    document.querySelectorAll('.works-table tbody tr').forEach((tr, i) => {
        tr.style.display = (i >= start && i < end) ? '' : 'none';
    });
    renderPagination();
}

function renderPagination() {
    const tp = totalPages();
    const area = document.getElementById('pagination-area');
    if (!area) return;
    if (tp <= 1) { area.innerHTML = ''; return; }
    const start = (currentPage - 1) * PAGE_SIZE + 1;
    const end = Math.min(currentPage * PAGE_SIZE, currentWorks.length);
    let pageBtns = '';
    for (let p = 1; p <= tp; p++) {
        if (p === currentPage) {
            pageBtns += `<span class="pg-current" style="padding:4px 10px; background:#1890ff; color:#fff; border-radius:4px; font-weight:600;">${p}</span>`;
        } else if (p <= 2 || p >= tp - 1 || (p >= currentPage - 2 && p <= currentPage + 2)) {
            pageBtns += `<button type="button" class="btn btn-sm pg-btn" data-page="${p}">${p}</button>`;
        } else if (p === 3 || p === tp - 2) {
            pageBtns += '<span style="color:#999;">...</span>';
        }
    }
    area.innerHTML = `
        <div style="display:flex; justify-content:space-between; align-items:center; margin-top:12px; padding:8px 0;">
            <span style="color:#666; font-size:13px;">显示 ${start}-${end} / 共 ${currentWorks.length} 首</span>
            <div style="display:flex; gap:6px; align-items:center;">
                <button type="button" class="btn btn-sm pg-prev" ${currentPage === 1 ? 'disabled' : ''}>上一页</button>
                ${pageBtns}
                <button type="button" class="btn btn-sm pg-next" ${currentPage === tp ? 'disabled' : ''}>下一页</button>
            </div>
        </div>
    `;
    area.querySelectorAll('.pg-btn').forEach(b => {
        b.addEventListener('click', () => { currentPage = parseInt(b.dataset.page, 10); applyPagination(); });
    });
    const prev = area.querySelector('.pg-prev');
    const next = area.querySelector('.pg-next');
    if (prev) prev.addEventListener('click', () => { if (currentPage > 1) { currentPage--; applyPagination(); } });
    if (next) next.addEventListener('click', () => { if (currentPage < tp) { currentPage++; applyPagination(); } });
}

function bindEvents() {
    const selectAll = document.getElementById('select-all');
    const applyBulk = document.getElementById('apply-bulk');
    const bulkType = document.getElementById('bulk-auth-type');
    const bulkRegion = document.getElementById('bulk-auth-region');

    bulkType.addEventListener('change', () => {
        bulkRegion.disabled = bulkType.value !== 'exclusive_agent';
    });

    selectAll.addEventListener('change', e => {
        document.querySelectorAll('.row-check').forEach(cb => {
            cb.checked = e.target.checked;
            updateRowState(cb.closest('tr'));
        });
        updateSubmit();
    });

    document.querySelectorAll('.row-check').forEach(cb => {
        cb.addEventListener('change', () => {
            updateRowState(cb.closest('tr'));
            updateSelectAllState();
            updateSubmit();
        });
    });

    document.querySelectorAll('.row-auth-type').forEach(sel => {
        sel.addEventListener('change', () => {
            const region = sel.closest('tr').querySelector('.row-auth-region');
            region.classList.toggle('muted', sel.value !== 'exclusive_agent');
        });
    });

    applyBulk.addEventListener('click', () => {
        const t = bulkType.value;
        const r = bulkRegion.value;
        document.querySelectorAll('.row-check:checked').forEach(cb => {
            const tr = cb.closest('tr');
            const sType = tr.querySelector('.row-auth-type');
            const sReg  = tr.querySelector('.row-auth-region');
            sType.value = t;
            sReg.value = r;
            sReg.classList.toggle('muted', t !== 'exclusive_agent');
        });
    });
}

function updateRowState(tr) {
    const checked = tr.querySelector('.row-check').checked;
    tr.classList.toggle('selected', checked);
    const sType = tr.querySelector('.row-auth-type');
    const sReg  = tr.querySelector('.row-auth-region');
    sType.disabled = !checked;
    sReg.disabled = !checked;
    sReg.classList.toggle('muted', checked && sType.value !== 'exclusive_agent');
    tr.querySelectorAll('.h-issue,.h-task,.h-work,.h-title').forEach(h => h.disabled = !checked);

    if (!sType.name) {
        sType.name = 'auth_type[]';
        sReg.name = 'auth_region[]';
        tr.querySelector('.h-issue').name = 'issue_id[]';
        tr.querySelector('.h-task').name = 'task_id[]';
        tr.querySelector('.h-work').name = 'work_id[]';
        tr.querySelector('.h-title').name = 'title[]';
    }
}

function updateSelectAllState() {
    const all = document.querySelectorAll('.row-check');
    const checked = document.querySelectorAll('.row-check:checked');
    const sa = document.getElementById('select-all');
    if (!sa) return;
    sa.checked = (checked.length === all.length && all.length > 0);
    sa.indeterminate = (checked.length > 0 && checked.length < all.length);
}

function updateSubmit() {
    const n = document.querySelectorAll('.row-check:checked').length;
    const cnt = document.getElementById('selected-count');
    if (cnt) cnt.textContent = n;
    submitBtn.disabled = (n === 0);
    submitBtn.textContent = `提交发行 (${n} 首)`;
}

async function loadWorks(accId, silent, forceRefresh) {
    if (!silent) {
        worksArea.innerHTML = '<p style="color:#999;">加载中...</p>';
        submitBtn.disabled = true;
        submitBtn.textContent = '提交发行 (0 首)';
    }
    try {
        let url = WORKS_URL + '?account_id=' + accId + '&work_type=' + currentWorkType;
        if (forceRefresh) url += '&refresh=1';
        const r = await fetch(url);
        const d = await r.json();
        if (!d.ok) {
            if (!silent) worksArea.innerHTML = '<p style="color:#f5222d;">加载失败</p>';
            return;
        }
        if (d.fetch_status === 'pending') {
            if (!silent) worksArea.innerHTML = '<p style="color:#999;">正在从抖音获取作品列表，请稍候...</p>';
            // Don't re-pass forceRefresh on polls — only first request invalidates cache
            setTimeout(() => loadWorks(accId, silent, false), 2000);
            return;
        }
        setCache(accId, currentWorkType, d.works || []);
        renderWorks(d.works || []);
    } catch (e) {
        if (!silent) worksArea.innerHTML = '<p style="color:#f5222d;">加载异常: ' + escapeHtml(e) + '</p>';
    }
}

function loadWorksWithCache(accId) {
    const cached = getCache(accId, currentWorkType);
    if (cached) {
        renderWorks(cached);
        // Background refresh
        loadWorks(accId, true);
    } else {
        loadWorks(accId, false);
    }
}

accSelect.addEventListener('change', function() {
    const tabContainer = document.getElementById('works-tabs-container');
    if (this.value) {
        if (tabContainer) tabContainer.style.display = 'block';
        localStorage.setItem(LS_KEY, this.value);
        loadWorksWithCache(this.value);
    } else {
        if (tabContainer) tabContainer.style.display = 'none';
        worksArea.innerHTML = '<p style="color:#999;">选择账号后自动加载...</p>';
        submitBtn.disabled = true;
        submitBtn.textContent = '提交发行 (0 首)';
    }
});
reloadBtn.addEventListener('click', () => {
    if (accSelect.value) {
        // Force fresh load: clear both client cache AND signal server cache invalidation
        sessionStorage.removeItem(cacheKey(accSelect.value, currentWorkType));
        loadWorks(accSelect.value, false, true);
    }
});

// Bind sub-tabs event listeners
document.querySelectorAll('.works-tab').forEach(btn => {
    btn.addEventListener('click', () => {
        const type = parseInt(btn.dataset.type, 10);
        if (type === currentWorkType) return;
        
        // Switch active tab styling
        document.querySelectorAll('.works-tab').forEach(b => {
            b.classList.remove('active');
        });
        btn.classList.add('active');
        
        currentWorkType = type;
        
        // Reset selection
        submitBtn.disabled = true;
        submitBtn.textContent = '提交发行 (0 首)';
        
        if (accSelect.value) {
            loadWorksWithCache(accSelect.value);
        }
    });
});

// Restore last selected account, fallback to first logged-in
(function() {
    const saved = localStorage.getItem(LS_KEY);
    const tabContainer = document.getElementById('works-tabs-container');
    if (saved) {
        // Check if saved account is still in options
        for (let i = 1; i < accSelect.options.length; i++) {
            if (accSelect.options[i].value === saved) {
                accSelect.value = saved;
                if (tabContainer) tabContainer.style.display = 'block';
                loadWorksWithCache(saved);
                return;
            }
        }
    }
    // Fallback: first logged-in account
    for (let i = 1; i < accSelect.options.length; i++) {
        if (accSelect.options[i].dataset.logged === '1') {
            accSelect.value = accSelect.options[i].value;
            localStorage.setItem(LS_KEY, accSelect.options[i].value);
            if (tabContainer) tabContainer.style.display = 'block';
            loadWorksWithCache(accSelect.options[i].value);
            break;
        }
    }
})();
})();
