<?php include "../autoload.php"; ?>

<script src="https://cdn.tailwindcss.com"></script>
    <script src="https://unpkg.com/lucide@latest"></script>
    <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>

            <!-- Input Form -->
            <div class="mb-12">
                <h2 class="text-3xl font-semibold text-gray-800 mb-6">Enter Your Appliance & Space Details</h2>
                <p class="text-gray-500 mb-8 text-lg">Slide or type to input your appliance and kitchen/laundry space dimensions to check if it fits perfectly.</p>
                <form id="applianceFitForm" class="space-y-8">
                    <div class="grid grid-cols-1 md:grid-cols-4 gap-6">
                        <div class="space-y-3">
                            <label for="applianceType" class="block text-sm font-medium text-gray-700">Appliance Type</label>
                            <div class="relative flex items-center">
                                <i data-lucide="refrigerator" class="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                                <select id="applianceType" 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="Fridge">Fridge</option>
                                    <option value="Oven">Oven</option>
                                    <option value="Washer">Washer</option>
                                </select>
                            </div>
                        </div>
                        <div class="space-y-3">
                            <label for="applianceWidth" class="block text-sm font-medium text-gray-700">Appliance Width (in)</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="applianceWidth" 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="36.0" step="0.1" min="20" max="60" value="36.0" required>
                            </div>
                            <input type="range" id="applianceWidthRange" class="range-input w-full h-2 bg-gray-200 rounded-lg cursor-pointer" min="20" max="60" step="0.1" value="36">
                            <p id="applianceWidthValue" class="text-sm text-gray-500">36.0 in</p>
                        </div>
                        <div class="space-y-3">
                            <label for="applianceDepth" class="block text-sm font-medium text-gray-700">Appliance Depth (in)</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="applianceDepth" 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="30.0" step="0.1" min="20" max="50" value="30.0" required>
                            </div>
                            <input type="range" id="applianceDepthRange" class="range-input w-full h-2 bg-gray-200 rounded-lg cursor-pointer" min="20" max="50" step="0.1" value="30">
                            <p id="applianceDepthValue" class="text-sm text-gray-500">30.0 in</p>
                        </div>
                        <div class="space-y-3">
                            <label for="spaceWidth" class="block text-sm font-medium text-gray-700">Space Width (in)</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="spaceWidth" 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="40.0" step="0.1" min="24" max="80" value="40.0" required>
                            </div>
                            <input type="range" id="spaceWidthRange" class="range-input w-full h-2 bg-gray-200 rounded-lg cursor-pointer" min="24" max="80" step="0.1" value="40">
                            <p id="spaceWidthValue" class="text-sm text-gray-500">40.0 in</p>
                        </div>
                    </div>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div class="space-y-3">
                            <label for="spaceDepth" class="block text-sm font-medium text-gray-700">Space Depth (in)</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="spaceDepth" 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="32.0" step="0.1" min="24" max="60" value="32.0" required>
                            </div>
                            <input type="range" id="spaceDepthRange" class="range-input w-full h-2 bg-gray-200 rounded-lg cursor-pointer" min="24" max="60" step="0.1" value="32">
                            <p id="spaceDepthValue" class="text-sm text-gray-500">32.0 in</p>
                        </div>
                        <div class="space-y-3">
                            <label for="spaceHeight" class="block text-sm font-medium text-gray-700">Space Height (in)</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="spaceHeight" 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="72.0" step="0.1" min="40" max="100" value="72.0" required>
                            </div>
                            <input type="range" id="spaceHeightRange" class="range-input w-full h-2 bg-gray-200 rounded-lg cursor-pointer" min="40" max="100" step="0.1" value="72">
                            <p id="spaceHeightValue" class="text-sm text-gray-500">72.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 Appliance 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 Appliance 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 industry standards for kitchen and laundry 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="fridge" class="mr-3 text-blue-500 h-6 w-6"></i>
                        Interactive Appliance & Space Visualization
                    </h3>
                    <div class="relative w-full h-96 bg-gray-200 rounded-xl overflow-hidden shadow-lg">
                        <canvas id="applianceCanvas" class="w-full h-full"></canvas>
                    </div>
                    <p class="text-sm text-gray-600 mt-4">Visualization showing the appliance size scaled to your available space 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 Appliance Placement
                    </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 1-2 in on each side and back for ventilation and door swing.</span>
                        </li>
                        <li class="flex items-start">
                            <i data-lucide="check" class="mr-2 text-green-500 h-5 w-5"></i>
                            <span><strong>Height Planning:</strong> Ensure cabinet or counter space above accommodates appliance height.</span>
                        </li>
                        <li class="flex items-start">
                            <i data-lucide="check" class="mr-2 text-green-500 h-5 w-5"></i>
                            <span><strong>Accessibility:</strong> Maintain 3 ft of clear floor space in front for safe operation.</span>
                        </li>
                        <li class="flex items-start">
                            <i data-lucide="check" class="mr-2 text-green-500 h-5 w-5"></i>
                            <span><strong>Utilities:</strong> Confirm electrical outlets or water lines align with appliance requirements.</span>
                        </li>
                        <li class="flex items-start">
                            <i data-lucide="check" class="mr-2 text-green-500 h-5 w-5"></i>
                            <span><strong>Workflow:</strong> Position appliances to optimize kitchen/laundry workflow (e.g., fridge near prep area).</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)} in`;
            });
            rangeInput.addEventListener('input', () => {
                numberInput.value = rangeInput.value;
                valueDisplay.textContent = `${parseFloat(rangeInput.value).toFixed(1)} in`;
            });
        }

        syncInputs('applianceWidth', 'applianceWidthRange', 'applianceWidthValue');
        syncInputs('applianceDepth', 'applianceDepthRange', 'applianceDepthValue');
        syncInputs('spaceWidth', 'spaceWidthRange', 'spaceWidthValue');
        syncInputs('spaceDepth', 'spaceDepthRange', 'spaceDepthValue');
        syncInputs('spaceHeight', 'spaceHeightRange', 'spaceHeightValue');

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

        function calculateApplianceFit() {
            const applianceType = document.getElementById('applianceType').value;
            const applianceWidth = parseFloat(document.getElementById('applianceWidth').value);
            const applianceDepth = parseFloat(document.getElementById('applianceDepth').value);
            const spaceWidth = parseFloat(document.getElementById('spaceWidth').value);
            const spaceDepth = parseFloat(document.getElementById('spaceDepth').value);
            const spaceHeight = parseFloat(document.getElementById('spaceHeight').value);

            if (!applianceWidth || !applianceDepth || !spaceWidth || !spaceDepth || !spaceHeight || 
                applianceWidth < 20 || applianceDepth < 20 || spaceWidth < 24 || spaceDepth < 24 || spaceHeight < 40) {
                alert('Please enter valid values (Appliance Width/Depth ≥ 20 in, Space Width/Depth ≥ 24 in, Space Height ≥ 40 in).');
                return;
            }

            // Standard appliance heights for validation (in inches)
            const applianceHeights = {
                'Fridge': 70, // Average for standard fridges
                'Oven': 36,   // Standard counter-height oven
                'Washer': 38  // Standard washer height
            };
            const applianceHeight = applianceHeights[applianceType];

            // Check fit with clearance (1 in on each side, 1 in back)
            const widthClearance = spaceWidth - applianceWidth >= 2; // 1 in each side
            const depthClearance = spaceDepth - applianceDepth >= 1; // 1 in back
            const heightClearance = spaceHeight - applianceHeight >= 2; // 2 in above
            const applianceFit = widthClearance && depthClearance && heightClearance ? 'Yes' : 'No';

            // 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">Appliance Type</p>
                        <p class="text-lg">${applianceType}</p>
                    </div>
                    <div>
                        <p class="font-medium text-gray-700">Appliance Dimensions</p>
                        <p class="text-xl text-blue-600 font-semibold">${applianceWidth.toFixed(1)} x ${applianceDepth.toFixed(1)} x ${applianceHeight.toFixed(1)} in</p>
                    </div>
                    <div>
                        <p class="font-medium text-gray-700">Space Dimensions</p>
                        <p class="text-lg">${spaceWidth.toFixed(1)} x ${spaceDepth.toFixed(1)} x ${spaceHeight.toFixed(1)} in</p>
                    </div>
                    <div>
                        <p class="font-medium text-gray-700">Fit Assessment</p>
                        <p class="text-lg ${applianceFit === 'Yes' ? 'text-green-600' : 'text-red-600'} font-semibold">
                            ${applianceFit === 'Yes' ? 'Perfect Fit' : 'May Not Fit Comfortably'}
                        </p>
                        <p class="text-sm text-gray-600">${
                            applianceFit === 'Yes' 
                                ? 'The appliance fits well with adequate clearance.' 
                                : `Issues: ${
                                    !widthClearance ? 'Insufficient width clearance (need ≥1 in each side). ' : ''
                                }${
                                    !depthClearance ? 'Insufficient depth clearance (need ≥1 in back). ' : ''
                                }${
                                    !heightClearance ? 'Insufficient height clearance (need ≥2 in above).' : ''
                                }`
                        }</p>
                    </div>
                </div>
                <div class="bg-blue-50 p-4 rounded-lg">
                    <p class="text-sm"><span class="font-medium">Tip:</span> Ensure utility connections (power, water) align with your appliance’s requirements.</p>
                </div>
            `;

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

            // Draw visualization
            drawVisualization(applianceWidth, applianceDepth, applianceHeight, spaceWidth, applianceType);

            // Setup PDF download
            setupPdfDownload(applianceType, applianceWidth, applianceDepth, applianceHeight, spaceWidth, spaceDepth, spaceHeight, applianceFit);
        }

        function drawVisualization(applianceWidth, applianceDepth, applianceHeight, spaceWidth, applianceType) {
            const canvas = document.getElementById('applianceCanvas');
            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 / (spaceWidth * 1.5); // Scale to fit canvas
            const applianceW = applianceWidth * scale;
            const applianceH = applianceDepth * scale; // Depth for top-down view
            const spaceW = spaceWidth * 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 space outline (dashed)
            ctx.strokeStyle = '#1e40af';
            ctx.lineWidth = 2;
            ctx.setLineDash([5, 5]);
            ctx.strokeRect(canvas.width * 0.55, canvas.height * 0.2, spaceW, applianceH + 20);
            ctx.fillStyle = '#bfdbfe';
            ctx.globalAlpha = 0.3;
            ctx.fillRect(canvas.width * 0.55, canvas.height * 0.2, spaceW, applianceH + 20);
            ctx.globalAlpha = 1.0;
            ctx.setLineDash([]);

            // Draw appliance with realistic effects
            ctx.shadowColor = 'rgba(0, 0, 0, 0.4)';
            ctx.shadowBlur = 15;
            ctx.shadowOffsetX = 8;
            ctx.shadowOffsetY = 8;
            ctx.fillStyle = '#4b5563';
            const applianceX = canvas.width * 0.15;
            const applianceY = canvas.height * 0.2;
            ctx.fillRect(applianceX, applianceY, applianceW, applianceH);

            // Draw appliance texture
            const applianceGradient = ctx.createLinearGradient(applianceX, applianceY, applianceX + applianceW, applianceY + applianceH);
            applianceGradient.addColorStop(0, 'rgba(255, 255, 255, 0.15)');
            applianceGradient.addColorStop(1, 'rgba(255, 255, 255, 0.05)');
            ctx.fillStyle = applianceGradient;
            ctx.fillRect(applianceX + 5, applianceY + 5, applianceW - 10, applianceH - 10);

            // Draw text
            ctx.shadowColor = 'transparent';
            ctx.fillStyle = '#ffffff';
            ctx.font = 'bold 18px Poppins';
            ctx.textAlign = 'center';
            ctx.fillText(`${applianceType} (${applianceWidth.toFixed(1)} x ${applianceDepth.toFixed(1)} in)`, applianceX + applianceW / 2, applianceY + applianceH / 2);
            ctx.fillStyle = '#1e40af';
            ctx.fillText(`Space (${spaceWidth.toFixed(1)} in)`, canvas.width * 0.55 + spaceW / 2, canvas.height * 0.2 + (applianceH + 20) / 2);
            ctx.font = '14px Poppins';
            ctx.fillStyle = '#4b5563';
            ctx.fillText(`${applianceType} vs. Available Space`, canvas.width / 2, canvas.height - 30);
        }

        function setupPdfDownload(applianceType, applianceWidth, applianceDepth, applianceHeight, spaceWidth, spaceDepth, spaceHeight, applianceFit) {
            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('<?= $name ?> - Appliance 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 Appliance Fit Assessment', 20, 40);

                doc.setFontSize(11);
                doc.text(`Appliance Type: ${applianceType}`, 20, 50);
                doc.text(`Appliance Dimensions: ${applianceWidth.toFixed(1)} x ${applianceDepth.toFixed(1)} x ${applianceHeight.toFixed(1)} in`, 20, 58);
                doc.text(`Space Dimensions: ${spaceWidth.toFixed(1)} x ${spaceDepth.toFixed(1)} x ${spaceHeight.toFixed(1)} in`, 20, 66);
                doc.text(`Fit Assessment: ${applianceFit === 'Yes' ? 'Perfect Fit' : 'May Not Fit Comfortably'}`, 20, 74);
                doc.text(`Recommendation: ${
                    applianceFit === 'Yes' 
                        ? 'The appliance is suitable for your space.' 
                        : 'Consider a smaller appliance or adjust your space layout.'
                }`, 20, 82);

                // Expert Insights
                doc.setFont('helvetica', 'bold');
                doc.setFontSize(12);
                doc.text('Expert Insights', 20, 94);
                doc.setFont('helvetica', 'normal');
                doc.setFontSize(10);
                doc.text('• Clearance: Allow 1-2 in on each side and back for ventilation.', 20, 102);
                doc.text('• Height Planning: Ensure space above accommodates height.', 20, 110);
                doc.text('• Accessibility: Maintain 3 ft clear floor space in front.', 20, 118);
                doc.text('• Utilities: Confirm electrical/water line alignment.', 20, 126);
                doc.text('• Workflow: Optimize appliance position for efficiency.', 20, 134);

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