﻿function ScientificCalculator({ t }) {
    const [display, setDisplay] = useState('0');
    const [expression, setExpression] = useState('');
    const [memory, setMemory] = useState(0);
    const [angleMode, setAngleMode] = useState('deg'); // deg or rad

    const appendToDisplay = (value) => {
        if (display === '0' && value !== '.') {
            setDisplay(value);
        } else {
            setDisplay(display + value);
        }
    };

    const appendToExpression = (value) => {
        setExpression(expression + value);
        setDisplay('0');
    };

    const clear = () => {
        setDisplay('0');
        setExpression('');
    };

    const backspace = () => {
        if (display.length > 1) {
            setDisplay(display.slice(0, -1));
        } else {
            setDisplay('0');
        }
    };

    const calculate = () => {
        try {
            const fullExpression = expression + display;
            const result = eval(fullExpression);
            setDisplay(String(result));
            setExpression('');
        } catch (error) {
            setDisplay('Error');
            setExpression('');
        }
    };

    const scientificFunction = (fn) => {
        try {
            let x = parseFloat(display);
            let result;

            // Convert to radians if in degree mode for trig functions
            if (angleMode === 'deg' && ['sin', 'cos', 'tan'].includes(fn)) {
                x = x * (Math.PI / 180);
            }

            switch (fn) {
                case 'sin': result = Math.sin(x); break;
                case 'cos': result = Math.cos(x); break;
                case 'tan': result = Math.tan(x); break;
                case 'asin': result = Math.asin(x) * (angleMode === 'deg' ? 180 / Math.PI : 1); break;
                case 'acos': result = Math.acos(x) * (angleMode === 'deg' ? 180 / Math.PI : 1); break;
                case 'atan': result = Math.atan(x) * (angleMode === 'deg' ? 180 / Math.PI : 1); break;
                case 'log': result = Math.log10(x); break;
                case 'ln': result = Math.log(x); break;
                case 'sqrt': result = Math.sqrt(x); break;
                case 'square': result = x * x; break;
                case 'cube': result = x * x * x; break;
                case 'factorial':
                    result = 1;
                    for (let i = 2; i <= x; i++) result *= i;
                    break;
                case 'inverse': result = 1 / x; break;
                case 'abs': result = Math.abs(x); break;
                case 'exp': result = Math.exp(x); break;
                default: result = x;
            }
            setDisplay(String(result));
        } catch (error) {
            setDisplay('Error');
        }
    };

    const handleOperator = (op) => {
        setExpression(expression + display + op);
        setDisplay('0');
    };

    const insertConstant = (constant) => {
        setDisplay(String(constant));
    };

    const memoryAdd = () => setMemory(memory + parseFloat(display));
    const memorySubtract = () => setMemory(memory - parseFloat(display));
    const memoryRecall = () => setDisplay(String(memory));
    const memoryClear = () => setMemory(0);

    return (
        <div className="card">
            <h3 style={{ marginBottom: '16px' }}>🔬 {t('tools.scientificCalculator') || "Scientific Calculator"}</h3>
            <div style={{ maxWidth: '500px', margin: '0 auto' }}>
                {/* Display */}
                <div style={{ marginBottom: '12px' }}>
                    <div style={{ background: 'var(--bg-tertiary)', padding: '8px 12px', borderRadius: '8px', marginBottom: '4px', fontSize: '14px', color: 'var(--text-secondary)', minHeight: '24px', textAlign: 'right', fontFamily: 'monospace' }}>
                        {expression || '\u00A0'}
                    </div>
                    <div style={{ background: 'var(--bg-tertiary)', padding: '16px', borderRadius: '8px', fontSize: '32px', textAlign: 'right', fontFamily: 'monospace', fontWeight: '600' }}>
                        {display}
                    </div>
                </div>

                {/* Mode and Memory Indicators */}
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '12px', fontSize: '12px' }}>
                    <div>
                        <button
                            className="btn btn-secondary"
                            onClick={() => setAngleMode(angleMode === 'deg' ? 'rad' : 'deg')}
                            style={{ padding: '4px 12px', fontSize: '12px' }}
                        >
                            {angleMode.toUpperCase()}
                        </button>
                    </div>
                    <div style={{ color: 'var(--text-secondary)', padding: '4px 8px' }}>
                        {memory !== 0 && `M: ${memory}`}
                    </div>
                </div>

                {/* Calculator Buttons */}
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '6px' }}>
                    {/* Row 1: Memory and Clear */}
                    <button className="btn btn-secondary" onClick={memoryClear} style={{ fontSize: '13px' }}>MC</button>
                    <button className="btn btn-secondary" onClick={memoryRecall} style={{ fontSize: '13px' }}>MR</button>
                    <button className="btn btn-secondary" onClick={memoryAdd} style={{ fontSize: '13px' }}>M+</button>
                    <button className="btn btn-secondary" onClick={memorySubtract} style={{ fontSize: '13px' }}>M-</button>
                    <button className="btn btn-danger" onClick={clear} style={{ fontSize: '13px' }}>C</button>

                    {/* Row 2: Scientific Functions */}
                    <button className="btn btn-secondary" onClick={() => scientificFunction('sin')} style={{ fontSize: '13px' }}>sin</button>
                    <button className="btn btn-secondary" onClick={() => scientificFunction('cos')} style={{ fontSize: '13px' }}>cos</button>
                    <button className="btn btn-secondary" onClick={() => scientificFunction('tan')} style={{ fontSize: '13px' }}>tan</button>
                    <button className="btn btn-secondary" onClick={() => appendToDisplay('(')} style={{ fontSize: '13px' }}>(</button>
                    <button className="btn btn-secondary" onClick={() => appendToDisplay(')')} style={{ fontSize: '13px' }}>)</button>

                    {/* Row 3: More Scientific Functions */}
                    <button className="btn btn-secondary" onClick={() => scientificFunction('asin')} style={{ fontSize: '13px' }}>sin⁻¹</button>
                    <button className="btn btn-secondary" onClick={() => scientificFunction('acos')} style={{ fontSize: '13px' }}>cos⁻¹</button>
                    <button className="btn btn-secondary" onClick={() => scientificFunction('atan')} style={{ fontSize: '13px' }}>tan⁻¹</button>
                    <button className="btn btn-secondary" onClick={() => scientificFunction('square')} style={{ fontSize: '13px' }}>x²</button>
                    <button className="btn btn-secondary" onClick={() => scientificFunction('sqrt')} style={{ fontSize: '13px' }}>√</button>

                    {/* Row 4: Advanced Functions */}
                    <button className="btn btn-secondary" onClick={() => scientificFunction('log')} style={{ fontSize: '13px' }}>log</button>
                    <button className="btn btn-secondary" onClick={() => scientificFunction('ln')} style={{ fontSize: '13px' }}>ln</button>
                    <button className="btn btn-secondary" onClick={() => scientificFunction('exp')} style={{ fontSize: '13px' }}>eˣ</button>
                    <button className="btn btn-secondary" onClick={() => scientificFunction('cube')} style={{ fontSize: '13px' }}>x³</button>
                    <button className="btn btn-secondary" onClick={() => handleOperator('^')} style={{ fontSize: '13px' }}>xʸ</button>

                    {/* Row 5: Numbers and Operations */}
                    <button className="btn btn-secondary" onClick={() => appendToDisplay('7')}>7</button>
                    <button className="btn btn-secondary" onClick={() => appendToDisplay('8')}>8</button>
                    <button className="btn btn-secondary" onClick={() => appendToDisplay('9')}>9</button>
                    <button className="btn btn-secondary" onClick={() => handleOperator('/')}>/</button>
                    <button className="btn btn-secondary" onClick={backspace} style={{ fontSize: '13px' }}>←</button>

                    <button className="btn btn-secondary" onClick={() => appendToDisplay('4')}>4</button>
                    <button className="btn btn-secondary" onClick={() => appendToDisplay('5')}>5</button>
                    <button className="btn btn-secondary" onClick={() => appendToDisplay('6')}>6</button>
                    <button className="btn btn-secondary" onClick={() => handleOperator('*')}>×</button>
                    <button className="btn btn-secondary" onClick={() => scientificFunction('factorial')} style={{ fontSize: '13px' }}>n!</button>

                    <button className="btn btn-secondary" onClick={() => appendToDisplay('1')}>1</button>
                    <button className="btn btn-secondary" onClick={() => appendToDisplay('2')}>2</button>
                    <button className="btn btn-secondary" onClick={() => appendToDisplay('3')}>3</button>
                    <button className="btn btn-secondary" onClick={() => handleOperator('-')}>-</button>
                    <button className="btn btn-secondary" onClick={() => scientificFunction('inverse')} style={{ fontSize: '13px' }}>1/x</button>

                    <button className="btn btn-secondary" onClick={() => appendToDisplay('0')}>0</button>
                    <button className="btn btn-secondary" onClick={() => appendToDisplay('.')}>.</button>
                    <button className="btn btn-primary" onClick={calculate} style={{ gridColumn: 'span 2' }}>=</button>
                    <button className="btn btn-secondary" onClick={() => handleOperator('+')}>+</button>

                    {/* Row 6: Constants */}
                    <button className="btn btn-secondary" onClick={() => insertConstant(Math.PI)} style={{ fontSize: '13px', gridColumn: 'span 2' }}>π</button>
                    <button className="btn btn-secondary" onClick={() => insertConstant(Math.E)} style={{ fontSize: '13px', gridColumn: 'span 2' }}>e</button>
                    <button className="btn btn-secondary" onClick={() => scientificFunction('abs')} style={{ fontSize: '13px' }}>|x|</button>
                </div>
            </div>
        </div>
    );
}

// Export to global registry
window.ScientificCalculator = ScientificCalculator;
