async function searchResults(keyword) {
    const results = [];

    try {
        const response = await fetchv2("https://hicartoon.to/search?keyword=" + encodeURIComponent(keyword));
        const html = await response.text();

        const blocks = html.split('<div class="flw-item">').slice(1);

        for (const block of blocks) {
            const href = block.match(/<a href="([^"]+)"/);
            const image = block.match(/data-src="([^"]+)"/) || block.match(/src="([^"]+)"/);
            const title = block.match(/title="([^"]+?)"/);

            if (href && image && title) {
                results.push({
                    title: title[1].trim(),
                    image: image[1].trim(),
                    href: href[1].trim()
                });
            }
        }

        return JSON.stringify(results);
    } catch (err) {
        return JSON.stringify([{
            title: "Error",
            image: "Error",
            href: "Error"
        }]);
    }
}

async function extractDetails(url) {
    try {
        const response = await fetchv2(url);
        const html = await response.text();

        const descMatch = html.match(/<div class="film-description m-hide">[\s\S]*?<div class="text">\s*([\s\S]*?)\s*<\/div>/);
        const dateMatch = html.match(/<strong>Released:\s*<\/strong>\s*([^<\n]+)/);

        const description = descMatch ? descMatch[1].trim() : "N/A";
        const airdate = dateMatch ? dateMatch[1].trim() : "N/A";

        return JSON.stringify([{
            description: description,
            aliases: "N/A",
            airdate: airdate
        }]);

    } catch (err) {
        return JSON.stringify([{
            description: "Error",
            aliases: "Error",
            airdate: "Error"
        }]);
    }
}

async function extractEpisodes(url) {
    const results = [];
    try {
        let watchUrl = url;
        if (!/\/watch\//.test(watchUrl)) {
            watchUrl = watchUrl.replace(/\/([^\/]+)$/, '/watch/$1');
        }

        const watchResp = await fetchv2(watchUrl);
        const watchHtml = await watchResp.text();
        const idMatch = watchHtml.match(/<div[^>]+id="wrapper"[^>]+data-id="(\d+)"[^>]*>/);
        if (!idMatch) throw new Error("movie_id not found");
        const movieId = idMatch[1];

        const epListResp = await fetchv2(`https://hicartoon.to/ajax/v2/episode/list?movie_id=${movieId}`);
        const epListJson = await epListResp.json();
        const epHtml = epListJson.html;

        const epRegex = /<a[^>]+class="ssl-item ep-item"[^>]+data-id="(\d+)"[^>]+href="([^"]+)"[^>]*>[\s\S]*?<div class="ssli-order"[^>]*>([^<]+)<\/div>[\s\S]*?<div class="ep-name e-dynamic-name"[^>]*>([^<]+)<\/div>/g;
            let match;
            let idx = 1;
            while ((match = epRegex.exec(epHtml)) !== null) {
                results.push({
                    href: match[1],
                    number: idx
                });
                idx++;
            }

        return JSON.stringify(results);
    } catch (err) {
        console.error(err);
        return JSON.stringify([{ id: "Error", href: "Error", number: "Error", title: "Error" }]);
    }
}

async function extractStreamUrl(ID) {
    try {
        let response;
        let json;
        let iframeMatch;
        
        // Try tserver
        try {
            response = await fetchv2(`https://hicartoon.to/ajax/v2/episode/sources?id=${ID}&s=tserver`);
            json = await response.json();
            iframeMatch = json.value ? json.value.match(/<iframe[^>]+src="([^"]+)"/) : null;
        } catch (e) {
            console.log("tserver failed, trying drserver");
        }
        
        if (!iframeMatch) {
            try {
                response = await fetchv2(`https://hicartoon.to/ajax/v2/episode/sources?id=${ID}&s=drserver`);
                json = await response.json();
                iframeMatch = json.value ? json.value.match(/<iframe[^>]+src="([^"]+)"/) : null;
            } catch (e) {
                console.log("drserver failed, trying vhserver");
            }
        }
        
        if (!iframeMatch) {
            try {
                response = await fetchv2(`https://hicartoon.to/ajax/v2/episode/sources?id=${ID}&s=vhserver`);
                json = await response.json();
                iframeMatch = json.value ? json.value.match(/<iframe[^>]+src="([^"]+)"/) : null;
            } catch (e) {
                console.log("vhserver failed");
            }
        }
        
        if (!iframeMatch) return "https://error.org/";
        const iframeUrl = iframeMatch[1];


        const streamHeaders = {
            "Referer": "https://kem.clvd.xyz/",
            "Origin": "https://kem.clvd.xyz/"
        };

        const iframeResp = await fetchv2(iframeUrl);
        const iframeHtml = await iframeResp.text();

        const hlsMatch = iframeHtml.match(/sources:\s*\[\{\s*"file":\s*"([^"]+)"/);
        const streamUrl = hlsMatch ? hlsMatch[1] : "";

        const subtitle = "";
        return JSON.stringify({
            streams: [
                {
                    title: "Server 1",
                    streamUrl: streamUrl,
                    headers: streamHeaders
                }
            ],
            subtitle: subtitle
        });
    } catch (err) {
        console.error(err);
        return "https://error.org/";
    }
}




