<script>
    import { onDestroy } from 'svelte';
    import { browser } from '$app/environment';
    import { ebookReader } from '$lib/stores/ebookReader';

    /** @type {boolean} Whether the ebooks tab is currently active */
    export let isActive = false;

    let ebooks = [];
    let loading = true;
    let error = null;
    let page = 1;
    let hasMore = true;
    let loadingMore = false;
    let refreshInterval = null;

    function timeAgo(dateStr) {
        const date = new Date(dateStr);
        const now = new Date();
        const seconds = Math.floor((now - date) / 1000);

        if (seconds < 60) return 'just now';
        if (seconds < 3600) return Math.floor(seconds / 60) + 'm';
        if (seconds < 86400) return Math.floor(seconds / 3600) + 'h';
        if (seconds < 604800) return Math.floor(seconds / 86400) + 'd';
        return date.toLocaleDateString();
    }

    async function loadEbooks(append = false) {
        if (!browser) return;

        try {
            error = null;
            const res = await fetch(`/api/ebooks?page=${page}&limit=20`);
            if (res.ok) {
                const data = await res.json();
                const fetchedEbooks = data.ebooks || [];
                if (append) {
                    ebooks = [...ebooks, ...fetchedEbooks];
                } else {
                    ebooks = fetchedEbooks;
                }
                hasMore = fetchedEbooks.length >= 20;
            } else {
                error = 'Failed to load ebooks';
            }
        } catch (e) {
            console.error('Failed to load ebooks:', e);
            error = 'Failed to load ebooks';
        } finally {
            loading = false;
            loadingMore = false;
        }
    }

    function loadMore() {
        if (loadingMore || !hasMore) return;
        loadingMore = true;  // Set immediately to prevent race condition
        page++;
        loadEbooks(true);
    }

    function startRefresh() {
        // Clear any existing interval first to prevent stacking
        stopRefresh();
        page = 1;
        loading = true;
        loadEbooks();
        // Refresh every 30 seconds (ebooks don't change as often as streams)
        refreshInterval = setInterval(() => {
            page = 1;
            loadEbooks();
        }, 30000);
    }

    function stopRefresh() {
        if (refreshInterval) {
            clearInterval(refreshInterval);
            refreshInterval = null;
        }
    }

    // Start/stop refresh based on active state
    $: if (browser && isActive) {
        startRefresh();
    } else {
        stopRefresh();
    }

    function openBook(ebook) {
        ebookReader.openBook({
            id: ebook.id,
            title: ebook.title,
            filePath: ebook.filePath,
            coverPath: ebook.coverPath,
            chapterCount: ebook.chapterCount,
            username: ebook.username,
            realmName: ebook.realmName
        });
    }

    function handleScroll(e) {
        const target = e.target;
        const nearBottom = target.scrollHeight - target.scrollTop <= target.clientHeight + 100;
        if (nearBottom && hasMore && !loadingMore) {
            loadMore();
        }
    }

    onDestroy(() => {
        stopRefresh();
    });
</script>

<div class="ebooks-tab">
    <div class="ebooks-header">
        <span class="ebooks-title">eBooks</span>
        <span class="ebook-count">{ebooks.length} loaded</span>
    </div>

    <div class="ebooks-list" on:scroll={handleScroll}>
        {#if loading}
            <div class="ebooks-loading">Loading ebooks...</div>
        {:else if error}
            <div class="ebooks-error">{error}</div>
        {:else if ebooks.length === 0}
            <div class="ebooks-empty">
                <div class="empty-icon">[ ◇ ]</div>
                <span>No ebooks found</span>
                <span class="empty-hint">Browse <a href="/ebooks">/ebooks</a> to upload</span>
            </div>
        {:else}
            {#each ebooks as ebook (ebook.id)}
                <div class="ebook-item">
                    <div class="ebook-cover">
                        {#if ebook.coverPath}
                            <img src={ebook.coverPath} alt={ebook.title} />
                        {:else}
                            <span class="cover-placeholder">◇</span>
                        {/if}
                    </div>
                    <div class="ebook-info">
                        <span class="ebook-title">{ebook.title}</span>
                        <span class="ebook-meta">
                            <span class="ebook-realm">{ebook.realmName}</span>
                            {#if ebook.chapterCount}
                                <span class="ebook-stats">{ebook.chapterCount} chapters</span>
                            {/if}
                        </span>
                        <span class="ebook-sub">
                            <span class="ebook-user">@{ebook.username}</span>
                            <span class="ebook-time">{timeAgo(ebook.createdAt)}</span>
                        </span>
                    </div>
                    <button
                        class="read-btn"
                        on:click={() => openBook(ebook)}
                        title="Open in reader"
                    >Read</button>
                </div>
            {/each}
            {#if loadingMore}
                <div class="loading-more">Loading more...</div>
            {/if}
        {/if}
    </div>
</div>

<style>
    .ebooks-tab {
        flex: 1;
        display: flex;
        flex-direction: column;
        overflow: hidden;
        background: #0d1117;
        font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
    }

    .ebooks-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0.5rem 0.75rem;
        border-bottom: 1px solid #30363d;
    }

    .ebooks-title {
        color: #3b82f6;
        font-size: 0.75rem;
        text-transform: uppercase;
        letter-spacing: 0.05em;
    }

    .ebook-count {
        color: #6e7681;
        font-size: 0.65rem;
    }

    .ebooks-list {
        flex: 1;
        overflow-y: auto;
        padding: 0.5rem;
    }

    .ebooks-list::-webkit-scrollbar {
        width: 6px;
    }

    .ebooks-list::-webkit-scrollbar-track {
        background: #0d1117;
    }

    .ebooks-list::-webkit-scrollbar-thumb {
        background: #30363d;
        border-radius: 3px;
    }

    .ebooks-loading,
    .loading-more {
        color: #8b949e;
        font-size: 0.75rem;
        text-align: center;
        padding: 1.5rem 1rem;
    }

    .ebooks-error {
        color: #f85149;
        font-size: 0.75rem;
        text-align: center;
        padding: 1.5rem 1rem;
    }

    .ebooks-empty {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 2rem 1rem;
        color: #6e7681;
        font-size: 0.75rem;
        gap: 0.25rem;
        flex: 1;
    }

    .empty-icon {
        font-size: 0.85rem;
        color: #3b82f6;
        margin-bottom: 0.25rem;
    }

    .empty-hint {
        font-size: 0.65rem;
        color: #484f58;
    }

    .empty-hint a {
        color: #3b82f6;
        text-decoration: none;
    }

    .empty-hint a:hover {
        text-decoration: underline;
    }

    .ebook-item {
        display: flex;
        align-items: center;
        gap: 0.6rem;
        padding: 0.5rem;
        border-radius: 4px;
        transition: background 0.15s ease;
        border-bottom: 1px solid #161b22;
    }

    .ebook-item:hover {
        background: rgba(59, 130, 246, 0.05);
    }

    .ebook-item:last-child {
        border-bottom: none;
    }

    .ebook-cover {
        width: 36px;
        height: 54px;
        border-radius: 2px;
        overflow: hidden;
        background: #161b22;
        border: 1px solid #30363d;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-shrink: 0;
    }

    .ebook-cover img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }

    .cover-placeholder {
        font-size: 0.9rem;
        color: #3b82f6;
        opacity: 0.5;
    }

    .ebook-info {
        flex: 1;
        min-width: 0;
        display: flex;
        flex-direction: column;
        gap: 0.15rem;
    }

    .ebook-title {
        color: #c9d1d9;
        font-size: 0.75rem;
        font-weight: 500;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }

    .ebook-meta {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        font-size: 0.65rem;
    }

    .ebook-realm {
        color: #3b82f6;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        max-width: 80px;
    }

    .ebook-stats {
        color: #6e7681;
    }

    .ebook-sub {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        font-size: 0.6rem;
        color: #484f58;
    }

    .ebook-user {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        cursor: pointer;
        transition: filter 0.15s ease;
    }

    .ebook-user:hover {
        filter: invert(1);
    }

    .ebook-time {
        white-space: nowrap;
    }

    .read-btn {
        padding: 0.3rem 0.6rem;
        background: rgba(59, 130, 246, 0.15);
        border: 1px solid rgba(59, 130, 246, 0.3);
        border-radius: 4px;
        color: #3b82f6;
        font-size: 0.65rem;
        font-family: inherit;
        cursor: pointer;
        transition: all 0.15s ease;
        flex-shrink: 0;
        text-transform: uppercase;
        letter-spacing: 0.05em;
    }

    .read-btn:hover {
        background: rgba(59, 130, 246, 0.25);
        border-color: #3b82f6;
    }

    .read-btn:active {
        background: rgba(59, 130, 246, 0.35);
    }
</style>
