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

    const formattedKeyword = keyword.replace(/ /g, '-');
    try {
        const response = await fetchv2("https://himovies.sx/search/" + encodeURIComponent(formattedKeyword));
        const html = await response.text();
        console.log("Search HTML: " + html);
        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: "https://himovies.sx" + 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="description">([\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 {
        const showIdMatch = url.match(/-(\d+)(?:\/)?$/);
        if (!showIdMatch) return JSON.stringify([]);

        const showId = showIdMatch[1];
        const seasonsRes = await fetchv2("https://himovies.sx/ajax/season/list/" + showId);
        const seasonsHtml = await seasonsRes.text();

        const seasonIdMatches = [...seasonsHtml.matchAll(/data-id="(\d+)"/g)];
        if (!seasonIdMatches.length) {
            return JSON.stringify([{
                href: "https://himovies.sx/ajax/episode/list/" + showId,
                number: 1,
                season: 1
            }]);
        }

        const allEpisodes = await Promise.all(seasonIdMatches.map(async (match, seasonIdx) => {
            const seasonId = match[1];
            const epsRes = await fetchv2("https://himovies.sx/ajax/season/episodes/" + seasonId);
            const epsHtml = await epsRes.text();
            const episodeMatches = epsHtml.match(/data-id="(\d+)"/g) || [];
            return episodeMatches.map((m, i) => {
                const id = m.replace(/data-id="|"/g, "");
                return {
                    href: "https://himovies.sx/ajax/episode/servers/" + id,
                    number: i + 1,
                    season: seasonIdx + 1
                };
            });
        }));

        const results = allEpisodes.flat();
        return JSON.stringify(results);
    } 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 idMatch = html.match(/data-id="([\w\d]+)"[^>]*title="Server MegaCloud"/i);
        if (!idMatch) return "https://error.org/";

        const api = await fetchv2("https://himovies.sx/ajax/episode/sources/" + idMatch[1]);
        const json = await api.json();

        const linkMatch = json.link.match(/\/embed-1\/v3\/e-1\/([\w\d]+)/);
        if (!linkMatch) return "https://error.org/";
        const playerId = linkMatch[1];
        const responseTwo = await fetchv2(json.link, {
            "referrer": "https://himovies.sx/",
        });
        const txtTwo = await responseTwo.text();
        let key = null;
        console.log("Response Text: " + txtTwo);
        const xyMatch = txtTwo.match(/window\._xy_ws\s*=\s*"([^"]+)"/);
        if (xyMatch) key = xyMatch[1];
        

        if (!key) {
            const lkMatch = txtTwo.match(/window\._lk_db\s*=\s*\{[^}]*x:\s*"([^"]+)"[^}]*y:\s*"([^"]+)"[^}]*z:\s*"([^"]+)"/);
            if (lkMatch) key = lkMatch[1] + lkMatch[2] + lkMatch[3];
        }

        if (!key) {
            const metaMatch = txtTwo.match(/<meta\s+name="_gg_fb"\s+content="([^"]+)"/i);
            if (metaMatch) key = metaMatch[1];
        }

        if (!key) {
            const dpiMatch = txtTwo.match(/data-dpi="([^"]+)"/);
            if (dpiMatch) key = dpiMatch[1];
        }

        if (!key) {
            const nonceMatch = txtTwo.match(/<script[^>]+nonce="([^"]+)"/i);
            if (nonceMatch) key = nonceMatch[1];
        }

        if (!key) {
            const commentMatch = txtTwo.match(/<!--\s*_is_th:\s*([^\s]+)\s*-->/);
            if (commentMatch) key = commentMatch[1];
        }

        if (!key) return "https://error.org/";

        const sourcesUrl = `https://videostr.net/embed-1/v3/e-1/getSources?id=${playerId}&_k=${key}`;
        const headers = {
            "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",
            "Referer": "https://videostr.net/",
            "x-Requested-With": "XMLHttpRequest",
            "accept": "application/json, text/javascript, */*; q=0.01"
        };
        const responseThree = await fetchv2(sourcesUrl, headers);
        const jsonThree = await responseThree.json();
        console.log("Extracted sources URL: " + JSON.stringify(jsonThree));

        let streamUrl = null;
        if (Array.isArray(jsonThree.sources)) {
            const hlsSource = jsonThree.sources.find(s => s.type === "hls" && s.file);
            if (hlsSource) streamUrl = hlsSource.file;
        }

        let subtitle = null;
        if (Array.isArray(jsonThree.tracks)) {
            const engSub = jsonThree.tracks.find(t => t.label && t.label.toLowerCase() === "english" && t.file);
            if (engSub) subtitle = engSub.file;
        }

        const streamHeaders = {
            "Host": "f9.megacdn.co:2228",
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:145.0) Gecko/20100101 Firefox/145.0",
            "Accept": "*/*",
            "Accept-Language": "en-US,en;q=0.5",
            "Accept-Encoding": "gzip, deflate, br, zstd",
            "Referer": "https://videostr.net/",
            "Origin": "https://videostr.net",
            "Connection": "keep-alive",
            "Sec-Fetch-Dest": "empty",
            "Sec-Fetch-Mode": "cors",
            "Sec-Fetch-Site": "cross-site"
        };

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