import { load } from 'cheerio';
import { renderToString } from 'hono/jsx/dom/server';

import type { Route } from '@/types';
import got from '@/utils/got';

export const route: Route = {
    path: '/explore',
    categories: ['social-media'],
    example: '/douban/explore',
    parameters: {},
    features: {
        requireConfig: false,
        requirePuppeteer: false,
        antiCrawler: false,
        supportBT: false,
        supportPodcast: false,
        supportScihub: false,
    },
    name: '浏览发现',
    maintainers: ['clarkzsd'],
    handler,
};

async function handler() {
    const response = await got({
        method: 'get',
        url: 'https://www.douban.com/explore',
    });

    const data = response.data;

    const $ = load(data);
    const list = $('div.item');

    return {
        title: '豆瓣-浏览发现',
        link: 'https://www.douban.com/explore',
        item: list.toArray().map((item) => {
            item = $(item);

            const title = item.find('.title a').first().text() ?? '#' + item.find('.icon-topic').text();
            const desc = item.find('.content p').text();
            const itemPic = item.find('a.cover').attr('style')
                ? item
                      .find('a.cover')
                      .attr('style')
                      .match(/\('(.*?)'\)/)[1]
                : '';
            const author = item.find('.usr-pic a').last().text();
            const link = item.find('.title a').attr('href') ?? item.find('.icon-topic a').attr('href');

            return {
                title,
                author,
                description: renderDescription({
                    author,
                    desc,
                    itemPic,
                }),
                link,
            };
        }),
    };
}

const renderDescription = ({ author, desc, itemPic }: { author: string; desc: string; itemPic?: string }): string =>
    renderToString(
        <>
            作者：{author}
            <br />
            描述：{desc}
            <br />
            {itemPic ? <img src={itemPic} /> : null}
        </>
    );
