﻿function TrainsCalculator() {
    const [problemType, setProblemType] = useState('meeting');
    const [speed1, setSpeed1] = useState('');
    const [speed2, setSpeed2] = useState('');
    const [length1, setLength1] = useState('');
    const [length2, setLength2] = useState('');
    const [distance, setDistance] = useState('');
    const [result, setResult] = useState(null);

    const calculate = () => {
        const s1 = parseFloat(speed1);
        const s2 = parseFloat(speed2);
        const l1 = parseFloat(length1) || 0;
        const l2 = parseFloat(length2) || 0;
        const d = parseFloat(distance);

        let calculated = {};

        if (problemType === 'meeting') {
            // Trains meeting (opposite direction)
            const relativeSpeed = s1 + s2;
            const timeToMeet = d / relativeSpeed;
            const dist1 = s1 * timeToMeet;
            const dist2 = s2 * timeToMeet;

            calculated = {
                relativeSpeed: relativeSpeed.toFixed(2),
                timeToMeet: timeToMeet.toFixed(2),
                distance1: dist1.toFixed(2),
                distance2: dist2.toFixed(2),
                formula: 'Relative Speed = Speed₁ + Speed₂ (opposite direction)',
                calculation: `Time to meet = ${d} / (${s1} + ${s2}) = ${timeToMeet.toFixed(2)} hours`
            };
        } else if (problemType === 'crossing') {
            // Trains crossing (same direction)
            const relativeSpeed = Math.abs(s1 - s2);
            const totalLength = l1 + l2;
            const timeToCross = (totalLength / 1000) / relativeSpeed; // Convert m to km

            calculated = {
                relativeSpeed: relativeSpeed.toFixed(2),
                totalLength: totalLength,
                timeToCross: timeToCross.toFixed(2),
                timeInMinutes: (timeToCross * 60).toFixed(2),
                formula: 'Relative Speed = |Speed₁ - Speed₂| (same direction)',
                calculation: `Time = (${l1} + ${l2}) m / ${relativeSpeed} km/h = ${timeToCross.toFixed(2)} hours`
            };
        } else if (problemType === 'platform') {
            // Train crossing platform
            const totalLength = l1 + (l2 || 0);
            const timeToCross = (totalLength / 1000) / s1; // Convert m to km

            calculated = {
                totalLength: totalLength,
                timeToCross: timeToCross.toFixed(2),
                timeInSeconds: (timeToCross * 3600).toFixed(2),
                formula: 'Time = (Train Length + Platform Length) / Speed',
                calculation: `Time = ${totalLength} m / ${s1} km/h = ${timeToCross.toFixed(2)} hours = ${(timeToCross * 3600).toFixed(2)} seconds`
            };
        }

        setResult(calculated);
    };

    return (
        <div>
            <div style={{ marginBottom: '16px' }}>
                <label className="form-label">Problem Type</label>
                <select className="form-input" value={problemType} onChange={(e) => setProblemType(e.target.value)}>
                    <option value="meeting">Trains Meeting (Opposite Direction)</option>
                    <option value="crossing">Trains Crossing (Same Direction)</option>
                    <option value="platform">Train Crossing Platform/Bridge</option>
                </select>
            </div>

            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '16px' }}>
                <div className="form-group" style={{ marginBottom: '0' }}>
                    <label className="form-label">Train 1 Speed (km/h)</label>
                    <input type="number" className="form-input" value={speed1} onChange={(e) => setSpeed1(e.target.value)} placeholder="60" />
                </div>
                {problemType !== 'platform' && (
                    <div className="form-group" style={{ marginBottom: '0' }}>
                        <label className="form-label">Train 2 Speed (km/h)</label>
                        <input type="number" className="form-input" value={speed2} onChange={(e) => setSpeed2(e.target.value)} placeholder="40" />
                    </div>
                )}
                {(problemType === 'crossing' || problemType === 'platform') && (
                    <>
                        <div className="form-group" style={{ marginBottom: '0' }}>
                            <label className="form-label">Train {problemType === 'platform' ? '' : '1'} Length (m)</label>
                            <input type="number" className="form-input" value={length1} onChange={(e) => setLength1(e.target.value)} placeholder="150" />
                        </div>
                        <div className="form-group" style={{ marginBottom: '0' }}>
                            <label className="form-label">{problemType === 'platform' ? 'Platform' : 'Train 2'} Length (m)</label>
                            <input type="number" className="form-input" value={length2} onChange={(e) => setLength2(e.target.value)} placeholder="100" />
                        </div>
                    </>
                )}
                {problemType === 'meeting' && (
                    <div className="form-group" style={{ marginBottom: '0', gridColumn: 'span 2' }}>
                        <label className="form-label">Distance Between Trains (km)</label>
                        <input type="number" className="form-input" value={distance} onChange={(e) => setDistance(e.target.value)} placeholder="200" />
                    </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' }}>
                        <strong>Calculation:</strong> {result.calculation}
                    </div>
                    <div style={{ borderTop: '1px solid var(--border-color)', paddingTop: '12px', marginTop: '12px' }}>
                        {result.relativeSpeed && <div><strong>Relative Speed:</strong> {result.relativeSpeed} km/h</div>}
                        {result.timeToMeet && <div style={{ fontSize: '18px', fontWeight: '600', color: 'var(--primary)', marginTop: '8px' }}>Time to Meet: {result.timeToMeet} hours</div>}
                        {result.distance1 && <div>Train 1 covers: {result.distance1} km</div>}
                        {result.distance2 && <div>Train 2 covers: {result.distance2} km</div>}
                        {result.timeToCross && <div style={{ fontSize: '18px', fontWeight: '600', color: 'var(--primary)', marginTop: '8px' }}>Time to Cross: {result.timeToCross} hours ({result.timeInMinutes || result.timeInSeconds} {result.timeInMinutes ? 'minutes' : 'seconds'})</div>}
                        {result.totalLength && <div>Total Length: {result.totalLength} m</div>}
                    </div>
                </div>
            )}
        </div>
    );
}

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