﻿function BasicCalculator({ t }) {
    const [display, setDisplay] = useState('0');
    const [prev, setPrev] = useState(null);
    const [op, setOp] = useState(null);

    const handleNumber = (num) => {
        setDisplay(display === '0' ? String(num) : display + num);
    };

    const handleOp = (operation) => {
        setPrev(parseFloat(display));
        setOp(operation);
        setDisplay('0');
    };

    const calculate = () => {
        const current = parseFloat(display);
        let result = 0;
        if (op === '+') result = prev + current;
        else if (op === '-') result = prev - current;
        else if (op === '*') result = prev * current;
        else if (op === '/') result = prev / current;
        setDisplay(String(result));
        setOp(null);
        setPrev(null);
    };

    const clear = () => {
        setDisplay('0');
        setPrev(null);
        setOp(null);
    };

    return (
        <div className="card">
            <h3 style={{ marginBottom: '16px' }}>➕ {t('tools.basicCalculator') || "Basic Calculator"}</h3>
            <div style={{ maxWidth: '300px', margin: '0 auto' }}>
                <div style={{ background: 'var(--bg-tertiary)', padding: '20px', borderRadius: '8px', marginBottom: '16px', fontSize: '32px', textAlign: 'right', fontFamily: 'monospace' }}>{display}</div>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '8px' }}>
                    {[7, 8, 9, '/'].map(btn => <button key={btn} className="btn btn-secondary" onClick={() => typeof btn === 'number' ? handleNumber(btn) : handleOp(btn)}>{btn}</button>)}
                    {[4, 5, 6, '*'].map(btn => <button key={btn} className="btn btn-secondary" onClick={() => typeof btn === 'number' ? handleNumber(btn) : handleOp(btn)}>{btn}</button>)}
                    {[1, 2, 3, '-'].map(btn => <button key={btn} className="btn btn-secondary" onClick={() => typeof btn === 'number' ? handleNumber(btn) : handleOp(btn)}>{btn}</button>)}
                    <button className="btn btn-secondary" onClick={() => handleNumber(0)}>0</button>
                    <button className="btn btn-secondary" onClick={() => handleNumber('.')}>.</button>
                    <button className="btn btn-primary" onClick={calculate}>=</button>
                    <button className="btn btn-secondary" onClick={() => handleOp('+')}>+</button>
                    <button className="btn btn-danger" onClick={clear} style={{ gridColumn: 'span 4' }}>Clear</button>
                </div>
            </div>
        </div>
    );
}

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