// social.js — Social dashboard and notifications (SocialState)
// Extracted from dashboard.html (lines 6851-7072)

// ── Social Dashboard ──────────────────────────────────
// _scPollInterval — managed by PollManager('social')
// SocialState.accounts / .currentFilter / .posts (namespaced above)

async function loadSocial() {
    try {
        const res = await apiFetch('/api/social/accounts');
        const data = await res.json();
        SocialState.accounts = data;
        const hasBsky = data.bluesky;
        const hasMasto = data.mastodon;
        if (!hasBsky && !hasMasto) {
            document.getElementById('sc-feed-list').innerHTML =
                '<div class="sc-empty-state"><i class="fas fa-share-alt"></i>' +
                '<p>No social platforms configured</p>' +
                '<a onclick="loadPanel(\'connect\')">Connect Bluesky or Mastodon in Connect</a></div>';
            document.getElementById('sc-filter-chips').style.display = 'none';
            _updateComposeCheckboxes(hasBsky, hasMasto);
            return;
        }
        document.getElementById('sc-filter-chips').style.display = '';
        _updateComposeCheckboxes(hasBsky, hasMasto);
        loadSocialFeed('');
        _startScPolling();
    } catch(e) {
        document.getElementById('sc-feed-list').innerHTML =
            '<div class="sc-empty-state">Failed to load social accounts</div>';
    }
}

function _updateComposeCheckboxes(hasBsky, hasMasto) {
    const row = document.getElementById('sc-platform-checks');
    let html = '';
    if (hasBsky) html += '<label><input type="checkbox" id="sc-check-bluesky" checked> Bluesky</label>';
    if (hasMasto) html += '<label><input type="checkbox" id="sc-check-mastodon" checked> Mastodon</label>';
    if (!html) html = '<span style="color:var(--text-dim);font-size:0.85rem">No platforms configured</span>';
    row.innerHTML = html;
}

async function loadSocialFeed(platform, cursor) {
    SocialState.currentFilter = platform;
    const list = document.getElementById('sc-feed-list');
    if (!cursor) list.innerHTML = '<div class="loading"><div class="spinner"></div></div>';
    try {
        let url = '/api/social/feed?platform=' + encodeURIComponent(platform);
        if (cursor) url += '&cursor=' + encodeURIComponent(cursor);
        const res = await apiFetch(url);
        const data = await res.json();
        const posts = data.posts || [];
        if (!cursor) SocialState.posts = posts; else SocialState.posts = SocialState.posts.concat(posts);
        renderFeedPosts(SocialState.posts);
    } catch(e) {
        if (!cursor) list.innerHTML = '<div class="sc-empty-state">Failed to load feed</div>';
    }
}

function renderFeedPosts(posts) {
    const list = document.getElementById('sc-feed-list');
    if (!posts.length) {
        list.innerHTML = '<div class="sc-empty-state"><i class="fas fa-stream"></i><p>No posts yet</p></div>';
        return;
    }
    let html = '';
    for (const p of posts) {
        const ts = formatDate(p.timestamp);
        const avatarHtml = p.avatar
            ? `<img class="sc-post-avatar" src="${_esc(p.avatar)}" alt="">`
            : '<div class="sc-post-avatar" style="display:flex;align-items:center;justify-content:center;font-size:1rem"><i class="fas fa-user"></i></div>';
        html += `<div class="sc-post-card">
            <div class="sc-post-header">
                ${avatarHtml}
                <div class="sc-post-author-wrap">
                    <div class="sc-post-display-name">${_esc(p.display_name || p.author)}</div>
                    <div class="sc-post-handle">${_esc(p.author)}</div>
                </div>
                <span class="sc-platform-badge ${p.platform}">${p.platform}</span>
            </div>
            <div class="sc-post-text">${_esc(p.text)}</div>
            <div class="sc-post-metrics">
                <span><i class="fas fa-heart"></i> ${p.likes || 0}</span>
                <span><i class="fas fa-retweet"></i> ${p.reposts || 0}</span>
                <span><i class="fas fa-reply"></i> ${p.replies || 0}</span>
                <span class="sc-post-time">${ts}</span>
            </div>
        </div>`;
    }
    list.innerHTML = html;
}

// _scFormatTime removed — use formatDate(str)

function filterSocialFeed(platform) {
    document.querySelectorAll('#sc-filter-chips .sc-chip').forEach(c => {
        c.classList.toggle('active', c.textContent.toLowerCase() === (platform || 'all'));
    });
    loadSocialFeed(platform);
}

function updateSocialCharCount() {
    const ta = document.getElementById('sc-compose-text');
    const counter = document.getElementById('sc-char-count');
    const len = ta.value.length;
    counter.textContent = len + ' / 300';
    counter.className = 'sc-char-count' + (len > 300 ? ' over' : '');
}

async function socialPost() {
    const ta = document.getElementById('sc-compose-text');
    const text = ta.value.trim();
    if (!text) return;

    const platforms = [];
    const bskyCheck = document.getElementById('sc-check-bluesky');
    const mastoCheck = document.getElementById('sc-check-mastodon');
    if (bskyCheck && bskyCheck.checked) platforms.push('bluesky');
    if (mastoCheck && mastoCheck.checked) platforms.push('mastodon');
    if (!platforms.length) { alert('Select at least one platform'); return; }

    const btn = document.getElementById('sc-post-btn');
    btn.disabled = true;
    btn.textContent = 'Posting...';
    try {
        const res = await apiFetch('/api/social/post', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({text, platforms})
        });
        const data = await res.json();
        if (res.ok) {
            ta.value = '';
            updateSocialCharCount();
            btn.textContent = 'Posted!';
            setTimeout(() => { btn.textContent = 'Post'; btn.disabled = false; }, 2000);
            // Show results
            const results = data.results || {};
            let msg = Object.entries(results).map(([k,v]) => k + ': ' + v).join('\n');
            if (msg) {
                const banner = document.getElementById('sc-error-banner');
                banner.style.display = '';
                banner.style.background = 'var(--success, #4caf50)';
                banner.textContent = msg;
                setTimeout(() => { banner.style.display = 'none'; }, 5000);
            }
        } else {
            btn.textContent = 'Error';
            setTimeout(() => { btn.textContent = 'Post'; btn.disabled = false; }, 2000);
        }
    } catch(e) {
        btn.textContent = 'Post';
        btn.disabled = false;
    }
}

async function loadSocialNotifications() {
    const list = document.getElementById('sc-notif-list');
    list.innerHTML = '<div class="loading"><div class="spinner"></div></div>';
    try {
        const res = await apiFetch('/api/social/notifications');
        const data = await res.json();
        const notifs = data.notifications || [];
        if (!notifs.length) {
            list.innerHTML = '<div class="sc-empty-state"><i class="fas fa-bell"></i><p>No notifications</p></div>';
            return;
        }
        const iconMap = {like:'fa-heart',favourite:'fa-heart',follow:'fa-user-plus',
            mention:'fa-at',reply:'fa-reply',repost:'fa-retweet',reblog:'fa-retweet'};
        let html = '';
        for (const n of notifs) {
            const icon = iconMap[n.type] || 'fa-bell';
            const ts = formatDate(n.timestamp);
            html += `<div class="sc-notif-card">
                <i class="fas ${icon} sc-notif-icon"></i>
                <div class="sc-notif-body">
                    <span class="sc-notif-author">${_esc(n.author)}</span>
                    <span class="sc-notif-type sc-platform-badge ${n.platform}">${n.type}</span>
                    ${n.text ? '<div class="sc-notif-text">' + _esc(n.text) + '</div>' : ''}
                    <div class="sc-notif-time">${ts}</div>
                </div>
            </div>`;
        }
        list.innerHTML = html;
    } catch(e) {
        list.innerHTML = '<div class="sc-empty-state">Failed to load notifications</div>';
    }
}

function switchSocialTab(tab) {
    const tabs = ['feed', 'compose', 'notifications'];
    document.querySelectorAll('#social-content .sc-tab').forEach((t, i) => {
        t.classList.toggle('active', tabs[i] === tab);
    });
    tabs.forEach(t => {
        const el = document.getElementById('sc-' + t + '-tab');
        if (el) el.style.display = (t === tab) ? '' : 'none';
    });
    if (tab === 'feed') loadSocialFeed(SocialState.currentFilter);
    if (tab === 'notifications') loadSocialNotifications();
}

function pollSocialNotifications() {
    apiFetch('/api/social/poll')
        .then(r => r.json())
        .then(data => {
            const badge = document.getElementById('sc-badge');
            const count = data.unread_count || 0;
            if (count > 0) {
                badge.textContent = count > 99 ? '99+' : count;
                badge.style.display = '';
            } else {
                badge.style.display = 'none';
            }
        }).catch(() => {});
}

function _startScPolling() {
    PollManager.start('social', pollSocialNotifications, APP_CONFIG.poll.social);
}

function _stopScPolling() {
    PollManager.stop('social');
}

