export function stripHtml(html: string): string {
    if (!html) return "";

    let text = html
        .replace(/<[^>]*>/g, "") // Remove HTML tags
        .replace(/&nbsp;|\u00a0/g, " ") // Handle non-breaking spaces
        .replace(/&amp;/g, "&")
        .replace(/&quot;/g, '"')
        .replace(/&apos;/g, "'")
        .replace(/&lt;/g, "<")
        .replace(/&gt;/g, ">")
        .replace(/&ndash;/g, "-")
        .replace(/&mdash;/g, "-")
        .replace(/&hellip;/g, "...")
        .replace(/&rsquo;/g, "'")
        .replace(/&lsquo;/g, "'")
        .replace(/&ldquo;/g, '"')
        .replace(/&rdquo;/g, '"')
        .replace(/&bull;/g, "•")
        .replace(/&copy;/g, "©")
        .replace(/&reg;/g, "®")
        .replace(/&trade;/g, "™");

    // Handle common accented characters if they are encoded
    const entities: { [key: string]: string } = {
        '&agrave;': 'à', '&aacute;': 'á', '&acirc;': 'â', '&atilde;': 'ã', '&auml;': 'ä',
        '&egrave;': 'è', '&eacute;': 'é', '&ecirc;': 'ê', '&euml;': 'ë',
        '&igrave;': 'ì', '&iacute;': 'í', '&icirc;': 'î', '&iuml;': 'ï',
        '&ograve;': 'ò', '&oacute;': 'ó', '&ocirc;': 'ô', '&otilde;': 'õ', '&ouml;': 'ö',
        '&ugrave;': 'ù', '&uacute;': 'ú', '&ucirc;': 'û', '&uuml;': 'ü',
        '&ccedil;': 'ç', '&ntilde;': 'ñ'
    };

    for (let ent in entities) {
        text = text.replace(new RegExp(ent, 'gi'), entities[ent]);
    }

    return text
        .replace(/\s+/g, " ") // Normalize multiple spaces/newlines
        .trim();
}

/**
 * Transforms a standard Google Drive sharing link into a direct download/view link 
 * compatible with Next.js Image component optimization.
 */
export function getDirectDriveLink(url: string | null | undefined): string {
    if (!url || typeof url !== 'string') return "";
    if (!url.includes("drive.google.com")) return url;

    try {
        let fileId = "";
        // Pattern for /file/d/ID/view
        const fileDMatch = url.match(/\/file\/d\/([a-zA-Z0-9_-]+)/);
        if (fileDMatch && fileDMatch[1]) {
            fileId = fileDMatch[1];
        } else {
            // Pattern for ?id=ID
            const idParamMatch = url.match(/[?&]id=([a-zA-Z0-9_-]+)/);
            if (idParamMatch && idParamMatch[1]) {
                fileId = idParamMatch[1];
            }
        }

        if (fileId) {
            // Use the thumbnail endpoint which is much more stable for public files
            // and avoids the 'too many redirects' / 'virus scan' warning pages
            return `https://drive.google.com/thumbnail?id=${fileId}&sz=w1600`;
        }
    } catch (e) {
        console.error("Error parsing Google Drive link:", e);
    }

    return url;
}

/**
 * Transforms a YouTube URL into an embeddable URL.
 */
export function getYouTubeEmbedUrl(url: string | null | undefined): string | null {
    if (!url || typeof url !== 'string') return null;

    // Regular expressions for various YouTube URL formats
    const patterns = [
        /(?:https?:\/\/)?(?:www\.)?youtube\.com\/watch\?v=([^&]+)/,
        /(?:https?:\/\/)?(?:www\.)?youtu\.be\/([^?]+)/,
        /(?:https?:\/\/)?(?:www\.)?youtube\.com\/embed\/([^?]+)/,
    ];

    for (const pattern of patterns) {
        const match = url.match(pattern);
        if (match && match[1]) {
            return `https://www.youtube-nocookie.com/embed/${match[1]}`;
        }
    }

    return null;
}
