const axios = require('axios');
const cheerio = require('cheerio');
const express = require('express');
const router = express.Router();

const { fetchWithRetry } = require('./asyncProxy'); 

const targetUrl = process.env.TARGET_URL;
const proxyUrl = process.env.PROXY_URL;

const applyHtmlModifications = ($, headerAds, bodyAds, req) => {
    
    const targetUrlsToReplace = [
        targetUrl, 
        'https://komikcast.li', 'https://komikcast.mom', 'https://komikcast.io', 'https://komikcast.net',
        'http://komikcast.li', 'http://komikcast.mom', 'http://komikcast.io', 'http://komikcast.net','https://komikcast.pics'
    ];

    const combinedTargetRegex = new RegExp(
        targetUrlsToReplace.map(url => url.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|'),
        'gi'
    );

    const replaceContentUrls = (content) => {
        if (!content) return content;
        if (combinedTargetRegex.test(content)) {
            return content.replace(combinedTargetRegex, proxyUrl);
        }
        return content;
    };

    // --- MULAI MODIFIKASI INJEKSI & STYLING ---
    $('head').append(headerAds);
    $('div.kln').append(bodyAds);
	
	
	// --- INJEKSI WEBMASTER DAN ANALITIK ---

    const gtmId = process.env.GTM_ID;
    const gaId = process.env.GA_ANALYTICS_ID;
    const webmasterTag = process.env.WEBMASTER_TAG;

    // 1. Injeksi Google Tag Manager (GTM)
    if (gtmId) {
        $('head').prepend(`
            <script>
                (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
                new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
                j=d.createElement(s),dl=l!='dataLayer'?'&'+l:'';j.async=true;j.src=
                'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
                })(window,document,'script','dataLayer','${gtmId}');
            </script>
        `);
        
        $('body').prepend(`
            <noscript>
                <iframe src="https://www.googletagmanager.com/ns.html?id=${gtmId}"
                height="0" width="0" style="display:none;visibility:hidden"></iframe>
            </noscript>
        `);
    }

    // 2. Injeksi Google Analytics (Legacy UA)
    if (gaId) {
        $('head').append(`
            <script async src="https://www.googletagmanager.com/gtag/js?id=${gaId}"></script>
            <script>
                window.dataLayer = window.dataLayer || [];
                function gtag(){dataLayer.push(arguments);}
                gtag('js', new Date());
                gtag('config', '${gaId}');
            </script>
        `);
    }

    // 3. Injeksi Webmaster/Verification Tag
    if (webmasterTag) {
        $('head').prepend(webmasterTag);
    }
    
    // --- AKHIR INJEKSI WEBMASTER DAN ANALITIK ---
	
    $('head').append(`
        <style>
            /* Class untuk menyembunyikan konten utama secara total di awal */
            .proxy-content-hide {
                visibility: hidden !important;
                opacity: 0 !important;
                transition: visibility 0s 0.5s, opacity 0.5s linear;
            }
            .proxy-content-show {
                visibility: visible !important;
                opacity: 1 !important;
            }

            /* -- ANIMASI DOT LOADER CSS -- */
            #css-loader-wrapper {
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background-color: #212121; 
                z-index: 99999; /* Z-INDEX SANGAT TINGGI */
                display: flex;
                justify-content: center;
                align-items: center;
                transition: opacity 0.5s;
            }
            .dot-loader {
                display: flex;
                align-items: center;
            }
            .dot-loader > div {
                width: 10px;
                height: 10px;
                margin: 0 5px;
                background-color: #FFA500; 
                border-radius: 50%;
                animation: scaleup 1s infinite alternate;
            }
            .dot-loader div:nth-child(2) { animation-delay: 0.3s; }
            .dot-loader div:nth-child(3) { animation-delay: 0.6s; }
            @keyframes scaleup {
                0% { transform: scale(0.6); opacity: 0.5; }
                100% { transform: scale(1.2); opacity: 1; }
            }
            /* -- AKHIR ANIMASI DOT LOADER -- */


            /* SHIMMER/SKELETON STYLE */
            @keyframes shimmer {
                to { background-position: -200% 0; }
            }
            .skeleton-active #content .releases-slider, .skeleton-active .utao-item, 
            .skeleton-active .releases > ul > li { position: relative; }
            
            .skeleton-active .utao-item > *, .skeleton-active .releases > ul > li > * { visibility: hidden; }
            
            .skeleton-active #content .releases-slider::before, .skeleton-active .utao-item::before, 
            .skeleton-active .releases > ul > li::before {
                content: '';
                position: absolute;
                top: 0; left: 0; width: 100%; height: 100%; display: block;
                background-color: #e2e2e2; border-radius: 4px; z-index: 50; 
                background-image: linear-gradient(90deg, #e2e2e2 0%, #f5f5f5 50%, #e2e2e2 100%);
                background-size: 200% 100%; animation: shimmer 1.5s infinite linear;
            }
            .skeleton-active #content .releases-slider::before { min-height: 400px; }
        </style>
    `);
    
    // Tetap tambahkan kelas penyembunyi dan skeleton/loader
    $('body').addClass('proxy-content-hide');
    $('body').addClass('skeleton-active'); 
    
    $('html').prepend(`
        <div id="css-loader-wrapper">
            <div class="dot-loader">
                <div></div>
                <div></div>
                <div></div>
            </div>
        </div>
    `);


	
    // --- SEO ON-PAGE ---

    const originalTitle = $('title').text();
    if (originalTitle) {
        const cleanedTitle = originalTitle.replace(/\|?\s*Komikcast\.li/i, '').trim();
        $('title').text(cleanedTitle + ' | Komik Proxy Service');
    }

    $('meta').each((i, element) => {
        const $meta = $(element);
        const metaContent = $meta.attr('content');
        if (metaContent) { $meta.attr('content', replaceContentUrls(metaContent)); }
        const itemid = $meta.attr('itemid');
        if (itemid) { $meta.attr('itemid', replaceContentUrls(itemid)); }
    });

    const currentPath = req.originalUrl;
    const canonicalUrl = proxyUrl + currentPath;
    $('link[rel="canonical"]').remove();
    $('head').append(`<link rel="canonical" href="${canonicalUrl}" />`);
    
    $('script[type="application/ld+json"]').each((i, element) => {
        const $script = $(element);
        let jsonContent = $script.html();
        if (jsonContent) { $script.html(replaceContentUrls(jsonContent)); }
    });

    // --- ELEMEN REMOVAL & STYLING ---

    $('script[src*="googletagmanager"], script:contains("UA-111351430-1"), noscript, #Evo, .lmt, .textwidget').remove();
    $('.section:has(.releases:contains("Join Our Discord Server!"))').remove();
    $('.section:has(.releases:contains("Chat"))').remove();

    $('nav.mm').attr('style', 'background-color: #FFA500;');
    $('span:contains("Home"), span:contains("Daftar Komik"), span:contains("Popular"), span:contains("Project"), span:contains("Bookmark"), span:contains("History")').css('color', '#212121');
    $('div.user-navigation.login-link').css('background-color', '#FFA500');
    $('.user-navigation-menu').css('background-color', '#FFA500');

    $('.releases h3 span').css({'color': '#87CEEB'});
    $('.releases h4 span').css({'color': '#87CEEB'});

    $('ul.genre li a, a.vl, a[href="/daftar-komik/?sortby=update"]').css({
        'background-color': '#FFA500', 'color': 'black', 'border-radius': '5px', 'text-decoration': 'none', 'display': 'inline-block'
    });

    $('img[itemprop="logo"]').attr('src', 'https://komikcast.pics/wp-content/uploads/2023/06/kclogo.png');

    $('#menu-bottom span').css('color', '#fff');
    $('a.scrollToTop').css({'background-color': '#FFA500'});
    
    $('#menu-bottom a[href="https://komikcast.li/"]').attr('href', proxyUrl + '/');


    $('form#form').attr('action', proxyUrl + '/');
    $('form#form meta[itemprop="target"]').attr('content', proxyUrl + '/?s={query}');
    $('form.komiklist_filter-form').attr('action', proxyUrl + '/daftar-komik/');
    $('img').removeAttr('loading'); 


    // --- IMPLEMENTASI LAZY LOADING ---
    $('img[src]').each((i, element) => {
        const $img = $(element);
        const originalSrc = $img.attr('src');
        
        if (originalSrc && (originalSrc.startsWith(proxyUrl) || originalSrc.includes('wp-content'))) {
            $img.attr('data-src', originalSrc);
            $img.removeAttr('src'); 
            $img.addClass('proxy-lazy-load');
        }
    });

    // --- PENGGANTIAN URL KOMPREHENSIF ---
    $('[hx-post], [data-report-url]').each((i, element) => {
        const $el = $(element);
        if ($el.attr('hx-post')) { $el.attr('hx-post', replaceContentUrls($el.attr('hx-post'))); }
        if ($el.attr('data-report-url')) { $el.attr('data-report-url', replaceContentUrls($el.attr('data-report-url'))); }
    });

    $('input[name="ajax-comment-main"]').each((i, element) => {
        const $input = $(element);
        if ($input.attr('value')) { $input.attr('value', replaceContentUrls($input.attr('value'))); }
    });
    
    $('button[onclick]').each((i, element) => {
        const $button = $(element);
        const onclick = $button.attr('onclick');
        if (onclick) {
            const newOnclick = onclick.replace(combinedTargetRegex, proxyUrl);
            $button.attr('onclick', newOnclick);
        }
    });

    $('a[href*="whatsapp://send"], a[href*="pinterest.com"], a[href*="linkedin.com"], a[href*="facebook.com"], a[href*="twitter.com"]').each((i, element) => {
        const href = $(element).attr('href');
        if (href) {
            try {
                const urlObj = new URL(href);
                const params = urlObj.searchParams;
                ['url', 'u', 'text'].forEach(param => {
                    if (params.has(param)) {
                        params.set(param, replaceContentUrls(params.get(param)));
                    }
                });
                $(element).attr('href', urlObj.toString());
            } catch (e) {
                $(element).attr('href', replaceContentUrls(href));
            }
        }
    });

    $('select#slch option').each((i, element) => {
        const value = $(element).attr('value');
        if (value) { $(element).attr('value', replaceContentUrls(value)); }
    });

    $('body').append(`
        <script>
            document.addEventListener('DOMContentLoaded', () => {
                const bookmarkButton = document.getElementById('bookmark');
                if (bookmarkButton) {
                    bookmarkButton.addEventListener('click', async (e) => {
                        e.preventDefault();
                        const comicPath = window.location.pathname;

                        try {
                            const response = await fetch('/bookmark-action', {
                                method: 'POST',
                                headers: { 'Content-Type': 'application/json' },
                                body: JSON.stringify({ comicPath: comicPath })
                            });
                            const data = await response.json();
                            if (data.status === 'success') {
                                const isBookmarked = bookmarkButton.getAttribute('data-bookmarked') === 'true';
                                if (isBookmarked) {
                                    bookmarkButton.setAttribute('data-bookmarked', 'false');
                                    bookmarkButton.innerHTML = '<i class="fas fa-heart"></i> Bookmark';
                                } else {
                                    bookmarkButton.setAttribute('data-bookmarked', 'true');
                                    bookmarkButton.innerHTML = '<i class="fas fa-heart" style="color: red;"></i> Bookmarked!';
                                }
                            }
                        } catch (error) { console.error('Gagal mengirim permintaan bookmark:', error); }
                    });
                }
            });
        </script>
    `);

    $('a, script, link, img, *[src], *[href], *[content], *[itemid]').each((i, element) => { 
        const $el = $(element);
        const attributesToProcess = ['href', 'src', 'content', 'srcset', 'data-src', 'data-original', 'itemid', 'value'];

        attributesToProcess.forEach(attr => {
            const attrValue = $el.attr(attr);
            if (attrValue) {
                const newValue = replaceContentUrls(attrValue);
                $el.attr(attr, newValue);
            }
        });
        
        const href = $el.attr('href');
        if (href && href.startsWith('/') && !href.startsWith('//')) {
             $el.attr('href', proxyUrl + href);
        }
    });

    $('script:not([type="application/ld+json"])').each((i, element) => {
        const scriptContent = $(element).html();
        if (scriptContent) {
            const newScriptContent = replaceContentUrls(scriptContent);
            $(element).html(newScriptContent);
        }
    });


    // --- LOGIKA PENUTUP (TAMPILKAN KONTEN & HILANGKAN LOADER) ---
    $('body').append(`
        <script>
            // Logika ini akan dieksekusi setelah halaman dimuat dan semua konten (yang sudah diambil oleh server) tersedia.
            window.addEventListener('load', function() {
                const body = document.body;
                const loaderWrapper = document.getElementById('css-loader-wrapper');
                
                const lazyImages = document.querySelectorAll('img.proxy-lazy-load');
                lazyImages.forEach(img => {
                    const dataSrc = img.getAttribute('data-src');
                    if (dataSrc) {
                        img.src = dataSrc;
                        img.classList.remove('proxy-lazy-load');
                        img.removeAttribute('data-src');
                    }
                });

                if (body.classList.contains('proxy-content-hide')) {
                    // Hapus kelas pemblokiran dan tampilkan konten
                    body.classList.remove('proxy-content-hide');
                    body.classList.remove('skeleton-active');
                    body.classList.add('proxy-content-show');
                }

                if (loaderWrapper) {
                    loaderWrapper.style.opacity = '0';
                    setTimeout(() => {
                        loaderWrapper.style.display = 'none';
                    }, 500); 
                }
            });
        </script>
    `);

    return $.html();
};


// --- ROUTER UTAMA ---

router.use(async (req, res) => {
    const { headerAds, bodyAds } = req.adsScripts;
    
    let fullTargetUrl = `${targetUrl}${req.url}`;
    
    if (req.path === '/history/' && req.query.chapter) {
         fullTargetUrl = `${targetUrl}/chapter/${req.query.chapter}`;
    }

    const requestHeaders = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
        'Cookie': req.headers.cookie || ''
    };

    if (req.method !== 'GET') {
        try {
            const response = await axios({
                method: req.method,
                url: fullTargetUrl,
                headers: requestHeaders,
                data: req.body,
                timeout: process.env.TARGET_TIMEOUT ? parseInt(process.env.TARGET_TIMEOUT) : 15000
            });

            const { data, headers } = response;
            let finalHtml = data;

            if (headers['content-type'] && headers['content-type'].includes('text/html')) {
                const $ = cheerio.load(data);
                finalHtml = applyHtmlModifications($, headerAds, bodyAds, req); 
            }
            
            if (headers['set-cookie']) {
                res.setHeader('Set-Cookie', headers['set-cookie']);
            }

            return res.status(response.status).set(headers).send(finalHtml);

        } catch (error) {
            console.error(`Error saat memproksi permintaan ${req.method} ke URL ${fullTargetUrl}: ${error.message}`);
            return res.status(error.response?.status || 500).send('Gagal memproses permintaan dari server target.');
        }

    } else {
        try {
            const { html, headers, status } = await fetchWithRetry(fullTargetUrl, requestHeaders);

            const $ = cheerio.load(html);
            const finalHtml = applyHtmlModifications($, headerAds, bodyAds, req); 
            
            if (headers['set-cookie']) {
                res.setHeader('Set-Cookie', headers['set-cookie']);
            }

            res.status(status).set(headers).send(finalHtml);

        } catch (error) {
            console.error(`[MAIN PROXY] Gagal total setelah retry ke URL ${fullTargetUrl}: ${error.message}`);
            
            const errorMessage = '<h1>503 Service Unavailable</h1><p>Gagal mengambil konten setelah maksimal percobaan. Server target tidak merespons atau memblokir akses.</p>';
            
            res.status(503).send(`
                <html>
                <head>
                    <meta name="viewport" content="width=device-width, initial-scale=1.0">
                    <title>Error</title>
                    <style>
                        #css-loader-wrapper {
                            position: fixed; top: 0; left: 0; width: 100%; height: 100%; 
                            background-color: #212121; z-index: 99999; 
                            display: flex; justify-content: center; align-items: center; 
                            color: white; flex-direction: column; text-align: center;
                        }
                    </style>
                </head>
                <body>
                    <div id="css-loader-wrapper">
                        ${errorMessage}
                        <p style="margin-top: 20px;">Silakan coba <a href="${proxyUrl}" style="color: #FFA500; text-decoration: none;">refresh</a> halaman.</p>
                    </div>
                </body>
                </html>
            `);
        }
    }
});

module.exports = router;
