﻿function ShapePackingCalculator() {
    const [mode, setMode] = useState('2d'); // 2d or 3d
    const [containerType, setContainerType] = useState('rectangle');
    const [itemType, setItemType] = useState('rectangle');
    const [cWidth, setCWidth] = useState('100');
    const [cHeight, setCHeight] = useState('100');
    const [cDepth, setCDepth] = useState('100');
    const [iWidth, setIWidth] = useState('10');
    const [iHeight, setIHeight] = useState('10');
    const [iDepth, setIDepth] = useState('10');
    const [allowRotation, setAllowRotation] = useState(true);
    const [result, setResult] = useState(null);

    const calculate = () => {
        const cw = parseFloat(cWidth);
        const ch = parseFloat(cHeight);
        const cd = parseFloat(cDepth);
        const iw = parseFloat(iWidth);
        const ih = parseFloat(iHeight);
        const id = parseFloat(iDepth);

        let count = 0;
        let efficiency = 0;

        if (mode === '2d') {
            if (containerType === 'rectangle') {
                if (itemType === 'rectangle') {
                    // Try both orientations to maximize
                    const count1 = Math.floor(cw / iw) * Math.floor(ch / ih);
                    const count2 = allowRotation ? Math.floor(cw / ih) * Math.floor(ch / iw) : 0;

                    let bestCount = Math.max(count1, count2);

                    if (allowRotation) {
                        // Try 2-block split packing (Vertical split)
                        for (let splitW = 0; splitW <= cw; splitW += Math.min(iw, ih)) {
                            const part1 = Math.floor(splitW / iw) * Math.floor(ch / ih) +
                                Math.floor((cw - splitW) / ih) * Math.floor(ch / iw);
                            const part2 = Math.floor(splitW / ih) * Math.floor(ch / iw) +
                                Math.floor((cw - splitW) / iw) * Math.floor(ch / ih);
                            bestCount = Math.max(bestCount, part1, part2);
                        }
                        // Try 2-block split packing (Horizontal split)
                        for (let splitH = 0; splitH <= ch; splitH += Math.min(iw, ih)) {
                            const part1 = Math.floor(cw / iw) * Math.floor(splitH / ih) +
                                Math.floor(cw / ih) * Math.floor((ch - splitH) / iw);
                            const part2 = Math.floor(cw / ih) * Math.floor(splitH / iw) +
                                Math.floor(cw / iw) * Math.floor((ch - splitH) / ih);
                            bestCount = Math.max(bestCount, part1, part2);
                        }
                    }

                    count = bestCount;
                    efficiency = ((count * iw * ih) / (cw * ch) * 100).toFixed(2);
                } else if (itemType === 'circle') {
                    const r = iw / 2;
                    const d = iw;
                    const sqCount = Math.floor(cw / d) * Math.floor(ch / d);
                    const rowDist = d * Math.sqrt(3) / 2;
                    const rows = Math.floor((ch - d) / rowDist) + 1;
                    const colsEven = Math.floor(cw / d);
                    const colsOdd = Math.floor((cw - r) / d);
                    const hexCount = Math.floor(rows / 2) * colsEven + Math.ceil(rows / 2) * colsOdd;

                    count = Math.max(sqCount, hexCount);
                    efficiency = ((count * Math.PI * r * r) / (cw * ch) * 100).toFixed(2);
                }
            }
        } else {
            const containerVol = cw * ch * cd;
            if (itemType === 'rectangle') {
                const orientations = [
                    [iw, ih, id], [iw, id, ih], [ih, iw, id],
                    [ih, id, iw], [id, iw, ih], [id, ih, iw]
                ];
                let bestCount = 0;
                const activeOrientations = allowRotation ? orientations : [orientations[0]];
                activeOrientations.forEach(([w, h, d]) => {
                    const c = Math.floor(cw / w) * Math.floor(ch / h) * Math.floor(cd / d);
                    if (c > bestCount) bestCount = c;
                });
                count = bestCount;
                efficiency = ((count * iw * ih * id) / containerVol * 100).toFixed(2);
            } else if (itemType === 'circle') {
                const r = iw / 2;
                const d = iw;
                const scCount = Math.floor(cw / d) * Math.floor(ch / d) * Math.floor(cd / d);
                const fccCount = Math.floor(Math.PI / (3 * Math.sqrt(2)) * (containerVol / (4 / 3 * Math.PI * r ** 3)));
                count = Math.max(scCount, Math.floor(fccCount * 0.95));
                efficiency = ((count * (4 / 3) * Math.PI * r ** 3) / containerVol * 100).toFixed(2);
            }
        }
        setResult({ count, efficiency });
    };

    return (
        <div className="card fade-in">
            <h3 style={{ marginBottom: '16px' }}>📦 Advanced Shape Packing ({mode.toUpperCase()})</h3>
            <div style={{ display: 'flex', gap: '8px', marginBottom: '20px' }}>
                <button onClick={() => setMode('2d')} className={`btn ${mode === '2d' ? 'btn-primary' : 'btn-secondary'}`} style={{ flex: 1 }}>2D Plane</button>
                <button onClick={() => setMode('3d')} className={`btn ${mode === '3d' ? 'btn-primary' : 'btn-secondary'}`} style={{ flex: 1 }}>3D Volume</button>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
                <div className="form-group">
                    <label className="form-label">Container Type</label>
                    <select className="form-input" value={containerType} onChange={(e) => setContainerType(e.target.value)}>
                        <option value="rectangle">{mode === '2d' ? 'Rectangle' : 'Box (Prism)'}</option>
                    </select>
                </div>
                <div className="form-group">
                    <label className="form-label">Item Type</label>
                    <select className="form-input" value={itemType} onChange={(e) => setItemType(e.target.value)}>
                        <option value="rectangle">{mode === '2d' ? 'Rectangle' : 'Box'}</option>
                        <option value="circle">{mode === '2d' ? 'Circle' : 'Sphere'}</option>
                    </select>
                </div>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '12px' }}>
                <div className="form-group">
                    <label className="form-label">Cont. Width</label>
                    <input type="number" className="form-input" value={cWidth} onChange={(e) => setCWidth(e.target.value)} />
                </div>
                <div className="form-group">
                    <label className="form-label">Cont. Height</label>
                    <input type="number" className="form-input" value={cHeight} onChange={(e) => setCHeight(e.target.value)} />
                </div>
                {mode === '3d' && (
                    <div className="form-group">
                        <label className="form-label">Cont. Depth</label>
                        <input type="number" className="form-input" value={cDepth} onChange={(e) => setCDepth(e.target.value)} />
                    </div>
                )}
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: itemType === 'rectangle' ? 'repeat(3, 1fr)' : '1fr', gap: '12px' }}>
                <div className="form-group">
                    <label className="form-label">{itemType === 'rectangle' ? 'Item Width' : 'Diameter'}</label>
                    <input type="number" className="form-input" value={iWidth} onChange={(e) => setIWidth(e.target.value)} />
                </div>
                {itemType === 'rectangle' && (
                    <div className="form-group">
                        <label className="form-label">Item Height</label>
                        <input type="number" className="form-input" value={iHeight} onChange={(e) => setIHeight(e.target.value)} />
                    </div>
                )}
                {itemType === 'rectangle' && mode === '3d' && (
                    <div className="form-group">
                        <label className="form-label">Item Depth</label>
                        <input type="number" className="form-input" value={iDepth} onChange={(e) => setIDepth(e.target.value)} />
                    </div>
                )}
            </div>
            {itemType === 'rectangle' && (
                <div className="form-group" style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                    <input type="checkbox" checked={allowRotation} onChange={(e) => setAllowRotation(e.target.checked)} id="rot" />
                    <label htmlFor="rot" style={{ fontSize: '14px', cursor: 'pointer' }}>Allow Mixed Orientation / Rotation</label>
                </div>
            )}
            <button className="btn btn-primary" onClick={calculate} style={{ width: '100%' }}>Calculate Packing</button>
            {result && (
                <div className="mt-4" style={{ padding: '24px', background: 'var(--bg-tertiary)', borderRadius: '12px', border: '1px solid var(--primary-light)' }}>
                    <div style={{ textAlign: 'center' }}>
                        <div style={{ fontSize: '14px', color: 'var(--text-secondary)', marginBottom: '4px' }}>ESTIMATED COUNT</div>
                        <div style={{ fontSize: '42px', fontWeight: '800', color: 'var(--primary)', lineHeight: '1' }}>{result.count}</div>
                        <div style={{ fontSize: '14px', color: 'var(--text-tertiary)', marginTop: '8px' }}>items fit in container</div>
                    </div>
                    <div style={{ marginTop: '20px', paddingTop: '16px', borderTop: '1px solid var(--border-color)' }}>
                        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>
                            <span style={{ fontSize: '14px', color: 'var(--text-secondary)' }}>Efficiency:</span>
                            <span style={{ fontSize: '14px', fontWeight: '700', color: result.efficiency > 80 ? 'var(--success)' : 'var(--text-primary)' }}>{result.efficiency}%</span>
                        </div>
                        <div style={{ height: '8px', background: 'var(--gray-200)', borderRadius: '4px', overflow: 'hidden' }}>
                            <div style={{ height: '100%', width: `${result.efficiency}%`, background: 'var(--primary)', borderRadius: '4px' }}></div>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}

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