const ProteinCalculatorExtension = { name: 'ext_protein_calculator_v2', // Changed name slightly to avoid cache issues if needed type: 'response', match: ({ trace }) => { if (!trace) return false; return ( trace.type === 'ext_protein_calculator_v2' || (trace.payload && trace.payload.name === 'ext_protein_calculator_v2') ) && trace.type !== 'typing'; }, render: ({ trace, element }) => { const container = document.createElement('div'); container.classList.add('procalc-container'); // Unique namespace // --- State Variables --- let currentStep = 1; const formData = { gender: '', age: '25', weight: '70', height: '170', activityLevel: '', goal: '' }; let result = null; let isCalculating = false; // To show loading state // --- HTML Structure --- container.innerHTML = `
1
البيانات
2
النشاط
3
الهدف
4
النتيجة
جاري الحساب...

البيانات الشخصية

أدخل معلوماتك لحساب احتياجك من البروتين.

ذكر
أنثى
سنة
سم
كجم

مستوى النشاط

حدد مستوى نشاطك اليومي.

ما هو هدفك؟

اختر هدفك الرئيسي لتخصيص كمية البروتين.

النتيجة النهائية

`; // --- DOM Element References --- const stepContents = container.querySelectorAll('.procalc-step-content'); const stepIndicators = container.querySelectorAll('.procalc-step-item'); const progressBar = container.querySelector('#procalc-progress-bar'); const nextBtn = container.querySelector('#procalc-next-btn'); const prevBtn = container.querySelector('#procalc-prev-btn'); const loadingOverlay = container.querySelector('#procalc-loading'); const resultsArea = container.querySelector('#procalc-results-area'); // --- Helper Functions --- function updateProgressBar() { const progressPercentage = ((currentStep - 1) / (stepIndicators.length -1)) * 100; // Ensure progress doesn't exceed 100 if results step is considered "complete" visually progressBar.style.width = `${Math.min(progressPercentage, 100)}%`; } function updateView() { stepContents.forEach(content => { content.classList.toggle('active', parseInt(content.dataset.stepContent) === currentStep); }); stepIndicators.forEach(indicator => { const stepNum = parseInt(indicator.dataset.step); indicator.classList.toggle('active', stepNum === currentStep); indicator.classList.toggle('completed', stepNum < currentStep); }); updateProgressBar(); prevBtn.disabled = currentStep === 1 || isCalculating; nextBtn.disabled = !isStepComplete(currentStep) || isCalculating; if (currentStep === stepIndicators.length) { // Results step nextBtn.classList.add('procalc-hidden'); prevBtn.textContent = 'إعادة الحساب'; prevBtn.disabled = isCalculating; // Disable only if calculating prevBtn.onclick = () => { if (!isCalculating) resetCalculator(); }; } else { nextBtn.classList.remove('procalc-hidden'); nextBtn.textContent = (currentStep === stepIndicators.length - 1) ? 'حساب النتيجة' : 'التالي'; prevBtn.textContent = 'السابق'; prevBtn.onclick = () => { if (!isCalculating) navigateStep(-1); }; } } function resetCalculator() { currentStep = 1; formData.gender = ''; formData.activityLevel = ''; formData.goal = ''; result = null; isCalculating = false; // Reset visual selections container.querySelectorAll('.procalc-gender-option.selected').forEach(opt => opt.classList.remove('selected')); container.querySelectorAll('.procalc-choice-option.selected').forEach(opt => { opt.classList.remove('selected'); const radio = opt.querySelector('input[type="radio"]'); if (radio) radio.checked = false; }); container.querySelector('#procalc-age-value').value = '25'; container.querySelector('#procalc-height-value').value = '170'; container.querySelector('#procalc-weight-value').value = '70'; resultsArea.innerHTML = ''; // Clear results loadingOverlay.style.display = 'none'; updateView(); } function isStepComplete(step) { switch (step) { case 1: return !!(formData.gender && formData.age && formData.weight && formData.height); case 2: return !!formData.activityLevel; case 3: return !!formData.goal; default: return false; } } function navigateStep(direction) { if (isCalculating) return; // Prevent navigation during calculation if (direction > 0 && !isStepComplete(currentStep)) { return; } const nextStepIndex = currentStep + direction; if (nextStepIndex > 0 && nextStepIndex <= stepIndicators.length) { if (currentStep === 3 && direction > 0) { // Trigger calculation process startCalculation(); } else { currentStep = nextStepIndex; updateView(); } } } // --- Calculation Logic (same as before) --- function calculateProteinLogic() { // ... (Calculation logic remains identical to the previous version) const age = parseInt(formData.age, 10); const weight = parseFloat(formData.weight); const height = parseFloat(formData.height); const gender = formData.gender; const activityLevel = formData.activityLevel; const goal = formData.goal; if (!age || !weight || !height || !gender || !activityLevel || !goal) return null; let bmr = (gender === 'male') ? (10 * weight + 6.25 * height - 5 * age + 5) : (10 * weight + 6.25 * height - 5 * age - 161); const activityMultipliers = { sedentary: 1.2, light: 1.375, moderate: 1.55, active: 1.725, veryActive: 1.9 }; const tdee = bmr * (activityMultipliers[activityLevel] || 1.2); let proteinPerKg, explanation; switch (goal) { case 'muscle': proteinPerKg = 1.8; explanation = "لبناء كتلة عضلية، يوصى بتناول كمية أعلى من البروتين (حوالي 1.6-2.2 جرام لكل كجم)."; break; case 'lose': proteinPerKg = 2.0; explanation = "عند فقدان الوزن، يساعد البروتين الأعلى (حوالي 1.8-2.2 جرام لكل كجم) على الحفاظ على العضلات وزيادة الشبع."; break; case 'maintain': default: proteinPerKg = 1.3; explanation = "للحفاظ على الوزن والصحة العامة، يكفي تناول بروتين معتدل (حوالي 1.2-1.4 جرام لكل كجم)."; break; } const dailyProtein = Math.round(weight * proteinPerKg); const caloriesFromProtein = dailyProtein * 4; const proteinPercentage = tdee > 0 ? Math.round((caloriesFromProtein / tdee) * 100) : 0; return { dailyProtein, tdee: Math.round(tdee), proteinPercentage, explanation }; } // --- Calculation Process --- function startCalculation() { isCalculating = true; loadingOverlay.style.display = 'flex'; updateView(); // Disable buttons // Simulate calculation delay (optional, but good UX) setTimeout(() => { result = calculateProteinLogic(); isCalculating = false; loadingOverlay.style.display = 'none'; if (result) { displayResults(); currentStep = 4; // Move to results step *after* calculation updateView(); // Update view to show results step and enable reset button sendResultsToVoiceflow(); } else { // Handle calculation error (e.g., show message) console.error("Calculation failed"); resultsArea.innerHTML = "

حدث خطأ أثناء الحساب. يرجى التحقق من المدخلات.

"; currentStep = 4; // Still go to results step to show error updateView(); } }, 1500); // Simulate 1.5 seconds calculation time } // --- Display Results --- function displayResults() { if (!result) return; const radius = 80; // Circle radius const circumference = 2 * Math.PI * radius; // Calculate offset based on protein percentage (max 100%) const progressOffset = circumference - (Math.min(result.proteinPercentage, 100) / 100) * circumference; resultsArea.innerHTML = `
${result.dailyProtein}
جرام بروتين يومياً
السعرات اليومية
${result.tdee}
نسبة البروتين
${result.proteinPercentage}%
توصية: ${result.explanation}
`; // Animate the progress circle after rendering setTimeout(() => { const progressCircle = resultsArea.querySelector('.procalc-result-circle-progress'); if (progressCircle) { progressCircle.style.strokeDashoffset = progressOffset; } }, 100); // Small delay to ensure element is in DOM for transition } // --- Send Data to Voiceflow --- function sendResultsToVoiceflow() { if (!result) return; if (window.voiceflow?.chat?.interact) { window.voiceflow.chat.interact({ type: 'complete', payload: { calculatedProtein: result.dailyProtein, calculatedTDEE: result.tdee, proteinPercentage: result.proteinPercentage, goal: formData.goal, explanation: result.explanation // Include original inputs if needed } }); // **REMOVED**: No longer hiding the calculator or showing checkmark } else { console.error("Voiceflow interact function not available."); } } // --- Event Listeners Setup --- function setupEventListeners() { // Gender container.querySelectorAll('.procalc-gender-option').forEach(option => { option.addEventListener('click', () => { if (isCalculating) return; container.querySelectorAll('.procalc-gender-option').forEach(opt => opt.classList.remove('selected')); option.classList.add('selected'); formData.gender = option.dataset.gender; updateView(); }); }); // Numeric Inputs const setupNumericInput = (inputId, decreaseBtnId, increaseBtnId, formKey, min, max) => { const valueElement = container.querySelector(`#${inputId}`); const decreaseBtn = container.querySelector(`#${decreaseBtnId}`); const increaseBtn = container.querySelector(`#${increaseBtnId}`); const updateValue = (newValue) => { newValue = Math.max(min, Math.min(max, parseInt(newValue, 10) || min)); valueElement.value = newValue; formData[formKey] = String(newValue); updateView(); }; decreaseBtn.addEventListener('click', () => { if (!isCalculating) updateValue(valueElement.value - 1); }); increaseBtn.addEventListener('click', () => { if (!isCalculating) updateValue(parseInt(valueElement.value, 10) + 1); }); valueElement.addEventListener('change', () => { if (!isCalculating) updateValue(valueElement.value); }); valueElement.addEventListener('input', () => { // Live update check if (!isCalculating) { const currentVal = parseInt(valueElement.value, 10); if (!isNaN(currentVal) && currentVal >= min && currentVal <= max) { formData[formKey] = String(currentVal); updateView(); } else if (valueElement.value === '') { formData[formKey] = ''; updateView(); } } else { // Prevent input change during calculation if desired valueElement.value = formData[formKey]; } }); }; setupNumericInput('procalc-age-value', 'procalc-age-decrease', 'procalc-age-increase', 'age', 14, 80); setupNumericInput('procalc-height-value', 'procalc-height-decrease', 'procalc-height-increase', 'height', 50, 250); setupNumericInput('procalc-weight-value', 'procalc-weight-decrease', 'procalc-weight-increase', 'weight', 30, 300); // Activity & Goal Choices const setupChoiceGroup = (groupId, formKey) => { container.querySelectorAll(`#${groupId} .procalc-choice-option`).forEach(label => { label.addEventListener('click', () => { if (isCalculating) return; container.querySelectorAll(`#${groupId} .procalc-choice-option`).forEach(opt => opt.classList.remove('selected')); label.classList.add('selected'); const radio = label.querySelector('input[type="radio"]'); if (radio) { radio.checked = true; formData[formKey] = radio.value; } updateView(); }); }); }; setupChoiceGroup('procalc-activity-group', 'activityLevel'); setupChoiceGroup('procalc-goal-group', 'goal'); // Navigation Buttons nextBtn.addEventListener('click', () => navigateStep(1)); // Prev button handler is set dynamically in updateView } // --- Initial Setup --- setupEventListeners(); updateView(); // Initialize the view element.appendChild(container); } }; // Branches Extension const BranchesExtension = { name: 'BranchesExtension', type: 'response', match: ({ trace }) => (trace.type === 'ext_branches' || trace.payload?.name === 'ext_branches') && trace.type !== 'typing', render: ({ trace, element }) => { const header = createBranchHeader(); const branchesContainer = createBranchesContainer(element); element.appendChild(header); element.appendChild(branchesContainer); } }; function createBranchHeader() { const header = document.createElement('div'); header.classList.add('jeddah-branches-header'); // تم تغيير اسم الـ class ليكون أكثر تخصيصاً header.innerText = 'فروعنا في جدة'; header.style.backgroundColor = '#228B22'; header.style.color = 'white'; header.style.padding = '15px'; header.style.fontSize = '1.7rem'; header.style.textAlign = 'center'; header.style.width = '200px'; header.style.fontWeight = 'bold'; header.style.boxShadow = '0 2px 4px rgba(0,0,0,0.1)'; header.style.borderRadius = '10px 10px 0 0'; return header; } function createBranchesContainer(element) { const branchesContainer = document.createElement('div'); branchesContainer.style.display = 'flex'; branchesContainer.style.flexWrap = 'wrap'; branchesContainer.style.justifyContent = 'center'; branchesContainer.style.width = '200px'; branchesContainer.style.gap = '10px'; branchesContainer.style.padding = '15px'; branchesContainer.style.backgroundColor = '#f4f4f4'; branchesContainer.style.borderRadius = '0 0 10px 10px'; // أسماء الفروع مع روابط الصور const branches = [ { name: 'صقر قريش', image: 'https://lh5.googleusercontent.com/p/AF1QipNfDi7llMovSplsBY9ygybB2p3ZKO2yfB4ZMoww=w408-h544-k-no' }, { name: 'أبحر الشمالية', image: 'https://lh5.googleusercontent.com/p/AF1QipMlpzEBCzWGt2M-PrZa5cJgJveq9TOnCNLuYQMh=w408-h725-k-no' }, { name: 'الحمدانية', image: 'https://lh5.googleusercontent.com/p/AF1QipOP5n_dNT1bKjWYByWJ-7X9fgZn6VItYPmhjyOL=w408-h306-k-no' }, { name: 'الروضة', image: 'https://lh5.googleusercontent.com/p/AF1QipPttcQYbeQ7uk0rhFKmHDWaOWPw97ryzoVejxC6=w408-h544-k-no' }, { name: 'المروة', image: 'https://lh5.googleusercontent.com/p/AF1QipPfI2G9_AalJbguPUUMF7jp3v5kDe__0dTGg-S0=w224-h298-k-no' }, { name: 'الزهراء', image: 'https://lh5.googleusercontent.com/p/AF1QipMUFGFvn9TGq7EMZLSEY61yC-ifMrxviMzRzLfV=w408-h544-k-no' }, { name: 'النهضة', image: 'https://lh5.googleusercontent.com/p/AF1QipP291aww9OSqidmBOgJzOFQAPO-dRQIb1RSa0oL=w408-h544-k-no' }, { name: 'الفيحاء', image: 'https://lh5.googleusercontent.com/p/AF1QipPV48U778SABXPg10S1DCxHkCs6nZjnEawLVvew=w224-h298-k-no' }, { name: 'البساتين', image: 'https://lh5.googleusercontent.com/p/AF1QipP291aww9OSqidmBOgJzOFQAPO-dRQIb1RSa0oL=w224-h298-k-no' }, { name: 'المرجان', image: 'https://lh5.googleusercontent.com/p/AF1QipOY1fL3jLWyzwiTXyMgIHjOfpwvy-4Rrmd6QDD_=w408-h544-k-no' }, { name: 'السنابل', image: 'https://play-lh.googleusercontent.com/XDe4Y9hNV9nnG2DM9OKe2zeOwgMrIFAsVbY90A9dPZh7V2TxvlSNBOoO1dAouwKWhd7c' }, { name: 'قريش', image: 'https://lh5.googleusercontent.com/p/AF1QipOC9je9MFV6S6S7LzdaR0q915OL4lQ28X0uci6D=w397-h298-k-no' } ]; // إنشاء أيقونات الفروع مع تحسينات التصميم branches.forEach((branch) => { const branchCard = document.createElement('div'); branchCard.style.width = '200px'; branchCard.style.height = '160px'; branchCard.style.position = 'relative'; branchCard.style.borderRadius = '12px'; branchCard.style.overflow = 'hidden'; branchCard.style.boxShadow = '0 4px 6px rgba(0,0,0,0.1)'; branchCard.style.transition = 'transform 0.3s ease'; // تأثير التحويم مع حافة خضراء branchCard.addEventListener('mouseenter', () => { branchCard.style.transform = 'scale(1.05)'; branchCard.style.border = '2px solid rgba(34, 139, 34, 0.5)'; }); branchCard.addEventListener('mouseleave', () => { branchCard.style.transform = 'scale(1)'; branchCard.style.border = 'none'; }); // صورة الخلفية const backgroundImg = document.createElement('div'); backgroundImg.style.width = '100%'; backgroundImg.style.height = '100%'; // --- التصحيح هنا --- // يجب أن تكون قيمة backgroundImage سلسلة نصية تحتوي على url() backgroundImg.style.backgroundImage = `url("${branch.image}")`; // --- نهاية التصحيح --- backgroundImg.style.backgroundSize = 'cover'; backgroundImg.style.backgroundPosition = 'center'; backgroundImg.style.filter = 'brightness(0.7)'; // طبقة التغطية مع تدرج لونى محسن const overlay = document.createElement('div'); overlay.style.position = 'absolute'; overlay.style.top = '0'; overlay.style.left = '0'; overlay.style.width = '100%'; overlay.style.height = '100%'; overlay.style.background = 'linear-gradient(to bottom, rgba(0,0,0,0.1), rgba(0,0,0,0.6))'; // زر الفرع بتصميم عصري const branchButton = document.createElement('button'); branchButton.innerText = branch.name; branchButton.style.position = 'absolute'; branchButton.style.bottom = '10px'; branchButton.style.left = '50%'; branchButton.style.transform = 'translateX(-50%)'; branchButton.style.backgroundColor = 'white'; branchButton.style.color = '#228B22'; branchButton.style.border = 'none'; branchButton.style.padding = '3px 6px'; branchButton.style.fontSize = '1.2rem'; branchButton.style.borderRadius = '20px'; branchButton.style.cursor = 'pointer'; branchButton.style.boxShadow = '0 2px 4px rgba(0,0,0,0.2)'; branchButton.style.transition = 'all 0.3s ease'; // تأثير النقر على الزر branchButton.addEventListener('mouseenter', () => { branchButton.style.backgroundColor = '#228B22'; branchButton.style.color = 'white'; }); branchButton.addEventListener('mouseleave', () => { branchButton.style.backgroundColor = 'white'; branchButton.style.color = '#228B22'; }); branchButton.addEventListener('click', () => { window.voiceflow.chat.interact({ type: 'complete', payload: { branch: branch.name }, }); element.innerHTML = ''; const successMessage = document.createElement('div'); successMessage.textContent = '✅'; successMessage.style.fontSize = "3rem"; successMessage.style.color = "#4C9A2A"; successMessage.style.marginTop = "4px"; successMessage.style.fontWeight = "bold"; successMessage.style.textAlign = "center"; element.appendChild(successMessage); }); branchCard.appendChild(backgroundImg); branchCard.appendChild(overlay); branchCard.appendChild(branchButton); branchesContainer.appendChild(branchCard); }); return branchesContainer; } // Riyadh Branches Extension const RiyadhBranchesExtension = { name: 'RiyadhBranchesExtension', type: 'response', match: ({ trace }) => (trace.type === 'ext_riyadh_branches' || trace.payload?.name === 'ext_riyadh_branches') && trace.type !== 'typing', render: ({ trace, element }) => { const header = createRiyadhBranchHeader(); const branchesContainer = createRiyadhBranchesContainer(element); element.appendChild(header); element.appendChild(branchesContainer); } }; function createRiyadhBranchHeader() { const header = document.createElement('div'); header.classList.add('riyadh-branches-header'); // تم تغيير اسم الـ class ليكون أكثر تخصيصاً header.innerText = 'فروعنا في الرياض'; header.style.backgroundColor = '#228B22'; header.style.color = 'white'; header.style.padding = '15px'; header.style.fontSize = '1.7rem'; header.style.textAlign = 'center'; header.style.width = '200px'; header.style.fontWeight = 'bold'; header.style.boxShadow = '0 2px 4px rgba(0,0,0,0.1)'; header.style.borderRadius = '10px 10px 0 0'; return header; } function createRiyadhBranchesContainer(element) { const branchesContainer = document.createElement('div'); branchesContainer.style.display = 'flex'; branchesContainer.style.flexWrap = 'wrap'; branchesContainer.style.justifyContent = 'center'; branchesContainer.style.width = '200px'; branchesContainer.style.gap = '10px'; branchesContainer.style.padding = '15px'; branchesContainer.style.backgroundColor = '#f4f4f4'; branchesContainer.style.borderRadius = '0 0 10px 10px'; // أسماء الفروع مع روابط الصور const branches = [ { name: 'حي الحمراء', image: 'https://lh5.googleusercontent.com/p/AF1QipN1agMmn_udNkJ5UXvg9SA-rTknxN4XvZxY0JjO=w408-h306-k-no' }, { name: 'حي النزهة', image: 'https://lh5.googleusercontent.com/p/AF1QipOcWeXSVfX30jMc2IGULygTdn3dHFTTJl-TG5St=w408-h544-k-no' }, { name: 'حى الصحافة', image: 'https://lh5.googleusercontent.com/p/AF1QipP3J3iUQbV_lZRz1xjGUFXV67CxJCTyXSbLpEHt=w408-h306-k-no' }, { name: 'حي الربيع', image: 'https://lh5.googleusercontent.com/p/AF1QipOZu8c786zvZkdLf00YJWaHIXDcP5saHKxNTdTo=w408-h306-k-no' } ]; // إنشاء أيقونات الفروع مع تحسينات التصميم branches.forEach((branch) => { const branchCard = document.createElement('div'); branchCard.style.width = '200px'; branchCard.style.height = '160px'; branchCard.style.position = 'relative'; branchCard.style.borderRadius = '12px'; branchCard.style.overflow = 'hidden'; branchCard.style.boxShadow = '0 4px 6px rgba(0,0,0,0.1)'; branchCard.style.transition = 'transform 0.3s ease'; // تأثير التحويم مع حافة خضراء branchCard.addEventListener('mouseenter', () => { branchCard.style.transform = 'scale(1.05)'; branchCard.style.border = '2px solid rgba(34, 139, 34, 0.5)'; }); branchCard.addEventListener('mouseleave', () => { branchCard.style.transform = 'scale(1)'; branchCard.style.border = 'none'; }); // صورة الخلفية const backgroundImg = document.createElement('div'); backgroundImg.style.width = '100%'; backgroundImg.style.height = '100%'; // --- التصحيح هنا --- // يجب أن تكون قيمة backgroundImage سلسلة نصية تحتوي على url() backgroundImg.style.backgroundImage = `url("${branch.image}")`; // --- نهاية التصحيح --- backgroundImg.style.backgroundSize = 'cover'; backgroundImg.style.backgroundPosition = 'center'; backgroundImg.style.filter = 'brightness(0.7)'; // طبقة التغطية مع تدرج لونى محسن const overlay = document.createElement('div'); overlay.style.position = 'absolute'; overlay.style.top = '0'; overlay.style.left = '0'; overlay.style.width = '100%'; overlay.style.height = '100%'; overlay.style.background = 'linear-gradient(to bottom, rgba(0,0,0,0.1), rgba(0,0,0,0.6))'; // زر الفرع بتصميم عصري const riyadhBranchButton = document.createElement('button'); riyadhBranchButton.innerText = branch.name; riyadhBranchButton.style.position = 'absolute'; riyadhBranchButton.style.bottom = '10px'; riyadhBranchButton.style.left = '50%'; riyadhBranchButton.style.transform = 'translateX(-50%)'; riyadhBranchButton.style.backgroundColor = 'white'; riyadhBranchButton.style.color = '#228B22'; riyadhBranchButton.style.border = 'none'; riyadhBranchButton.style.padding = '3px 6px'; riyadhBranchButton.style.fontSize = '1.2rem'; riyadhBranchButton.style.borderRadius = '20px'; riyadhBranchButton.style.cursor = 'pointer'; riyadhBranchButton.style.boxShadow = '0 2px 4px rgba(0,0,0,0.2)'; riyadhBranchButton.style.transition = 'all 0.3s ease'; // تأثير النقر على الزر riyadhBranchButton.addEventListener('mouseenter', () => { riyadhBranchButton.style.backgroundColor = '#228B22'; riyadhBranchButton.style.color = 'white'; }); riyadhBranchButton.addEventListener('mouseleave', () => { riyadhBranchButton.style.backgroundColor = 'white'; riyadhBranchButton.style.color = '#228B22'; }); riyadhBranchButton.addEventListener('click', () => { window.voiceflow.chat.interact({ type: 'complete', payload: { branch: branch.name }, }); element.innerHTML = ''; const successMessage = document.createElement('div'); successMessage.textContent = '✅'; successMessage.style.fontSize = "3rem"; successMessage.style.color = "#4C9A2A"; successMessage.style.marginTop = "4px"; successMessage.style.fontWeight = "bold"; successMessage.style.textAlign = "center"; element.appendChild(successMessage); }); branchCard.appendChild(backgroundImg); branchCard.appendChild(overlay); branchCard.appendChild(riyadhBranchButton); branchesContainer.appendChild(branchCard); }); return branchesContainer; } const ProductCarouselExtension = { name: 'ProductCarousel', type: 'response', match: ({ trace }) => (trace.type === 'ext_productCarousel' || (trace.payload && trace.payload.name === 'ext_productCarousel')) && trace.type !== 'typing', render: ({ trace, element }) => { // استخراج بيانات المنتج من الـ payload const payload = trace.payload || {}; const products = []; console.log("Full payload received:", JSON.stringify(payload)); // التحقق إذا كان الـ payload يحتوي على مصفوفة منتجات if (payload.products && Array.isArray(payload.products)) { // معالجة مصفوفة المنتجات payload.products.forEach((product) => { // *** تعديل الشرط هنا *** // التحقق إذا كان اسم المنتج موجودًا وليس "Unused" if (product.name && product.name !== 'Unused') { products.push({ name: product.name, price: product.price, image: product.image, link: product.link, }); } }); } else { // التوافق مع الصيغة القديمة: محاولة استخدام الصيغة القديمة مع خصائص مسطحة console.log("Using flat format, checking product variables"); // التعامل مع المنتج الأول بشكل صريح // *** تعديل الشرط هنا *** // التحقق إذا كان اسم المنتج الأول موجودًا وليس "Unused" if (payload.productName && payload.productName !== 'Unused') { console.log("Adding first product:", payload.productName); products.push({ name: payload.productName, price: payload.productPrice || '', image: payload.productImage || '', link: payload.productLink || '#', }); } // التعامل مع المنتجات الإضافية (من 2 إلى 10) for (let i = 2; i <= 10; i++) { const name = payload[`productName${i}`]; const price = payload[`productPrice${i}`]; const image = payload[`productImage${i}`]; const link = payload[`productLink${i}`]; // *** تعديل الشرط هنا *** // التحقق إذا كان اسم المنتج موجودًا وليس "Unused" if (name && name !== 'Unused') { console.log(`Adding product ${i}:`, name); products.push({ name, price: price || '', image: image || '', link: link || '#', }); } } } const productCount = products.length; console.log('Number of products found:', productCount); console.log('Products array:', products); // إرسال عدد المنتجات إلى Voiceflow if (window.voiceflow && window.voiceflow.interact) { console.log("Sending numberOfProducts to Voiceflow:", productCount); window.voiceflow.interact({ type: 'setVariables', payload: { // Use payload for setVariables variables: { numberOfProducts: productCount } } }); // إرسال حدث لـ Voiceflow للانتقال إلى المسار المناسب setTimeout(() => { if (productCount > 0) { console.log("Products were displayed, sending event to Voiceflow"); window.voiceflow.interact({ type: 'request', payload: { type: 'The_products_were_displayed' // يمكنك إضافة بيانات إضافية هنا إذا لزم الأمر // payload: { customData: 'someValue' } } }); } else { console.log("Products were not displayed, sending event to Voiceflow"); window.voiceflow.interact({ type: 'request', payload: { type: 'The_products_were_not_displayed' // يمكنك إضافة بيانات إضافية هنا إذا لزم الأمر // payload: { customData: 'someValue' } } }); } }, 100); // تأخير صغير للتأكد من أن متغير numberOfProducts تم تعيينه أولاً } else { console.log("Voiceflow interact not available"); } // لا نعرض أي شيء إذا لم تكن هناك منتجات if (productCount === 0) { console.log("No products to display, exiting render function"); return; // نخرج من الدالة بدون إضافة أي عناصر إلى DOM } // إنشاء حاوية بفئة مساحة اسم const container = document.createElement('div'); container.classList.add('prc-carousel-container'); // إضافة اتجاه RTL للعربية container.setAttribute('dir', 'rtl'); // إنشاء HTML بناءً على عدد المنتجات const carouselHTML = `
${products .map( (product) => `
${product.name}
${product.name}
${product.price ? `
${product.price}
` : ''} ${product.link && product.link !== '#' ? `شوف المنتج 🛍️` : ''}
` ) .join('')}
`; console.log("Rendering product carousel with", productCount, "products"); container.innerHTML = carouselHTML; element.appendChild(container); }, }; (function(d, t) { var v = d.createElement(t), s = d.getElementsByTagName(t)[0]; v.onload = function() { window.voiceflow.chat.load({ verify: { projectID: '67f994f3fb9958d3e522e312' }, url: 'https://general-runtime.voiceflow.com', versionID: 'production', assistant: { extensions: [ ProteinCalculatorExtension, BranchesExtension, RiyadhBranchesExtension, ProductCarouselExtension ], stylesheet: "data:text/css;base64,LnZmcmMtc3lzdGVtLXJlc3BvbnNlLS1hY3Rpb25zIHsKICAgIGRpc3BsYXk6IGZsZXggIWltcG9ydGFudDsKICAgIHZpc2liaWxpdHk6IHZpc2libGUgIWltcG9ydGFudDsKICAgIG9wYWNpdHk6IDEgIWltcG9ydGFudDsKfQoKLnZmcmMtc3lzdGVtLXJlc3BvbnNlLS1jb250cm9scyB7CiAgICBkaXNwbGF5OiBmbGV4ICFpbXBvcnRhbnQ7CiAgICB2aXNpYmlsaXR5OiB2aXNpYmxlICFpbXBvcnRhbnQ7CiAgICBvcGFjaXR5OiAxICFpbXBvcnRhbnQ7Cn0KLyogSGlkZSBvcmlnaW5hbCBkb3RzICovCi52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XQtLXN0YXR1cyAuXzFvNjlveWMyIHsKICAgIGNvbG9yOiAjNjY2NjY2OyAgLyog2YTZiNmGINix2YXYp9iv2Yog2K/Yp9mD2YYgKi8KfQoKLyog2KrYutmK2YrYsSDYp9mE2YbYtSDZhdio2KfYtNix2KkgKi8KLnZmcmMtY2hhdC0tc3RhdHVzIC5fMW82OW95YzI6bm90KDplbXB0eSkgewogICAgZm9udC1mYW1pbHk6IGluaGVyaXQ7CiAgICB0ZXh0LWFsaWduOiBjZW50ZXI7Cn0KCi8qINin2LPYqtio2K/Yp9mEINin2YTZhti1INin2YTYpdmG2KzZhNmK2LLZiiDYqNin2YTYudix2KjZiiAqLwoudmZyYy1jaGF0LS1zdGF0dXMgLl8xbzY5b3ljMjpub3QoOmVtcHR5KTo6YWZ0ZXIgewogICAgY29udGVudDogItin2YbYqtmH2Kog2KfZhNmF2K3Yp9iv2KvYqSI7Cn0KCi52ZnJjLWNoYXQtLXN0YXR1cyAuXzFvNjlveWMyOm5vdCg6ZW1wdHkpIHsKICAgIHZpc2liaWxpdHk6IGhpZGRlbjsKfQoKLnZmcmMtY2hhdC0tc3RhdHVzIC5fMW82OW95YzI6bm90KDplbXB0eSk6OmFmdGVyIHsKICAgIHZpc2liaWxpdHk6IHZpc2libGU7CiAgICBwb3NpdGlvbjogYWJzb2x1dGU7CiAgICBsZWZ0OiA1MCU7CiAgICB0cmFuc2Zvcm06IHRyYW5zbGF0ZVgoLTUwJSk7Cn0KCi52ZnJjLXByb2FjdGl2ZSB7CiAgcG9zaXRpb246IGZpeGVkICFpbXBvcnRhbnQ7CiAgcmlnaHQ6IC0xMDBweCAhaW1wb3J0YW50OwogIGJvdHRvbTogNTBweCAhaW1wb3J0YW50Owp9" }, voice: { url: "https://runtime-api.voiceflow.com" } }).then(() => { window.voiceflow.chat.proactive.clear(); // يمسح أي رسالة سابقة window.voiceflow.chat.proactive.push( { type: 'text', payload: { message: 'هلا 👋' } }, { type: 'text', payload: { message: 'تبغى مساعدة بشيء؟' } } ); }); }; v.src = "https://cdn.voiceflow.com/widget-next/bundle.mjs"; v.type = "text/javascript"; s.parentNode.insertBefore(v, s); })(document, 'script');