﻿function AverageSpeedCalculator() {
    const [type, setType] = useState('equal_distance');
    const [speed1, setSpeed1] = useState('');
    const [speed2, setSpeed2] = useState('');
    const [distance1, setDistance1] = useState('');
    const [distance2, setDistance2] = useState('');
    const [time1, setTime1] = useState('');
    const [time2, setTime2] = useState('');
    const [result, setResult] = useState(null);

    const calculate = () => {
        const s1 = parseFloat(speed1);
        const s2 = parseFloat(speed2);
        let calculated = {};

        if (type === 'equal_distance') {
            // Harmonic mean for equal distances
            const avgSpeed = (2 * s1 * s2) / (s1 + s2);
            calculated = {
                avgSpeed: avgSpeed.toFixed(2),
                formula: 'Average Speed = 2 × S₁ × S₂ / (S₁ + S₂) [Harmonic Mean]',
                calculation: `Avg Speed = 2 × ${s1} × ${s2} / (${s1} + ${s2}) = ${avgSpeed.toFixed(2)} km/h`,
                note: 'Used when equal distances are covered at different speeds'
            };
        } else if (type === 'different_distance') {
            const d1 = parseFloat(distance1);
            const d2 = parseFloat(distance2);
            const totalDist = d1 + d2;
            const totalTime = (d1 / s1) + (d2 / s2);
            const avgSpeed = totalDist / totalTime;

            calculated = {
                avgSpeed: avgSpeed.toFixed(2),
                totalDistance: totalDist,
                totalTime: totalTime.toFixed(2),
                formula: 'Average Speed = Total Distance / Total Time',
                calculation: `Total Distance = ${d1} + ${d2} = ${totalDist} km\nTotal Time = ${d1}/${s1} + ${d2}/${s2} = ${totalTime.toFixed(2)} hours\nAvg Speed = ${totalDist} / ${totalTime.toFixed(2)} = ${avgSpeed.toFixed(2)} km/h`
            };
        } else {
            const t1 = parseFloat(time1);
            const t2 = parseFloat(time2);
            const totalDist = (s1 * t1) + (s2 * t2);
            const totalTime = t1 + t2;
            const avgSpeed = totalDist / totalTime;

            calculated = {
                avgSpeed: avgSpeed.toFixed(2),
                totalDistance: totalDist.toFixed(2),
                totalTime: totalTime,
                formula: 'Average Speed = Total Distance / Total Time',
                calculation: `Total Distance = (${s1} × ${t1}) + (${s2} × ${t2}) = ${totalDist.toFixed(2)} km\nTotal Time = ${t1} + ${t2} = ${totalTime} hours\nAvg Speed = ${totalDist.toFixed(2)} / ${totalTime} = ${avgSpeed.toFixed(2)} km/h`
            };
        }

        setResult(calculated);
    };

    return (
        <div>
            <div style={{ marginBottom: '16px' }}>
                <label className="form-label">Problem Type</label>
                <select className="form-input" value={type} onChange={(e) => setType(e.target.value)}>
                    <option value="equal_distance">Equal Distances, Different Speeds</option>
                    <option value="different_distance">Different Distances, Different Speeds</option>
                    <option value="different_time">Different Times, Different Speeds</option>
                </select>
            </div>

            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '16px' }}>
                <div className="form-group" style={{ marginBottom: '0' }}>
                    <label className="form-label">Speed 1 (km/h)</label>
                    <input type="number" className="form-input" value={speed1} onChange={(e) => setSpeed1(e.target.value)} placeholder="60" />
                </div>
                <div className="form-group" style={{ marginBottom: '0' }}>
                    <label className="form-label">Speed 2 (km/h)</label>
                    <input type="number" className="form-input" value={speed2} onChange={(e) => setSpeed2(e.target.value)} placeholder="40" />
                </div>

                {type === 'different_distance' && (
                    <>
                        <div className="form-group" style={{ marginBottom: '0' }}>
                            <label className="form-label">Distance 1 (km)</label>
                            <input type="number" className="form-input" value={distance1} onChange={(e) => setDistance1(e.target.value)} placeholder="120" />
                        </div>
                        <div className="form-group" style={{ marginBottom: '0' }}>
                            <label className="form-label">Distance 2 (km)</label>
                            <input type="number" className="form-input" value={distance2} onChange={(e) => setDistance2(e.target.value)} placeholder="80" />
                        </div>
                    </>
                )}

                {type === 'different_time' && (
                    <>
                        <div className="form-group" style={{ marginBottom: '0' }}>
                            <label className="form-label">Time 1 (hours)</label>
                            <input type="number" className="form-input" value={time1} onChange={(e) => setTime1(e.target.value)} placeholder="2" />
                        </div>
                        <div className="form-group" style={{ marginBottom: '0' }}>
                            <label className="form-label">Time 2 (hours)</label>
                            <input type="number" className="form-input" value={time2} onChange={(e) => setTime2(e.target.value)} placeholder="3" />
                        </div>
                    </>
                )}
            </div>

            <button className="btn btn-primary mt-4" onClick={calculate}>Calculate</button>

            {result && (
                <div className="mt-4" style={{ padding: '20px', background: 'var(--bg-tertiary)', borderRadius: '8px' }}>
                    <div style={{ marginBottom: '12px' }}>
                        <strong>Formula:</strong> {result.formula}
                    </div>
                    <div style={{ marginBottom: '12px', whiteSpace: 'pre-line' }}>
                        <strong>Calculation:</strong><br />{result.calculation}
                    </div>
                    {result.note && (
                        <div style={{ marginBottom: '12px', fontSize: '13px', color: 'var(--text-secondary)', fontStyle: 'italic' }}>
                            Note: {result.note}
                        </div>
                    )}
                    <div style={{ borderTop: '1px solid var(--border-color)', paddingTop: '12px', marginTop: '12px' }}>
                        <div style={{ fontSize: '20px', fontWeight: '700', color: 'var(--primary)' }}>Average Speed: {result.avgSpeed} km/h</div>
                        {result.totalDistance && <div className="mt-2">Total Distance: {result.totalDistance} km</div>}
                        {result.totalTime && <div>Total Time: {result.totalTime} hours</div>}
                    </div>
                </div>
            )}
        </div>
    );
}

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