const ContinueWatchingManager = {
    API_BASE: '/api',

    async load(containerId, status = 'watching', entryType = 'ANIME') {
        if (!AuthUtils.isAuthenticated()) return;

        const container = document.getElementById(containerId);
        if (!container) return;

        try {
            const res = await fetch(`${this.API_BASE}/list/filter?status=${status}&entry_type=${entryType}`, {
                headers: AuthUtils.getAuthHeaders()
            });

            if (!res.ok) return;

            const data = await res.json();
            const list = data.results || [];

            this.render(containerId, list, entryType);
        } catch (err) {
            console.error(`Continue ${entryType === 'ANIME' ? 'Watching' : 'Reading'} Error:`, err);
        }
    },

    render(containerId, list, entryType = 'ANIME') {
        const container = document.getElementById(containerId);
        if (!container) return;

        container.innerHTML = '';

        if (list.length === 0) {
            const label = entryType === 'ANIME' ? 'watching anime' : 'reading manga';
            container.innerHTML = `<div style="padding:1rem; color:#888">No ${label}</div>`;
            return;
        }

        list.sort((a, b) => new Date(b.updated_at) - new Date(a.updated_at));

        list.forEach(item => {
            const card = this.createCard(item, entryType);
            container.appendChild(card);
        });
    },

    createCard(item, entryType) {
        const el = document.createElement('div');
        el.className = 'card';

        const nextProgress = (item.progress || 0) + 1;
        let url;

        if (entryType === 'ANIME') {
            url = item.source === 'anilist'
                ? `/anime/${item.entry_id}?episode=${nextProgress}`
                : `/anime/${item.entry_id}/${item.source}/?episode=${nextProgress}`;
        } else {
            url = item.source === 'anilist'
                ? `/book/${item.entry_id}?chapter=${nextProgress}`
                : `/read/${item.source}/${nextProgress}/${item.entry_id}?source=${item.source}`;
        }

        el.onclick = () => window.location.href = url;

        const progressText = item.total_episodes || item.total_chapters
            ? `${item.progress || 0}/${item.total_episodes || item.total_chapters}`
            : `${item.progress || 0}`;

        const unitLabel = entryType === 'ANIME' ? 'Ep' : 'Ch';

        el.innerHTML = `
            <div class="card-img-wrap">
                <img src="${item.poster}" loading="lazy" alt="${item.title}">
            </div>
            <div class="card-content">
                <h3>${item.title}</h3>
                <p>${unitLabel} ${progressText} - ${item.source}</p>
            </div>
        `;

        return el;
    }
};

window.ContinueWatchingManager = ContinueWatchingManager;