async function searchResults(keyword) {
    const results = [];
    const postData = `{"query":"${keyword}"}`;
    const headers = {
        "Content-Type": "application/json"
    };
    try {
        const response = await fetchv2("https://kickass-anime.ro/api/search", headers, "POST", postData);
        const data = await response.json();

        data.forEach(item => {
            results.push({
                title: item.title_en || item.title,
                image: `https://kickass-anime.ro/image/poster/${item.poster.hq}.webp`,
                href: `${item.slug}`
            });
        });

        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://kickass-anime.ro/" + slug);
        const html = await response.text();

        const synopsisMatch = html.match(/f\.synopsis\s*=\s*"([^"]*)"/);
        const description = synopsisMatch ? synopsisMatch[1] : "N/A";

        const aliasesMatch = html.match(/f\.title_original\s*=\s*"([^"]*)"/);
        const aliases = aliasesMatch ? aliasesMatch[1] : "N/A";

        const airdateMatch = html.match(/f\.start_date\s*=\s*"([^"]*)"/);
        const airdate = airdateMatch ? airdateMatch[1] : "N/A";

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

async function extractEpisodes(slug) {
    const results = [];
    try {
        const cleanSlug = slug.replace("anime/", "");
        const responseEn = await fetchv2(`https://kickass-anime.ro/api/show/${cleanSlug}/episodes?ep=1&page=1&lang=en-US`);
        const dataEn = await responseEn.json();
        const responseJa = await fetchv2(`https://kickass-anime.ro/api/show/${cleanSlug}/episodes?ep=1&page=1&lang=ja-JP`);
        const dataJa = await responseJa.json();

        const enMap = {};
        dataEn.result.forEach(episode => {
            enMap[episode.episode_number] = episode.slug;
        });

        dataJa.result.forEach(episode => {
            const enSlug = enMap[episode.episode_number];
            const hrefSlug = enSlug ? `${enSlug}|${episode.slug}` : episode.slug;
            results.push({
                href: `https://kickass-anime.ro/${cleanSlug}/ep-${episode.episode_number}-${hrefSlug}`,
                number: episode.episode_number
            });
        });

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

async function fetchDetails(srcUrl) {
    const response = await fetchv2(srcUrl);
    const html = await response.text();

    const manifestMatch = html.match(/&quot;manifest&quot;:\[0,&quot;([^&]*)&quot;\]/);
    const manifest = manifestMatch ? manifestMatch[1] : null;

    const enSubMatch = html.match(/&quot;language&quot;:\[0,&quot;en&quot;\],&quot;name&quot;:\[0,&quot;English&quot;\],&quot;src&quot;:\[0,&quot;([^&]*)&quot;\]/);
    const enSub = enSubMatch ? enSubMatch[1] : null;

    return { manifest, enSub };
}

async function fetchSrc(epUrl) {
    const response = await fetchv2(epUrl);
    const html = await response.text();
    const match = html.match(/src:\s*"([^"]*)"/);
    return match ? match[1].replace(/\\u002F/g, '/') : null;
}

async function extractStreamUrl(url) {
    try {

        const parts = url.split('/');

        const cleanSlug = parts[parts.length - 2];
        const last = parts[parts.length - 1];

        const [ep, number, slugs] = last.split('-');

        const slugParts = slugs.split('|');

        const enSlug = slugParts.length > 1 ? slugParts[0] : null;
        const jaSlug = slugParts[slugParts.length - 1];

        const streams = [];

        let enDetails = null;
        if (enSlug) {
            const enUrl = `https://kickass-anime.ro/${cleanSlug}/ep-${number}-${enSlug}`;
            const src = await fetchSrc(enUrl);
            if (src) {
                enDetails = await fetchDetails(src);
                if (enDetails.manifest) {
                    streams.push({
                        title: "English Dubbed",
                        streamUrl: enDetails.manifest,
                        headers: {
                            "Origin": "https://krussdomi.com"
                        }
                    });
                }
            }
        }

        const jaUrl = `https://kickass-anime.ro/${cleanSlug}/ep-${number}-${jaSlug}`;
        const jaSrc = await fetchSrc(jaUrl);
        let subtitle = "https://placeholder.com/subtitles.vtt";
        if (jaSrc) {
            const jaDetails = await fetchDetails(jaSrc);
            if (jaDetails.manifest) {
                streams.push({
                    title: "Japanese Subbed",
                    streamUrl: jaDetails.manifest,
                    headers: {
                        "Origin": "https://krussdomi.com"
                    }
                });
            }
            if (jaDetails.enSub) {
                subtitle = jaDetails.enSub;
            }
        }

        return JSON.stringify({
            streams: streams,
            subtitle: subtitle
        });
    } catch (err) {
        console.log("Error extracting stream URL:", err);
        return JSON.stringify({
            streams: [],
            subtitle: "https://placeholder.com/subtitles.vtt"
        });
    }
}
