<?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 Room & Area Rug Details</h2>
                <p class="text-gray-500 mb-8 text-lg">Input room dimensions, rug size, and layout to check if the rug fits your room aesthetically.</p>
                <form id="areaRugFitForm" class="space-y-8">
                    <div class="grid grid-cols-1 md:grid-cols-4 gap-6">
                        <div class="space-y-3">
                            <label for="roomType" class="block text-sm font-medium text-gray-700">Room Type</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>
                                <select id="roomType" 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="Living Room" selected>Living Room</option>
                                    <option value="Dining Room">Dining Room</option>
                                    <option value="Bedroom">Bedroom</option>
                                </select>
                            </div>
                        </div>
                        <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="expand" 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="12.0" step="0.1" min="8" max="30" value="12.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="30" step="0.1" value="12.0">
                            <p id="roomWidthValue" class="text-sm text-gray-500">12.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="expand" 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="15.0" step="0.1" min="8" max="30" value="15.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="30" step="0.1" value="15.0">
                            <p id="roomLengthValue" class="text-sm text-gray-500">15.0 ft</p>
                        </div>
                        <div class="space-y-3">
                            <label for="layoutType" class="block text-sm font-medium text-gray-700">Furniture Layout</label>
                            <div class="relative flex items-center">
                                <i data-lucide="layout" class="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                                <select id="layoutType" 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="All Legs On" selected>All Legs On (Living Room)</option>
                                    <option value="Front Legs On">Front Legs On (Living Room)</option>
                                    <option value="Under Table">Under Table (Dining Room)</option>
                                    <option value="Under Bed">Under Bed (Bedroom)</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                        <div class="space-y-3">
                            <label for="rugWidth" class="block text-sm font-medium text-gray-700">Rug Width (ft)</label>
                            <div class="relative flex items-center">
                                <i data-lucide="square" class="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                                <input type="number" id="rugWidth" 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="4" max="20" value="8.0" required>
                            </div>
                            <input type="range" id="rugWidthRange" class="range-input w-full h-2 bg-gray-200 rounded-lg cursor-pointer" min="4" max="20" step="0.1" value="8.0">
                            <p id="rugWidthValue" class="text-sm text-gray-500">8.0 ft</p>
                        </div>
                        <div class="space-y-3">
                            <label for="rugLength" class="block text-sm font-medium text-gray-700">Rug Length (ft)</label>
                            <div class="relative flex items-center">
                                <i data-lucide="square" class="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                                <input type="number" id="rugLength" 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="4" max="20" value="10.0" required>
                            </div>
                            <input type="range" id="rugLengthRange" class="range-input w-full h-2 bg-gray-200 rounded-lg cursor-pointer" min="4" max="20" step="0.1" value="10.0">
                            <p id="rugLengthValue" class="text-sm text-gray-500">10.0 ft</p>
                        </div>
                        <div class="space-y-3">
                            <label for="clearanceSpace" class="block text-sm font-medium text-gray-700">Clearance Around Rug (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="clearanceSpace" 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="5" value="2.0" required>
                            </div>
                            <input type="range" id="clearanceSpaceRange" class="range-input w-full h-2 bg-gray-200 rounded-lg cursor-pointer" min="1" max="5" step="0.1" value="2.0">
                            <p id="clearanceSpaceValue" 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 Area Rug 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 Area Rug 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 interior design guidelines for rug sizing and room layouts.</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="square" class="mr-3 text-blue-500 h-6 w-6"></i>
                        Interactive Room & Area Rug Visualization
                    </h3>
                    <div class="relative w-full h-96 bg-gray-200 rounded-xl overflow-hidden shadow-lg">
                        <canvas id="rugCanvas" class="w-full h-full"></canvas>
                    </div>
                    <p class="text-sm text-gray-600 mt-4">Visualization showing the rug in the room with furniture layout and clearance.</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 Area Rug Selection
                    </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>Proportions:</strong> Rug should cover 60-80% of room width for balance.</span>
                        </li>
                        <li class="flex items-start">
                            <i data-lucide="check" class="mr-2 text-green-500 h-5 w-5"></i>
                            <span><strong>Clearance:</strong> Maintain 1-2 ft clearance around rug for walkways.</span>
                        </li>
                        <li class="flex items-start">
                            <i data-lucide="check" class="mr-2 text-green-500 h-5 w-5"></i>
                            <span><strong>Living Room:</strong> Choose "All Legs On" for cohesive look or "Front Legs On" for smaller rugs.</span>
                        </li>
                        <li class="flex items-start">
                            <i data-lucide="check" class="mr-2 text-green-500 h-5 w-5"></i>
                            <span><strong>Dining Room:</strong> Rug should extend 2 ft beyond table edges.</span>
                        </li>
                        <li class="flex items-start">
                            <i data-lucide="check" class="mr-2 text-green-500 h-5 w-5"></i>
                            <span><strong>Bedroom:</strong> Rug should extend 1-2 ft beyond bed sides.</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('roomWidth', 'roomWidthRange', 'roomWidthValue');
        syncInputs('roomLength', 'roomLengthRange', 'roomLengthValue');
        syncInputs('rugWidth', 'rugWidthRange', 'rugWidthValue');
        syncInputs('rugLength', 'rugLengthRange', 'rugLengthValue');
        syncInputs('clearanceSpace', 'clearanceSpaceRange', 'clearanceSpaceValue');

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

        function calculateRugFit() {
            const roomType = document.getElementById('roomType').value;
            const roomWidth = parseFloat(document.getElementById('roomWidth').value);
            const roomLength = parseFloat(document.getElementById('roomLength').value);
            const layoutType = document.getElementById('layoutType').value;
            const rugWidth = parseFloat(document.getElementById('rugWidth').value);
            const rugLength = parseFloat(document.getElementById('rugLength').value);
            const clearanceSpace = parseFloat(document.getElementById('clearanceSpace').value);

            if (!roomType || !roomWidth || !roomLength || !layoutType || !rugWidth || !rugLength || !clearanceSpace ||
                roomWidth < 8 || roomLength < 8 || rugWidth < 4 || rugLength < 4 || clearanceSpace < 1) {
                alert('Please enter valid values (Room Width/Length ≥ 8 ft, Rug Width/Length ≥ 4 ft, Clearance ≥ 1 ft).');
                return;
            }

            // Calculate fit based on layout and interior design guidelines
            const totalWidth = rugWidth + (clearanceSpace * 2); // Clearance on both sides
            const totalLength = rugLength + (clearanceSpace * 2); // Clearance on both sides
            const widthFit = totalWidth <= roomWidth;
            const lengthFit = totalLength <= roomLength;
            const proportionFit = rugWidth >= roomWidth * 0.6 && rugWidth <= roomWidth * 0.8; // 60-80% room width
            let layoutFit = true;
            let layoutMessage = '';

            // Layout-specific checks
            if (roomType === 'Living Room' && (layoutType === 'All Legs On' || layoutType === 'Front Legs On')) {
                // Living room: Rug should be 60-80% of room width, with clearance
                layoutFit = rugWidth >= 6 && rugLength >= 8; // Minimum rug size for living room
                layoutMessage = layoutFit
                    ? `The rug is suitable for a ${layoutType} layout in a living room.`
                    : `The rug is too small for a ${layoutType} layout (recommend ≥6 x 8 ft).`;
            } else if (roomType === 'Dining Room' && layoutType === 'Under Table') {
                // Dining room: Rug should extend 2 ft beyond table (assume table is ~1/2 room size)
                const tableWidth = roomWidth * 0.5;
                const tableLength = roomLength * 0.5;
                layoutFit = rugWidth >= tableWidth + 4 && rugLength >= tableLength + 4;
                layoutMessage = layoutFit
                    ? `The rug extends sufficiently beyond the dining table.`
                    : `The rug is too small (should extend ≥2 ft beyond table: ${tableWidth + 4} x ${tableLength + 4} ft).`;
            } else if (roomType === 'Bedroom' && layoutType === 'Under Bed') {
                // Bedroom: Rug should extend 1-2 ft beyond bed sides (assume bed is ~1/2 room size)
                const bedWidth = roomWidth * 0.5;
                const bedLength = roomLength * 0.5;
                layoutFit = rugWidth >= bedWidth + 2 && rugLength >= bedLength + 2;
                layoutMessage = layoutFit
                    ? `The rug extends sufficiently beyond the bed.`
                    : `The rug is too small (should extend ≥1-2 ft beyond bed: ${bedWidth + 2} x ${bedLength + 2} ft).`;
            }

            const overallFit = widthFit && lengthFit && proportionFit && layoutFit ? 'Yes' : 'No';

            // Calculate clearances
            const widthClearance = roomWidth - rugWidth;
            const lengthClearance = roomLength - rugLength;

            // 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">Room Type</p>
                        <p class="text-xl text-blue-600 font-semibold">${roomType}</p>
                    </div>
                    <div>
                        <p class="font-medium text-gray-700">Room Dimensions</p>
                        <p class="text-lg">${roomWidth.toFixed(1)} x ${roomLength.toFixed(1)} ft</p>
                    </div>
                    <div>
                        <p class="font-medium text-gray-700">Furniture Layout</p>
                        <p class="text-lg">${layoutType}</p>
                    </div>
                    <div>
                        <p class="font-medium text-gray-700">Rug Dimensions</p>
                        <p class="text-lg">${rugWidth.toFixed(1)} x ${rugLength.toFixed(1)} ft</p>
                    </div>
                    <div>
                        <p class="font-medium text-gray-700">Clearance Around Rug</p>
                        <p class="text-lg">${clearanceSpace.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 Aesthetically'}
                        </p>
                        <p class="text-sm text-gray-600">${
                            overallFit === 'Yes'
                                ? `The rug fits well in the ${roomType.toLowerCase()} with ${widthClearance.toFixed(1)} ft width clearance and ${lengthClearance.toFixed(1)} ft length clearance. ${layoutMessage}`
                                : `Issues: ${
                                    !widthFit ? `Insufficient width clearance (need ≤${totalWidth.toFixed(1)} ft, have ${roomWidth.toFixed(1)} ft). ` : ''
                                }${
                                    !lengthFit ? `Insufficient length clearance (need ≤${totalLength.toFixed(1)} ft, have ${roomLength.toFixed(1)} ft). ` : ''
                                }${
                                    !proportionFit ? `Rug width not proportional (should be 60-80% of room width: ${roomWidth.toFixed(1)} ft). ` : ''
                                }${
                                    !layoutFit ? layoutMessage : ''
                                }`
                        }</p>
                    </div>
                </div>
                <div class="bg-blue-50 p-4 rounded-lg">
                    <p class="text-sm"><span class="font-medium">Tip:</span> Choose a rug size that balances the room and complements the furniture layout for optimal aesthetics.</p>
                </div>
            `;

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

            // Draw visualization
            drawVisualization(roomType, roomWidth, roomLength, layoutType, rugWidth, rugLength, clearanceSpace);

            // Setup PDF download
            setupPdfDownload(roomType, roomWidth, roomLength, layoutType, rugWidth, rugLength, clearanceSpace, overallFit, widthClearance, lengthClearance, layoutMessage);
        }

        function drawVisualization(roomType, roomWidth, roomLength, layoutType, rugWidth, rugLength, clearanceSpace) {
            const canvas = document.getElementById('rugCanvas');
            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 / (roomLength * 1.5));
            const roomW = roomWidth * scale;
            const roomL = roomLength * scale;
            const rugW = rugWidth * scale;
            const rugL = rugLength * scale;
            const clearanceS = clearanceSpace * 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.2, canvas.width, canvas.height * 0.8);

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

            // Draw rug
            ctx.shadowColor = 'rgba(0, 0, 0, 0.4)';
            ctx.shadowBlur = 15;
            ctx.shadowOffsetX = 8;
            ctx.shadowOffsetY = 8;
            ctx.fillStyle = '#0284c7';
            const rugX = roomX + (roomW - rugW) / 2;
            const rugY = roomY + (roomL - rugL) / 2;
            ctx.fillRect(rugX, rugY, rugW, rugL);

            // Draw rug texture
            const rugGradient = ctx.createLinearGradient(rugX, rugY, rugX + rugW, rugY + rugL);
            rugGradient.addColorStop(0, 'rgba(255, 255, 255, 0.15)');
            rugGradient.addColorStop(1, 'rgba(255, 255, 255, 0.05)');
            ctx.fillStyle = rugGradient;
            ctx.fillRect(rugX + 5, rugY + 5, rugW - 10, rugL - 10);

            // Draw furniture based on layout
            ctx.fillStyle = '#4b5563';
            if (layoutType === 'All Legs On' || layoutType === 'Front Legs On') {
                // Living room: Sofa and chairs
                const sofaW = rugW * 0.6;
                const sofaL = rugL * 0.3;
                const sofaX = rugX + (rugW - sofaW) / 2;
                const sofaY = layoutType === 'All Legs On' ? rugY + rugL * 0.1 : rugY - sofaL * 0.5;
                ctx.fillRect(sofaX, sofaY, sofaW, sofaL);
                ctx.fillRect(rugX + rugW * 0.1, rugY + rugL * 0.5, rugW * 0.2, rugL * 0.2); // Chair 1
                ctx.fillRect(rugX + rugW * 0.7, rugY + rugL * 0.5, rugW * 0.2, rugL * 0.2); // Chair 2
            } else if (layoutType === 'Under Table') {
                // Dining room: Table
                const tableW = rugW * 0.5;
                const tableL = rugL * 0.5;
                ctx.fillRect(rugX + (rugW - tableW) / 2, rugY + (rugL - tableL) / 2, tableW, tableL);
            } else if (layoutType === 'Under Bed') {
                // Bedroom: Bed
                const bedW = rugW * 0.5;
                const bedL = rugL * 0.6;
                ctx.fillRect(rugX + (rugW - bedW) / 2, rugY + (rugL - bedL) / 2, bedW, bedL);
            }

            // Draw text
            ctx.shadowColor = 'transparent';
            ctx.fillStyle = '#ffffff';
            ctx.font = 'bold 18px Poppins';
            ctx.textAlign = 'center';
            ctx.fillText(`Rug (${rugWidth.toFixed(1)} x ${rugLength.toFixed(1)} ft)`, rugX + rugW / 2, rugY + rugL / 2);
            ctx.fillStyle = '#1e40af';
            ctx.fillText(`${roomType} (${roomWidth.toFixed(1)} x ${roomLength.toFixed(1)} ft)`, roomX + roomW / 2, roomY - 10);
            ctx.font = '14px Poppins';
            ctx.fillStyle = '#4b5563';
            ctx.fillText(`Clearance: ${clearanceSpace.toFixed(1)} ft, Layout: ${layoutType}`, canvas.width / 2, canvas.height - 30);
        }

        function setupPdfDownload(roomType, roomWidth, roomLength, layoutType, rugWidth, rugLength, clearanceSpace, overallFit, widthClearance, lengthClearance, layoutMessage) {
            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 - Area Rug Fit Assessment for ${roomType}`, 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 Area Rug Fit Assessment`, 20, 40);

                doc.setFontSize(11);
                doc.text(`Room Type: ${roomType}`, 20, 50);
                doc.text(`Room Dimensions: ${roomWidth.toFixed(1)} x ${roomLength.toFixed(1)} ft`, 20, 58);
                doc.text(`Furniture Layout: ${layoutType}`, 20, 66);
                doc.text(`Rug Dimensions: ${rugWidth.toFixed(1)} x ${rugLength.toFixed(1)} ft`, 20, 74);
                doc.text(`Clearance Around Rug: ${clearanceSpace.toFixed(1)} ft`, 20, 82);
                doc.text(`Fit Assessment: ${overallFit === 'Yes' ? 'Perfect Fit' : 'May Not Fit Aesthetically'}`, 20, 90);
                doc.text(`Clearances: ${widthClearance.toFixed(1)} ft (width), ${lengthClearance.toFixed(1)} ft (length)`, 20, 98);
                doc.text(`Recommendation: ${layoutMessage || (overallFit === 'Yes' ? `The rug is suitable for the ${roomType.toLowerCase()}.` : `Consider a different rug size or layout.`)}`, 20, 106);

                // Expert Insights
                doc.setFont('helvetica', 'bold');
                doc.setFontSize(12);
                doc.text('Expert Insights', 20, 118);
                doc.setFont('helvetica', 'normal');
                doc.setFontSize(10);
                doc.text('• Proportions: Rug should cover 60-80% of room width for balance.', 20, 126);
                doc.text('• Clearance: Maintain 1-2 ft clearance around rug for walkways.', 20, 134);
                doc.text('• Living Room: Choose "All Legs On" for cohesive look or "Front Legs On" for smaller rugs.', 20, 142);
                doc.text('• Dining Room: Rug should extend 2 ft beyond table edges.', 20, 150);
                doc.text('• Bedroom: Rug should extend 1-2 ft beyond bed sides.', 20, 158);

                doc.save(`HomeFit_Area_Rug_${roomType}_Fit_Assessment.pdf`);
            };
        }
    </script>