const puppeteer = require('puppeteer');
const fs = require('fs');
const path = require('path');

(async () => {
    const screenshotDir = path.join(__dirname, 'screenshots');
    if (!fs.existsSync(screenshotDir)) {
        fs.mkdirSync(screenshotDir, { recursive: true });
    }

    const browser = await puppeteer.launch({
        headless: "new",
        args: [
            '--no-sandbox',
            '--disable-setuid-sandbox',
            '--disable-dev-shm-usage',
            '--user-data-dir=' + path.join(__dirname, 'temp_browser_data_manual')
        ],
        defaultViewport: { width: 1366, height: 768 }
    });

    const page = await browser.newPage();
    const baseUrl = 'http://localhost/shtaller-gk';

    const waitAndClick = async (selector) => {
        try {
            await page.waitForSelector(selector, { visible: true, timeout: 3000 });
            await page.click(selector);
        } catch (e) {
            console.log(`Note: Could not click ${selector}`);
        }
    };

    try {
        // --- LOGIN ---
        console.log('Navigating to Login...');
        await page.goto(`${baseUrl}/login.php`, { waitUntil: 'networkidle0' });
        if (page.url().includes('login.php')) {
            await page.type('input[name="usuario"]', 'admin');
            await page.type('input[name="password"]', 'admin123');
            await Promise.all([
                page.click('button[type="submit"]'),
                page.waitForNavigation({ waitUntil: 'networkidle0' })
            ]);
        }

        // --- MODULE 1: DASHBOARD GENERAL ---
        console.log('Capturing Module 1: Dashboard...');
        await page.goto(`${baseUrl}/index.php`, { waitUntil: 'networkidle0' });
        await new Promise(r => setTimeout(r, 1000));
        await page.screenshot({ path: path.join(screenshotDir, 'dashboard_principal.png') });

        // --- MODULE 2: CLIENTES / TURNOS ---
        console.log('Capturing Module 2: Clientes...');
        await page.goto(`${baseUrl}/clientes.php`, { waitUntil: 'networkidle0' });
        // Try to open "Nuevo Cliente" modal to show data entry
        await waitAndClick('button[data-bs-target="#modalNuevo"]');
        await new Promise(r => setTimeout(r, 800)); // Wait for modal
        await page.screenshot({ path: path.join(screenshotDir, 'gestion_clientes_turnos.png') });

        // --- MODULE 3: OPERACIONES TECNICAS ---
        console.log('Capturing Module 3: Orden Tecnica Header...');
        await page.goto(`${baseUrl}/orden_frenos.php`, { waitUntil: 'networkidle0' });
        await page.setViewport({ width: 1366, height: 800 });
        await new Promise(r => setTimeout(r, 1000));
        await page.screenshot({ path: path.join(screenshotDir, 'orden_tecnica_v2.png') });

        console.log('Capturing Module 3: Footer Totales...');
        // Add a line to make it interesting
        await waitAndClick('button.btn-add-line');
        // Scroll to bottom
        await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight));
        await new Promise(r => setTimeout(r, 800));
        await page.screenshot({ path: path.join(screenshotDir, 'footer_totales_violeta.png') });

        // --- MODULE 4: PANEL FINANCIERO ---
        console.log('Capturing Module 4: Panel Financiero...');
        await page.goto(`${baseUrl}/dashboard_financiero.php`, { waitUntil: 'networkidle0' });
        // Scroll a bit to show charts if any, or just full view
        await new Promise(r => setTimeout(r, 1000));
        await page.screenshot({ path: path.join(screenshotDir, 'panel_financiero.png') });

        // --- MODULE 5: ADMIN / AYUDA ---
        console.log('Capturing Module 5: Admin...');
        await page.goto(`${baseUrl}/admin.php`, { waitUntil: 'networkidle0' });
        await new Promise(r => setTimeout(r, 1000));
        await page.screenshot({ path: path.join(screenshotDir, 'admin_panel.png') });

        console.log('All comprehensive screenshots captured.');

    } catch (e) {
        console.error('Script Error:', e);
    } finally {
        await browser.close();
        try {
            fs.rmSync(path.join(__dirname, 'temp_browser_data_manual'), { recursive: true, force: true });
        } catch (e) { }
    }
})();
