const LOCAL_SCENE_KEY = 'nanavstevu_local_scene'; const LAST_SCENE_KEY_PREFIX = 'nanavstevu_testpage_last_scene_'; const LAST_SCENE_INDEX_KEY = 'nanavstevu_testpage_last_scenes_index'; const LAST_SCENE_MAX_ROOMS = 10; const SAVE_DEBOUNCE_MS = 800; var currentRoom = null; var pendingRoom = null; var lastSceneJson = null; var lastScene = null; var shoppingItems = []; var shoppingRun = 0; var _localSaveRequested = false; var _sceneJsonResolver = null; const sceneSaver = { timer: null, schedule() { this.cancel(); this.timer = setTimeout(() => { this.timer = null; this.publish(); }, SAVE_DEBOUNCE_MS); }, saveNow() { this.cancel(); this.publish(); }, flush() { if (this.timer) { this.saveNow(); } }, cancel() { if (this.timer) { clearTimeout(this.timer); this.timer = null; } }, publish() { sendToUnity('GetSceneJson'); } }; document.addEventListener('visibilitychange', () => { if (document.hidden) { sceneSaver.flush(); } }); function onSceneLoaded() { console.log('Scene has been loaded'); unitySceneLoaded = true; if (pendingRoom) { const room = pendingRoom; pendingRoom = null; applyRoomToUnity(room); } } function openRoomInDesigner(room) { sceneSaver.cancel(); currentRoom = room; $('#room-name').textContent = room.name + (room.local ? ' (local only)' : ''); if (!activeTab) { activateTab('furniture'); } if (!unitySceneLoaded) { pendingRoom = room; setSceneStatus('waiting for Unity to load the scene…'); return; } applyRoomToUnity(room); } function applyRoomToUnity(room) { resetDesignerState(); const sceneData = typeof room.sceneData === 'string' ? room.sceneData : ''; const hasScene = sceneData.length > 10; lastSceneJson = null; setLastScene(hasScene ? sceneData : null); sendToUnity('LoadJson', hasScene ? sceneData : ''); sendToUnity('ThreeD'); setViewModeUi(true); sendToUnity('TransformMode', '0'); setSceneStatus(hasScene ? 'room scene loaded' : 'empty room loaded'); if (room.onboarding) { openRoomSizeDialog(true); } } function setLastScene(json) { lastScene = null; if (json) { try { lastScene = JSON.parse(json); } catch (e) { console.warn('scene json is not valid JSON', e); } } recomputeShoppingList(); } function getSceneJson(sceneJson) { if (_sceneJsonResolver) { const resolve = _sceneJsonResolver; _sceneJsonResolver = null; resolve(sceneJson); } if (_localSaveRequested) { _localSaveRequested = false; try { localStorage.setItem(LOCAL_SCENE_KEY, sceneJson); toast('Scene saved to localStorage'); } catch (e) { toast('Local save failed: ' + e.message, 'error'); } } if (sceneJson === lastSceneJson) { return; } lastSceneJson = sceneJson; if (currentRoom) { storeLastScene(currentRoom.id, sceneJson); } setSceneStatus('scene captured ' + new Date().toLocaleTimeString() + ' (kept locally, not uploaded)'); setLastScene(sceneJson); } function storeLastScene(roomId, sceneJson) { try { let index = JSON.parse(localStorage.getItem(LAST_SCENE_INDEX_KEY) || '[]'); if (!Array.isArray(index)) { index = []; } for (let i = localStorage.length - 1; i >= 0; i--) { const key = localStorage.key(i); if (key && key.startsWith(LAST_SCENE_KEY_PREFIX + 'blank-')) { localStorage.removeItem(key); } } index = [roomId].concat(index.filter((id) => id !== roomId)); index.slice(LAST_SCENE_MAX_ROOMS).forEach((id) => localStorage.removeItem(LAST_SCENE_KEY_PREFIX + id)); index = index.slice(0, LAST_SCENE_MAX_ROOMS); localStorage.setItem(LAST_SCENE_INDEX_KEY, JSON.stringify(index)); localStorage.setItem(LAST_SCENE_KEY_PREFIX + roomId, sceneJson); } catch (e) { console.warn('last scene not stored locally', e); } } function requestSceneJson() { return new Promise((resolve) => { _sceneJsonResolver = resolve; sendDev('GetSceneJson'); }); } function setSceneStatus(message) { $('#scene-status').textContent = 'scene: ' + message; } function sceneAccessoryIds(scene) { if (!scene || !Array.isArray(scene._rooms)) { return []; } return scene._rooms .flatMap((room) => room._objects || []) .map((object) => object._accesoryId) .filter((id) => id && String(id).trim() !== ''); } function accessoryPrice(accessory) { const price = Number(accessory && accessory.primaryVariant ? accessory.primaryVariant.price : undefined); return Number.isFinite(price) ? price : 0; } async function recomputeShoppingList() { const run = ++shoppingRun; const button = $('#shopping-total'); const ids = sceneAccessoryIds(lastScene); if (offlineMode) { shoppingItems = []; button.textContent = 'Shopping list: offline (' + ids.length + ' items)'; return; } if (ids.length === 0) { shoppingItems = []; button.textContent = 'Shopping list: ' + formatCzk(0); return; } button.textContent = 'Shopping list: calculating…'; await loadManufacturers(); const unique = [...new Set(ids)]; const results = await Promise.all(unique.map((id) => fetchAccessoryById(id))); if (run !== shoppingRun) { return; } const byId = new Map(unique.map((id, index) => [id, results[index]])); shoppingItems = ids.map((id) => byId.get(id)).filter(Boolean); const total = shoppingItems.reduce((sum, accessory) => sum + accessoryPrice(accessory), 0); button.textContent = 'Shopping list: ' + formatCzk(total); } function openShoppingList() { const dialog = openDialog('Shopping list', { wide: true }); const ids = sceneAccessoryIds(lastScene); if (shoppingItems.length === 0) { dialog.body.appendChild(el('p', { class: 'muted', text: ids.length === 0 ? 'No priced items placed yet.' : 'No items could be resolved from the backend (' + ids.length + ' ids in scene).' })); return; } const groups = new Map(); shoppingItems.forEach((accessory) => { const key = accessory.id + '|' + (accessory.primaryVariant ? accessory.primaryVariant.id : ''); const group = groups.get(key) || { accessory, count: 0 }; group.count++; groups.set(key, group); }); const rows = [...groups.values()].map(({ accessory, count }) => { const price = accessoryPrice(accessory); const shopUrl = safeHttpUrl(accessory.primaryVariant && accessory.primaryVariant.url); return el('tr', null, [ el('td', { text: accessory.name || accessory.id }), el('td', { text: manufacturerName(accessory) }), el('td', { class: 'num', text: formatCzk(price) }), el('td', { class: 'num', text: String(count) }), el('td', { class: 'num', text: formatCzk(price * count) }), el('td', null, [shopUrl ? el('a', { href: shopUrl, target: '_blank', rel: 'noopener', text: 'shop' }) : null]) ]); }); const total = shoppingItems.reduce((sum, accessory) => sum + accessoryPrice(accessory), 0); dialog.body.appendChild(el('table', { class: 'shopping-table' }, [ el('thead', null, [el('tr', null, ['Item', 'Manufacturer', 'Price', 'Count', 'Subtotal', ''].map((h) => el('th', { text: h })))]), el('tbody', null, rows), el('tfoot', null, [el('tr', null, [el('td', { colspan: '4', text: 'Total' }), el('td', { class: 'num', text: formatCzk(total) }), el('td')])]) ])); }