import { codeToHtml } from '@pierre/highlights';
import type { Lang, Theme } from '@pierre/highlights';
import { monoDark, monoLight } from './theme';
import { raw } from './raw';
import styles from '@/components/CodeBlock/CodeBlock.module.scss';

export type Options = {
    file: string;
    lang?: Lang | (string & {});
    path?: string;
    isIndex?: boolean;
    themes?: {
        light?: Theme;
        dark?: Theme;
    };
};

function convertToLink({
    link,
    quote,
    label = `${quote}${link}${quote}`,
    prefix,
    path,
    isPath,
    isIndex,
}: {
    link: string;
    quote: string;
    label?: string;
    prefix?: string;
    path?: string;
    isPath?: boolean;
    isIndex?: boolean;
}) {
    if (link.split('/')[0] === 'next') {
        return label;
    }

    if (label === 'styles') {
        return label;
    }

    let slug = link.replace('@/', '/').replace('./', path ? `${path}/` : '');

    if (link.includes('components')) {
        if (isPath) {
            slug = `${slug}/index.ts`;
        } else {
            slug = `${slug}/${label}.tsx`;
        }
    } else if (!isIndex) {
        const parts = slug.split('.');
        const hasExt = parts.length > 1 && parts.at(-1);

        if (!hasExt) {
            slug = `${slug}.ts`;
        }
    }

    if (isIndex && prefix?.trim() === 'export') {
        slug = `${slug}.tsx`;
    }

    return `<a class="${styles.import}" href="${slug}">${label}</a>`;
}

function separateAndConvertNamesToLinks({
    names,
    link,
    quote,
    prefix,
    path,
    isIndex,
}: {
    names: string;
    link: string;
    quote: string;
    prefix?: string;
    path?: string;
    isIndex?: boolean;
}) {
    return names.replace(/\b(?!type\b|as\b)(\w+)/g, (name) =>
        convertToLink({ link, quote, label: name, prefix, path, isIndex }),
    );
}

export function html({ file, lang, path, isIndex, themes }: Options) {
    const text = raw(file);

    const bytes = codeToHtml(text, {
        lang: lang || 'tsx',
        themes: {
            light: themes?.light || monoLight,
            dark: themes?.dark || monoDark,
        },
        defaultColor: 'light-dark()',
    });

    return (
        new TextDecoder()
            .decode(bytes)
            // External links
            .replace(/(https?:\/\/[^\s<"']+)/g, '<a href="$1" target="_blank" rel="noopener noreferrer">$1</a>')
            // Internal routes
            .replace(/(['"])((?:<[^>]+>)*)(\/[a-zA-Z0-9/_-]*)((?:<[^>]+>)*)\1/g, '$1$2<a href="$3">$3</a>$4$1')
            // Markdown Links
            // /(?<!!)\[([^\]]+)\]\(([^)]+)\)/g // ignore images variant
            .replace(/\[([^\]]+)\]\(([^)]+)\)/g, '[$1](<a href="$2">$2</a>)')
            // Named imports/exports & combined direct + named imports
            .replace(
                /(\b(?:import|export)[^\S\r\n]+(?:type[^\S\r\n]+)?)(?:(\w+)([^\S\r\n]*,[^\S\r\n]*))?\{([^}\r\n]+)\}([^\S\r\n]+from[^\S\r\n]+)(['"])([^'"\r\n]+)\6/g,
                (
                    _match,
                    prefix: string,
                    direct: string | undefined,
                    comma: string | undefined,
                    names: string,
                    from: string,
                    quote: string,
                    link: string,
                ) => {
                    const directPart = direct ? `${convertToLink({ link, quote, label: direct, path })}${comma}` : '';

                    return `${prefix}${directPart}{${separateAndConvertNamesToLinks({ names, link, quote, prefix, path, isIndex })}}${from}${convertToLink({ link, quote, path, isPath: true, prefix, isIndex })}`;
                },
            )
            // Direct imports
            .replace(
                /(\bimport[^\S\r\n]+(?:type[^\S\r\n]+)?)(\w+)([^\S\r\n]+from[^\S\r\n]+)(['"])([^'"\r\n]+)\4/g,
                (_match, prefix: string, direct: string, from: string, quote: string, link: string) => {
                    return `${prefix}${convertToLink({ link: link, quote: quote, label: direct, path })}${from}${convertToLink({ link: link, quote: quote, path })}`;
                },
            )
            // Unnamed imports
            .replace(/(\bimport[^\S\r\n]+)(['"])([^'"\r\n]+)\2/g, (_match, p1: string, p2: string, p3: string) => {
                return `${p1}${convertToLink({ link: p3, quote: p2, path })}`;
            })
    );
}
# Pages

[Home](/)
[Index](/index)
[Docs](/docs)