async function searchResults(keyword) {
    const results = [];
    try {
        const response = await fetchv2("https://animeler.pw/wp-json/kiranime/v1/anime/search?query=" + encodeURIComponent(keyword) + "&lang=jp&_locale=user");
        const data = await response.json();
        const html = data.result;

        const regex = /<a href="([^"]+)"[^>]*>[\s\S]*?<img[^>]+src='([^']+)'[^>]*>[\s\S]*?<h3[^>]*>([^<]+)<\/h3>/g;
        let match;

        while ((match = regex.exec(html)) !== null) {
            results.push({
                title: match[3].trim(),
                image: match[2].trim(),
                href: match[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 regex = /<div\s+class="block\s+w-full[^"]*"[^>]*>(.*?)<\/div>/s;
        const match = html.match(regex);
        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(url) {
    const results = [];
    try {
        const response = await fetchv2(url);
        const html = await response.text();

        const regex = /<div\s+class="swiper-slide[^"]*"[^>]*>\s*<a\s+href="(https:\/\/animeler\.pw\/[^"]+)"[^>]*title="[^"]*"[^>]*class="w-full[^"]*"[^>]*>[\s\S]*?<span[^>]*>\s*Bölüm\s+(\d+)\s*<\/span>[\s\S]*?<\/a>/gi;
        let match;
        
        while ((match = regex.exec(html)) !== null) {
            results.push({
                href: match[1].trim(),
                number: parseInt(match[2], 10)
            });
        }

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

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

        const match = html.match(/<iframe[^>]+src=['"](https:\/\/play\.animeler\.pw\/fireplayer\/video\/([a-f0-9]+))['"]/i);
        if (match) {
            const fireplayerUrl = match[1];
            const hash = match[2];

            const postData = "hash=" + hash + "&r=https%3A%2F%2Fanimeler.pw%2F&s=";
            const headers = {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
                'Origin': 'https://play.animeler.pw',
                'Referer': fireplayerUrl,
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3',
                "X-Requested-With": "XMLHttpRequest"
            };

            const streamResponse = await fetchv2(fireplayerUrl + "?do=getVideo", headers, "POST", postData);
            const streamData = await streamResponse.json();

            const sibnetUrl = streamData.videoSrc;
            const streamHeaders = {
                "Host": "dv32-1.sibnet.ru",
                "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:145.0) Gecko/20100101 Firefox/145.0",
                "Accept": "video/webm,video/ogg,video/*;q=0.9,application/ogg;q=0.7,audio/*;q=0.6,*/*;q=0.5",
                "Accept-Language": "en-US,en;q=0.5",
                "Accept-Encoding": "gzip, deflate, br, zstd, identity",
                "Range": "bytes=0-",
                "Referer": "https://video.sibnet.ru/",
                "Connection": "keep-alive",
                "Sec-Fetch-Dest": "video",
                "Sec-Fetch-Mode": "no-cors",
                "Sec-Fetch-Site": "same-site",
                "Priority": "u=0"
            };

            const subtitleUrl = "https://none.com/subtitles.vtt";

            const data = await sibnetExtractor(sibnetUrl);

            return JSON.stringify({
                streams: [
                    {
                        title: "Server 1",
                        streamUrl: data ? data.url : 'deijdiw',
                        headers: streamHeaders
                    }
                ],
                subtitle: subtitleUrl
            });
        }

        return JSON.stringify({
            streams: [],
            subtitle: ""
        });
    } catch (err) {
        return JSON.stringify({
            streams: [],
            subtitle: ""
        });
    }
}

async function sibnetExtractor(embedUrl) {
    const headers = {
        Referer: embedUrl
    };

    try {
        const response = await soraFetch(embedUrl, {
            headers,
            method: 'GET',
            encoding: 'windows-1251'
        });
        const html = await response.text();

        const videoMatch = html.match(
            /player\.src\s*\(\s*\[\s*\{\s*src\s*:\s*["']([^"']+)["']/i
        );

        if (!videoMatch || !videoMatch[1]) {
            throw new Error("Sibnet video source not found");
        }

        const videoPath = videoMatch[1];
        const videoUrl = videoPath.startsWith("http")
            ? videoPath
            : `https://video.sibnet.ru${videoPath}`;

        return {
            url: videoUrl,
            headers: headers
        };
    } catch (error) {
        console.log("SibNet extractor error: " + error.message);
        return null;
    }
}


async function soraFetch(url, options = { headers: {}, method: 'GET', body: null, encoding: 'utf-8' }) {
    try {
        return await fetchv2(
            url,
            options.headers ?? {},
            options.method ?? 'GET',
            options.body ?? null,
            true,
            options.encoding ?? 'utf-8'
        );
    } catch(e) {
        try {
            return await fetch(url, options);
        } catch(error) {
            return null;
        }
    }
}

function decodeHTMLEntities(text) {
    text = text.replace(/&#(\d+);/g, (match, dec) => String.fromCharCode(dec));
    
    const entities = {
        '&quot;': '"',
        '&amp;': '&',
        '&apos;': "'",
        '&lt;': '<',
        '&gt;': '>'
    };
    
    for (const entity in entities) {
        text = text.replace(new RegExp(entity, 'g'), entities[entity]);
    }

    return text;
}

