const escapeRegExp = (string) => {
    return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
};

const computeScore = (src) => {
    if (!src || !src.trim()) return -100; // empty => not-js
    let score = 0;

    // 1pt keywords/syntax
    const onePt = [
        'const', 'let', 'var', 'function', '=>', 'async', 'await', 'typeof', 'undefined', 'null', 'NaN', 'this', 'new', 'class', 'import', 'export', 'require', 'module.exports', 'prototype', 'Promise', 'callback'
    ];
    onePt.forEach(tok => {
        try {
            const re = tok.includes('=>') || tok.includes('.') || tok.includes('module') ? new RegExp(escapeRegExp(tok), 'g') : new RegExp('\\b' + escapeRegExp(tok) + '\\b', 'g');
            if (re.test(src)) score += 1;
        } catch (e) { }
    });

    // 2pt built-in APIs
    const twoPt = [
        'console.log', 'console.error', 'document\\.', 'window\\.', 'fetch\\(', 'setTimeout', 'setInterval', 'addEventListener', 'JSON.parse', 'JSON.stringify', 'localStorage', 'Array.from', 'Object.keys', 'Math\\.', 'Date\\.'
    ];
    twoPt.forEach(s => { if (new RegExp(s, 'g').test(src)) score += 2; });

    // 2pt syntax patterns
    const patterns = [
        /\w+\s*=>\s*/g, // arrow
        /`[^`]*`/g, // template
        /(?:const|let)\s*\{?\s*/g, // destructuring (approx)
        /\.\.\.\w+/g, // spread
        /\?\./g, // optional chaining
        /\?\s*[^:\n]+\s*:/g // ternary
    ];
    patterns.forEach(re => { if (re.test(src)) score += 2; });

    // anti-patterns deduct 3
    const anti = [
        /\bdef\s+\w+\s*:/g, /\bprint\s*\(/g, /\belif\b/g, /\bimport\s+numpy\b/g, /\bimport\s+pandas\b/g, /:\s*\n/g,
        /public\s+static/g, /System\.out/g, /\bvoid\s+main\b/g, /#include\b/g, /\bcout\b/g,
        /<\?php/g, /\becho\b/g, /\$\w+/g,
        /\bputs\b/g, /\bend\b/g,
        /fn\s+main\b/g, /println!\b/g, /let\s+mut\b/g
    ];
    anti.forEach(re => { if (re.test(src)) score -= 3; });

    return score;
};

const App = () => {
    const [state, setState] = React.useState('input'); // input | analyzing | result-js | result-notjs
    const [code, setCode] = React.useState('');
    const [now, setNow] = React.useState(new Date());

    React.useEffect(() => {
        const id = setInterval(() => setNow(new Date()), 1000);
        return () => clearInterval(id);
    }, []);

    const handleAnalyze = React.useCallback(() => {
        setState('analyzing');
    }, []);

    const handleComplete = React.useCallback(() => {
        const s = computeScore(code || '');
        if (s >= 3) setState('result-js');
        else setState('result-notjs');
    }, [code]);

    const reset = React.useCallback(() => {
        setCode('');
        setState('input');
    }, []);

    let content = null;
    if (state === 'input') {
        content = (
            <InputScreen
                value={code}
                onChange={(e) => setCode(e.target.value)}
                onAnalyze={handleAnalyze}
            />
        );
    } else if (state === 'analyzing') {
        content = (
            <AnalyzingScreen onComplete={handleComplete} code={code} />
        );
    } else if (state === 'result-js') {
        content = (
            <SuccessScreen onReset={reset} />
        );
    } else if (state === 'result-notjs') {
        content = (
            <ErrorScreen onReset={reset} />
        );
    }

    return (
        <div className="app">
            <div className="status-bar">
                <div className="status-left">
                    <svg width="18" height="18" viewBox="0 0 630 630" xmlns="http://www.w3.org/2000/svg" style={{ marginRight: 8, borderRadius: 2 }}>
                        <rect width="630" height="630" fill="#f7df1e" />
                        <path d="m423.7 492.19c12.69 20.72 29.2 35.92 58.4 35.92 24.53 0 40.2-12.26 40.2-29.2 0-20.3-16.1-27.49-43.1-39.3l-14.8-6.35c-42.72-18.2-71.1-41-71.1-89.2 0-44.4 33.83-78.2 86.7-78.2 37.64 0 64.7 13.1 84.23 47.4l-46.1 29.6c-10.15-18.2-21.1-25.37-38.1-25.37-17.34 0-28.33 9.3-28.33 21.601 0 16.5 10.15 23.25 34.25 33.8l14.8 6.35c52.87 22.83 82.05 45.25 82.05 97.26 0 54.98-44.4 83.3-98.5 83.3-58.37 0-91.34-29.2-106.6-57.7zm-141.5-185.34h54.1v238.13c0 39.75-21.6 57.1-59.6 57.1-23.7 0-43.601-7.6-55.45-21.15l31.3-18.6c6.75 8.45 13.55 12.25 24.1 12.25 15.25 0 20.3-7.2 20.3-25.8v-241.93z" fill="#000" />
                    </svg>
                    notjs@analyzer:~$
                </div>
                <div className="status-right">{now.toLocaleString()}</div>
            </div>

            <div className="terminal">
                <Header />
                <Body>{content}</Body>
            </div>

            <div className="app-footer">
                Developed by <a href="https://github.com/rohan-shridhar" target="_blank" rel="noopener noreferrer" style={{ color: 'inherit', fontWeight: 'bold', textDecoration: 'underline' }}>@rohan-shridhar</a>. Built with bias. Powered by JavaScript supremacy.
            </div>
        </div>
    );
}