const itemMainContentContainer = document.getElementById('item-main-content');
let currentItem = null;

function getAuthHeaders(extra = {}) {
    const token = localStorage.getItem("token");
    return token
        ? { ...extra, Authorization: `Bearer ${token}` }
        : extra;
}

function getProxiedItemUrl(url, headers = null) {
    if (!url || !headers) {
        return url;
    }

    let proxyUrl = `/api/proxy?url=${encodeURIComponent(url)}`;

    const lowerCaseHeaders = {};
    for (const key in headers) {
        if (Object.prototype.hasOwnProperty.call(headers, key)) {
            lowerCaseHeaders[key.toLowerCase()] = headers[key];
        }
    }

    const referer = lowerCaseHeaders.referer;
    if (referer) {
        proxyUrl += `&referer=${encodeURIComponent(referer)}`;
    }

    const origin = lowerCaseHeaders.origin;
    if (origin) {
        proxyUrl += `&origin=${encodeURIComponent(origin)}`;
    }

    const userAgent = lowerCaseHeaders['user-agent'];
    if (userAgent) {
        proxyUrl += `&userAgent=${encodeURIComponent(userAgent)}`;
    }

    return proxyUrl;
}

function getUrlParams() {
    const path = window.location.pathname.split('/').filter(s => s);
    if (path.length < 3 || path[0] !== 'gallery') return null;

    if (path[1] === 'favorites' && path[2]) {
        return { fromFavorites: true, id: path[2] };
    } else {
        return { provider: path[1], id: path.slice(2).join('/') };
    }
}

async function toggleFavorite() {
    if (!currentItem?.id) return;

    const btn = document.getElementById('fav-btn');
    const wasFavorited = btn.classList.contains('favorited');

    try {
        if (wasFavorited) {
            await fetch(`/api/gallery/favorites/${encodeURIComponent(currentItem.id)}`, {
                method: 'DELETE',
                headers: getAuthHeaders()
            });
        } else {
            const serializedHeaders = currentItem.headers ? JSON.stringify(currentItem.headers) : "";
            const tagsString = Array.isArray(currentItem.tags) ? currentItem.tags.join(',') : (currentItem.tags || '');

            await fetch('/api/gallery/favorites', {
                method: 'POST',
                headers: getAuthHeaders({
                    'Content-Type': 'application/json'
                }),
                body: JSON.stringify({
                    id: currentItem.id,
                    title: currentItem.title || 'Waifu',
                    image_url: currentItem.originalImage,
                    thumbnail_url: currentItem.originalImage,
                    tags: tagsString,
                    provider: currentItem.provider || "",
                    headers: serializedHeaders
                })
            });

        }

        btn.classList.toggle('favorited', !wasFavorited);
        btn.innerHTML = !wasFavorited
            ? `<i class="fas fa-heart"></i> Saved!`
            : `<i class="far fa-heart"></i> Save Image`;

    } catch (err) {
        console.error('Error toggling favorite:', err);
        alert('Error updating favorites');
    }
}

function copyLink() {
    navigator.clipboard.writeText(window.location.href);
    const btn = document.getElementById('copy-link-btn');
    const old = btn.innerHTML;
    btn.innerHTML = `<i class="fas fa-check"></i> Copied!`;
    setTimeout(() => btn.innerHTML = old, 2000);
}

async function loadSimilarImages(item) {
    if (!item.tags || item.tags.length === 0) {
        document.getElementById('similar-section').innerHTML = '<p style="text-align:center;color:var(--color-text-secondary);padding:3rem 0;">No tags available to search for similar images.</p>';
        return;
    }

    const firstTag = item.tags[0];
    const container = document.getElementById('similar-section');

    try {
        const res = await fetch(`/api/gallery/search?q=${encodeURIComponent(firstTag)}&perPage=20`);
        if (!res.ok) throw new Error();

        const data = await res.json();
        const results = (data.results || [])
            .filter(r => r.id !== item.id)
            .slice(0, 15);

        if (results.length === 0) {
            container.innerHTML = '<p style="text-align:center;color:var(--color-text-secondary);padding:3rem 0;">No similar images found.</p>';
            return;
        }

        container.innerHTML = `
            <h3 style="text-align:center;margin:2rem 0 1.5rem;font-size:1.7rem;">
                More images tagged with "<span style="color:var(--color-primary);">${firstTag}</span>"
            </h3>
            <div class="similar-grid">
                ${results.map(img => {
            const imageUrl = img.image || img.image_url || img.thumbnail_url;
            const proxiedUrl = getProxiedItemUrl(imageUrl, img.headers);

            return `
                        <a href="/gallery/${img.provider || 'unknown'}/${encodeURIComponent(img.id)}" class="similar-card">
                            <img src="${proxiedUrl}" alt="Similar" loading="lazy">
                            <div class="similar-overlay">${img.provider || 'Global'}</div>
                        </a>
                    `;
        }).join('')}
            </div>
        `;

    } catch (err) {
        container.innerHTML = '<p style="text-align:center;color:var(--color-text-secondary);opacity:0.6;padding:3rem 0;">Could not load similar images.</p>';
    }
}

function renderItem(item) {
    const proxiedFullImage = getProxiedItemUrl(item.fullImage, item.headers);

    let sourceText;
    if (item.fromFavorites) {
        sourceText = item.headers && item.provider && item.provider !== 'Favorites'
            ? `Source: ${item.provider}`
            : 'Favorites';
    } else {
        sourceText = `Source: ${item.provider}`;
    }

    const originalProviderText = (item.fromFavorites && item.provider && item.provider !== 'Favorites')
        ? ` (Original: ${item.provider})`
        : '';

    itemMainContentContainer.innerHTML = `
        <div class="item-content-flex-wrapper">
            <div class="image-col">
                <img class="item-image loaded" src="${proxiedFullImage}" alt="${item.title}">
            </div>

            <div class="info-col">
                <div class="info-header">
                    <span class="provider-name">
                        ${sourceText}${originalProviderText} 
                    </span>
                    <h1>${item.title}</h1>
                </div>

                <div class="actions-row">
                    <button id="fav-btn" class="action-btn fav-action">
                        <i class="far fa-heart"></i> Save Image
                    </button>

                    <button id="copy-link-btn" class="action-btn copy-link-btn">
                        <i class="fas fa-link"></i> Copy Link
                    </button>
                </div>

                <div class="tags-section">
                    <h3>Tags</h3>
                    <div class="tag-list">
                        ${item.tags.length > 0
        ? item.tags.map(tag => `
                                <a class="tag-item">${tag}</a>
                            `).join('')
        : '<span style="opacity:0.6;color:var(--color-text-secondary);">No tags</span>'
    }
                    </div>
                </div>
            </div>
        </div>
    `;

    document.getElementById('fav-btn').addEventListener('click', toggleFavorite);
    document.getElementById('copy-link-btn').addEventListener('click', copyLink);

    loadSimilarImages(item);
}

function renderError(msg) {
    itemMainContentContainer.innerHTML = `
        <div style="text-align:center;padding:8rem 1rem;">
            <i class="fa-solid fa-heart-crack" style="font-size:5rem;color:#ff6b6b;opacity:0.7;"></i>
            <h2 style="margin:2rem 0;color:var(--color-text-primary);">Image Not Available</h2>
            <p style="color:var(--color-text-secondary);max-width:600px;margin:0 auto 2rem;">${msg}</p>
            <a href="/gallery" style="padding:1rem 2.5rem;background:var(--color-primary);color:white;border-radius:99px;text-decoration:none;font-weight:600;">
                Back to Gallery
            </a>
        </div>
    `;

    document.getElementById('similar-section').style.display = 'none';
}

async function loadFromFavorites(id) {
    try {
        const res = await fetch(`/api/gallery/favorites/${encodeURIComponent(id)}`, {
            headers: getAuthHeaders()
        });
        if (!res.ok) throw new Error('Not found');

        const { favorite: fav } = await res.json();

        const item = {
            id: fav.id,
            title: fav.title || 'No title',
            fullImage: fav.image_url,
            originalImage: fav.image_url,
            tags: typeof fav.tags === 'string' ? fav.tags.split(',').map(t => t.trim()).filter(Boolean) : (fav.tags || []),
            provider: 'Favorites',
            fromFavorites: true,
            headers: fav.headers
        };

        currentItem = item;
        renderItem(item);
        document.getElementById('page-title').textContent = `WaifuBoard - ${item.title}`;

        document.getElementById('fav-btn')?.classList.add('favorited');
        const btn = document.getElementById('fav-btn');
        if (btn) {
            btn.innerHTML = `<i class="fa-solid fa-heart"></i> Saved!`;
        }

    } catch (err) {
        renderError('This image is no longer in your favorites.');
    }
}

async function loadFromProvider(provider, id) {
    try {
        const res = await fetch(`/api/gallery/fetch/${id}?provider=${provider}`);
        if (!res.ok) throw new Error();

        const data = await res.json();

        if (!data.image) throw new Error();

        const item = {
            id,
            title: data.title || 'Beautiful Art',
            fullImage: data.image,
            originalImage: data.image,
            tags: data.tags || [],
            provider,
            headers: data.headers
        };

        currentItem = item;
        renderItem(item);
        document.getElementById('page-title').textContent = `WaifuBoard - ${item.title}`;

        const favRes = await fetch(`/api/gallery/favorites/${encodeURIComponent(id)}`, {
            headers: getAuthHeaders()
        });
        if (favRes.ok) {
            document.getElementById('fav-btn')?.classList.add('favorited');
            const btn = document.getElementById('fav-btn');
            if (btn) {
                btn.innerHTML = `<i class="fa-solid fa-heart"></i> Saved!`;
            }
        }

    } catch (err) {
        renderError('Image not found.');
    }
}

if (itemMainContentContainer) {
    const params = getUrlParams();
    if (!params) {
        renderError('Invalid URL');
    } else if (params.fromFavorites) {
        loadFromFavorites(params.id);
    } else {
        loadFromProvider(params.provider, params.id);
    }
} else {
    document.getElementById('item-content').innerHTML = `<p style="text-align:center;padding:5rem;color:red;">Error: HTML container 'item-main-content' not found. Please update gallery-image.html.</p>`;
    document.getElementById('similar-section').style.display = 'none';
}

window.addEventListener('scroll', () => {
    document.getElementById('navbar')?.classList.toggle('scrolled', window.scrollY > 50);
});