async function searchResults(keyword) {
    const results = [];
    try {
        const response = await fetchv2("https://api-search.anroll.net/data?q=" + encodeURIComponent(keyword));
        const data = await response.json();

        data.data.forEach(item => {
            const baseUrl = item.generic_path.trim().startsWith('/f/') 
                ? "https://www.anroll.net/_next/image?url=https://static.anroll.net/images/filmes/capas/" 
                : "https://www.anroll.net/_next/image?url=https://static.anroll.net/images/animes/capas/";
            
            results.push({
                title: item.title.trim(),
                image: baseUrl + item.slug.trim() + ".jpg&w=384&q=75",
                href: item.generic_path.trim()
            });
        });

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

async function extractDetails(slug) {
    try {
        const response = await fetchv2("https://www.anroll.net/" + slug);
        const html = await response.text();

        const match = html.match(/<div class="sinopse">(.*?)<\/div>/s);
        const description = match ? match[1].trim() : "N/A";

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


async function extractEpisodes(slug) {
    const results = [];
    try {
        // If slug starts with /f/ (movie), extract ID and return as single episode
        if (slug.startsWith('/f/')) {
            results.push({
                href: slug,
                number: 1
            });
            return JSON.stringify(results);
        }

        // Only process if slug starts with /a/ (anime)
        if (!slug.startsWith('/a/')) {
            return JSON.stringify(results);
        }

        const response = await fetchv2("https://www.anroll.net" + slug);
        const html = await response.text();

        // Extract series ID from __NEXT_DATA__
        const scriptMatch = html.match(/<script id="__NEXT_DATA__" type="application\/json">({.*?})<\/script>/);
        if (!scriptMatch) return JSON.stringify(results);

        const jsonData = JSON.parse(scriptMatch[1]);
        const seriesId = jsonData?.props?.pageProps?.data?.id_serie;
        if (!seriesId) return JSON.stringify(results);

        // Fetch all episodes from all pages
        let page = 1;
        let hasNextPage = true;

        while (hasNextPage) {
            const episodesResponse = await fetchv2(`https://apiv3-prd.anroll.net/animes/${seriesId}/episodes?page=${page}&order=desc`);
            const episodesData = await episodesResponse.json();

            if (episodesData.data && episodesData.data.length > 0) {
                episodesData.data.forEach(episode => {
                    results.push({
                        href: episode.generate_id,
                        number: parseInt(episode.n_episodio, 10)
                    });
                });

                hasNextPage = episodesData.meta?.hasNextPage || false;
                page++;
            } else {
                hasNextPage = false;
            }
        }

        return JSON.stringify(results.reverse());
    } catch (err) {
        return JSON.stringify([]);
    }
}

async function extractStreamUrl(ID) {
    try {
        if (!ID.startsWith('/f/')) {
            const response = await fetchv2("https://www.anroll.net/watch/e/" + ID);
            const html = await response.text();
            
            const streamMatch = html.match(/streamUrl\\?":\\?"(https:\/\/[^"\\]+\.m3u8)/);
            
            if (!streamMatch) return JSON.stringify({
                streams: [{
                    title: "Server 1",
                    streamUrl: "https://error.org/no-stream-found",
                    headers: {}
                }],
                subtitle: ""
            });
            
            const streamUrl = streamMatch[1];
            
            return JSON.stringify({
                streams: [
                    {
                        title: "Server 1",
                        streamUrl: streamUrl,
                        headers: {
                            "Referer": "https://www.anroll.net/",
                            "Origin": "https://www.anroll.net"
                        }
                    }
                ],
                subtitle: ""
            });
        }

        const response = await fetchv2("https://www.anroll.net" + ID);
        const html = await response.text();

        const scriptMatch = html.match(/<script id="__NEXT_DATA__" type="application\/json">({.*?})<\/script>/);
        if (!scriptMatch) return "https://error.org/no-next-data";

        const jsonData = JSON.parse(scriptMatch[1]);
        const movieData = jsonData?.props?.pageProps?.data?.data_movie;
        
        if (!movieData || !movieData.slug_filme) {
            return "https://error.org/no-movie-data";
        }

        const slug = movieData.slug_filme;
        const streamUrl = `https://cdn-zenitsu-2-gamabunta.b-cdn.net/cf/hls/movies/${slug}/movie.mp4/media-1/stream.m3u8`;

        return JSON.stringify({
            streams: [
                {
                    title: "Server 1",
                    streamUrl: streamUrl,
                    headers: {
                        "Referer": "https://www.anroll.net/",
                        "Origin": "https://www.anroll.net"
                    }
                }
            ],
            subtitle: ""
        });
    } catch (err) {
        return "https://error.org/";
    }
}
