// App Updates tab (KL-51). Polls /api/updates/check on mount and every
// 6 hours, drives both the sidebar tab status line and the panel
// content. The download button opens the platform-appropriate URL
// from latest.json in a new browser tab.

const POLL_INTERVAL_MS = 6 * 60 * 60 * 1000;  // 6h
const PLATFORM_LABELS = {
    mac: 'macOS',
    windows: 'Windows',
    other: 'your platform',
};

function formatBytes(n) {
    if (!Number.isFinite(n) || n <= 0) return '';
    const mb = n / (1024 * 1024);
    if (mb >= 100) return `(${Math.round(mb)} MB)`;
    return `(${mb.toFixed(1)} MB)`;
}

function formatChecked(ts) {
    if (!ts) return '';
    try {
        const dt = new Date(ts * 1000);
        const opts = {hour: 'numeric', minute: '2-digit'};
        return `Last checked ${dt.toLocaleTimeString(undefined, opts)}`;
    } catch (_) {
        return '';
    }
}

export function initUpdates() {
    const tabBtn = document.getElementById('tab-btn-updates');
    const tabStatus = document.getElementById('updates-tab-status');
    const card = document.getElementById('updates-card');
    if (!tabBtn || !card) return;

    const currentEl = document.getElementById('updates-current-version');
    const latestUptodate = document.getElementById('updates-latest-uptodate');
    const latestAvailable = document.getElementById('updates-latest-available');
    const releasedEl = document.getElementById('updates-released');
    const downloadBtn = document.getElementById('updates-download-btn');
    const platformLabel = document.getElementById('updates-platform-label');
    const sizeEl = document.getElementById('updates-size');
    const altLink = document.getElementById('updates-alt-link');
    const errorDetail = document.getElementById('updates-error-detail');
    const recheckBtn = document.getElementById('btn-updates-recheck');
    const checkedAt = document.getElementById('updates-checked-at');

    function showState(state) {
        card.dataset.state = state;
        for (const node of card.querySelectorAll('[data-state-for]')) {
            node.hidden = (node.dataset.stateFor !== state);
        }
    }

    function setTabState(state, text) {
        tabBtn.dataset.updateState = state;
        if (tabStatus) tabStatus.textContent = text;
    }

    function render(data) {
        if (currentEl) currentEl.textContent = `v${data.current || '?'}`;
        if (checkedAt) checkedAt.textContent = formatChecked(data.checked_at);

        if (data.error && !data.latest) {
            setTabState('error', 'Update check failed');
            if (errorDetail) errorDetail.textContent = data.error;
            showState('error');
            return;
        }

        if (data.platform === 'other' || !data.download_url) {
            setTabState('uptodate', 'Up to date');
            showState('unsupported');
            return;
        }

        const latest = `v${data.latest || '?'}`;

        if (data.update_available) {
            setTabState('available', `${latest} available`);
            if (latestAvailable) latestAvailable.textContent = latest;
            if (releasedEl) {
                releasedEl.textContent = data.released
                    ? `· released ${data.released}`
                    : '';
            }
            if (downloadBtn) {
                downloadBtn.href = data.download_url;
                downloadBtn.setAttribute(
                    'download',
                    data.download_url.split('/').pop() || ''
                );
            }
            if (platformLabel) {
                platformLabel.textContent = PLATFORM_LABELS[data.platform] || 'your platform';
            }
            if (sizeEl) sizeEl.textContent = formatBytes(data.size_bytes);

            if (altLink && data.alt_url) {
                altLink.href = data.alt_url;
                altLink.hidden = false;
            } else if (altLink) {
                altLink.hidden = true;
            }
            showState('available');
        } else {
            setTabState('uptodate', 'Up to date');
            if (latestUptodate) latestUptodate.textContent = latest;
            showState('uptodate');
        }
    }

    async function fetchStatus(force) {
        try {
            const url = '/api/updates/check' + (force ? '?force=1' : '');
            const resp = await fetch(url);
            const data = await resp.json();
            render(data);
        } catch (e) {
            setTabState('error', 'Update check failed');
            if (errorDetail) {
                errorDetail.textContent = 'Network error reaching the dashboard backend.';
            }
            showState('error');
        }
    }

    if (recheckBtn) {
        recheckBtn.addEventListener('click', async () => {
            recheckBtn.disabled = true;
            const original = recheckBtn.textContent;
            recheckBtn.textContent = 'Checking…';
            await fetchStatus(true);
            recheckBtn.textContent = original;
            recheckBtn.disabled = false;
        });
    }

    fetchStatus(false);
    setInterval(() => fetchStatus(false), POLL_INTERVAL_MS);
}
