import { test, expect } from '@playwright/test';
import { MOCK_FS_INIT_SCRIPT } from './fixtures/mock-fs-api.js';
import * as path from 'path';

const HTML_PATH = path.resolve('mdedit/dist/mdedit.html');

test.describe('Markdown Editor', () => {
    test.beforeEach(async ({ page }) => {
        await page.addInitScript(MOCK_FS_INIT_SCRIPT);
    });

    test('loads without errors', async ({ page }) => {
        // Use 'load' rather than 'networkidle' — the bundled Toast UI/Tailwind
        // scripts run inline so there is no external network activity to wait for.
        await page.goto(`file://${HTML_PATH}`, { waitUntil: 'load' });
        await page.waitForSelector('#app', { timeout: 15000 });

        // Scratchpad opens by default with welcome content seeded into the editor.
        await expect(page.locator(`.file-item[data-path="__scratchpad__"]`)).toBeVisible();
        await expect(page.locator('#content-container')).toBeVisible();

        // Add Local Directory button is present and enabled
        const addDirBtn = page.locator('#addDirectoryBtn');
        await expect(addDirBtn).toBeVisible();
        await expect(addDirBtn).not.toBeDisabled();
    });

    test('renders a file tree from a mock directory', async ({ page }) => {
        await page.goto(`file://${HTML_PATH}`, { waitUntil: 'load' });
        await page.waitForSelector('#addDirectoryBtn', { timeout: 15000 });

        // Set up mock directory before triggering the picker
        await page.evaluate(() => {
            window.__setMockDirectory('notes', [
                { name: 'readme.md', content: '# Hello\n\nWelcome.', size: 30 },
                { name: 'notes.md', content: '# Notes\n\nSome notes.', size: 25 },
            ]);
        });

        await page.locator('#addDirectoryBtn').click();

        // File tree should populate with the two files
        await page.waitForFunction(
            () => document.querySelector('#file-tree')?.children.length > 0,
            { timeout: 10000 }
        );

        const items = await page.locator('#file-tree *').count();
        expect(items).toBeGreaterThanOrEqual(2);
    });

    test('DEBUG flag is defined and console.log calls are gated', async ({ page }) => {
        const logs = [];
        page.on('console', msg => msg.type() === 'log' && logs.push(msg.text()));

        await page.goto(`file://${HTML_PATH}`, { waitUntil: 'load' });
        await page.waitForSelector('#addDirectoryBtn', { timeout: 15000 });

        const probe = await page.evaluate(() => ({
            debugDefined: typeof DEBUG !== 'undefined',
            debugValue:   typeof DEBUG !== 'undefined' ? DEBUG : null,
        }));

        expect(probe.debugDefined).toBe(true);
        expect(probe.debugValue).toBe(false);

        // With DEBUG=false, no console.log should fire from app code on load.
        // (Browser/Toast-UI may still log; we only check none of the gated lines fired.)
        const ourLogs = logs.filter(l =>
            l.startsWith('Opened scratchpad') ||
            l.startsWith('Directory selected') ||
            l.startsWith('File ') ||
            l.startsWith('Created new file')
        );
        expect(ourLogs).toEqual([]);
    });
});
