chrome.runtime.onInstalled.addListener(() => {
    console.log('Tripstips Toolbox installed');
});

const BASE_URL = 'https://tripstips.online';

// Map content type to WP REST API slug
const ENDPOINTS = {
    location: 'location',
    event:    'event',
    particle: 'particle'
};

// small helper to timeout fetches
function fetchWithTimeout(url, options = {}, timeout = 15000) {
    return new Promise((resolve, reject) => {
        const timer = setTimeout(() => {
            reject(new Error('Fetch timeout'));
        }, timeout);
        fetch(url, options).then(res => {
            clearTimeout(timer);
            resolve(res);
        }).catch(err => {
            clearTimeout(timer);
            reject(err);
        });
    });
}

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    // Open URL in new tab
    if (message.openNewTab) {
        chrome.tabs.create({ url: message.url });
        sendResponse({ success: true });
        return true;
    }

    // Fetch a single page of any content type
    if (message.type === 'fetchPage') {
        const contentType = ENDPOINTS[message.contentType] || 'location';
        const perPage = message.per_page || 100;
        const page = message.page || 1;
        const url = `${BASE_URL}/wp-json/wp/v2/${contentType}/?per_page=${perPage}&page=${page}`;
        fetchWithTimeout(url, {}, 15000)
            .then(async resp => {
                if (!resp.ok) {
                    const text = await resp.text().catch(() => '');
                    console.error(`Background fetch ${contentType} non-ok`, resp.status, text);
                    sendResponse({ success: false, error: `HTTP ${resp.status}` });
                    return;
                }
                const items = await resp.json().catch(() => []);
                const totalPages = parseInt(resp.headers.get('X-WP-TotalPages') || '1', 10);
                console.log(`Background fetch ${contentType} page`, page, 'items', items.length, 'totalPages', totalPages);
                sendResponse({ success: true, items, totalPages });
            })
            .catch(err => {
                console.error('Background fetch error', err && err.message);
                sendResponse({ success: false, error: err && err.message ? err.message : String(err) });
            });
        return true;
    }

    // Fetch all pages for a content type
    if (message.type === 'fetchAll') {
        const contentType = ENDPOINTS[message.contentType] || 'location';
        const perPage = message.per_page || 100;
        const results = [];
        const firstUrl = `${BASE_URL}/wp-json/wp/v2/${contentType}/?per_page=${perPage}&page=1`;
        fetchWithTimeout(firstUrl, {}, 15000)
            .then(async resp => {
                if (!resp.ok) {
                    const txt = await resp.text().catch(() => '');
                    sendResponse({ success: false, error: `HTTP ${resp.status} ${txt}` });
                    return;
                }
                const items = await resp.json().catch(() => []);
                const totalPages = parseInt(resp.headers.get('X-WP-TotalPages') || '1', 10);
                results.push(...items);
                if (totalPages <= 1) {
                    sendResponse({ success: true, items: results, totalPages });
                } else {
                    const fetchPromises = [];
                    for (let p = 2; p <= totalPages; p++) {
                        const url = `${BASE_URL}/wp-json/wp/v2/${contentType}/?per_page=${perPage}&page=${p}`;
                        fetchPromises.push(
                            fetchWithTimeout(url, {}, 15000)
                                .then(r => r.json().catch(() => []))
                                .then(data => results.push(...data))
                        );
                    }
                    Promise.all(fetchPromises)
                        .then(() => sendResponse({ success: true, items: results, totalPages }))
                        .catch(err => sendResponse({ success: false, error: err && err.message ? err.message : String(err) }));
                }
            })
            .catch(err => sendResponse({ success: false, error: err && err.message ? err.message : String(err) }));
        return true;
    }

    return false;
});
