<?php include "../autoload.php"; ?>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600;700&display=swap');
        .gradient-bg {
            background: linear-gradient(135deg, #1e40af 0%, #60a5fa 100%);
        }
        .result-card {
            background: linear-gradient(145deg, #ffffff, #f0f7ff);
            box-shadow: 0 12px 24px rgba(0, 0, 0, 0.15);
            transition: transform 0.3s ease, opacity 0.3s ease;
        }
        .result-card.hidden {
            transform: translateY(20px);
            opacity: 0;
        }
        .result-card:not(.hidden) {
            transform: translateY(0);
            opacity: 1;
        }
        .input-container {
            background: linear-gradient(145deg, #ffffff, #f9fafb);
            transition: all 0.3s ease;
        }
        .input-container:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 12px rgba(0, 0, 0, 0.1);
        }
        .range-input::-webkit-slider-thumb {
            -webkit-appearance: none;
            appearance: none;
            width: 20px;
            height: 20px;
            background: #1e40af;
            border-radius: 50%;
            cursor: pointer;
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
        }
        .range-input::-moz-range-thumb {
            width: 20px;
            height: 20px;
            background: #1e40af;
            border-radius: 50%;
            cursor: pointer;
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
        }
        .btn-primary {
            transition: all 0.3s ease;
        }
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2);
        }
        .visual-container {
            background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100"><rect fill="%23f3f4f6" width="100" height="100"/><circle cx="50" cy="50" r="30" fill="%23dbeafe" opacity="0.5"/></svg>') repeat;
            border-radius: 12px;
            box-shadow: inset 0 2px 8px rgba(0, 0, 0, 0.05);
        }
        select {
            appearance: none;
            background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24"><path fill="%234b5563" d="M7 10l5 5 5-5H7z"/></svg>');
            background-repeat: no-repeat;
            background-position: right 0.75rem center;
            background-size: 12px;
        }
    </style>

    <div class="x">
        <div class="x">
            <!-- Input Form -->
            <div class="mb-12">
                <h2 class="text-3xl font-semibold text-gray-800 mb-6">Enter Your Bunk/Loft Bed & Bedroom Details</h2>
                <p class="text-gray-500 mb-8 text-lg">Input bed dimensions, room size, and clearances to check if the bunk or loft bed fits with sufficient ceiling clearance.</p>
                <form id="bedFitForm" class="space-y-8">
                    <div class="grid grid-cols-1 md:grid-cols-4 gap-6">
                        <div class="space-y-3">
                            <label for="bedType" class="block text-sm font-medium text-gray-700">Bed Type</label>
                            <div class="relative flex items-center">
                                <i data-lucide="bed" class="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                                <select id="bedType" class="pl-12 pr-10 py-3 block w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-600 focus:ring focus:ring-blue-600 focus:ring-opacity-50 text-lg" required>
                                    <option value="Bunk Bed" selected>Bunk Bed</option>
                                    <option value="Loft Bed">Loft Bed</option>
                                </select>
                            </div>
                        </div>
                        <div class="space-y-3">
                            <label for="bedWidth" class="block text-sm font-medium text-gray-700">Bed Width (ft)</label>
                            <div class="relative flex items-center">
                                <i data-lucide="expand" class="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                                <input type="number" id="bedWidth" class="pl-12 pr-4 py-3 block w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-600 focus:ring focus:ring-blue-600 focus:ring-opacity-50 text-lg" placeholder="3.5" step="0.1" min="3" max="6" value="3.5" required>
                            </div>
                            <input type="range" id="bedWidthRange" class="range-input w-full h-2 bg-gray-200 rounded-lg cursor-pointer" min="3" max="6" step="0.1" value="3.5">
                            <p id="bedWidthValue" class="text-sm text-gray-500">3.5 ft</p>
                        </div>
                        <div class="space-y-3">
                            <label for="bedLength" class="block text-sm font-medium text-gray-700">Bed Length (ft)</label>
                            <div class="relative flex items-center">
                                <i data-lucide="expand" class="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                                <input type="number" id="bedLength" class="pl-12 pr-4 py-3 block w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-600 focus:ring focus:ring-blue-600 focus:ring-opacity-50 text-lg" placeholder="6.5" step="0.1" min="6" max="8" value="6.5" required>
                            </div>
                            <input type="range" id="bedLengthRange" class="range-input w-full h-2 bg-gray-200 rounded-lg cursor-pointer" min="6" max="8" step="0.1" value="6.5">
                            <p id="bedLengthValue" class="text-sm text-gray-500">6.5 ft</p>
                        </div>
                        <div class="space-y-3">
                            <label for="bedHeight" class="block text-sm font-medium text-gray-700">Bed Height (ft)</label>
                            <div class="relative flex items-center">
                                <i data-lucide="ruler" class="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                                <input type="number" id="bedHeight" class="pl-12 pr-4 py-3 block w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-600 focus:ring focus:ring-blue-600 focus:ring-opacity-50 text-lg" placeholder="5.0" step="0.1" min="4" max="6" value="5.0" required>
                            </div>
                            <input type="range" id="bedHeightRange" class="range-input w-full h-2 bg-gray-200 rounded-lg cursor-pointer" min="4" max="6" step="0.1" value="5.0">
                            <p id="bedHeightValue" class="text-sm text-gray-500">5.0 ft</p>
                        </div>
                    </div>
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                        <div class="space-y-3">
                            <label for="roomWidth" class="block text-sm font-medium text-gray-700">Room Width (ft)</label>
                            <div class="relative flex items-center">
                                <i data-lucide="home" class="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                                <input type="number" id="roomWidth" class="pl-12 pr-4 py-3 block w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-600 focus:ring focus:ring-blue-600 focus:ring-opacity-50 text-lg" placeholder="10.0" step="0.1" min="8" max="20" value="10.0" required>
                            </div>
                            <input type="range" id="roomWidthRange" class="range-input w-full h-2 bg-gray-200 rounded-lg cursor-pointer" min="8" max="20" step="0.1" value="10.0">
                            <p id="roomWidthValue" class="text-sm text-gray-500">10.0 ft</p>
                        </div>
                        <div class="space-y-3">
                            <label for="roomLength" class="block text-sm font-medium text-gray-700">Room Length (ft)</label>
                            <div class="relative flex items-center">
                                <i data-lucide="home" class="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                                <input type="number" id="roomLength" class="pl-12 pr-4 py-3 block w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-600 focus:ring focus:ring-blue-600 focus:ring-opacity-50 text-lg" placeholder="12.0" step="0.1" min="8" max="20" value="12.0" required>
                            </div>
                            <input type="range" id="roomLengthRange" class="range-input w-full h-2 bg-gray-200 rounded-lg cursor-pointer" min="8" max="20" step="0.1" value="12.0">
                            <p id="roomLengthValue" class="text-sm text-gray-500">12.0 ft</p>
                        </div>
                        <div class="space-y-3">
                            <label for="ceilingHeight" class="block text-sm font-medium text-gray-700">Ceiling Height (ft)</label>
                            <div class="relative flex items-center">
                                <i data-lucide="ruler" class="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                                <input type="number" id="ceilingHeight" class="pl-12 pr-4 py-3 block w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-600 focus:ring focus:ring-blue-600 focus:ring-opacity-50 text-lg" placeholder="8.0" step="0.1" min="7" max="12" value="8.0" required>
                            </div>
                            <input type="range" id="ceilingHeightRange" class="range-input w-full h-2 bg-gray-200 rounded-lg cursor-pointer" min="7" max="12" step="0.1" value="8.0">
                            <p id="ceilingHeightValue" class="text-sm text-gray-500">8.0 ft</p>
                        </div>
                    </div>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div class="space-y-3">
                            <label for="floorClearance" class="block text-sm font-medium text-gray-700">Floor Clearance Around Bed (ft)</label>
                            <div class="relative flex items-center">
                                <i data-lucide="hand" class="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                                <input type="number" id="floorClearance" class="pl-12 pr-4 py-3 block w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-600 focus:ring focus:ring-blue-600 focus:ring-opacity-50 text-lg" placeholder="2.0" step="0.1" min="1" max="3" value="2.0" required>
                            </div>
                            <input type="range" id="floorClearanceRange" class="range-input w-full h-2 bg-gray-200 rounded-lg cursor-pointer" min="1" max="3" step="0.1" value="2.0">
                            <p id="floorClearanceValue" class="text-sm text-gray-500">2.0 ft</p>
                        </div>
                        <div class="space-y-3">
                            <label for="ceilingClearance" class="block text-sm font-medium text-gray-700">Ceiling Clearance Above Bed (ft)</label>
                            <div class="relative flex items-center">
                                <i data-lucide="hand" class="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                                <input type="number" id="ceilingClearance" class="pl-12 pr-4 py-3 block w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-600 focus:ring focus:ring-blue-600 focus:ring-opacity-50 text-lg" placeholder="2.0" step="0.1" min="1.5" max="3" value="2.0" required>
                            </div>
                            <input type="range" id="ceilingClearanceRange" class="range-input w-full h-2 bg-gray-200 rounded-lg cursor-pointer" min="1.5" max="3" step="0.1" value="2.0">
                            <p id="ceilingClearanceValue" class="text-sm text-gray-500">2.0 ft</p>
                        </div>
                    </div>
                    <button type="submit" class="btn-primary w-full bg-blue-600 text-white py-4 px-8 rounded-xl hover:bg-blue-700 flex items-center justify-center text-lg">
                        <i data-lucide="search" class="mr-3 h-5 w-5"></i>
                        Check Bunk/Loft Bed Fit
                    </button>
                </form>
            </div>

            <!-- Result Section -->
            <div id="resultSection" class="result-card rounded-2xl p-10 hidden">
                <h2 class="text-3xl font-semibold text-gray-800 mb-6 flex items-center">
                    <i data-lucide="check-circle-2" class="mr-3 text-green-500 h-7 w-7"></i>
                    Your Bunk/Loft Bed Fit Assessment
                </h2>
                <div id="resultOutput" class="text-gray-700 space-y-6 text-base">
                    <!-- Results will be dynamically inserted here -->
                </div>
                <div class="mt-10 flex flex-col md:flex-row justify-between items-center gap-6">
                    <div class="flex items-center text-blue-600">
                        <i data-lucide="info" class="mr-2 h-5 w-5"></i>
                        <p class="text-sm font-medium">Based on standard bedroom dimensions and bunk/loft bed safety guidelines.</p>
                    </div>
                    <button id="downloadPdf" class="btn-primary bg-green-600 text-white py-3 px-8 rounded-xl hover:bg-green-700 flex items-center text-base">
                        <i data-lucide="download" class="mr-2 h-5 w-5"></i>
                        Download PDF Report
                    </button>
                </div>
                <!-- Visual Representation -->
                <div class="mt-10 visual-container p-8">
                    <h3 class="text-xl font-medium text-gray-800 mb-4 flex items-center">
                        <i data-lucide="bed" class="mr-3 text-blue-500 h-6 w-6"></i>
                        Interactive Bunk/Loft Bed Visualization
                    </h3>
                    <div class="relative w-full h-96 bg-gray-200 rounded-xl overflow-hidden shadow-lg">
                        <canvas id="bedCanvas" class="w-full h-full"></canvas>
                    </div>
                    <p class="text-sm text-gray-600 mt-4">Visualization showing the bunk or loft bed in the room with floor and ceiling clearances.</p>
                </div>
                <!-- Expert Insights -->
                <div class="mt-10 bg-blue-50 p-8 rounded-xl shadow-sm">
                    <h3 class="text-xl font-medium text-gray-800 mb-4 flex items-center">
                        <i data-lucide="lightbulb" class="mr-3 text-yellow-500 h-6 w-6"></i>
                        Expert Insights for Bunk/Loft Bed Installation
                    </h3>
                    <ul class="list-none space-y-4 text-gray-700 text-sm">
                        <li class="flex items-start">
                            <i data-lucide="check" class="mr-2 text-green-500 h-5 w-5"></i>
                            <span><strong>Ceiling Clearance:</strong> Ensure ≥1.5-2 ft above top bunk for safety.</span>
                        </li>
                        <li class="flex items-start">
                            <i data-lucide="check" class="mr-2 text-green-500 h-5 w-5"></i>
                            <span><strong>Floor Clearance:</strong> Maintain 1-3 ft around bed for access and safety.</span>
                        </li>
                        <li class="flex items-start">
                            <i data-lucide="check" class="mr-2 text-green-500 h-5 w-5"></i>
                            <span><strong>Bunk Bed:</strong> Ensure both bunks have sufficient headroom (≥2.5 ft per bunk).</span>
                        </li>
                        <li class="flex items-start">
                            <i data-lucide="check" class="mr-2 text-green-500 h-5 w-5"></i>
                            <span><strong>Loft Bed:</strong> Verify under-bed space for desk or storage (≥4 ft).</span>
                        </li>
                        <li class="flex items-start">
                            <i data-lucide="check" class="mr-2 text-green-500 h-5 w-5"></i>
                            <span><strong>Stability:</strong> Secure bed to wall to prevent tipping.</span>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Initialize Lucid Icons
        lucide.createIcons();

        // Sync range and number inputs
        function syncInputs(numberId, rangeId, valueId, unit = 'ft') {
            const numberInput = document.getElementById(numberId);
            const rangeInput = document.getElementById(rangeId);
            const valueDisplay = document.getElementById(valueId);

            numberInput.addEventListener('input', () => {
                rangeInput.value = numberInput.value;
                valueDisplay.textContent = `${parseFloat(numberInput.value).toFixed(1)} ${unit}`;
            });
            rangeInput.addEventListener('input', () => {
                numberInput.value = rangeInput.value;
                valueDisplay.textContent = `${parseFloat(rangeInput.value).toFixed(1)} ${unit}`;
            });
        }

        syncInputs('bedWidth', 'bedWidthRange', 'bedWidthValue');
        syncInputs('bedLength', 'bedLengthRange', 'bedLengthValue');
        syncInputs('bedHeight', 'bedHeightRange', 'bedHeightValue');
        syncInputs('roomWidth', 'roomWidthRange', 'roomWidthValue');
        syncInputs('roomLength', 'roomLengthRange', 'roomLengthValue');
        syncInputs('ceilingHeight', 'ceilingHeightRange', 'ceilingHeightValue');
        syncInputs('floorClearance', 'floorClearanceRange', 'floorClearanceValue');
        syncInputs('ceilingClearance', 'ceilingClearanceRange', 'ceilingClearanceValue');

        // Form Submission
        document.getElementById('bedFitForm').addEventListener('submit', function (e) {
            e.preventDefault();
            calculateBedFit();
        });

        function calculateBedFit() {
            const bedType = document.getElementById('bedType').value;
            const bedWidth = parseFloat(document.getElementById('bedWidth').value);
            const bedLength = parseFloat(document.getElementById('bedLength').value);
            const bedHeight = parseFloat(document.getElementById('bedHeight').value);
            const roomWidth = parseFloat(document.getElementById('roomWidth').value);
            const roomLength = parseFloat(document.getElementById('roomLength').value);
            const ceilingHeight = parseFloat(document.getElementById('ceilingHeight').value);
            const floorClearance = parseFloat(document.getElementById('floorClearance').value);
            const ceilingClearance = parseFloat(document.getElementById('ceilingClearance').value);

            if (!bedType || !bedWidth || !bedLength || !bedHeight || !roomWidth || !roomLength || !ceilingHeight || !floorClearance || !ceilingClearance ||
                bedWidth < 3 || bedLength < 6 || bedHeight < 4 || roomWidth < 8 || roomLength < 8 || ceilingHeight < 7 || floorClearance < 1 || ceilingClearance < 1.5) {
                alert('Please enter valid values (Bed Width ≥ 3 ft, Length ≥ 6 ft, Height ≥ 4 ft, Room Width/Length ≥ 8 ft, Ceiling Height ≥ 7 ft, Floor Clearance ≥ 1 ft, Ceiling Clearance ≥ 1.5 ft).');
                return;
            }

            // Calculate fit
            const widthFit = bedWidth + (floorClearance * 2) <= roomWidth; // Clearance on both sides
            const lengthFit = bedLength + (floorClearance * 2) <= roomLength; // Clearance on both sides
            const heightFit = bedHeight + ceilingClearance <= ceilingHeight; // Sufficient ceiling clearance
            let typeFit = true;
            let typeMessage = '';

            // Bed type-specific checks
            if (bedType === 'Bunk Bed') {
                // Bunk bed: Each bunk needs ~2.5 ft headroom
                typeFit = bedHeight >= 4.5 && (ceilingHeight - bedHeight) >= 2.5;
                typeMessage = typeFit
                    ? `The bunk bed provides sufficient headroom for both bunks.`
                    : `Insufficient headroom for bunk bed (need ≥4.5 ft bed height and ≥2.5 ft ceiling clearance, have ${bedHeight.toFixed(1)} ft and ${(ceilingHeight - bedHeight).toFixed(1)} ft).`;
            } else if (bedType === 'Loft Bed') {
                // Loft bed: Under-bed space ≥4 ft for desk/storage
                typeFit = bedHeight >= 4 && (ceilingHeight - bedHeight) >= 1.5;
                typeMessage = typeFit
                    ? `The loft bed provides sufficient under-bed space and ceiling clearance.`
                    : `Insufficient under-bed space or ceiling clearance for loft bed (need ≥4 ft bed height and ≥1.5 ft ceiling clearance, have ${bedHeight.toFixed(1)} ft and ${(ceilingHeight - bedHeight).toFixed(1)} ft).`;
            }

            const overallFit = widthFit && lengthFit && heightFit && typeFit ? 'Yes' : 'No';

            // Calculate clearances
            const widthClearance = roomWidth - bedWidth;
            const lengthClearance = roomLength - bedLength;
            const actualCeilingClearance = ceilingHeight - bedHeight;

            // Generate output
            const output = `
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6 bg-white p-6 rounded-xl shadow-sm">
                    <div>
                        <p class="font-medium text-gray-700">Bed Type</p>
                        <p class="text-xl text-blue-600 font-semibold">${bedType}</p>
                    </div>
                    <div>
                        <p class="font-medium text-gray-700">Bed Dimensions</p>
                        <p class="text-lg">${bedWidth.toFixed(1)} x ${bedLength.toFixed(1)} x ${bedHeight.toFixed(1)} ft</p>
                    </div>
                    <div>
                        <p class="font-medium text-gray-700">Room Dimensions</p>
                        <p class="text-lg">${roomWidth.toFixed(1)} x ${roomLength.toFixed(1)} x ${ceilingHeight.toFixed(1)} ft</p>
                    </div>
                    <div>
                        <p class="font-medium text-gray-700">Clearances</p>
                        <p class="text-lg">Floor: ${floorClearance.toFixed(1)} ft, Ceiling: ${ceilingClearance.toFixed(1)} ft</p>
                    </div>
                    <div>
                        <p class="font-medium text-gray-700">Fit Assessment</p>
                        <p class="text-lg ${overallFit === 'Yes' ? 'text-green-600' : 'text-red-600'} font-semibold">
                            ${overallFit === 'Yes' ? 'Perfect Fit' : 'May Not Fit Properly'}
                        </p>
                        <p class="text-sm text-gray-600">${
                            overallFit === 'Yes'
                                ? `The ${bedType.toLowerCase()} fits with ${widthClearance.toFixed(1)} ft width clearance, ${lengthClearance.toFixed(1)} ft length clearance, and ${actualCeilingClearance.toFixed(1)} ft ceiling clearance. ${typeMessage}`
                                : `Issues: ${
                                    !widthFit ? `Insufficient width clearance (need ≤${(bedWidth + floorClearance * 2).toFixed(1)} ft, have ${roomWidth.toFixed(1)} ft). ` : ''
                                }${
                                    !lengthFit ? `Insufficient length clearance (need ≤${(bedLength + floorClearance * 2).toFixed(1)} ft, have ${roomLength.toFixed(1)} ft). ` : ''
                                }${
                                    !heightFit ? `Insufficient ceiling clearance (need ≤${(bedHeight + ceilingClearance).toFixed(1)} ft, have ${ceilingHeight.toFixed(1)} ft). ` : ''
                                }${
                                    !typeFit ? typeMessage : ''
                                }`
                        }</p>
                    </div>
                </div>
                <div class="bg-blue-50 p-4 rounded-lg">
                    <p class="text-sm"><span class="font-medium">Tip:</span> Ensure the bed is securely anchored and allows safe access for users.</p>
                </div>
            `;

            document.getElementById('resultOutput').innerHTML = output;
            document.getElementById('resultSection').classList.remove('hidden');

            // Draw visualization
            drawVisualization(bedType, bedWidth, bedLength, bedHeight, roomWidth, roomLength, ceilingHeight, floorClearance, ceilingClearance);

            // Setup PDF download
            setupPdfDownload(bedType, bedWidth, bedLength, bedHeight, roomWidth, roomLength, ceilingHeight, floorClearance, ceilingClearance, overallFit, widthClearance, lengthClearance, actualCeilingClearance, typeMessage);
        }

        function drawVisualization(bedType, bedWidth, bedLength, bedHeight, roomWidth, roomLength, ceilingHeight, floorClearance, ceilingClearance) {
            const canvas = document.getElementById('bedCanvas');
            const ctx = canvas.getContext('2d');
            canvas.width = canvas.offsetWidth;
            canvas.height = canvas.offsetHeight;

            // Clear canvas
            ctx.clearRect(0, 0, canvas.width, canvas.height);

            // Scale factors
            const scale = Math.min(canvas.width / (roomWidth * 1.5), canvas.height / (ceilingHeight * 1.2));
            const bedW = bedWidth * scale;
            const bedL = bedLength * scale;
            const bedH = bedHeight * scale;
            const roomW = roomWidth * scale;
            const roomL = roomLength * scale;
            const roomH = ceilingHeight * scale;
            const floorC = floorClearance * scale;
            const ceilingC = ceilingClearance * scale;

            // Draw background (room interior)
            const gradient = ctx.createLinearGradient(0, 0, 0, canvas.height);
            gradient.addColorStop(0, '#e5e7eb');
            gradient.addColorStop(1, '#d1d5db');
            ctx.fillStyle = gradient;
            ctx.fillRect(0, 0, canvas.width, canvas.height);

            // Draw floor
            ctx.fillStyle = 'rgba(120, 113, 108, 0.2)';
            ctx.fillRect(0, canvas.height * 0.7, canvas.width, canvas.height * 0.3);

            // Draw room outline
            ctx.strokeStyle = '#1e40af';
            ctx.lineWidth = 2;
            ctx.setLineDash([5, 5]);
            const roomX = (canvas.width - roomW) / 2;
            const roomY = canvas.height - roomH;
            ctx.strokeRect(roomX, roomY, roomW, roomH);
            ctx.fillStyle = '#bfdbfe';
            ctx.globalAlpha = 0.3;
            ctx.fillRect(roomX, roomY, roomW, roomH);
            ctx.globalAlpha = 1.0;
            ctx.setLineDash([]);

            // Draw bed (side view)
            ctx.shadowColor = 'rgba(0, 0, 0, 0.4)';
            ctx.shadowBlur = 15;
            ctx.shadowOffsetX = 8;
            ctx.shadowOffsetY = 8;
            ctx.fillStyle = '#0284c7';
            const bedX = roomX + floorC;
            const bedY = bedType === 'Bunk Bed' ? canvas.height - bedH : canvas.height - bedH - (bedH * 0.4); // Loft bed raised
            ctx.fillRect(bedX, bedY, bedW, bedH);

            // Draw bed texture
            const bedGradient = ctx.createLinearGradient(bedX, bedY, bedX + bedW, bedY + bedH);
            bedGradient.addColorStop(0, 'rgba(255, 255, 255, 0.15)');
            bedGradient.addColorStop(1, 'rgba(255, 255, 255, 0.05)');
            ctx.fillStyle = bedGradient;
            ctx.fillRect(bedX + 5, bedY + 5, bedW - 10, bedH - 10);

            // Draw second bunk for bunk bed
            if (bedType === 'Bunk Bed') {
                ctx.fillStyle = '#0284c7';
                ctx.fillRect(bedX, bedY + bedH * 0.6, bedW, bedH * 0.4); // Lower bunk
                ctx.fillStyle = bedGradient;
                ctx.fillRect(bedX + 5, bedY + bedH * 0.6 + 5, bedW - 10, bedH * 0.4 - 10);
            } else {
                // Draw under-bed space for loft bed
                ctx.fillStyle = '#4b5563';
                ctx.fillRect(bedX, canvas.height - (bedH * 0.4), bedW, bedH * 0.4); // Desk/storage
            }

            // Draw ceiling clearance
            ctx.fillStyle = 'rgba(34, 197, 94, 0.3)';
            ctx.fillRect(bedX, bedY - ceilingC, bedW, ceilingC);

            // Draw text
            ctx.shadowColor = 'transparent';
            ctx.fillStyle = '#ffffff';
            ctx.font = 'bold 18px Poppins';
            ctx.textAlign = 'center';
            ctx.fillText(`${bedType} (${bedWidth.toFixed(1)} x ${bedHeight.toFixed(1)} ft)`, bedX + bedW / 2, bedY + bedH / 2);
            ctx.fillStyle = '#1e40af';
            ctx.fillText(`Room (${roomWidth.toFixed(1)} x ${ceilingHeight.toFixed(1)} ft)`, roomX + roomW / 2, roomY - 10);
            ctx.font = '14px Poppins';
            ctx.fillStyle = '#4b5563';
            ctx.fillText(`Floor Clearance: ${floorClearance.toFixed(1)} ft, Ceiling Clearance: ${ceilingClearance.toFixed(1)} ft`, canvas.width / 2, canvas.height - 30);
        }

        function setupPdfDownload(bedType, bedWidth, bedLength, bedHeight, roomWidth, roomLength, ceilingHeight, floorClearance, ceilingClearance, overallFit, widthClearance, lengthClearance, actualCeilingClearance, typeMessage) {
            document.getElementById('downloadPdf').onclick = function () {
                const { jsPDF } = window.jspdf;
                const doc = new jsPDF();

                // Header
                doc.setFont('helvetica', 'bold');
                doc.setFontSize(20);
                doc.setTextColor(31, 64, 175);
                doc.text(`HomeFit Tools - ${bedType} Fit Assessment`, 20, 20);

                doc.setFont('helvetica', 'normal');
                doc.setFontSize(10);
                doc.setTextColor(100, 100, 100);
                doc.text(`Generated on: ${new Date().toLocaleString()}`, 20, 28);

                // Results
                doc.setFontSize(14);
                doc.setTextColor(0, 0, 0);
                doc.text(`Your ${bedType} Fit Assessment`, 20, 40);

                doc.setFontSize(11);
                doc.text(`Bed Type: ${bedType}`, 20, 50);
                doc.text(`Bed Dimensions: ${bedWidth.toFixed(1)} x ${bedLength.toFixed(1)} x ${bedHeight.toFixed(1)} ft`, 20, 58);
                doc.text(`Room Dimensions: ${roomWidth.toFixed(1)} x ${roomLength.toFixed(1)} x ${ceilingHeight.toFixed(1)} ft`, 20, 66);
                doc.text(`Clearances: Floor: ${floorClearance.toFixed(1)} ft, Ceiling: ${ceilingClearance.toFixed(1)} ft`, 20, 74);
                doc.text(`Fit Assessment: ${overallFit === 'Yes' ? 'Perfect Fit' : 'May Not Fit Properly'}`, 20, 82);
                doc.text(`Clearances: ${widthClearance.toFixed(1)} ft (width), ${lengthClearance.toFixed(1)} ft (length), ${actualCeilingClearance.toFixed(1)} ft (ceiling)`, 20, 90);
                doc.text(`Recommendation: ${typeMessage || (overallFit === 'Yes' ? `The ${bedType.toLowerCase()} is suitable for the room.` : `Consider a smaller bed or different room.`)}`, 20, 98);

                // Expert Insights
                doc.setFont('helvetica', 'bold');
                doc.setFontSize(12);
                doc.text('Expert Insights', 20, 110);
                doc.setFont('helvetica', 'normal');
                doc.setFontSize(10);
                doc.text('• Ceiling Clearance: Ensure ≥1.5-2 ft above top bunk for safety.', 20, 118);
                doc.text('• Floor Clearance: Maintain 1-3 ft around bed for access and safety.', 20, 126);
                doc.text('• Bunk Bed: Ensure both bunks have sufficient headroom (≥2.5 ft per bunk).', 20, 134);
                doc.text('• Loft Bed: Verify under-bed space for desk or storage (≥4 ft).', 20, 142);
                doc.text('• Stability: Secure bed to wall to prevent tipping.', 20, 150);

                doc.save(`HomeFit_${bedType.replace(' ', '_')}_Fit_Assessment.pdf`);
            };
        }
    </script>