async function searchContent(keyword, page=0) {
    const results = [];
    try {
        const response = await fetch("https://kaliscan.io/service/backend/search/?q=" + encodeURIComponent(keyword));
        const html = await response.text();

        const regex = /href="([^"]*manga[^"]*)"[^>]*>[\s\S]*?<img src="([^"]*)"[\s\S]*?<h3><a[^>]*>([\s\S]*?)<\/a><\/h3>/g;
        
        let match;
        while ((match = regex.exec(html)) !== null) {
            results.push({
                id: "https://kaliscan.io" + match[1].trim(),
                imageURL: match[2].trim(),
                title: match[3].replace(/<[^>]+>/g, '').trim()
            });
        }

        return results;
    } catch (err) {
        return [];
    }
}

async function getContentData(url) {
    try {
        const response = await fetch(url);
        const html = await response.text();

        const descRegex = /<meta name="description" content="([^"]+)"/i;
        const descMatch = descRegex.exec(html);
        const description = descMatch ? descMatch[1].trim() : "";
        return {
            description,
            tags: []
        };
    } catch (err) {
        return {
            description: "Error",
            tags: []
        };
    }
}

async function getChapters(url) {
    const results = [];
    try {
        const idRegex = /\/manga\/(\d+)-/;
        const idMatch = url.match(idRegex);
        if (!idMatch) return { en: [] };
        const manga_id = idMatch[1];

        const chapUrl = `https://kaliscan.io/service/backend/chaplist/?manga_id=${manga_id}`;
        const response = await fetch(chapUrl);
        const html = await response.text();

        const regex = /<li id="c-\d+">\s*<a href="([^"]*)" title=" - Chapter (\d+)">\s*<div><strong class="chapter-title">Chapter \2<\/strong>/g;
        
        let match;
        
        while ((match = regex.exec(html)) !== null) {
            const chapterUrl = "https://kaliscan.io" + match[1];
            const chapterNum = match[2];
            results.push([
                String(chapterNum),
                [{
                    id: chapterUrl,
                    chapter: parseInt(chapterNum),
                    scanlation_group: `Chapter ${chapterNum}`
                }]
            ]);
        }

        results.reverse();

        return { en: results };
    } catch (err) {
        return { en: [] };
    }
}

async function getChapterImages(url) {
    const results = [];
    try {
        const response = await fetch(url);
        const html = await response.text();
        const regex = /var chapImages = "([^"]*)"/;
        const match = regex.exec(html);
        if (match) {
            const imagesString = match[1];
            const images = imagesString.split(',');
            results.push(...images);
        }

        return results;
    } catch (err) {
        return [];
    }
}