<?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);display: none;
        }
        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>


            <!-- Input Form -->
            <div class="input-containerx mb-12">
                <h2 class="text-3xl font-semibold text-gray-800 mb-6">Enter Your Mattress & Bedroom Details</h2>
                <p class="text-gray-500 mb-8 text-lg">Select a mattress size and input bedroom and nightstand dimensions to check if it fits comfortably.</p>
                <form id="mattressFitForm" class="space-y-8">
                    <div class="grid grid-cols-1 md:grid-cols-4 gap-6">
                        <div class="space-y-3">
                            <label for="mattressSize" class="block text-sm font-medium text-gray-700">Mattress Size</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="mattressSize" 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="Twin">Twin (38 x 75 in)</option>
                                    <option value="Twin XL">Twin XL (38 x 80 in)</option>
                                    <option value="Full">Full (54 x 75 in)</option>
                                    <option value="Queen" selected>Queen (60 x 80 in)</option>
                                    <option value="King">King (76 x 80 in)</option>
                                    <option value="California King">California King (72 x 84 in)</option>
                                </select>
                            </div>
                        </div>
                        <div class="space-y-3">
                            <label for="roomWidth" class="block text-sm font-medium text-gray-700">Bedroom Width (ft)</label>
                            <div class="relative flex items-center">
                                <i data-lucide="maximize" 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">
                            <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">Bedroom 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="12.0" step="0.1" min="8" max="30" 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="30" step="0.1" value="12">
                            <p id="roomLengthValue" class="text-sm text-gray-500">12.0 ft</p>
                        </div>
                        <div class="space-y-3">
                            <label for="nightstandWidth" class="block text-sm font-medium text-gray-700">Nightstand Width (in)</label>
                            <div class="relative flex items-center">
                                <i data-lucide="table" class="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                                <input type="number" id="nightstandWidth" 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="24.0" step="0.1" min="0" max="40" value="24.0" required>
                            </div>
                            <input type="range" id="nightstandWidthRange" class="range-input w-full h-2 bg-gray-200 rounded-lg cursor-pointer" min="0" max="40" step="0.1" value="24">
                            <p id="nightstandWidthValue" class="text-sm text-gray-500">24.0 in</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 Mattress 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 Mattress 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 standards for bedroom space planning.</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 Mattress & Room Visualization
                    </h3>
                    <div class="relative w-full h-96 bg-gray-200 rounded-xl overflow-hidden shadow-lg">
                        <canvas id="mattressCanvas" class="w-full h-full"></canvas>
                    </div>
                    <p class="text-sm text-gray-600 mt-4">Visualization showing the mattress and nightstands scaled to your bedroom width.</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 Bedroom Layout
                    </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>Clearance:</strong> Allow at least 2 ft on each side of the mattress for easy access.</span>
                        </li>
                        <li class="flex items-start">
                            <i data-lucide="check" class="mr-2 text-green-500 h-5 w-5"></i>
                            <span><strong>Traffic Flow:</strong> Ensure 3 ft of walkway space around the bed to avoid congestion.</span>
                        </li>
                        <li class="flex items-start">
                            <i data-lucide="check" class="mr-2 text-green-500 h-5 w-5"></i>
                            <span><strong>Nightstands:</strong> Place nightstands (18-30 in wide) on one or both sides for balance and functionality.</span>
                        </li>
                        <li class="flex items-start">
                            <i data-lucide="check" class="mr-2 text-green-500 h-5 w-5"></i>
                            <span><strong>Room Proportion:</strong> The mattress should occupy no more than 50% of the room width for a spacious feel.</span>
                        </li>
                        <li class="flex items-start">
                            <i data-lucide="check" class="mr-2 text-green-500 h-5 w-5"></i>
                            <span><strong>Furniture Layout:</strong> Position the bed against a wall or centered to optimize space and aesthetics.</span>
                        </li>
                    </ul>
                </div>
            </div>

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

        // Sync range and number inputs
        function syncInputs(numberId, rangeId, valueId) {
            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)} ${numberId.includes('Width') || numberId.includes('Length') ? 'ft' : 'in'}`;
            });
            rangeInput.addEventListener('input', () => {
                numberInput.value = rangeInput.value;
                valueDisplay.textContent = `${parseFloat(rangeInput.value).toFixed(1)} ${numberId.includes('Width') || numberId.includes('Length') ? 'ft' : 'in'}`;
            });
        }

        syncInputs('roomWidth', 'roomWidthRange', 'roomWidthValue');
        syncInputs('roomLength', 'roomLengthRange', 'roomLengthValue');
        syncInputs('nightstandWidth', 'nightstandWidthRange', 'nightstandWidthValue');

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

        function calculateMattressFit() {
            const mattressSize = document.getElementById('mattressSize').value;
            const roomWidth = parseFloat(document.getElementById('roomWidth').value);
            const roomLength = parseFloat(document.getElementById('roomLength').value);
            const nightstandWidth = parseFloat(document.getElementById('nightstandWidth').value);

            if (!roomWidth || !roomLength || roomWidth < 8 || roomLength < 8 || nightstandWidth < 0 || nightstandWidth > 40) {
                alert('Please enter valid values (Room Width/Length ≥ 8 ft, Nightstand Width 0-40 in).');
                return;
            }

            // Standard mattress dimensions (in inches)
            const mattressDimensions = {
                'Twin': { width: 38, length: 75 },
                'Twin XL': { width: 38, length: 80 },
                'Full': { width: 54, length: 75 },
                'Queen': { width: 60, length: 80 },
                'King': { width: 76, length: 80 },
                'California King': { width: 72, length: 84 }
            };

            const mattress = mattressDimensions[mattressSize];
            const totalWidth = mattress.width + (nightstandWidth * 2); // Two nightstands
            const roomWidthInches = roomWidth * 12;
            const roomLengthInches = roomLength * 12;

            // Check fit with clearance (2 ft on each side, 3 ft at foot for walkway)
            const widthClearance = roomWidthInches - totalWidth >= 48; // 2 ft each side
            const lengthClearance = roomLengthInches - mattress.length >= 36; // 3 ft at foot
            const proportionCheck = mattress.width / roomWidthInches <= 0.5; // ≤50% room width
            const mattressFit = widthClearance && lengthClearance && proportionCheck ? 'Yes' : 'No';

            // Calculate clearance/overages
            const widthClearanceFt = (roomWidthInches - totalWidth) / 12;
            const lengthClearanceFt = (roomLengthInches - mattress.length) / 12;

            // 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">Mattress Size</p>
                        <p class="text-xl text-blue-600 font-semibold">${mattressSize} (${mattress.width} x ${mattress.length} in)</p>
                    </div>
                    <div>
                        <p class="font-medium text-gray-700">Bedroom Dimensions</p>
                        <p class="text-lg">${roomWidth.toFixed(1)} x ${roomLength.toFixed(1)} ft</p>
                    </div>
                    <div>
                        <p class="font-medium text-gray-700">Nightstand Width</p>
                        <p class="text-lg">${nightstandWidth.toFixed(1)} in (each, two assumed)</p>
                    </div>
                    <div>
                        <p class="font-medium text-gray-700">Fit Assessment</p>
                        <p class="text-lg ${mattressFit === 'Yes' ? 'text-green-600' : 'text-red-600'} font-semibold">
                            ${mattressFit === 'Yes' ? 'Perfect Fit' : 'May Not Fit Comfortably'}
                        </p>
                        <p class="text-sm text-gray-600">${
                            mattressFit === 'Yes' 
                                ? `The mattress and nightstands fit with ${widthClearanceFt.toFixed(1)} ft width clearance and ${lengthClearanceFt.toFixed(1)} ft length clearance.` 
                                : `Issues: ${
                                    !widthClearance ? `Insufficient width clearance (need ≥2 ft each side, have ${widthClearanceFt.toFixed(1)} ft). ` : ''
                                }${
                                    !lengthClearance ? `Insufficient length clearance (need ≥3 ft at foot, have ${lengthClearanceFt.toFixed(1)} ft). ` : ''
                                }${
                                    !proportionCheck ? 'Mattress too wide for room proportion (≤50% recommended).' : ''
                                }`
                        }</p>
                    </div>
                </div>
                <div class="bg-blue-50 p-4 rounded-lg">
                    <p class="text-sm"><span class="font-medium">Tip:</span> Consider a smaller mattress or fewer nightstands to improve clearance and room flow.</p>
                </div>
            `;

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

            // Draw visualization
            drawVisualization(mattress.width, mattress.length, nightstandWidth, roomWidth);

            // Setup PDF download
            setupPdfDownload(mattressSize, mattress.width, mattress.length, roomWidth, roomLength, nightstandWidth, mattressFit, widthClearanceFt, lengthClearanceFt);
        }

        function drawVisualization(mattressWidth, mattressLength, nightstandWidth, roomWidth) {
            const canvas = document.getElementById('mattressCanvas');
            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 = canvas.width / (roomWidth * 12 * 1.5); // Scale to fit canvas
            const mattressW = mattressWidth * scale;
            const mattressH = mattressLength * scale;
            const nightstandW = nightstandWidth * scale;
            const roomW = roomWidth * 12 * scale;

            // Draw background with floor texture
            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 (dashed)
            ctx.strokeStyle = '#1e40af';
            ctx.lineWidth = 2;
            ctx.setLineDash([5, 5]);
            ctx.strokeRect(canvas.width * 0.55, canvas.height * 0.2, roomW, mattressH + 20);
            ctx.fillStyle = '#bfdbfe';
            ctx.globalAlpha = 0.3;
            ctx.fillRect(canvas.width * 0.55, canvas.height * 0.2, roomW, mattressH + 20);
            ctx.globalAlpha = 1.0;
            ctx.setLineDash([]);

            // Draw mattress with realistic effects
            ctx.shadowColor = 'rgba(0, 0, 0, 0.4)';
            ctx.shadowBlur = 15;
            ctx.shadowOffsetX = 8;
            ctx.shadowOffsetY = 8;
            ctx.fillStyle = '#2d3748';
            const mattressX = canvas.width * 0.15 + nightstandW;
            const mattressY = canvas.height * 0.2;
            ctx.fillRect(mattressX, mattressY, mattressW, mattressH);

            // Draw mattress texture
            const mattressGradient = ctx.createLinearGradient(mattressX, mattressY, mattressX + mattressW, mattressY + mattressH);
            mattressGradient.addColorStop(0, 'rgba(255, 255, 255, 0.15)');
            mattressGradient.addColorStop(1, 'rgba(255, 255, 255, 0.05)');
            ctx.fillStyle = mattressGradient;
            ctx.fillRect(mattressX + 5, mattressY + 5, mattressW - 10, mattressH - 10);

            // Draw nightstands
            ctx.fillStyle = '#4b5563';
            ctx.fillRect(mattressX - nightstandW, mattressY, nightstandW, mattressH * 0.3); // Left nightstand
            ctx.fillRect(mattressX + mattressW, mattressY, nightstandW, mattressH * 0.3); // Right nightstand

            // Draw text
            ctx.shadowColor = 'transparent';
            ctx.fillStyle = '#ffffff';
            ctx.font = 'bold 18px Poppins';
            ctx.textAlign = 'center';
            ctx.fillText(`Mattress (${mattressWidth} x ${mattressLength} in)`, mattressX + mattressW / 2, mattressY + mattressH / 2);
            ctx.fillStyle = '#1e40af';
            ctx.fillText(`Room (${roomWidth.toFixed(1)} ft)`, canvas.width * 0.55 + roomW / 2, canvas.height * 0.2 + (mattressH + 20) / 2);
            if (nightstandWidth > 0) {
                ctx.fillStyle = '#ffffff';
                ctx.font = '14px Poppins';
                ctx.fillText(`${nightstandWidth.toFixed(1)} in`, mattressX - nightstandW / 2, mattressY + (mattressH * 0.3) / 2);
                ctx.fillText(`${nightstandWidth.toFixed(1)} in`, mattressX + mattressW + nightstandW / 2, mattressY + (mattressH * 0.3) / 2);
            }
            ctx.font = '14px Poppins';
            ctx.fillStyle = '#4b5563';
            ctx.fillText(`Mattress & Nightstands vs. Bedroom Width`, canvas.width / 2, canvas.height - 30);
        }

        function setupPdfDownload(mattressSize, mattressWidth, mattressLength, roomWidth, roomLength, nightstandWidth, mattressFit, widthClearanceFt, lengthClearanceFt) {
            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 - Mattress Fit Assessment Report', 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 Mattress Fit Assessment', 20, 40);

                doc.setFontSize(11);
                doc.text(`Mattress Size: ${mattressSize} (${mattressWidth} x ${mattressLength} in)`, 20, 50);
                doc.text(`Bedroom Dimensions: ${roomWidth.toFixed(1)} x ${roomLength.toFixed(1)} ft`, 20, 58);
                doc.text(`Nightstand Width: ${nightstandWidth.toFixed(1)} in (each, two assumed)`, 20, 66);
                doc.text(`Fit Assessment: ${mattressFit === 'Yes' ? 'Perfect Fit' : 'May Not Fit Comfortably'}`, 20, 74);
                doc.text(`Clearance: ${widthClearanceFt.toFixed(1)} ft (width), ${lengthClearanceFt.toFixed(1)} ft (length)`, 20, 82);
                doc.text(`Recommendation: ${
                    mattressFit === 'Yes' 
                        ? 'The mattress and nightstands are suitable for your bedroom.' 
                        : 'Consider a smaller mattress or fewer nightstands to improve clearance.'
                }`, 20, 90);

                // Expert Insights
                doc.setFont('helvetica', 'bold');
                doc.setFontSize(12);
                doc.text('Expert Insights', 20, 102);
                doc.setFont('helvetica', 'normal');
                doc.setFontSize(10);
                doc.text('• Clearance: Allow 2 ft on each side for easy access.', 20, 110);
                doc.text('• Traffic Flow: Ensure 3 ft walkway space around the bed.', 20, 118);
                doc.text('• Nightstands: Use 18-30 in wide nightstands for balance.', 20, 126);
                doc.text('• Room Proportion: Mattress ≤50% of room width for spaciousness.', 20, 134);
                doc.text('• Furniture Layout: Center or wall-align bed for aesthetics.', 20, 142);

                doc.save('HomeFit_Mattress_Fit_Assessment.pdf');
            };
        }
    </script>