{
  "version": 3,
  "sources": ["/cdn/shop/t/9/assets/btk-kitchen-planner.js?cb=2682"],
  "sourcesContent": ["/**\n * BTK Kitchen Planner - entry point\n * ----------------------------------------------------------------\n * Step 20: state pivots from a free-floating `room` polygon to a\n * structured `roomConfig`. Each render builds two polygons from it:\n *\n *   - room       (carved)  \u2192  renderer, placement engine, clamp\n *   - baseRoom   (corner-to-corner)  \u2192  Wall A/D/C/B dimension labels\n *\n * Perimeter items (columns and partial walls) live on the\n * roomConfig and are CARVED into the polygon, so they become part\n * of the room outline rather than freestanding boxes. The pillar\n * shape supplies a synthetic starter column at top-left.\n *\n * Cabinets keep their step-19 rotationDeg model and migrate on load\n * from older saves.\n */\n\nimport { getBoundingBox, getWalls }             from './btk-kitchen-planner-engine-room.js?v=2';\nimport {\n  DEFAULT_ROOM_CONFIG,\n  getShapeParamsDefaults,\n  buildRoomPolygon,\n  buildBaseRoom,\n  makeStarterPillar,\n  makeStarterStepBlock,\n  makeStarterBeam,\n  makeStarterSlopedCeiling,\n  makeStarterVaultedCeiling,\n  makeStarterBoiler,\n  boilerDefaults,\n  makeStarterConsumerUnit,\n  makeStarterWaterTank,\n  makeStarterRadiator,\n  makeStarterElectricalPoint,\n  makeStarterStopcock,\n  electricalPlateSize,\n  makeStarterFreeBlock,\n  makeStarterCookerAlcove,\n  makeStarterAngledCut,\n  makeStarterWall,\n  makeStarterPillarFeature,\n  cornerAnchorPosition,\n  getDefaultItemPosition,\n  getPentagonVerticesWorld,\n  wallShapeParam\n}                                                from './btk-kitchen-planner-engine-room-builder.js?v=58';\nimport { renderGrid, drawWallBand, drawWallShape, clearWallBand, wallBandPoints, rotatedPillarFaces, drawFocusBar, clearFocusBar } from './btk-kitchen-planner-2d-grid.js?v=43';\nimport { renderWallDimensions, computeDimensionTiers, deriveWallLabels } from './btk-kitchen-planner-2d-dimensions.js?v=58';\nimport { renderCabinets, refreshLShapeBody, heightLetterOf, reducedOnSiteMm } from './btk-kitchen-planner-2d-cabinets.js?v=396';\nimport { renderWorktops }                       from './btk-kitchen-planner-2d-worktops.js?v=5';\nimport { renderWorktopItems }                   from './btk-kitchen-planner-2d-worktop-items.js?v=8';\nimport { appendFurnitureDrawing }               from './btk-kitchen-planner-2d-furniture.js?v=12';\nimport { renderSplashbacks }                    from './btk-kitchen-planner-2d-splashbacks.js?v=3';\nimport { computeSplashbackStrips, worktopIsHeatSafe } from './btk-kitchen-planner-engine-splashbacks.js?v=30';\nimport { renderFeatures, applyTouchClasses }    from './btk-kitchen-planner-2d-features.js?v=71';\nimport { renderOpenings, updateOpeningElement, setOpeningLayer } from './btk-kitchen-planner-2d-openings.js?v=18';\nimport { mountRoomEditor } from './btk-kitchen-planner-ui-room-editor.js?v=7';\nimport { initSelectionPanel }                   from './btk-kitchen-planner-ui-selection-panel.js?v=680';\nimport { makeDraggable }                        from './btk-kitchen-planner-2d-drag.js?v=4';\nimport { snapAndClamp, clampToRoom, computeAutoRotation, snapToAngledWall, findFreeOpeningOffset, getEffectiveAABB, getVisualFootprintAABB, canCabinetsOverlap, getCornersForPush, obbOverlapAxes, snapFootprintAABB, getPillarSnapWalls } from './btk-kitchen-planner-engine-placement.js?v=157';\nimport { renderClearance }                     from './btk-kitchen-planner-2d-clearance.js?v=6';\nimport {\n  WALL_COLOURS, FLOOR_COLOURS,\n  DEFAULT_WALL_COLOUR_HANDLE, DEFAULT_FLOOR_COLOUR_HANDLE,\n  getWallColour, getFloorColour\n} from './btk-kitchen-planner-decor-palette.js?v=5';\nimport { createBasketPlanStore, normaliseLoadedPayload, addPlanTime, pendingPlanTime, resetPlanTime } from './btk-kitchen-planner-engine-storage.js?v=33';\nimport { fetchUnitTypesFromStorefront }        from './btk-unit-types-storefront.js?v=7';\nimport { Catalogue }                            from './btk-kitchen-planner-engine-catalogue.js?v=209';\nimport { computeWorktopBillingByMaterial,\n         computeBoardBilling,\n         computeBespokeSlabs, bespokeProcessQuantities, priceBespokeProcesses,\n         pickPriceBands, bespokeCornerCounts, templatingZoneFor,\n         windowCillSize, countStripStock, rectangleSlabs,\n         pieceJoints, mitreLine, mitreShapes,\n         diagonalStrips, snapPieceDepths,\n         onsiteEdgeRuns, mergeAdjacentRuns, slabEdgeKind, slabDims,\n         clipOutlineX, bestFrame, slabToRects,\n         unionOutlines } from './btk-kitchen-planner-engine-worktop-pricing.js?v=63';\nimport { getWorktopItemCatalogue, buildWorktopItemDefinition } from './btk-kitchen-planner-engine-worktop-items.js?v=6';\nimport { getRadiusUnitCatalogue, buildRadiusUnitCabinet, buildRadiusBacking, buildRadiusFiller } from './btk-kitchen-planner-engine-radius-units.js?v=5';\nimport { getLShapeUnitCatalogue, buildLShapeUnitCabinet } from './btk-kitchen-planner-engine-l-shape-units.js?v=3';\nimport { getDiagonalCornerUnitCatalogue, buildDiagonalCornerUnitCabinet, diagonalCornerFootprintPolygon, diagonalCornerDoorSegment, isWalkInLarder, unitInsideWalkInLarder, walkInInteriorFaces, pointOverWalkInLarder, WALK_IN_BOARD_MM, walkInFrameBasis, walkInToWorld } from './btk-kitchen-planner-engine-diagonal-corner-units.js?v=8';\nimport { WALK_IN_SET_OPTIONS, isWalkInFrame, walkInSetHeightKey, walkInSetTemplates, walkInSetPose } from './btk-kitchen-planner-engine-walkin-sets.js?v=3';\nimport { getDiagonalCornerWallUnitCatalogue, buildDiagonalCornerWallUnitCabinet } from './btk-kitchen-planner-engine-diagonal-corner-wall-units.js?v=1';\nimport { getWalkInCornerLarderUnitCatalogue, buildWalkInCornerLarderUnitCabinet } from './btk-kitchen-planner-engine-walk-in-corner-larder-units.js?v=4';\nimport { getDiagonalCornerLarderUnitCatalogue, buildDiagonalCornerLarderUnitCabinet } from './btk-kitchen-planner-engine-diagonal-corner-larder-units.js?v=1';\nimport { getLShapeWallUnitCatalogue, buildLShapeWallUnitCabinet } from './btk-kitchen-planner-engine-l-shape-wall-units.js?v=1';\nimport { getOpenBaseUnitCatalogue, buildOpenBaseUnitCabinet } from './btk-kitchen-planner-engine-open-base-units.js?v=1';\nimport { getTallOvenHousingUnitCatalogue, buildTallOvenHousingUnitCabinet } from './btk-kitchen-planner-engine-tall-oven-housing-units.js?v=1';\nimport { getCornerWallUnitCatalogue, buildCornerWallUnitCabinet } from './btk-kitchen-planner-engine-corner-wall-units.js?v=1';\nimport { getBelfastSinkUnitCatalogue, buildBelfastSinkUnitCabinet } from './btk-kitchen-planner-engine-belfast-sink-units.js?v=1';\nimport { getOvenHousingUnitCatalogue, buildOvenHousingUnitCabinet } from './btk-kitchen-planner-engine-oven-housing-units.js?v=1';\nimport { getSinkBaseUnitCatalogue, buildSinkBaseUnitCabinet } from './btk-kitchen-planner-engine-sink-base-units.js?v=1';\nimport { getEndPanelsFillersCatalogue, buildEndPanelFillerCabinet } from './btk-kitchen-planner-engine-end-panels-fillers.js?v=3';\nimport { getCornerPostVoidCatalogue, buildCornerPostVoidCabinet } from './btk-kitchen-planner-engine-corner-post-void.js?v=4';\nimport { findFillerCorners, cornerDeficitMm, boardMm as fillerCornerBoardMm, CORNER_FILLER_TOUCH_MM, CORNER_FILLER_DEPTH_MM } from './btk-kitchen-planner-engine-filler-corners.js?v=1';\nimport { computeWarnings, computeOpeningWarnings } from './btk-kitchen-planner-engine-warnings.js?v=96';\nimport { computeTrimRuns, railActiveSegments, railFittings, cutRailPieces, plinthKindOf, PLINTH_ALT_FEATURES } from './btk-kitchen-planner-engine-trim.js?v=139';\nimport { wallUnitVerticalRange, isWallMounted, isWorktopDresserType, isWorktopDresserCab, worktopDresserLevel, WALL_MOUNT_TOPS } from './btk-kitchen-planner-engine-wall-mount.js?v=12';\nimport { resolveStackAnchors, stackTrimOf, unitVerticalRange, isInCarcaseColumn, isStacked, isApplianceStackMode, STACK_WORKTOP_FALLBACK_MM, footprintsOverlap, planFootprintAABB, floatHeightMmOf, clampPlinthMm, plinthHeightOf, hasPlinthBand, PLINTH_STD_MM, isFloatingUnit, isUnderWorktopUnit, isHungBetweenUnit, unitTopY, carriesWorktop, isPastrySet, pastryKindOf, PASTRY_COLUMN_MM, pastryPostSection, pastrySetParts } from './btk-kitchen-planner-engine-stack.js?v=29';\nimport { computeMediaRuns, towerPanelBottomMm, acousticPanelCount, findBoardForFace, collectEndPanelFaces, stampFreestandingPanels, nestPanels, panelOwnCodes, parseBackPanelCode, stampBackPanelSegments, backPanelColour, backPanelFinish, backPanelRunOf, backPanelUserExt, BACK_PANEL_EXT_MAX_MM, EP_FEATURE_CODES, EP_RADIUS_CORNICE_BLOCK, endFeatureLengthMm, packEndFeatureBins, packEndFeatureLengths } from './btk-kitchen-planner-engine-end-panel-yield.js?v=95';\nimport { computeWorktops, addWorktopWindowReveals, insertWindowTabs, stripWindowTabs,\n         windowTakesWorktop, WT_INTO_WINDOW_CILL_MM } from './btk-kitchen-planner-engine-worktops.js?v=191';\n/* The 3D renderer (~694KB) pulls three.js + 13 addons (~1.77MB) from a\n   third-party CDN. As a STATIC import that was over half of everything the\n   planner downloaded before it would open - for a view that starts in 2D.\n   It is now loaded on demand, and additionally warmed in the background once\n   the browser goes idle (see below), so switching to 3D is usually instant\n   without any of it blocking the initial open. */\nlet _r3dPromise = null;\nfunction load3DRenderer() {\n  if (!_r3dPromise) {\n    _r3dPromise = import('./btk-kitchen-planner-3d-renderer.js?v=1216');\n  }\n  return _r3dPromise;\n}\n\n/* Opening-style thumbnails (the pictures in the Doors / Windows popups) are\n   rendered from each style's GLB. They go through a HEADLESS renderer of\n   their own rather than the live viewport: the popup lives in Room Setup and\n   is normally opened while the user is still in 2D, so borrowing the live\n   handle would either force the 3D viewport to initialise early or - worse -\n   render nothing because it doesn't exist yet. Headless mode skips the DOM\n   mount, controls and animation loop, and each call builds and disposes its\n   own offscreen scene, so this can never disturb the plan being worked on.\n   The module itself is shared with the live viewport and idle-warmed anyway,\n   so in practice this costs one small renderer object. */\nlet _thumb3DPromise = null;\nfunction openingThumbnailRenderer() {\n  if (!_thumb3DPromise) {\n    _thumb3DPromise = load3DRenderer()\n      .then(({ init3DRenderer }) => init3DRenderer(null, { catalogue: Catalogue, headless: true }))\n      .catch(() => null);\n  }\n  return _thumb3DPromise;\n}\n/* Unit pictures (the Add Units cards, the selected unit's panel) go through\n   the SAME headless renderer. They used to call ensure3DReady(), which starts\n   the whole live 3D view - every unit in the plan, lights, controls - just to\n   draw one card, and did it on the main thread the moment Add Units opened:\n   the list could not be scrolled for 2-3 seconds (Arden, 2026-09-29).\n   renderCabinetThumbnail builds its own off-screen scene either way, so the\n   picture is the same; the headless one simply never builds the kitchen. */\nasync function renderCabinetThumbHeadless(cab, opts) {\n  // ?btktime=1 only: say WHY a picture was not drawn, on screen.\n  const tmark = (l) => { try { window.BTKKPTiming && window.BTKKPTiming.mark(l); } catch (_) {} };\n  try {\n    const h = await openingThumbnailRenderer();\n    tmark(h ? 'picture renderer ready' : 'picture renderer could not start');\n    if (!h || typeof h.renderCabinetThumbnail !== 'function') return null;\n    const url = await h.renderCabinetThumbnail(cab, opts);\n    if (!url) tmark('renderer returned no picture for ' + ((cab && cab.unitTypeId) || 'a unit'));\n    return url;\n  } catch (e) {\n    console.warn('[BTK units] thumbnail failed', e);\n    tmark('picture failed: ' + ((e && e.message) || e));\n    return null;\n  }\n}\nasync function renderOpeningThumbnail(style, opts) {\n  try {\n    const h = await openingThumbnailRenderer();\n    if (!h || typeof h.renderOpeningThumbnail !== 'function') return null;\n    return await h.renderOpeningThumbnail(style, opts);\n  } catch (e) {\n    // Worth a word: the popup silently keeps its fallback picture otherwise,\n    // which is exactly how a dead render path went unnoticed.\n    console.warn('[BTK openings] thumbnail failed', e);\n    return null;\n  }\n}\n\n/* Background warm-up: the user lands on 2D and spends a few seconds getting\n   oriented, so use that time. requestIdleCallback keeps it off the critical\n   path - it will not start until the browser has finished the work that\n   actually puts the planner on screen. */\nif (typeof window !== 'undefined') {\n  const _warm3D = () => { load3DRenderer().catch(() => {}); };\n  if (typeof window.requestIdleCallback === 'function') {\n    window.requestIdleCallback(_warm3D, { timeout: 5000 });\n  } else {\n    setTimeout(_warm3D, 2500);\n  }\n}\nimport { initRoomShapeUI }                      from './btk-kitchen-planner-ui-room-shape.js?v=180';\nimport { initDoorsWindowsUI }                   from './btk-kitchen-planner-ui-doors-windows.js?v=79';\nimport { initCabinetsUI }                       from './btk-kitchen-planner-ui-cabinets.js?v=351';\nimport { initStyleColoursUI }                   from './btk-kitchen-planner-ui-style-colours.js?v=71';\nimport { initWorktopsPopup }                    from './btk-kitchen-planner-ui-worktops.js?v=205';\nimport { initFurnitureUI, furnitureColours, mountFurnitureControls } from './btk-kitchen-planner-ui-furniture.js?v=25';\nimport { initFinishesUI }                       from './btk-kitchen-planner-ui-finishes.js?v=98';\nimport { initDesignControls }                   from './btk-kitchen-planner-ui-design-controls.js?v=6';\nimport { initPricingDisplay }                   from './btk-kitchen-planner-ui-pricing.js?v=9';\nimport { initStepper }                          from './btk-kitchen-planner-ui-stepper.js?v=2';\nimport { showContextMenu }                      from './btk-kitchen-planner-ui-context-menu.js?v=3';\nimport { isPantryCab, pantryDepthMm, pantryInternalsKey, pantryCutSummary, pantryFitterNote, PANTRY_HEIGHT_MM, PANTRY_INTERNALS, FITTERS_PANEL } from './btk-kitchen-planner-engine-pantry.js?v=8';\n\n// Build marker - confirms which build is actually running in the\n// browser. Check the console; if this line is missing or old, the\n// browser is serving a cached/stale orchestrator.\n// Better Bedrooms: wardrobes stand 2155 carcase + 100mm legs, so the High line\n// (where top boxes hang from) is their top. Shared object, so every module sees it.\nWALL_MOUNT_TOPS.high = 2255;\n\nconsole.log('%c[BTK build] orchestrator - corner-unit + flicker-lock + end-panel rule + dim-void + post-snap reach + corner-neighbour + corner GLB/colours/plinth', 'color:#0a7d2a;font-weight:bold');\n\nconst ROOT_SELECTOR    = '#btk-kp-root';\nconst MAIN_SELECTOR    = '#btk-kp-main';\nconst SIDEBAR_SELECTOR = '#btk-kp-sidebar';\n\n// Backward-compat helper that mimics the old findCabinet(code) signature\n// using the new Catalogue. The argument is treated as a Shopify variant ID\n// (numeric or numeric string). Returns a plain object with the fields the\n// rest of the planner expects: code, name, category, widthMm, depthMm,\n// heightMm, priceGbp. Returns null if not found.\n// Backward-compat helper that mimics the old findCabinet(code) signature.\n// Accepts: a numeric variant ID, a numeric ID as a string, a unit-type code\n// string (e.g. \"SHB\"), or a cabinet object (uses its .variantId or .code).\n// Returns an object with the fields the rest of the planner expects, or null.\nfunction findCabinet(idOrCodeOrCabinet) {\n  if (idOrCodeOrCabinet == null) return null;\n\n  // Cabinet object \u2192 drill down to its variantId or code\n  if (typeof idOrCodeOrCabinet === 'object') {\n    if (idOrCodeOrCabinet.variantId) return _findByVariantId(idOrCodeOrCabinet.variantId);\n    if (idOrCodeOrCabinet.code)      return findCabinet(idOrCodeOrCabinet.code);\n    return null;\n  }\n\n  // Numeric \u2192 variant ID\n  if (typeof idOrCodeOrCabinet === 'number') {\n    return _findByVariantId(idOrCodeOrCabinet);\n  }\n\n  // String \u2192 either a numeric ID, or a unit-type code like \"SHB\"\n  const str = String(idOrCodeOrCabinet);\n  if (/^\\d+$/.test(str)) return _findByVariantId(parseInt(str, 10));\n\n  // Treat as a unit-type code: find first matching product, return first variant\n  for (const product of Catalogue.getProducts()) {\n    if (product.kbbUnitTypeCode === str) {\n      const firstId = product.variants?.[0]?.id;\n      if (firstId) return _findByVariantId(firstId);\n    }\n  }\n  return null;\n}\n\nfunction _findByVariantId(variantId) {\n  const info = Catalogue.getVariantInfo(variantId);\n  if (!info) return null;\n  const ut = Catalogue.getUnitType(info.product.unitTypeId);\n  return {\n    code:     ut?.code || info.product.kbbUnitTypeCode || info.product.handle,\n    name:     info.product.title,\n    // Behaviour category so mixed appliance housings resolve to base/\n    // tall/wall (mirrors buildCabinetDefinition); 1:1 for everything else.\n    category: (Catalogue.behaviourCategoryOfUnitType && ut)\n      ? Catalogue.behaviourCategoryOfUnitType(ut, info.heightMm || ut.carcaseHeightMm)\n      : (Catalogue.behaviourCategory\n        ? Catalogue.behaviourCategory(ut?.categoryHandle, ut?.unitTypeGroupHandle, info.heightMm || ut?.carcaseHeightMm)\n        : ut?.categoryHandle),\n    widthMm:  info.widthMm,\n    depthMm:  info.depthMm,\n    heightMm: (ut?.carcaseHeightMm || 720) + (ut?.plinthHeightMm || 0),\n    priceGbp: info.priceCents != null ? info.priceCents / 100 : null\n  };\n}\n// Must exceed BB_BACK_GAP_MM (100mm) so a freshly-duplicated cab's\n// back isn't auto-detected as coincident with the original's (which\n// would force backPanel and backEndPost off on both cabs).\nconst CABINET_STAGGER_MM    = 150;\n// Stagger wraps every Nth cabinet so the offset stays small enough\n// that new units always spawn on-screen near the room centre, even\n// after dozens of placements. Matches the wrap convention the\n// worktop spawner already uses.\nconst CABINET_STAGGER_WRAP  = 8;\nconst ROTATION_PROXIMITY_MM = 50;\nconst ROTATION_EPSILON_DEG  = 0.1;\n\n// Set a cabinet element's rotation so the CSS transition (on\n// .btk-kp-cabinet's transform property) animates via the SHORTEST\n// visual path. CSS interpolates literal angles, so going from\n// rotate(90deg) \u2192 rotate(0deg) naturally takes the short -90\u00B0 path,\n// BUT 0deg \u2192 270deg goes the long way round through 135\u00B0/180\u00B0\n// instead of the equivalent -90\u00B0 path.\n//\n// We track the actual DOM-applied angle on each element via\n// dataset.domRotation (seeded by the 2D renderer at first render\n// to match cabinet.rotationDeg). On each update we offset the\n// target by multiples of 360\u00B0 so |delta| \u2264 180, then write that\n// offset value to the transform - the logical rotationDeg stays in\n// [0, 360) but the DOM may sit at e.g. -90\u00B0 or 450\u00B0 to keep the\n// animation short.\nfunction setCabinetRotation(el, deg) {\n  const curDom = parseFloat(el.dataset.domRotation);\n  if (!isFinite(curDom)) {\n    el.dataset.domRotation = String(deg);\n    el.style.transform = `rotate(${deg}deg)`;\n    return;\n  }\n  const delta  = ((deg - curDom) % 360 + 540) % 360 - 180;\n  const target = curDom + delta;\n  el.dataset.domRotation = String(target);\n  el.style.transform = `rotate(${target}deg)`;\n}\n\nconst ROTATION_FROM_DOOR_SIDE = { top: 0, right: 90, bottom: 180, left: 270 };\n\n// Find the nearest real cabinet (skip other panels and the panel\n// itself) within `threshold` mm of the dragged panel's bbox. Used\n// to make snap-to-face rotation relative to the neighbouring unit's\n// rotation, so a panel dropped beside a 90\u00B0-rotated base unit lines\n// up with that unit rather than the wall behind it.\nfunction nearestCabinetForPanelSnap(panel, x, y, cabinets, threshold) {\n  const pw = panel.widthMm || 0;\n  const pd = panel.depthMm || 0;\n  let best = null;\n  let bestDist = Infinity;\n  for (const c of cabinets) {\n    if (!c || c.id === panel.id) continue;\n    if (c.endPanelFiller) continue;\n    const cw = c.widthMm || 0;\n    const cd = c.depthMm || 0;\n    // Gap between bboxes on each axis (negative when they overlap).\n    const gapX = Math.max(0, Math.max(x - (c.x + cw), c.x - (x + pw)));\n    const gapY = Math.max(0, Math.max(y - (c.y + cd), c.y - (y + pd)));\n    const dist = Math.hypot(gapX, gapY);\n    if (dist >= threshold) continue;\n    if (dist >= bestDist) continue;\n    bestDist = dist;\n    best = c;\n  }\n  return best;\n}\n\n// Corner units (blank-panel type). Detected when the unit type's\n// planner2D.shape is 'corner-blank'. The placeholder keeps a plain\n// rectangular carcase; the door / corner-post / blank-panel split\n// and the L-shaped corner post are drawn as attachments. The plan\n// footprint is the cabinet width plus a reserved corner void.\n//   widthMm (footprint) = doorMm + postXMm + blankMm + voidMm\nconst CORNER_BLANK_SHAPE   = 'corner-blank';\n// Metaobject shape values arrive with whatever whitespace / casing the\n// data carries, so every OTHER shape test normalises before comparing\n// (diagonal, lshape, radius all do). corner-blank was the one strict\n// `===`, which meant a unit_type set to \"Corner-Blank \" or \"corner-blank \"\n// silently missed the corner marker - and with no marker there is no\n// corner cabinet in 2D or 3D, no corner drag, and the hinge control\n// reappears because `isCorner` is derived from that marker.\nconst isCornerBlankShape = (shape) =>\n  String(shape || '').trim().toLowerCase() === CORNER_BLANK_SHAPE;\nconst CORNER_BLANK_DEFAULTS = {\n  cabinetMm: 1000,  // total cabinet width (door + post + blank) - FIXED\n  doorMm:    500,   // accessible door section - fixed size\n  postXMm:   40,    // corner post - size along the run   (adjustable, 0..70)\n  postYMm:   40     // corner post - forward protrusion   (adjustable, 0..70)\n};\nconst CORNER_POST_MIN_MM  = 20;\nconst CORNER_POST_MAX_MM  = 70;\n// XL return: the post is replaced by a WALL END PANEL, whose stock board is\n// 990 x 375 (EP-WALL), so 375mm is the deepest return a single panel can make.\nconst CORNER_POST_XL_MAX_MM = 375;\nconst CORNER_MIN_BLANK_MM = 50;   // blank panel never shrinks below this\n// The corner post's wall-side (back) edge always sits this far from\n// the room corner - it's the cabinet depth, where the perpendicular\n// run's front plane lands. So void + blank panel = this constant,\n// which is what keeps the post from ever moving closer to the wall.\nconst CORNER_POST_REACH_MM = 570;\n// Wall corner blanks reach only the shallow wall-run depth, so their void is\n// much smaller than a base corner's. (A base default of 570 gave the wall a\n// ~310mm void instead of a shallow one.)\nconst CORNER_POST_REACH_WALL_MM = 330;\n\n// Normalise / backfill a cabinet's cornerUnit block. The cabinet's\n// total width (cabinetMm) and the door are FIXED. The corner post and\n// the blank panel SHARE the leftover cabinet width - the blank panel\n// shrinks as the post grows - so the cabinet itself never changes\n// size. The void grows with the post, so the overall footprint does\n// change. blankMm and voidMm are always DERIVED, never stored.\n//\n// `reachMm` carries the cab's perpendicular reach (= the depth of the\n// adjacent perpendicular run's front plane). Base corner unit = 570mm\n// (the default), wall corner unit = 330mm. Older saves without\n// `reachMm` fall back to the base default.\nfunction normaliseCornerUnit(cu) {\n  cu = cu || {};\n  const num = (v, d) => (typeof v === 'number' && isFinite(v) && v >= 0 ? v : d);\n  const cabinetMm = num(cu.cabinetMm, CORNER_BLANK_DEFAULTS.cabinetMm);\n  const doorMm    = num(cu.doorMm,    CORNER_BLANK_DEFAULTS.doorMm);\n  const postXMm   = num(cu.postXMm,   CORNER_BLANK_DEFAULTS.postXMm);\n  const reachMm   = num(cu.reachMm,   CORNER_POST_REACH_MM);\n  // The blank panel takes the leftover cabinet width; the void fills\n  // the rest of the post's reach (void + blank = reachMm) so the\n  // post's wall-side edge never moves. As the post grows the blank\n  // shrinks and the void grows by the same amount.\n  const blankMm = Math.max(0, cabinetMm - doorMm - postXMm);\n  // postInMm: how far the post's wall-side edge has come IN from reachMm\n  // towards the corner. The run post grows into the blank panel, door and\n  // footprint fixed, when the units round the corner stand further forward\n  // than the reach - wall units lined up with tall housings (bug sheet,\n  // Planner Phase 2 row 36). void + blank + postIn = reachMm.\n  const postInMm = Math.min(Math.max(0, reachMm - blankMm), num(cu.postInMm, 0));\n  // 'peninsulaIn' butts the void end against a single wall with the run\n  // turning into the room (see cornerUnitPeninsulaPlacement).\n  const placement = cu.placement === 'peninsulaIn' ? 'peninsulaIn' : 'auto';\n  return {\n    // Spread FIRST so fields this normaliser doesn't know about survive it.\n    // It used to return a pure whitelist, which silently dropped every\n    // MEASURED field stamped on the corner unit later in the pipeline -\n    // neighbourBackExtMm (detectCornerVoidExtensions) and voidEdgeExposed\n    // (autoDetectBackPanels). Whichever ran last won, so the breakfast-bar\n    // wrap flickered between honouring the walled void end and ignoring it\n    // depending on the order a given interaction happened to take. The\n    // normalised keys below still override, so nothing else changes.\n    ...cu,\n    type:    cu.type === 'blankPanel' ? cu.type : 'blankPanel',\n    hand:    cu.hand === 'right' ? 'right' : 'left',\n    placement,\n    cabinetMm,\n    doorMm,\n    postXMm,\n    postYMm: num(cu.postYMm, CORNER_BLANK_DEFAULTS.postYMm),\n    reachMm,\n    blankMm,\n    postInMm,\n    voidMm:  Math.max(0, reachMm - postInMm - blankMm)\n  };\n}\n\n// Blank-panel corner units are sold LEFT and RIGHT panel as separate variants\n// (\u2026-LHP- / \u2026-RHP-), so the variant has to follow the hand. Every hand change -\n// the Corner Side pane, the drag-end auto-flip, Magic Layout - used to move\n// only the drawing, leaving the basket line on the side the unit was added\n// with. Re-points the cab at the matching variant (same size, other options\n// kept), in place. No-op when the product sells no panel side, or when its\n// style's products aren't loaded yet. See Catalogue.cornerHandVariant.\nfunction syncCornerHandVariant(cab) {\n  if (!cab || !cab.cornerUnit || !Catalogue.cornerHandVariant) return cab;\n  const info = Catalogue.cornerHandVariant(cab.variantId, cab.cornerUnit.hand);\n  if (!info || !info.variant || info.variant.id === cab.variantId) return cab;\n  cab.variantId      = info.variant.id;\n  cab.priceCents     = info.priceCents;\n  cab.compareAtCents = (typeof info.compareAtCents === 'number') ? info.compareAtCents : null;\n  return cab;\n}\n\n// Tolerance (mm) for treating a corner unit as \"seated\" in a room\n// corner - a footprint corner must land this close to a room corner.\nconst CORNER_SEAT_TOL_MM = 150;\n\n// Auto-hand-flip only applies to ~90\u00B0 room corners. Angled-room\n// vertices (e.g. a 135\u00B0 splay) can't physically seat a rectangular\n// corner / L-shape unit flush against both walls, so we leave the\n// user's chosen hand alone there rather than flip to a worse fit.\nconst CORNER_NINETY_TOL_DEG = 12;\n\nfunction roomVertexAngleDeg(verts, i) {\n  const n = verts.length;\n  if (n < 3) return null;\n  const prev = verts[(i - 1 + n) % n];\n  const v    = verts[i];\n  const next = verts[(i + 1) % n];\n  const ax = prev.x - v.x, ay = prev.y - v.y;\n  const bx = next.x - v.x, by = next.y - v.y;\n  const la = Math.hypot(ax, ay), lb = Math.hypot(bx, by);\n  if (la === 0 || lb === 0) return null;\n  const cosT = (ax * bx + ay * by) / (la * lb);\n  return Math.acos(Math.max(-1, Math.min(1, cosT))) * 180 / Math.PI;\n}\n\n// For a corner unit seated in a room corner, the hand it SHOULD have\n// so the void faces INTO the corner (and the door faces the room).\n// Returns 'left' / 'right', or null when the unit isn't seated in a\n// corner. The void sits at cabinet-local -X for a left-hand unit,\n// +X for a right-hand one - so the corner must be on the void's end.\nfunction cornerUnitDesiredHand(cabinet, x, y, room, perimeterItems) {\n  if (!cabinet || !cabinet.cornerUnit) return null;\n  const verts = (room && room.vertices) || [];\n  if (verts.length < 3) return null;\n  const W = cabinet.widthMm, D = cabinet.depthMm;\n  const cx = x + W / 2, cy = y + D / 2;\n  const th = ((cabinet.rotationDeg || 0) * Math.PI) / 180;\n  const cs = Math.cos(th), sn = Math.sin(th);\n  // The unit's footprint corners in world space.\n  const fps = [[-W/2,-D/2],[W/2,-D/2],[W/2,D/2],[-W/2,D/2]].map(([lx, ly]) => ({\n    x: cx + lx * cs - ly * sn,\n    y: cy + lx * sn + ly * cs\n  }));\n  // Build the candidate-vertex list: every room polygon vertex\n  // (covers convex outer corners + concave internal corners) AND\n  // every pillar corner (every footprint vertex of each perimeter\n  // item). Room vertices keep their polygon index so the right-\n  // angle check can still gate angled-wall vertices out; pillar\n  // corners are tagged with roomIdx=-1 (skip the angle check \u2014\n  // pillars are 90\u00B0 at every corner by construction).\n  const candidates = [];\n  for (let i = 0; i < verts.length; i++) {\n    candidates.push({ pt: verts[i], roomIdx: i });\n  }\n  for (const ob of (perimeterItems || [])) {\n    if (!ob || !ob.widthMm || !ob.depthMm) continue;\n    const obRot = ((ob.rotationDeg || 0) * Math.PI) / 180;\n    const ocs = Math.cos(obRot), osn = Math.sin(obRot);\n    const obCx = ob.x + ob.widthMm / 2;\n    const obCy = ob.y + ob.depthMm / 2;\n    for (const [lx, ly] of [\n      [-ob.widthMm / 2, -ob.depthMm / 2],\n      [ ob.widthMm / 2, -ob.depthMm / 2],\n      [ ob.widthMm / 2,  ob.depthMm / 2],\n      [-ob.widthMm / 2,  ob.depthMm / 2]\n    ]) {\n      candidates.push({\n        pt: { x: obCx + lx * ocs - ly * osn, y: obCy + lx * osn + ly * ocs },\n        roomIdx: -1\n      });\n    }\n  }\n  // Find the candidate closest to any footprint corner.\n  let corner = null, cornerRoomIdx = -1, bestD = Infinity;\n  for (const cand of candidates) {\n    for (const fp of fps) {\n      const d = Math.hypot(cand.pt.x - fp.x, cand.pt.y - fp.y);\n      if (d < bestD) { bestD = d; corner = cand.pt; cornerRoomIdx = cand.roomIdx; }\n    }\n  }\n  if (!corner || bestD > CORNER_SEAT_TOL_MM) return null;   // not in a corner\n  // For ROOM-polygon vertices, gate by the ~90\u00B0 angle test - angled\n  // walls (e.g. 135\u00B0 splay) can't seat a rectangular corner unit\n  // flush. Pillar corners (roomIdx === -1) are 90\u00B0 by construction;\n  // skip the gate for them.\n  if (cornerRoomIdx >= 0) {\n    const ang = roomVertexAngleDeg(verts, cornerRoomIdx);\n    if (ang === null || Math.abs(ang - 90) > CORNER_NINETY_TOL_DEG) return null;\n  }\n  // Which width-end of the unit is the corner on? proj < 0 \u2192 the\n  // corner is toward cabinet-local -X, which is the left-hand void.\n  const proj = (corner.x - cx) * cs + (corner.y - cy) * sn;\n  if (Math.abs(proj) < 20) return null;     // ambiguous\n  return proj < 0 ? 'left' : 'right';\n}\n\n// For an L-shape unit seated in a room corner, the hand it SHOULD\n// have so the OUTER corner of the L (where the two arms meet at the\n// walls) sits in the room corner - putting the cutout into the open\n// room with the doors facing it. Returns 'NE' / 'NW' / 'SE' / 'SW',\n// or null when the unit isn't seated in a corner.\n//\n// Per-hand outer corner in cab-local plan coords:\n//   NE (cutout TR) \u2192 outer = BL (0, D)\n//   NW (cutout TL) \u2192 outer = BR (W, D)\n//   SE (cutout BR) \u2192 outer = TL (0, 0)\n//   SW (cutout BL) \u2192 outer = TR (W, 0)\n// So whichever cab-local footprint corner lands on the room corner\n// dictates the hand inversely (the cutout is at the OPPOSITE corner).\nfunction lShapeUnitDesiredHand(cabinet, x, y, room, perimeterItems) {\n  if (!cabinet || !cabinet.lShapeUnit) return null;\n  const verts = (room && room.vertices) || [];\n  if (verts.length < 3) return null;\n  const W = cabinet.widthMm, D = cabinet.depthMm;\n  const cx = x + W / 2, cy = y + D / 2;\n  const th = ((cabinet.rotationDeg || 0) * Math.PI) / 180;\n  const cs = Math.cos(th), sn = Math.sin(th);\n  const cornersLocal = [\n    { key: 'TL', lx: -W/2, ly: -D/2 },\n    { key: 'TR', lx:  W/2, ly: -D/2 },\n    { key: 'BR', lx:  W/2, ly:  D/2 },\n    { key: 'BL', lx: -W/2, ly:  D/2 }\n  ];\n  // Build the candidate-vertex list (room polygon vertices +\n  // pillar corners). roomIdx === -1 marks a pillar corner - we skip\n  // the angle check for those (pillars are 90\u00B0 by construction).\n  const candidates = [];\n  for (let i = 0; i < verts.length; i++) {\n    candidates.push({ pt: verts[i], roomIdx: i });\n  }\n  for (const ob of (perimeterItems || [])) {\n    if (!ob || !ob.widthMm || !ob.depthMm) continue;\n    const obRot = ((ob.rotationDeg || 0) * Math.PI) / 180;\n    const ocs = Math.cos(obRot), osn = Math.sin(obRot);\n    const obCx = ob.x + ob.widthMm / 2;\n    const obCy = ob.y + ob.depthMm / 2;\n    for (const [lx, ly] of [\n      [-ob.widthMm / 2, -ob.depthMm / 2],\n      [ ob.widthMm / 2, -ob.depthMm / 2],\n      [ ob.widthMm / 2,  ob.depthMm / 2],\n      [-ob.widthMm / 2,  ob.depthMm / 2]\n    ]) {\n      candidates.push({\n        pt: { x: obCx + lx * ocs - ly * osn, y: obCy + lx * osn + ly * ocs },\n        roomIdx: -1\n      });\n    }\n  }\n  let bestKey = null, bestRoomIdx = -1, bestD = Infinity;\n  for (const { key, lx, ly } of cornersLocal) {\n    const wx = cx + lx * cs - ly * sn;\n    const wy = cy + lx * sn + ly * cs;\n    for (const cand of candidates) {\n      const d = Math.hypot(cand.pt.x - wx, cand.pt.y - wy);\n      if (d < bestD) { bestD = d; bestKey = key; bestRoomIdx = cand.roomIdx; }\n    }\n  }\n  if (!bestKey || bestD > CORNER_SEAT_TOL_MM) return null;\n  // Room polygon vertices: gate by ~90\u00B0 (angled walls can't seat a\n  // rectangular L-shape flush). Pillar corners are 90\u00B0 by construction\n  // \u2192 skip the gate.\n  if (bestRoomIdx >= 0) {\n    const ang = roomVertexAngleDeg(verts, bestRoomIdx);\n    if (ang === null || Math.abs(ang - 90) > CORNER_NINETY_TOL_DEG) return null;\n  }\n  return { BL: 'NE', BR: 'NW', TL: 'SE', TR: 'SW' }[bestKey];\n}\n\n// Diagonal corner unit - same hand convention as the L-shape (NE/NW/\n// SE/SW = compass of cutout), so the desired-hand math is identical.\n// Thin wrapper that swaps the marker check; otherwise unchanged.\nfunction diagonalCornerUnitDesiredHand(cabinet, x, y, room, perimeterItems) {\n  if (!cabinet || !cabinet.diagonalCornerUnit) return null;\n  const proxy = { ...cabinet, lShapeUnit: cabinet.diagonalCornerUnit };\n  return lShapeUnitDesiredHand(proxy, x, y, room, perimeterItems);\n}\n\n// Pin the radius backing + filler back to their canonical position +\n// rotation relative to the radius unit. This is the same layout\n// addRadiusUnit spawns: backing centre at (radius_centre + (0, +280)\n// in the unrotated frame), filler centre at radius_centre + (0,\n// +415). Whatever rotation+translation the radius unit has been\n// through, the auxiliaries follow rigidly. Acts as a safety net so\n// any precision drift / mid-drag partial update gets reset to the\n// fixed assembly geometry on each drop.\nfunction reAnchorRadiusGroup(cabinets, radius) {\n  if (!radius || !radius.radiusUnit || !radius.groupId) return;\n  const rRot = ((radius.rotationDeg || 0) % 360 + 360) % 360;\n  const rW = radius.widthMm || 0, rD = radius.depthMm || 0;\n  const rCx = (radius.x || 0) + rW / 2;\n  const rCy = (radius.y || 0) + rD / 2;\n  const th = (rRot * Math.PI) / 180;\n  const cs = Math.cos(th), sn = Math.sin(th);\n  const place = (m, lx, ly, extraRot) => {\n    // Rotate the local offset into world coords (cab-local +X = user\n    // left, +Y = back of cabinet - same convention as elsewhere).\n    const wx = rCx + lx * cs - ly * sn;\n    const wy = rCy + lx * sn + ly * cs;\n    m.x = wx - (m.widthMm || 0) / 2;\n    m.y = wy - (m.depthMm || 0) / 2;\n    m.rotationDeg = ((rRot + (extraRot || 0)) % 360 + 360) % 360;\n  };\n  const hand = radius.radiusUnit.hand === 'left' ? 'left' : 'right';\n  // Backing local-frame centre relative to radius centre:\n  //   (0, rD/2 + 130). For a 300\u00D7300 radius and 260\u00D7300 backing\n  //   that's (0, 280). hand=right adds +90\u00B0 to backing's rotation\n  //   (the 260-wide carcase turned 90\u00B0 so its 300mm face runs along\n  //   the wall); hand=left adds -90\u00B0.\n  // Filler local-frame centre: (0, rD/2 + backingThickness + fillerHalf)\n  //   = (0, 150 + 260 + 5) = (0, 415).\n  const backingExtraRot = hand === 'left' ? -90 : 90;\n  for (const m of cabinets) {\n    if (m.groupId !== radius.groupId) continue;\n    if (!m.radiusGroup) continue;\n    if (m.radiusGroup.role === 'backing') {\n      place(m, 0, rD / 2 + 130, backingExtraRot);\n    } else if (m.radiusGroup.role === 'filler') {\n      if (/^wall/i.test(radius.category || '')) {\n        // Wall end-of-run: the \"cut-off\" back 30mm door slice, standing 90\u00B0 to\n        // the wall along the exposed side flat, in the gap between the unit's\n        // back and the wall. Rotated \u00B190\u00B0 so the 30mm door face runs along the\n        // side (perpendicular to the wall), 18mm thick. Length (30) runs in the\n        // perpendicular (Y) direction; thickness (18) sits just outside the\n        // side face.\n        // Exposed side = the hand side the door wraps to (arc corner). The\n        // filler extends that side's door edge back into the wall gap.\n        const sideSign = hand === 'left' ? -1 : 1;\n        const fThick   = m.depthMm || 18;             // 18 - sits just outside the side face\n        const fLen     = m.widthMm || 30;             // 30 - runs back into the wall gap\n        // Tuck it into the 30mm wall gap: its FRONT edge at the curve back\n        // (rD/2), BACK edge at the wall (rD/2 + fLen) \u2192 centre = rD/2 + fLen/2.\n        place(m, sideSign * (rW / 2 + fThick / 2), (rD / 2) + fLen / 2, sideSign * 90);\n      } else {\n        // Base end-of-run: filler sits BEHIND the 260 backing.\n        place(m, 0, rD / 2 + 260 + (m.depthMm || 10) / 2, 0);\n      }\n    }\n  }\n}\n\nfunction readShopifyContext(root) {\n  const tags = (root.dataset.customerTags || '')\n    .split(',')\n    .map(t => t.trim().toLowerCase())\n    .filter(Boolean);\n  return {\n    shopDomain: root.dataset.shopDomain || null,\n    currency:   root.dataset.currency   || null,\n    customerId: root.dataset.customerId || null,\n    // Printed on the report's footer bar. Empty for a guest.\n    customerName: root.dataset.customerName || null,\n    customerTags: tags,\n    // UI gate only - never trust this for privileged actions; the\n    // Node backend must re-verify the account's salesperson tag.\n    isSalesperson: tags.includes('salesperson')\n  };\n}\n\n// UK date + 24-hour clock: \"08/09/2026 16:25\". A bare time was ambiguous the\n// moment a plan was more than a day old, and 24-hour drops the am/pm.\nfunction formatTime(iso) {\n  const d = new Date(iso);\n  if (isNaN(d.getTime())) return '';\n  return d.toLocaleString('en-GB', {\n    day: '2-digit', month: '2-digit', year: 'numeric',\n    hour: '2-digit', minute: '2-digit', hour12: false\n  }).replace(',', '');\n}\n\nfunction computeNextId(items, fallback = 0) {\n  let max = fallback;\n  items.forEach(item => {\n    const m = /(\\d+)$/.exec(item.id || '');\n    if (m) max = Math.max(max, parseInt(m[1], 10));\n  });\n  return max + 1;\n}\n\n// The thickest a free-placed end-panel board can be. Anything wider was a\n// back panel placed with its length as its width - see the add path.\nconst EP_UNIT_MAX_THICK_MM = 50;\n\n// A Belfast unit's worktop notch is the chosen sink's cut-out, cut from the\n// worktop's front edge: cutout_width_mm wide, cutout_depth_mm back from that\n// edge (as a fitter quotes it). The Classic Belfast sits under the worktop,\n// which laps its rim 20mm at the sides and back: 555 x 425 on the 595 x 455\n// sink, whose front stands 10mm ahead of the worktop edge. The Hartland apron\n// front sits on the worktop: its own cut-out, 594 x 460 (Arden, 2026-10-24).\n// No sink, or no sizes: the unit type's notch. Never wider than the unit.\nfunction isApronFrontSink(installType) {\n  return /apron/i.test(String(installType || ''));\n}\n\n// The sink a new sink unit loads with: the first of its unit type's\n// default_sinks (Arden, 2026-10-24: the Classic Belfast on the 600 Classic\n// Belfast unit) that fits it - its minimum cabinet width, and on a Belfast\n// unit a double bowl for an 800, a single for a 600 (the Choose Sink rule) -\n// and that the plan's worktop can take (`allowed`, by handle).\nfunction defaultSinkFor(def, allowed) {\n  if (!def || !(def.belfastSink || def.sinkBase) || !Catalogue.getPlannerSink) return null;\n  const ut = Catalogue.getUnitType ? Catalogue.getUnitType(def.unitTypeId) : null;\n  const handles = (ut && Array.isArray(ut.defaultSinkHandles)) ? ut.defaultSinkHandles : [];\n  const w = def.widthMm || 0;\n  for (const h of handles) {\n    const sk = Catalogue.getPlannerSink(h);\n    if (!sk || (sk.minCabinetWidthMm || 0) > w) continue;\n    if (def.belfastSink && ((Number(sk.bowlCount) >= 2) !== (w >= 800))) continue;\n    if (typeof allowed === 'function' && !allowed(h)) continue;\n    return h;\n  }\n  return null;\n}\nfunction belfastNotchForSink(marker, cab) {\n  if (!marker) return marker;\n  const sk = (cab && cab.plannerSinkHandle && Catalogue.getPlannerSink)\n    ? Catalogue.getPlannerSink(cab.plannerSinkHandle) : null;\n  if (!sk) return marker;\n  const out = { ...marker };\n  if (sk.cutoutWidthMm > 0) out.sinkCutoutWidthMm = Math.min(sk.cutoutWidthMm, (cab.widthMm || sk.cutoutWidthMm));\n  if (sk.cutoutDepthMm > 0) out.sinkCutoutDepthMm = sk.cutoutDepthMm;\n  return out;\n}\n\n// A Filler Panel / Tall Filler Panel placed on its own (Add Units > Doors,\n// Panels & Accessories > Filler Panels). Planner Bugs row 22 (Arden,\n// 2026-10-26): a forward-facing board - width along the run, 18 thick -\n// standing on the plinth line, sized in its Edit Filler Size popup.\nconst FILLER_PANEL_THICK_MM = 18;\nconst FILLER_PANEL_PLINTH_MM = 150;\nfunction isFillerPanelCab(c) {\n  if (!c || !c.endPanelUnit) return false;\n  const ut = Catalogue.getUnitType?.(c.unitTypeId);\n  return ut ? ut.unitTypeGroupHandle === 'filler-panels' : /^(715FILL|FILLPLIN|FILLPLIN3M)$/i.test(String(c.code || ''));\n}\n\nfunction migrateCabinet(c) {\n  // Fillers saved side-on like an end panel (18 across, 147 deep): turned to\n  // face forward, about their centre, and lifted onto the plinth line.\n  if (c && !c.fillerFacing && isFillerPanelCab(c)) {\n    const face = c.widthMm > FILLER_PANEL_THICK_MM + 0.5 ? c.widthMm : (c.depthMm || 147);\n    const cx = c.x + (c.widthMm || 0) / 2, cy = c.y + (c.depthMm || 0) / 2;\n    c = { ...c, widthMm: face, depthMm: FILLER_PANEL_THICK_MM,\n          x: cx - face / 2, y: cy - FILLER_PANEL_THICK_MM / 2, fillerFacing: true,\n          heightOffGroundMm: c.heightOffGroundMm || FILLER_PANEL_PLINTH_MM };\n  }\n  // Breakfast bar back panels saved as a 1200 x 570 box (Karen Pratt's plan,\n  // 2026-10-20): back to a board, its length on the depth axis like any end\n  // panel, turned a quarter so it lies along the line it was placed on.\n  if (c && c.endPanelUnit && c.widthMm > EP_UNIT_MAX_THICK_MM) {\n    const ut = Catalogue.getUnitType?.(c.unitTypeId);\n    if (ut && ut.unitTypeGroupHandle === 'end-panels') {\n      const len = ut.defaultDepthMm || c.widthMm;\n      const cx = c.x + c.widthMm / 2, cy = c.y + c.depthMm / 2;\n      c = { ...c, widthMm: 18, depthMm: len, x: cx - 9, y: cy - len / 2,\n            rotationDeg: (((c.rotationDeg || 0) + 90) % 360) };\n    }\n  }\n  // Built-under double ovens placed before the end-panel walk skipped them had\n  // both panels switched on by it - clear them once (Arden, 2026-10-12).\n  if (c && c.freestandingAppliance && c.freestandingAppliance.fillsOpening && !c.freestandingAppliance.panelsCleared) {\n    const off = (ep) => ({ ...(ep || {}), active: false });\n    c = { ...c, endPanels: { ...(c.endPanels || {}), left: off(c.endPanels && c.endPanels.left), right: off(c.endPanels && c.endPanels.right) },\n          freestandingAppliance: { ...c.freestandingAppliance, panelsCleared: true } };\n  }\n  // Wine coolers first placed at 570 deep (the worktop stepped back over\n  // them) - deepen to the 600 a built-under appliance is planned at, keeping\n  // the BACK where it is so one against a wall stays against it.\n  if (c && c.freestandingAppliance && c.freestandingAppliance.code === 'wine-cooler' && c.depthMm === 570) {\n    const add = 30, rad = (c.rotationDeg || 0) * Math.PI / 180;\n    const cx = c.x + c.widthMm / 2 + Math.sin(rad) * add / 2;\n    const cy = c.y + c.depthMm / 2 - Math.cos(rad) * add / 2;\n    c = { ...c, depthMm: 600, x: cx - c.widthMm / 2, y: cy - 600 / 2 };\n  }\n  // True Handleless wall units saved at 300 deep - their variants said 300,\n  // they are 330 (see the catalogue's indexProduct). Deepen them, keeping the\n  // BACK on the wall it hangs on (Arden, 2026-10-14).\n  if (c && c.depthMm === 300 && /^(wall|bridging)/i.test(c.category || '')\n      && /^(true-handleless|th)-/i.test(String(c.unitTypeId || ''))) {\n    const add = 30, rad = (c.rotationDeg || 0) * Math.PI / 180;\n    const cx = c.x + c.widthMm / 2 + Math.sin(rad) * add / 2;\n    const cy = c.y + c.depthMm / 2 - Math.cos(rad) * add / 2;\n    c = { ...c, depthMm: 330, x: cx - c.widthMm / 2, y: cy - 330 / 2 };\n  }\n  // Backfill category from the catalogue for very old saves that\n  // didn't store it on the cabinet (the .btk-kp-cabinet-{category}\n  // CSS class depends on it).\n  if (!c.category && c.code) {\n    const def = findCabinet(c.code);\n    if (def) c = { ...c, category: def.category };\n  }\n\n  // Resolve planner2D (shape + fill / stroke colours) and the cutout\n  // schema from the current catalogue so the plan reflects the live\n  // unit-type metaobject - including admin edits to opening counts /\n  // door layouts - rather than a stale saved snapshot. For unit\n  // types with a per-height `variants` schema, resolve down to the\n  // cab's CURRENT height variant; downstream code reads\n  // cab.cutoutSchema.openings as a plain array.\n  if (c.unitTypeId) {\n    const ut = Catalogue.getUnitType(c.unitTypeId);\n    if (ut && ut.planner2D) c = { ...c, planner2D: ut.planner2D };\n    // Re-resolve the behaviour category for saved MIXED appliance\n    // housings - older saves stored the literal 'appliance-housings',\n    // which matches no plinth/cornice/worktop gate. Only touches that\n    // mixed category; every other unit keeps its saved category.\n    if (ut && ut.categoryHandle === 'appliance-housings' && Catalogue.behaviourCategory) {\n      const carcaseHeightMm = Math.max(0, (c.heightMm || 0) - (ut.plinthHeightMm || 0));\n      // Per unit TYPE, so the Integrated Extractor door re-loads as the wall\n      // unit it was placed as, not a base unit (Arden, 2026-10-12).\n      const bcat = Catalogue.behaviourCategoryOfUnitType\n        ? Catalogue.behaviourCategoryOfUnitType(ut, carcaseHeightMm)\n        : Catalogue.behaviourCategory(ut.categoryHandle, ut.unitTypeGroupHandle, carcaseHeightMm);\n      if (bcat) c = { ...c, category: bcat };\n    }\n    if (ut && ut.cutoutSchema) {\n      const carcaseHeightMm = Math.max(0, (c.heightMm || 0) - (ut.plinthHeightMm || 0));\n      const resolved = (Catalogue.resolveCutoutSchema)\n        ? Catalogue.resolveCutoutSchema(ut.cutoutSchema, {\n            heightMm:       carcaseHeightMm,\n            widthMm:        c.widthMm,   // pairDoorsFromWidthMm (wide larders: door pairs)\n            categoryHandle: ut.categoryHandle,\n            groupHandle:    ut.unitTypeGroupHandle,\n            optionValues:   Catalogue.nonDimensionOptionValues ? Catalogue.nonDimensionOptionValues(c.variantId) : []\n          })\n        : ut.cutoutSchema;\n      c = { ...c, cutoutSchema: resolved || ut.cutoutSchema };\n      // A chosen appliance whose slot the unit no longer has goes - it would\n      // have no badge and no render but still be BILLED. (The Semi Integrated\n      // dishwasher door lost its slot: we sell no semi-integrated dishwashers -\n      // Arden, 2026-10-12.)\n      if (c.appliances && Object.keys(c.appliances).length && Catalogue.applianceSlotsOf) {\n        const _slotIdx = new Set(Catalogue.applianceSlotsOf(c.cutoutSchema).map(s => String(s.i)));\n        // ...and a warming drawer under a compact in a single-oven slot (index + 0.5).\n        for (const s of Catalogue.applianceSlotsOf(c.cutoutSchema)) {\n          if (Catalogue.isComboSlot && Catalogue.isComboSlot(s.o)) _slotIdx.add(String(s.i + 0.5));\n        }\n        const _kept = {};\n        for (const k of Object.keys(c.appliances)) if (_slotIdx.has(String(k)) && c.appliances[k]) _kept[k] = c.appliances[k];\n        // A layout corrected under a saved plan can move the appliance door: the\n        // 70/30 2 Door housing's fridge was behind its 2nd door, now its 1st\n        // (2026-10-30). One orphaned appliance and one free slot: it moves there.\n        const _orphans = Object.keys(c.appliances).filter(k => !_slotIdx.has(String(k)) && c.appliances[k]);\n        const _free = Catalogue.applianceSlotsOf(c.cutoutSchema).map(s => String(s.i)).filter(k => !_kept[k]);\n        if (_orphans.length === 1 && _free.length === 1) _kept[_free[0]] = c.appliances[_orphans[0]];\n        c = { ...c, appliances: Object.keys(_kept).length ? _kept : null };\n      }\n      // Top-hung (lift-up flap) doors have no user-selectable side, so the\n      // schema's 'top' is authoritative. Pin cab.hingeSide to it on load \u2014\n      // corrects stale saves (a bridging unit placed before the schema\n      // declared 'top' kept hingeSide 'left', which then fought the 3D flap\n      // and sent a bogus \"Left\" hinge to the basket).\n      const firstDoorOpening = (c.cutoutSchema?.openings || []).find(o => o.type === 'door');\n      if (firstDoorOpening && firstDoorOpening.hingeSide === 'top') {\n        c = { ...c, hingeSide: 'top' };\n      }\n      // Hinge-selectability is resolved PER VARIANT from the schema, so it\n      // can flip when the height variant changes (a Medium may be a flap on\n      // one housing and hinged on another - no pattern). Re-derive it from\n      // the live catalogue on load; the saved snapshot may predate the\n      // schema declaring this height a flap, which would otherwise leave a\n      // stale Left/Right toggle + a bogus Hinge on the basket line.\n      if (Catalogue.isHingeSelectable) {\n        const _prod = Catalogue.getProductForUnitInStyle\n          ? Catalogue.getProductForUnitInStyle(c.unitTypeId, c.kitchenStyleId)\n          : null;\n        c = { ...c, hingeSelectable: Catalogue.isHingeSelectable(c.cutoutSchema, _prod, c.unitTypeId) };\n        // ...and fill a MISSING hand. hingeSide is stamped once at spawn, so a\n        // cab saved while its front wasn't recognised as door-bearing (glass\n        // units, before 'glass' counted as doorish) keeps a null forever - and\n        // the Hinge control needs it. Only filled when absent, so a hand the\n        // user chose is never overwritten.\n        if (!c.hingeSide && c.hingeSelectable && Catalogue.getDefaultHingeSide) {\n          const _hs = Catalogue.getDefaultHingeSide(c.cutoutSchema);\n          if (_hs) c = { ...c, hingeSide: _hs };\n        }\n      }\n    }\n    // Belfast sink units: re-derive the lowered-carcase + sink marker from\n    // the live catalogue and pin the cab to worktop level (so the bowl\n    // fills the gap and the worktop lines up with neighbours). Old stub\n    // Belfast cabs (unitTypeId not a real metaobject) return null here and\n    // keep their saved marker untouched.\n    const belfastMarker = Catalogue.getBelfastSinkMarker\n      ? Catalogue.getBelfastSinkMarker(c.unitTypeId, c.widthMm)\n      : null;\n    if (belfastMarker) {\n      c = { ...c, belfastSink: belfastNotchForSink(belfastMarker, c), heightMm: 720 + (belfastMarker.plinthMm || 150) };\n    }\n    // Splay end units: re-derive the angled-geometry marker from the live\n    // catalogue so a saved splay cab (placed before the marker wiring, or\n    // any reload) renders as the trapezoid, not a rectangle.\n    const splayMarker = Catalogue.getSplayEndMarker\n      ? Catalogue.getSplayEndMarker(c.unitTypeId)\n      : null;\n    if (splayMarker) {\n      c = { ...c, splayEnd: splayMarker };\n    }\n    // Midi units: re-derive the worktop-not-cornice flag from the live\n    // catalogue so saved plans (and cabs placed before the flag existed)\n    // pick it up on reload.\n    if (ut) c = { ...c, isMidiUnit: (ut.isMidiUnit === true) };\n    // Worktop dressers: re-derive so dressers placed before the flag existed\n    // come down off their mount line onto the worktop on reload.\n    if (ut) c = { ...c, dresserUnit: isWorktopDresserType(ut) };\n    // True Handleless handed flag: re-derive from the live catalogue so saved\n    // plans (and cabs placed before the flag existed) pick up the Rail toggle.\n    if (ut) c = { ...c, trueHandlelessHanded: (ut.trueHandlelessHanded === true) };\n  }\n\n  // Backfill colour handles for saves made before Phase B2. Defaults\n  // are first-available for the style; renderer falls back to default\n  // hex if the handle ends up unresolvable.\n  if (!c.doorColourHandle && c.kitchenStyleId) {\n    const first = (Catalogue.getDoorColoursForStyle(c.kitchenStyleId) || [])[0];\n    if (first) c = { ...c, doorColourHandle: first.handle };\n  }\n  // A unit with no carcase colour (no_carcase_colour: panels, appliance\n  // doors) is never given one - the backfill used to hand it the first\n  // colour, which then showed up as a carcase combination of its own.\n  const _noCarcase = !!(Catalogue.getUnitType && Catalogue.getUnitType(c.unitTypeId) || {}).noCarcaseColour;\n  if (_noCarcase) {\n    // nothing to backfill or snap\n  } else if (!c.carcaseColourHandle && c.kitchenStyleId) {\n    const first = (Catalogue.getCarcaseColoursForUnit(c.unitTypeId, c.kitchenStyleId) || [])[0];\n    if (first) c = { ...c, carcaseColourHandle: first.handle };\n  } else if (c.carcaseColourHandle && c.kitchenStyleId) {\n    // A unit sold in only some carcase colours (the Larder Pantry is Davenport\n    // Oak only) may be carrying a colour from before that rule existed, or one\n    // a bulk \"apply to all\" pushed onto it. Snap it, so a saved plan corrects\n    // itself on load rather than ordering a carcase that isn't made. Only the\n    // backfill above ran before, and that fires only when the handle is ABSENT.\n    const allowed = Catalogue.getCarcaseColoursForUnit(c.unitTypeId, c.kitchenStyleId) || [];\n    if (allowed.length && !allowed.some(x => x.handle === c.carcaseColourHandle)) {\n      c = { ...c, carcaseColourHandle: allowed[0].handle };\n    }\n  }\n\n  // Backfill endPanels for saves made before Stage 2 and migrate\n  // older shapes:\n  //   pre-Stage-2:       no endPanels   \u2192 both off\n  //   Stage-2 booleans:  { left: true } \u2192 { left: { active: true, \u2026 } }\n  //   Stage-2 lite:      already objects (current shape)\n  function normaliseEpSide(value) {\n    // toFloor = the floor-height \"Tall End Panel\" on a deep bridging unit\n    // (American fridge housing). Off by default; only the picker sets it.\n    const base = { active: false, style: 'flat', inline: false, pelmetExt: 'modern', toFloor: false };\n    if (value === true)  return { ...base, active: true };\n    if (value === false || value == null) return base;\n    return { ...base, ...value };   // object with possibly-missing fields\n  }\n  if (!c.endPanels) {\n    c = { ...c, endPanels: { left: normaliseEpSide(false), right: normaliseEpSide(false) } };\n  } else {\n    c = { ...c, endPanels: {\n      left:  normaliseEpSide(c.endPanels.left),\n      right: normaliseEpSide(c.endPanels.right)\n    } };\n  }\n  if (!c.endPanelColours) c = { ...c, endPanelColours: { left: null,  right: null  } };\n\n  // Corner units carry a cornerUnit descriptor; normalise it so a\n  // partial save round-trips cleanly. Non-corner cabinets are left\n  // untouched (no cornerUnit field).\n  if (c.cornerUnit) {\n    c = { ...c, cornerUnit: normaliseCornerUnit(c.cornerUnit) };\n    // The VOID end of a blank-panel corner unit is finished by the blank\n    // panel and corner post - it never takes an end panel. The auto pass\n    // already forced it off, but that pass is skippable: it returns early\n    // in manual end-panel mode, and it does not run at all on some paths\n    // that MOVE the unit. So a panel set while the unit was elsewhere\n    // survived, and in peninsula placement - void end flushed to a wall -\n    // it stood proud of that wall. Clear it here instead, on the\n    // normaliser every cabinet passes through, so it holds whatever route\n    // the unit arrived by: drag, placement toggle, hand flip, or a\n    // reloaded plan that was saved with it on.\n    const voidSide = c.cornerUnit.hand === 'right' ? 'left' : 'right';\n    if (c.endPanels && c.endPanels[voidSide] && c.endPanels[voidSide].active) {\n      c = { ...c, endPanels: {\n        ...c.endPanels,\n        [voidSide]: { ...c.endPanels[voidSide], active: false }\n      } };\n    }\n  }\n\n  // Backfill fillers for saves made before Phase A. Default off,\n  // 20mm wide, no setback (autoDetect re-derives setBackMm per\n  // render, so a saved value is just a starting point).\n  function normaliseFillerSide(value) {\n    const base = { active: false, widthMm: 20, setBackMm: 0 };\n    if (value == null || typeof value !== 'object') return base;\n    return { ...base, ...value };\n  }\n  if (!c.fillers) {\n    c = { ...c, fillers: { left: normaliseFillerSide(null), right: normaliseFillerSide(null) } };\n  } else {\n    c = { ...c, fillers: {\n      left:  normaliseFillerSide(c.fillers.left),\n      right: normaliseFillerSide(c.fillers.right)\n    } };\n  }\n\n  // Backfill the Phase-2 per-unit worktop extension. Default 0 mm\n  // all sides (left/right up to 1000, front/back up to 300).\n  {\n    const w = (c.worktop && typeof c.worktop === 'object') ? c.worktop : {};\n    c = { ...c, worktop: {\n      left:  Number(w.left)  || 0,\n      right: Number(w.right) || 0,\n      front: Number(w.front) || 0,\n      back:  Number(w.back)  || 0\n    } };\n  }\n  if (c.rotationDeg !== undefined) return c;\n  const doorSide = c.doorSide || 'top';\n  const rotationDeg = ROTATION_FROM_DOOR_SIDE[doorSide] ?? 0;\n\n  const def = findCabinet(c.code);\n  let widthMm = c.widthMm;\n  let depthMm = c.depthMm;\n  if (def && def.widthMm !== widthMm) {\n    widthMm = def.widthMm;\n    depthMm = def.depthMm;\n  }\n  const cx = c.x + c.widthMm / 2;\n  const cy = c.y + c.depthMm / 2;\n  const migrated = { ...c, x: cx - widthMm / 2, y: cy - depthMm / 2, widthMm, depthMm, rotationDeg };\n  delete migrated.doorSide;\n  // \"Exclude from Quote\" flag - when true the cabinet stays in the plan\n  // (movable, recolourable) but is dropped from auto-numbering, the quote\n  // drawer list, the quote total, and the cart. Backfill false for older\n  // saves that predate the feature.\n  migrated.excludeFromQuote = c.excludeFromQuote === true;\n  return migrated;\n}\n\n\n\nfunction init() {\n  const _initAt = performance.now();   // ?btktime=1 Plan Online timing reads it\n  const root = document.querySelector(ROOT_SELECTOR);\n  if (!root) {\n    console.warn('[BTK Kitchen Planner] Root element not found:', ROOT_SELECTOR);\n    return;\n  }\n  // Debug hook - lets the console test the LIVE catalogue code path\n  // (buildCabinetDefinition / isHingeSelectable) to confirm which build is running.\n  try { window.__btkCatalogue = Catalogue; } catch (e) {}\n\n  // UNIT TYPES THAT ARRIVE AFTER THE PLAN (Arden, 2026-10-20). The unit types\n  // past Liquid's 250 cap - 72 of the 73 True Handleless ones - merge in a\n  // moment after boot (mergeUnitTypeTail). A plan restored before then went\n  // through migrateCabinet with no unit type for those units, so it kept their\n  // SAVED cutout schema, 2D shape and category: fixing a TH unit's schema in\n  // admin never reached a plan that already had one (Jonathan Print's double\n  // oven + mic housing kept its old High layout). Run those units through\n  // migrateCabinet again once their unit types are here, and redraw.\n  window.addEventListener('btk:unit-types-merged', (ev) => {\n    const ids = new Set(((ev && ev.detail && ev.detail.ids) || []).map(String));\n    if (!ids.size || !Array.isArray(cabinets)) return;\n    if (!cabinets.some(c => c && ids.has(String(c.unitTypeId)))) return;\n    cabinets = cabinets.map(c => (c && ids.has(String(c.unitTypeId))) ? migrateCabinet(c) : c);\n    try { rerender(); } catch (e) { console.warn('[BTK Kitchen Planner] redraw after the unit-type merge failed', e); }\n  });\n\n  const context = readShopifyContext(root);\n  console.log('[BTK Kitchen Planner] Mounted. Shopify context:', context);\n\n  // Cover the boot when arriving from the basket's \"Edit Plan\" button\n  // (always carries view3d=1) - that path restores a plan + warms the\n  // 3D view, which takes a moment. Hidden once the autoload settles\n  // below. Gated so normal/fast planner visits don't flash a loader.\n  const _bootViewParam = new URLSearchParams(window.location.search).get('view3d');\n  if (_bootViewParam === '1' && window.BTKLoader) {\n    window.BTKLoader.show({ message: 'Rebuilding your 3D plan\u2026' });\n  }\n\n  // Live joint-session boot params (salesperson-guided co-design). Captured\n  // here - BEFORE the deep-link handler strips the query string - so the\n  // driver push / viewer poll can still build App-Proxy URLs (which need cid)\n  // after the address bar has been cleaned. See the LiveSession module below.\n  const _bootLive = (() => {\n    try {\n      const p = new URLSearchParams(window.location.search);\n      return {\n        session: (p.get('session') || '').trim(),\n        role:    (p.get('role')    || '').trim().toLowerCase(),\n        // A viewer never uses a staff pass, even if an older link carries one:\n        // the customer watching a session must authenticate as themselves.\n        cid:     (p.get('role') || '').trim().toLowerCase() === 'viewer'\n                   ? '' : (p.get('cid') || '').trim(),\n        // Signed token authorising the cid override (staff acting as customer).\n        // Forwarded on session calls + reused on the viewer link (same customer).\n        cidt:    (p.get('role') || '').trim().toLowerCase() === 'viewer'\n                   ? '' : (p.get('cidt') || '').trim(),\n        // Carry the staging preview-theme id (if the driver arrived on a\n        // preview) onto the viewer link, so the customer opens the SAME theme\n        // - otherwise they'd land on the live theme (old code, no session).\n        preview: (p.get('preview_theme_id') || '').trim()\n      };\n    } catch (e) { return { session: '', role: '', cid: '', cidt: '', preview: '' }; }\n  })();\n\n  // A PURCHASED plan, opened read-only from the account's Orders list. The\n  // basket id is the whole parameter: everything else comes from the server's\n  // frozen snapshot of what was bought.\n  const _bootOrdered = (() => {\n    try { return (new URLSearchParams(window.location.search).get('ordered') || '').trim(); }\n    catch (e) { return ''; }\n  })();\n\n  // A SAVED plan opened to look at only - the account's View Plan on a phone,\n  // where the planner itself cannot be used (2026-10-16). Same lock as a bought\n  // plan below; the plan is never saved back. Only with a plan link.\n  const _bootViewOnly = (() => {\n    try {\n      const p = new URLSearchParams(window.location.search);\n      return p.get('viewonly') === '1' && !!((p.get('planId') || '').trim() || (p.get('plan') || '').trim());\n    } catch (e) { return false; }\n  })();\n\n  // An \"Edit Plan\" link to one saved plan (the account's Plans tab, Odoo's\n  // \"Edit in Planner\"). The loader stays up until THAT plan is on screen at\n  // Add Units. Dropping it once the UI was built showed Home for 3-5 seconds\n  // while the old autosave restored, then Room Setup, then the plan (Arden,\n  // 2026-09-29). Not for a live-session viewer: it ignores plan links.\n  // The website's Start Planning (?journey=&style=): the boot loader stays up\n  // until the name popup is on screen. Dropped when the UI was built, it\n  // showed the bare Start page for a second or more while the last plan\n  // loaded - read as a hang (Arden, 2026-10-07).\n  const _bootJourneyLink = (() => {\n    try {\n      const p = new URLSearchParams(window.location.search);\n      return !!((p.get('journey') || '').trim() && (p.get('style') || '').trim());\n    } catch (e) { return false; }\n  })();\n  let journeyLinkLanded = false;\n  function dropJourneyLinkLoader() {\n    if (!_bootJourneyLink || journeyLinkLanded) return;\n    journeyLinkLanded = true;\n    // Once the name popup has painted, so no bare frame shows in between.\n    requestAnimationFrame(() => requestAnimationFrame(() => {\n      if (window.BTKLoader && window.BTKLoader.hide) window.BTKLoader.hide();\n    }));\n  }\n  // Back through pre-checkout's Basket step. Read here because the boot strips\n  // the address, and that used to happen before startFreshIfOrdered looked, so\n  // the hold was never released and the customer was asked about a checkout\n  // they had just left (Ellie Wing, 2026-11-02). Used once: a later refused save\n  // on this page could be a checkout running in another tab.\n  let _bootBasketStepReturn = false;\n  try { _bootBasketStepReturn = new URLSearchParams(window.location.search).get('openbasket') === '1'; } catch (e) {}\n  const _bootPlanLink = (() => {\n    if (_bootOrdered) return false;\n    try {\n      const p = new URLSearchParams(window.location.search);\n      if ((p.get('role') || '').trim().toLowerCase() === 'viewer') return false;\n      // restoreVersion: Odoo's Plan History \"Restore as Copy\" - the same\n      // arrival, opening an earlier version of a plan as a new one.\n      return !!((p.get('plan') || '').trim() || (p.get('planId') || '').trim()\n        || (p.get('restoreVersion') || '').trim() || (p.get('worktopquote') || '').trim());\n    } catch (e) { return false; }\n  })();\n  // Set once the plan-link path owns the loader, so the boot's own \"drop the\n  // loader\" steps leave it alone.\n  let planLinkLanding = false;\n  let planLinkLanded = false;\n\n  // ---- Purchased plan VIEWER: look, do not touch -------------------------\n  // The plan IS the record of what was sold, so nothing here may change it:\n  // no dragging, no deleting, no right-click menu. Stopped at the window in\n  // the capture phase, before any planner listener runs - gating each handler\n  // one by one is how one gets missed (the live viewer above learned this).\n  // Selection, the camera and the popups stay live: reading a unit's details\n  // is the entire point of the screen.\n  if (_bootOrdered || _bootViewOnly) {\n    window.__btkKpDragLocked = true;\n    // The green staff bar too: it sits on <body>, whose btk-kp-active class\n    // made its Back to Odoo look like a planner control, so the click was\n    // swallowed and staff were stuck in the viewer (Arden, 2026-10-27).\n    const ORDERED_ALLOW = '.btk-kp-dialog-overlay, [data-btk-kp-ordered-bar], #btk-staff-banner';\n    const allowedO = (t) => !!(t && t.closest && t.closest(ORDERED_ALLOW));\n    const blockO = (e) => {\n      if (allowedO(e.target)) return;\n      e.stopImmediatePropagation();\n      if (e.cancelable) e.preventDefault();\n    };\n    // Right-click and native drag are edit-only, so they go entirely.\n    ['contextmenu', 'dragstart'].forEach((ev) =>\n      window.addEventListener(ev, blockO, { capture: true, passive: false }));\n    // Keys reach nothing: Delete, the arrow nudges and every shortcut. Only\n    // propagation is stopped, so browser shortcuts still work. Escape gets\n    // through so a popup that is open can still be closed.\n    ['keydown', 'keyup', 'keypress'].forEach((ev) =>\n      window.addEventListener(ev, (e) => {\n        if (allowedO(e.target) || e.key === 'Escape') return;\n        e.stopImmediatePropagation();\n      }, { capture: true }));\n    // Every button, field and link the planner draws is an edit waiting to\n    // happen (Swap, Delete, Lock Room, a size box...), so none of them work\n    // here. Let through only what LOOKS: the 2D/3D switch, Show/Hide Units and\n    // anything that closes a popup. The canvas itself is not a control, so\n    // clicking a unit to read it and turning the 3D camera still work. Scoped to\n    // the planner's own markup (popups are hoisted to <body>), so the site's\n    // header and footer links are untouched. Whatever still slips past is put\n    // back by the snapshot check in pushUndoSnapshot.\n    const ORDERED_CONTROL = 'button, input, select, textarea, label, a[href], '\n      + '[role=\"button\"], [role=\"tab\"], [role=\"checkbox\"], [role=\"switch\"], [contenteditable]';\n    // Door Open/Close is a 3D view state, not part of the plan, so it stays.\n    const ORDERED_VIEW_ONLY = '[data-btk-kp-view-toggle], [data-btk-kp-hide-units-toggle], '\n      + '[data-action=\"toggle-open\"], [data-btk-kp-ordered-close], '\n      + '[data-btk-kp-popup-close], .btk-kp-popup-close, [data-btk-kp-focus-close], '\n      + '[data-btk-kp-close-selection], .btk-kp-panel-close, [data-btk-kp-modal-close], '\n      + '.btk-kp-panel-iconbtn--close, [data-btk-kp-basket-embed-close], '\n      // saveBlob's link: a download, not an edit. Without it the Kitchen\n      // Manual's Download saved nothing in this viewer (Arden, 2026-11-13).\n      + '[data-btk-kp-save-file]';\n    const blockControl = (e) => {\n      const t = e.target;\n      if (!t || !t.closest || allowedO(t) || t.closest(ORDERED_VIEW_ONLY)) return;\n      if (!t.closest(ORDERED_CONTROL)) return;\n      if (!t.closest('.btk-kp-app, [class*=\"btk-kp-\"]')) return;\n      e.stopImmediatePropagation();\n      if (e.cancelable) e.preventDefault();\n    };\n    ['pointerdown', 'mousedown', 'touchstart', 'click', 'dblclick',\n      'input', 'change', 'drop', 'paste', 'submit'].forEach((ev) =>\n      window.addEventListener(ev, blockControl, { capture: true, passive: false }));\n  }\n\n  // ---- Live session VIEWER: watch only ----------------------------------\n  // The customer watching a session must not be able to change the plan. In\n  // testing they could drag units about - their moves never reached the\n  // salesperson, so the two screens silently disagreed. The existing drag lock\n  // (window.__btkKpDragLocked) only covers dragging in 2D; a viewer also has\n  // the sidebar, the unit panel, the keyboard shortcuts and 3D click-to-select.\n  //\n  // So input is stopped at the very top of the chain - window, capture phase,\n  // which runs before every listener the planner registers anywhere - rather\n  // than gating each handler one by one and missing one. The customer does not\n  // need their own controls: their view follows the salesperson's.\n  //\n  // Let through: dialogs (the consent prompt, sign-in) and the viewer banner.\n  // Keys only have propagation stopped, not their default, so the browser's\n  // own shortcuts - refresh, close tab - still work.\n  //\n  // Also let through the clicks the MIRROR itself makes (window.__btkLiveReplay):\n  // following the salesperson into a popup opens it the way a click would, so\n  // its contents are built by the same code as on their screen.\n  if (_bootLive.session && _bootLive.role === 'viewer') {\n    window.__btkKpDragLocked = true;\n    const LIVE_VIEWER_ALLOW = '#btk-live-viewer, .btk-kp-dialog-overlay';\n    const allowed = (t) => !!(t && t.closest && t.closest(LIVE_VIEWER_ALLOW));\n    const stopPointer = (e) => {\n      if (window.__btkLiveReplay) return;\n      if (allowed(e.target)) return;\n      e.stopImmediatePropagation();\n      if (e.cancelable) e.preventDefault();\n    };\n    const stopKey = (e) => {\n      if (allowed(e.target)) return;\n      e.stopImmediatePropagation();\n    };\n    ['pointerdown', 'pointerup', 'mousedown', 'mouseup', 'click', 'dblclick',\n     'contextmenu', 'touchstart', 'touchmove', 'touchend', 'wheel', 'dragstart']\n      .forEach((ev) => window.addEventListener(ev, stopPointer, { capture: true, passive: false }));\n    ['keydown', 'keyup', 'keypress']\n      .forEach((ev) => window.addEventListener(ev, stopKey, { capture: true }));\n  }\n\n  // Persistence boundary. Plans now persist through the SAME save\n  // object as the advanced basket (BTKBasketAPI) - a planner basket\n  // carries the 3D design plus its line items. One Project per\n  // customer, one seam to point at Node later (set BTKBasketAPI's\n  // ADAPTER='server'). Falls back to local storage if the basket API\n  // failed to load.\n  const planStore = createBasketPlanStore();\n  // EVERY save of the plan on screen carries its price and its last 3D\n  // picture, whichever path saves it (autosave, the basket, Save, Save As):\n  // a save without them showed \"no preview\" and no value in Odoo's Kitchen\n  // Plans until the next explicit save (Arden, 2026-11-06).\n  for (const [method, at] of [['save', 0], ['saveAs', 1]]) {\n    const own = planStore[method];\n    if (typeof own !== 'function') continue;\n    planStore[method] = function (...args) {\n      const d = args[at];\n      if (d && typeof d === 'object' && d.plannerPlanId && d.plannerPlanId === plannerPlanId) {\n        stampPlanPrice(d);\n        if (!d.thumbnail && planThumb) d.thumbnail = planThumb;\n      }\n      return own.apply(this, args);\n    };\n  }\n  // The boot restore (planStore.load, right at the bottom of this file) fills\n  // `cabinets` and `activePlanName` ASYNCHRONOUSLY. Anything that decides\n  // whether the planner is 'empty' before it settles gets the wrong answer -\n  // see enterStyleSetup. Deliberately a synchronous FLAG, not a promise to\n  // await: nothing on the boot path may block on a network call.\n  let bootRestoreSettled   = false;\n  let pendingStyleSetupEntry = false;\n\n  // Reveal the internal (salesperson-only) tools strip. Visibility is\n  // a convenience gate; the Node backend re-verifies the role before\n  // any privileged action (e.g. assigning a plan to a customer).\n  if (context.isSalesperson) {\n    const internal = root.querySelector('[data-btk-kp-internal-tools]');\n    if (internal) internal.hidden = false;\n  }\n\n  const main    = root.querySelector(MAIN_SELECTOR);\n  const sidebar = root.querySelector(SIDEBAR_SELECTOR);\n  if (!main || !sidebar) {\n    console.warn('[BTK Kitchen Planner] Main or sidebar element not found.');\n    return;\n  }\n\n  document.body.classList.add('btk-kp-active');\n\n  // Reveal the real site top-bar above the planner: measure its height\n  // and expose it as --btk-kp-top-offset so this fixed overlay sits\n  // directly below it. The bar's height varies (announcement image,\n  // viewport), so we measure live rather than hardcode.\n  // The green staff bar (btk-basket-api.js, #btk-staff-banner) counts too: it\n  // is put on <body> after the planner boots, and the planner was drawn under\n  // it, so it covered the top of the canvas - the 2D/3D switch in the ordered\n  // plan viewer (Arden, 2026-10-27). The planner now starts below whichever\n  // reaches lower.\n  (function syncTopBarOffset() {\n    const topBar = document.querySelector('.btk-top-bar');\n    const watched = new Set();\n    const ro = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(() => apply()) : null;\n    const watch = (el) => { if (el && ro && !watched.has(el)) { watched.add(el); ro.observe(el); } };\n    function apply() {\n      const banner = document.getElementById('btk-staff-banner');\n      watch(banner);\n      const bottom = (el) => (el ? Math.max(0, el.getBoundingClientRect().bottom) : 0);\n      const h = Math.max(topBar ? topBar.getBoundingClientRect().height : 0, bottom(banner));\n      document.documentElement.style.setProperty('--btk-kp-top-offset', h + 'px');\n    }\n    watch(topBar);\n    apply();\n    // The staff bar arrives later (and only in staff mode).\n    if (!document.getElementById('btk-staff-banner') && typeof MutationObserver !== 'undefined') {\n      const mo = new MutationObserver(() => {\n        if (document.getElementById('btk-staff-banner')) { mo.disconnect(); apply(); }\n      });\n      mo.observe(document.body, { childList: true });\n    }\n    window.addEventListener('resize', apply);\n  })();\n\n  // Re-fit the plan whenever its container (#btk-kp-main) actually changes size:\n  // opening/closing the basket (the panel slides in over ~0.36s and reflows the\n  // 2D canvas), window resize, layout toggles. The grid's pxPerMm fit is\n  // computed once per render, so WITHOUT this the grid stays fitted to whatever\n  // (often transient, too-small) size it was built at - the room then renders\n  // tiny in the basket 2D view. Debounced so the animation's intermediate sizes\n  // fire ONE rebuild after the size settles; zoom/pan survive (view2d persists).\n  (function observeMainResize() {\n    if (typeof ResizeObserver === 'undefined') return;\n    let t = null, lastW = main.clientWidth, lastH = main.clientHeight;\n    const ro = new ResizeObserver(() => {\n      const w = main.clientWidth, h = main.clientHeight;\n      if (Math.abs(w - lastW) < 2 && Math.abs(h - lastH) < 2) return;\n      lastW = w; lastH = h;\n      clearTimeout(t);\n      t = setTimeout(() => { try { rerender(); } catch (e) {} }, 150);\n    });\n    ro.observe(main);\n  })();\n\n  // DEV: `btkAppliances()` in the console prints every appliance the planner\n  // loaded with its new metafields parsed, so you can confirm each product's\n  // placement / footprint / GLB is coming through as you tag them in Shopify.\n  if (typeof window !== 'undefined') {\n    window.btkAppliances = () => {\n      try {\n        const list = (Catalogue.getAllAppliances && Catalogue.getAllAppliances()) || [];\n        const rows = list.map(a => ({\n          handle:    a.handle,\n          title:     a.title,\n          category:  a.category,\n          placement: a.placement || '(blank)',\n          builtIn:   Catalogue.isApplianceBuiltIn ? Catalogue.isApplianceBuiltIn(a) : null,\n          aperture:  (a.apertureWMm != null || a.apertureHMm != null) ? `${a.apertureWMm || '?'}x${a.apertureHMm || '?'}` : '',\n          footprint: a.footprint ? `${a.footprint.wMm}x${a.footprint.dMm}x${a.footprint.hMm}` : '(none)',\n          glb:       a.glbUrl ? 'yes' : 'no'\n        }));\n        console.table(rows);\n        return `${rows.length} appliances loaded`;\n      } catch (e) { console.error('[btkAppliances]', e); }\n    };\n  }\n\n  // Clear the \"Loading planner\u2026\" placeholder but preserve the static\n  // viewport overlay markup (2D/3D toggle + lighting gear) that lives\n  // inside #btk-kp-main.\n  Array.from(main.children).forEach(child => {\n    if (child.classList?.contains('btk-kp-viewport-overlay')) return;\n    if (child.hasAttribute?.('data-btk-kp-home')) return;   // Planner Home content layer\n    child.remove();\n  });\n\n  // ---- State ----\n  // A new plan's room. Its splashbacks follow the hob heat rule\n  // (engine-splashbacks: a heat-safe splashback runs behind the hob, and a hob\n  // splashback can stand on a stone upstand); plans saved before it keep the\n  // rule they were made with (Arden, 2026-11-12: no changes to saved plans).\n  function freshRoomConfig() {\n    const rc = JSON.parse(JSON.stringify(DEFAULT_ROOM_CONFIG));\n    rc.splashbacks = { ...(rc.splashbacks || {}), hobHeatRule: true };\n    return rc;\n  }\n  let roomConfig = freshRoomConfig();\n  let cabinets   = [];\n  // ---- __btkZ() ------------------------------------------------------\n  // \"Is the pillar actually above the unit, and am I even running this\n  // build?\" Prints every layer under .btk-kp-grid with its COMPUTED\n  // z-index, and where the first pillar / internal wall actually lives.\n  // If the structure layer is missing from the table, the browser is\n  // running an older bundle - which is the first thing to rule out.\n  window.__BTK_BUILD = 'cb=1714 | A bare appliance side no longer suppresses its neighbour';\n  window.__btkZ = () => {\n    const g = document.querySelector('.btk-kp-grid');\n    if (!g) { console.log('[__btkZ] no .btk-kp-grid in the DOM'); return; }\n    console.log('[__btkZ] build =', window.__BTK_BUILD);\n    console.table([...g.children].map(el => ({\n      layer: el.className || '(no class)',\n      zIndex: getComputedStyle(el).zIndex,\n      children: el.children.length\n    })));\n    const structural = document.querySelectorAll(\n      '.btk-kp-feature[data-feature-type=\"column\"], .btk-kp-feature[data-feature-type=\"wall\"]');\n    console.log('[__btkZ] structural features found:', structural.length);\n    structural.forEach((el, i) => {\n      const par = el.parentElement;\n      console.log('  #' + i,\n        '| type=' + el.dataset.featureType,\n        '| classes=' + el.className,\n        '| parent=' + (par ? par.className : 'none'),\n        '| parentZ=' + (par ? getComputedStyle(par).zIndex : '-'),\n        '| ownZ=' + getComputedStyle(el).zIndex);\n    });\n    const cabLayer = document.querySelector('.btk-kp-cabinets-layer');\n    console.log('[__btkZ] cabinets layer z =',\n      cabLayer ? getComputedStyle(cabLayer).zIndex : 'not found');\n    const ccUnits = (cabinets || []).filter(c => c && c.customFit);\n    console.log('[__btkZ] units with customFit:', ccUnits.length,\n      ccUnits.map(c => ({ num: c.displayNumber, ignore: !!c.customFit.ignoreClash, notes: c.customFit.notes })));\n  };\n\n\n  // ---- btkPanelWhy() -----------------------------------------------\n  // Console diagnostic for \"there is a panel here that should not be\".\n  // Registered EARLY and unconditionally so it exists even if something\n  // later in init throws, and it reports every object that can draw a\n  // strip at a unit's end - not just endPanels, which is the one I kept\n  // assuming. A separate end-panel PRODUCT is its own cabinet and renders\n  // red (#CE0402), so it looks exactly like an attached panel on the plan.\n  window.btkPanelWhy = function (cabId) {\n    const all = cabinets || [];\n    const corners = all.filter(c => c && c.cornerUnit && (!cabId || c.id === cabId));\n    console.log('%c[btkPanelWhy]', 'font-weight:bold',\n                'cabinets:', all.length,\n                '| corner units:', corners.length,\n                '| autoEndPanels:', autoEndPanels);\n    const out = { cabinets: all.length, cornerUnits: corners.length,\n                  autoEndPanels: autoEndPanels, units: [] };\n    if (!corners.length) { console.log('  no corner units in the plan'); return out; }\n\n    for (const cab of corners) {\n      const hand     = cab.cornerUnit.hand;\n      const doorSide = hand === 'right' ? 'right' : 'left';\n      const voidSide = doorSide === 'left' ? 'right' : 'left';\n      const ep  = cab.endPanels || {};\n      const fil = cab.fillers   || {};\n      console.log('%c#' + (cab.displayNumber ?? '?') + ' ' + (cab.code || cab.unitTypeId),\n                  'font-weight:bold',\n                  '| hand=' + hand + ' (door=' + doorSide + ', void=' + voidSide + ')',\n                  '| placement=' + (cab.cornerUnit.placement || 'auto'),\n                  '| rot=' + Math.round(cab.rotationDeg || 0),\n                  '| x=' + Math.round(cab.x) + ' y=' + Math.round(cab.y),\n                  '| w=' + Math.round(cab.widthMm) + ' d=' + Math.round(cab.depthMm));\n      console.table(['left', 'right'].map(side => ({\n        side,\n        role:       side === doorSide ? 'DOOR' : 'VOID',\n        panelOn:    !!(ep[side] && ep[side].active),\n        panelStyle: (ep[side] && ep[side].style) || '-',\n        toFloor:    !!(ep[side] && ep[side].toFloor),\n        doorLine:   !!(ep[side] && ep[side].doorLine),\n        userOff:    !!(ep[side] && ep[side].userOff),\n        fillerOn:   !!(fil[side] && fil[side].active)\n      })));\n      // Everything ELSE that paints a strip at an end.\n      console.log('   backPanel.active =', !!(cab.backPanel && cab.backPanel.active),\n                  '| useFullSizeEndPanel =', !!cab.useFullSizeEndPanel,\n                  '| backEndPost =', !!(cab.backEndPost && cab.backEndPost.active),\n                  '| railGripSide =', cab.railGripSide || '-');\n      // Separate end-panel PRODUCTS / free-place panels sitting nearby -\n      // these are their own cabinets and draw red.\n      const near = all.filter(o => o && o.id !== cab.id &&\n        (o.endPanelUnit || o.endPanelFiller) &&\n        Math.hypot((o.x + (o.widthMm || 0) / 2) - (cab.x + cab.widthMm / 2),\n                   (o.y + (o.depthMm || 0) / 2) - (cab.y + cab.depthMm / 2)) < 1500);\n      if (near.length) {\n        console.log('   separate end-panel ITEMS within 1.5m (these render red):');\n        console.table(near.map(o => ({\n          id: o.id, num: o.displayNumber ?? '?', code: o.code || o.unitTypeId,\n          kind: o.endPanelUnit ? 'endPanelUnit(product)' : 'endPanelFiller(free-place)',\n          x: Math.round(o.x), y: Math.round(o.y),\n          w: Math.round(o.widthMm || 0), d: Math.round(o.depthMm || 0),\n          rot: Math.round(o.rotationDeg || 0)\n        })));\n      } else {\n        console.log('   separate end-panel items nearby: none');\n      }\n      // What is actually IN THE DOM for this cabinet, and WHERE. The\n      // decision data has been clean for two rounds while the plan still\n      // showed a strip, so name the element that is drawing it and give\n      // its screen position relative to the cabinet - left edge or right.\n      let domInfo = 'probe failed';\n      try {\n        const esc = (window.CSS && CSS.escape) ? CSS.escape(String(cab.id)) : String(cab.id);\n        const host = document.querySelector('[data-cabinet-id=\"' + esc + '\"]');\n        if (!host) domInfo = 'no cabinet element';\n        else {\n          const hr = host.getBoundingClientRect();\n          const kids = Array.from(host.querySelectorAll('*')).filter(n => {\n            const r = n.getBoundingClientRect();\n            if (!r.width || !r.height) return false;\n            // narrow strips only - a panel is thin in one axis\n            return (r.width < hr.width * 0.25) || (r.height < hr.height * 0.25);\n          });\n          domInfo = kids.map(n => {\n            const r = n.getBoundingClientRect();\n            const dl = Math.round(r.left - hr.left);\n            const dr = Math.round(hr.right - r.right);\n            const where = dl <= 4 ? 'LEFT-edge' : dr <= 4 ? 'RIGHT-edge'\n                        : (r.top - hr.top) <= 4 ? 'TOP-edge'\n                        : (hr.bottom - r.bottom) <= 4 ? 'BOTTOM-edge' : 'inner';\n            return where + ' ' + Math.round(r.width) + 'x' + Math.round(r.height) +\n                   ' [' + (n.className || n.tagName) + ']';\n          });\n          // anything sticking out past the cabinet box entirely\n          const outside = kids.filter(n => {\n            const r = n.getBoundingClientRect();\n            return r.left < hr.left - 1 || r.right > hr.right + 1;\n          }).map(n => (n.className || n.tagName));\n          if (outside.length) domInfo = domInfo.concat(['OUTSIDE THE CAB BOX: ' + outside.join(', ')]);\n        }\n        console.log('   DOM strips:', domInfo);\n      } catch (e) { console.log('   DOM probe failed:', e.message); }\n\n      out.units.push({\n        num: cab.displayNumber ?? '?', code: cab.code || cab.unitTypeId, id: cab.id,\n        hand, doorSide, voidSide,\n        placement: cab.cornerUnit.placement || 'auto',\n        rot: Math.round(cab.rotationDeg || 0),\n        leftPanelOn:  !!(ep.left  && ep.left.active),\n        rightPanelOn: !!(ep.right && ep.right.active),\n        voidPanelOn:  !!(ep[voidSide] && ep[voidSide].active),\n        doorPanelOn:  !!(ep[doorSide] && ep[doorSide].active),\n        leftFiller:   !!(fil.left  && fil.left.active),\n        rightFiller:  !!(fil.right && fil.right.active),\n        backPanel:    !!(cab.backPanel && cab.backPanel.active),\n        fullSizeEndPanel: !!cab.useFullSizeEndPanel,\n        backEndPost:  !!(cab.backEndPost && cab.backEndPost.active),\n        separateEndPanelItemsNearby: near.length,\n        domStrips: domInfo\n      });\n    }\n    console.log('[btkPanelWhy] done - the returned object below has the same data.');\n    return out;\n  };\n  console.log('[BTK build] planner - btkPanelWhy() ready');\n  // During a drag the real `cabinets` array isn't mutated until drop (the drag\n  // moves DOM elements + a temp copy). This holds the LIVE per-move positions so\n  // currentDesign() - and therefore the live-session push - reflects the drag in\n  // progress instead of only the dropped position. Null when not dragging.\n  let liveDragCabs = null;\n  // Sinks + hobs placed on the worktops. Same x,y/rotation model as\n  // cabinets so the existing drag mechanic can move them. The Phase-1\n  // catalogue is a hard-coded stub; future phases swap in metaobjects.\n  let worktopItems = [];\n  // Sinks in the basket no unit has (refreshSpareSinks), by the sink unit each\n  // is offered to, and the Add Other Items lines among them (refreshExtraSinks).\n  let spareSinkByCab = new Map();\n  let extraSinkLines = [];\n  let nextWorktopItemId = 1;\n  // Free-standing furniture placed on the floor (Customise \u2192 Add\n  // Furniture). { id, furnitureId, name, glbUrl, x, y, rotationDeg }.\n  let furnitureItems = [];\n  let nextFurnitureItemId = 1;\n\n  // Flythrough waypoints - ordered list of { x, y, look? } plan-mm\n  // points the 3D Play button visits when set. Empty array \u2192 fall\n  // back to auto-orbit (door entry + ring around the room interior).\n  // `look` is an optional { x, y } target the camera looks at while\n  // travelling through that waypoint; otherwise the camera looks at\n  // the next waypoint.\n  let flythroughWaypoints = [];\n  let waypointAddMode     = false;   // toggled by the \"+W\" overlay button\n  let waypointLookSetIdx  = -1;      // waypoint index waiting for a look-at click; -1 = inactive\n  let flythroughSpeed     = 1;       // 0.5 .. 2 - slider in the 3D gear popover\n\n  // Lights - standalone placed light sources. Each: { id, x, y,\n  // settings: { brightness, colour, spread } }. Position (x, y) is in\n  // plan-mm world coords. The 3D renderer decides whether to mount\n  // each light UNDER the wall cab it sits inside, or on the CEILING\n  // when there's no wall cab at that point. Persisted with the plan.\n  let lights        = [];\n  let nextLightId   = 1;\n  let lightDropMode = false;  // toggled by the Light overlay button (2D)\n  let paintMode     = false;  // Magic paint mode (declared early - rerender reads it)\n  let lightsOn      = true;   // global on/off - toggled by the 3D-view Light button\n  // Footprint sizes learned from the GLB, keyed by catalogue furnitureId,\n  // so free-space placement knows a model's size even on first drop.\n  const furnitureSizeCache = {};\n  let nextCabinetId      = 1;\n  let nextPerimeterItemId = 1;\n  let nextOpeningId      = 1;\n  let selectedItem       = null;          // { kind: 'cabinet'|'feature'|'opening', id }\n  let selectedCabinetIds = new Set();     // multi-select of cabinets\n  let endPanelLayout     = null;          // computeEndPanelLayout() result for the current plan\n  let currentStep        = 'room-setup';\n  // Stages that draw the plan WITHOUT the big overhead shapes - see the filter\n  // in the 2D render. Room Setup is where they are placed, so it keeps them;\n  // Review Order is a read-back of the finished room, so it does too.\n  const HIDE_CEILING_SHAPES_IN = new Set(['add-units', 'style-colours']);\n\n  // Global colour state - defaults for new cabinets and source for the\n  // \"Apply to all\" action in the Add Units panel. Reset on kitchen\n  // style change. Persisted in save/load.\n  //\n  // Seed from sessionStorage.btk_kitchen_context if the user has\n  // already picked a buying style elsewhere (kitchen units listing\n  // page, style detail page) so the planner opens on the SAME\n  // style/colour combo they've been browsing with.\n  let kitchenStyleId           = 'moderna-on-trend-colours';\n  let globalDoorColourHandle    = null;\n  let globalCarcaseColourHandle = null;\n  // Style Setup's chosen buying/planning styles (up to 3). Each entry =\n  // { styleId, doorHandle, carcaseHandle }. buyingStyles[0] is the active /\n  // initial style and mirrors the three globals above. Persisted with the plan\n  // (currentDesign/applyState); becomes the palette the Customise popups draw\n  // from later (Phase C - \"Style Setup feeds Customise\").\n  let buyingStyles = [];\n  // Style Setup's other multi-option stages (up to 3 each, [0] = applied):\n  // handles {designId,designName,finishHandle,finishName}; worktops {handle,name};\n  // rails {handle,name} (True-Handleless profile). Persisted with the plan; the\n  // alternates are saved \"options\" (like buyingStyles' alternates) - only [0] is\n  // applied to the plan globally.\n  let buyingHandles  = [];\n  let buyingWorktops = [];\n  let buyingRails    = [];\n  // Wall/floor always have a default colour, so \"ticked\" tracks whether the\n  // user has actively PICKED one in Style Setup (default or not), not whether\n  // it differs from the default.\n  let wallChosen  = false;\n  let floorChosen = false;\n  try {\n    const _seed = JSON.parse(sessionStorage.getItem('btk_kitchen_context') || 'null');\n    if (_seed && _seed.style)  kitchenStyleId           = _seed.style;\n    if (_seed && _seed.colour) globalDoorColourHandle    = _seed.colour;\n    if (_seed && _seed.carcase) globalCarcaseColourHandle = _seed.carcase;\n  } catch (_) {}\n  // Cross-tab restore: sessionStorage is per-tab, so a fresh tab has no\n  // buying-style context. If it's empty, rehydrate from the cart (shared\n  // across tabs) - active from kitchen_style, alternates from\n  // kitchen_comparison_styles - then fire the event so the Add-Units bar paints.\n  (function restoreBuyingStylesFromCart() {\n    let hasCtx = false, hasAlts = false;\n    try { hasCtx = !!sessionStorage.getItem('btk_kitchen_context'); hasAlts = !!sessionStorage.getItem('btk_comparison_styles'); } catch (_) { return; }\n    if (hasCtx && hasAlts) return;\n    fetch('/cart.js').then(r => r.json()).then(cart => {\n      const a = cart.attributes || {};\n      try {\n        if (!sessionStorage.getItem('btk_kitchen_context') && a.kitchen_style && a.kitchen_colour) {\n          sessionStorage.setItem('btk_kitchen_context', JSON.stringify(window.BTKCtxClean.ctx({\n            style: a.kitchen_style, styleName: a.kitchen_style_name || '',\n            colour: a.kitchen_colour, colourName: '', carcase: a.kitchen_carcase_colour || 'white'\n          })));\n        }\n        if (!sessionStorage.getItem('btk_comparison_styles') && a.kitchen_comparison_styles) {\n          sessionStorage.setItem('btk_comparison_styles', window.BTKCtxClean.alts(a.kitchen_comparison_styles));\n        }\n      } catch (_) {}\n      try { document.dispatchEvent(new CustomEvent('btk:style-changed', {})); } catch (_) {}\n    }).catch(() => {});\n  })();\n  let wallColourHandle  = DEFAULT_WALL_COLOUR_HANDLE;\n  // FEATURE WALLS (Arden, 2026-10-13): walls of the room, by number (the room\n  // outline edge), given their own paint or a pattern. { [wallNo]: { colourHandle }\n  // | { patternId } }. Saved with the plan; drawn by the 3D view per wall.\n  let featureWalls = {};\n  const wallPatternList = (Catalogue.getWallPatterns && Catalogue.getWallPatterns()) || [];\n  function resolveFeatureWalls() {\n    const out = {};\n    const surfaces = fwSurfaces();\n    for (const [k, v] of Object.entries(featureWalls || {})) {\n      if (!v) continue;\n      const w = surfaces.find(x => x.key === String(k));\n      if (!w) continue;   // its wall or pillar has gone\n      const ends = w.featureId != null\n        ? { itemId: w.featureId, dir: w.dir }\n        : { wallIndex: w.wallIndex, fromMm: w.fromMm, toMm: w.toMm };\n      if (v.patternId) {\n        const p = wallPatternList.find(x => x.id === v.patternId);\n        if (p) out[k] = { textureUrl: p.textureUrl, textureMm: p.textureMm, ...ends };\n      } else if (v.colourHandle) {\n        out[k] = { hex: getWallColour(v.colourHandle).hex, ...ends };\n      }\n    }\n    return out;\n  }\n  function applyFeatureWallsTo3D(h = handle3D) {\n    if (h && h.setFeatureWalls) h.setFeatureWalls(resolveFeatureWalls());\n  }\n\n  // Floor colours - from the 3d_planner_floor_colours metaobject when\n  // present (each carries a texture image), else the built-in palette.\n  // Shape used by the picker + 3D: { handle, name, category, textureUrl,\n  // swatchUrl, hex }. The hex is a neutral fallback for non-3D use.\n  const _catalogueFloors = (Catalogue.getFloorColours && Catalogue.getFloorColours()) || [];\n  const floorColourList = _catalogueFloors.length\n    ? _catalogueFloors.map(f => ({\n        handle:     f.id,\n        name:       f.name,\n        label:      f.name,\n        category:   f.category || 'wooden',\n        textureUrl: f.textureUrl || null,\n        // Real-world mm the floor image covers (Floor Colours metaobject); null = 1000.\n        textureMm:  Number(f.textureMm) > 0 ? Number(f.textureMm) : null,\n        swatchUrl:  f.swatchUrl || f.textureUrl || null,\n        hex:        f.hex || ((f.category === 'tiles') ? '#bdbdb8' : '#caa472')\n      }))\n    : FLOOR_COLOURS.map(f => ({ ...f, name: f.label, category: f.category || 'wooden' }));\n  // Default the planner floor to Oak Flooring when that swatch exists in\n  // the metaobject list (else the first floor), pre-rotated 90\u00B0 and\n  // slightly zoomed in. Computed once so loadState can fall back to the\n  // same default for blank / pre-floor saves.\n  const _defaultFloor =\n    floorColourList.find(f => /oak\\s*floor/i.test(f.name || '')) ||\n    floorColourList.find(f => /\\boak\\b/i.test(f.name || '')) ||\n    floorColourList[0] || null;\n  const DEFAULT_FLOOR_HANDLE = _defaultFloor ? _defaultFloor.handle : DEFAULT_FLOOR_COLOUR_HANDLE;\n  const DEFAULT_FLOOR_SETTINGS = _defaultFloor\n    ? { [_defaultFloor.handle]: { rotationDeg: 90, zoom: 1.25 } }\n    : {};\n  let floorColourHandle = DEFAULT_FLOOR_HANDLE;\n  // Per-floor texture transform, keyed by floor handle:\n  // { [handle]: { rotationDeg: 0|90|180|270, zoom: number } }. Persisted\n  // in save/load so each texture remembers its rotation + size.\n  let floorSettings = { ...DEFAULT_FLOOR_SETTINGS };\n  function getFloorSettings(handle) {\n    const s = floorSettings[handle] || {};\n    return { rotationDeg: s.rotationDeg || 0, zoom: s.zoom || 1 };\n  }\n\n  // Resolve a floor handle to its record (metaobject list, then the\n  // built-in palette as a last resort).\n  function resolveFloorColour(handle) {\n    return floorColourList.find(f => f.handle === handle) || floorColourList[0] || getFloorColour(handle);\n  }\n  // Apply the current floor to the 3D view: a texture (with its rotation\n  // + zoom) if the chosen floor has one, otherwise its flat colour.\n  function applyFloorTo3D(h = handle3D) {\n    if (!h) return;\n    const fc = resolveFloorColour(floorColourHandle);\n    if (fc && fc.textureUrl && h.setFloorTexture) {\n      h.setFloorTexture(fc.textureUrl, { ...getFloorSettings(floorColourHandle), tileMm: fc.textureMm });\n    } else if (h.setFloorColour) {\n      h.setFloorColour((fc && fc.hex) || getFloorColour(floorColourHandle).hex);\n    }\n  }\n  // Rotate the floor texture by 90\u00B0 (cycles 0\u219290\u2192180\u2192270) and apply.\n  function handleRotateFloor(handle) {\n    const target = handle || floorColourHandle;\n    const cur = getFloorSettings(target);\n    floorSettings = { ...floorSettings, [target]: { ...cur, rotationDeg: (cur.rotationDeg + 90) % 360 } };\n    floorColourHandle = target;\n    applyFloorTo3D();\n    roomShapeHandle?.refresh();\n  }\n  // Set the floor texture zoom (size multiplier) and apply.\n  function handleSetFloorZoom(handle, zoom) {\n    const target = handle || floorColourHandle;\n    const z = Math.max(0.25, Math.min(4, Number(zoom) || 1));\n    const cur = getFloorSettings(target);\n    floorSettings = { ...floorSettings, [target]: { ...cur, zoom: z } };\n    floorColourHandle = target;\n    applyFloorTo3D();\n  }\n\n  // Worktop colour - a global default plus per-worktop overrides\n  // keyed by the engine's stable spatial-hash worktopId. Selecting a\n  // worktop and picking a swatch sets just that section; \"Apply to\n  // all\" sets the global and clears the overrides. Persisted with\n  // save/load.\n  const DEFAULT_WORKTOP_COLOUR = '#cfc7b8';\n  let worktopColourHex = DEFAULT_WORKTOP_COLOUR;\n  let worktopColours   = {};   // { worktopId: hex }\n  // Per-worktop corner radius overrides - { worktopId: { tl, tr, bl,\n  // br } }, each 0 / 70 / 300. Chosen from the worktop selection\n  // panel; the engine rounds the slab's world-bbox corners. Persisted.\n  let worktopCornerRadii = {}; // { worktopId: { tl: 0|70|300, ... } }\n  // Worktop MATERIAL selection - mirrors the colour pair: one global\n  // default material (a Catalogue worktop-material product handle) plus\n  // per-section overrides. null = no material chosen (worktop renders as\n  // the plain placeholder slab + isn't charged). Persisted with save/load.\n  let worktopMaterialHandle     = null;   // global default (product handle)\n  // \"I am buying my worktops elsewhere\" (the Worktops popup): the plan still\n  // draws its worktops, but nothing is charged for them.\n  let worktopsNotPriced         = false;\n  // A board worktop's matching upstand / splashback, as chosen in the Worktops\n  // popup: the product each is bought as ({ variantId, priceCents,\n  // compareAtCents, lengthMm, widthMm, name, variantTitle, url }), or null.\n  // Kept with the plan so a saved plan prices the same without asking Shopify\n  // again; what the plan DRAWS is roomConfig.splashbacks, as ever.\n  let worktopParts              = { upstand: null, splashback: null, edging: null };\n  let worktopMaterialsBySection = {};     // { worktopId: handle }\n  // BESPOKE worktop job options (made-to-measure quartz / porcelain). One set\n  // per plan, persisted with save/load. See normaliseBespokeOptions.\n  let worktopBespoke = normaliseBespokeOptions(null);\n  // The bespoke worktop waiting on a price from our team, as the last\n  // computeWorktopCharges() found it, or null (see buildQuote: basket.priceRequest).\n  let lastWorktopPriceRequest = null;\n\n  // Feature settings (Plinth / Cornice / Pelmet). Placeholders for now:\n  // selection is held in state and persisted with save/load, but does\n  // not yet drive 2D/3D rendering or per-feature colour overrides.\n  // plinthPosition: where a SKIRTING plinth sits, whole plan - 'proud' (its back\n  // on the door front) or 'flush' (its front on the door front) (Arden, 2026-10-27).\n  const DEFAULT_FEATURE_STYLES = { plinth: 'standard', cornice: 'modern', pelmet: 'modern', plinthPosition: 'proud', plinthHeightMm: PLINTH_STD_MM };\n  let featureStyles = { ...DEFAULT_FEATURE_STYLES };\n\n  // True Handleless RAIL finish - ONE whole-kitchen choice (the aluminium\n  // profile finish: Brushed Silver / Copper / Bronze / \u2026 ). Applies to every\n  // rail profile everywhere; only relevant when the active style's\n  // handle_system is 'true-rail'. Default = the first catalogue finish; null\n  // until the rail_finish palette is authored. Persisted with save/load.\n  const _railFinishes = (Catalogue.getRailFinishes && Catalogue.getRailFinishes()) || [];\n  const DEFAULT_RAIL_FINISH_HANDLE = _railFinishes[0]?.handle || null;\n  let railFinishHandle = DEFAULT_RAIL_FINISH_HANDLE;\n  function handleSetRailFinish(handle) {\n    if (!handle || handle === railFinishHandle) return;\n    railFinishHandle = handle;\n    // Re-render so the 3D rail profiles pick up the new finish material.\n    // (Rail geometry lands in a later step; the selection persists now.)\n    rerender();\n  }\n\n  // Per-trim-segment colour overrides. Keys are stable spatial-hash\n  // segment IDs (see btk-kitchen-planner-engine-trim.js); values are\n  // master-door-colour handles. Missing entries mean \"use the\n  // default global door colour\", so removing an override is just a\n  // delete. Persisted with save/load.\n  let segmentColours = {};\n\n  // Handle hardware - a global default { designId, finishHandle,\n  // sizeMm } that every cab inherits, plus a per-cab override on\n  // cab.handle. null on any field means \"inherit the global\". The\n  // handle GLB renders on each door/drawer front per the opening's\n  // `handle` block in the cutout schema. Persisted with save/load.\n  //\n  // Handles are chosen per POSITION GROUP - Base doors, Wall doors, Tall\n  // doors and Drawers can each carry a different design / finish / size /\n  // orientation. A cab resolves to one group via Catalogue.handleGroupKey.\n  // (Was a single `globalHandle`; migrated on load - see loadStateInto.)\n  const HANDLE_GROUP_KEYS = ['base', 'wall', 'tall', 'drawers', 'pan-drawers'];\n  const emptyHandleGroup = () => ({ designId: null, finishHandle: null, sizeMm: null, orientation: null });\n  const emptyHandleGroups = () => HANDLE_GROUP_KEYS.reduce((o, k) => { o[k] = emptyHandleGroup(); return o; }, {});\n  let handleGroups = emptyHandleGroups();\n\n  // ---- Derived (rebuilt per render) ----\n  let room     = buildRoomPolygon(roomConfig);\n  let baseRoom = buildBaseRoom(roomConfig);\n\n  // ---- UI handles ----\n  let roomShapeHandle      = { refresh:   () => {} };\n  let doorsWindowsHandle   = { refresh:   () => {} };\n  // ---- Room Shape snapshot (Cancel) --------------------------------\n  // Room Shape edits commit LIVE, and three of their effects cannot be\n  // undone by putting the shape back: every cabinet is re-clamped\n  // against the new outline, wall openings that no longer fit are\n  // dropped, and switching shape wipes perimeterItems + wallOpenings\n  // outright. The planner has no undo stack, so the popup snapshots the\n  // whole of the state it can touch on OPEN, and Cancel restores it.\n  //\n  // Confirm / backdrop / Esc deliberately KEEP the changes: they have\n  // been live the whole time the popup was open, so treating a stray\n  // click outside as \"discard my work\" would be a worse failure than\n  // the one this fixes. Reverting has to be a deliberate press.\n  // Room LOCK. Fixes the room's size and features, and stops doors /\n  // windows being dragged - both in the Room Shape preview and on the\n  // planning canvas, where they were easy to catch by accident. Lives on\n  // roomConfig so it saves and loads with the plan.\n  const isRoomLocked = () => !!(roomConfig && roomConfig.locked);\n\n  function handleToggleRoomLock(next) {\n    roomConfig = { ...roomConfig, locked: !!next };\n    rerender();\n  }\n\n  // Reset the ROOM only - shape, size, corner features, doors and\n  // windows. Units are kept; the re-clamp below moves any that no longer\n  // fit. (handleClear, by contrast, wipes the whole plan.)\n  function handleResetRoom() {\n    roomConfig = freshRoomConfig();\n    const fresh = buildRoomPolygon(roomConfig);\n    cabinets = cabinets.map(c => {\n      const others = cabinets.filter(o => o.id !== c.id);\n      const { x, y } = snapAndClamp(c, c.x, c.y, fresh, others, [], []);\n      return { ...c, x, y };\n    });\n    autoDetectBackPanels();\n    rerender();\n  }\n  // Use Existing Room (Room Shape popup): the room from one of the customer's\n  // saved plans - outline, corners, features, doors and windows - becomes this\n  // plan's room. Units stay, kept inside it, as on a reset (Arden, 2026-10-07).\n  function handleUseExistingRoom(rc) {\n    if (!rc) return;\n    roomConfig = JSON.parse(JSON.stringify(rc));\n    const fresh = buildRoomPolygon(roomConfig);\n    cabinets = cabinets.map(c => {\n      const others = cabinets.filter(o => o.id !== c.id);\n      const { x, y } = snapAndClamp(c, c.x, c.y, fresh, others, [], []);\n      return { ...c, x, y };\n    });\n    autoDetectBackPanels();\n    rerender();\n  }\n\n  let roomShapeSnapshot = null;\n  // structuredClone is exact and throws on anything it can't copy; the\n  // JSON fallback covers older engines. Both round-trip a cabinet -\n  // dims, flags and nested plain objects (endPanels, fillers,\n  // cutoutSchema, and catalogue entries like cab.hob).\n  function deepCopyState(v) {\n    try { return structuredClone(v); }\n    catch (_) { return JSON.parse(JSON.stringify(v)); }\n  }\n  function snapshotRoomShape() {\n    try {\n      roomShapeSnapshot = {\n        roomConfig: deepCopyState(roomConfig),\n        cabinets:   deepCopyState(cabinets)\n      };\n    } catch (err) {\n      // Never block opening the popup over a snapshot failure - Cancel\n      // just becomes a no-op, which is the behaviour we had before.\n      console.warn('[BTK Kitchen Planner] room-shape snapshot failed:', err);\n      roomShapeSnapshot = null;\n    }\n  }\n  function restoreRoomShape() {\n    if (!roomShapeSnapshot) return;\n    roomConfig = roomShapeSnapshot.roomConfig;\n    cabinets   = roomShapeSnapshot.cabinets;\n    roomShapeSnapshot = null;\n    rerender();\n  }\n\n  let cabinetsHandle       = { refresh:   () => {} };\n  let styleColoursHandle   = { refresh:   () => {} };\n  let worktopsPopupHandle  = null;   // the Customise Worktops popup (ui-worktops)\n  let finishesHandle       = { refresh:   () => {} };\n  let selectionPanelHandle = { show: () => {}, hide: () => {}, refresh: () => {} };\n  let basketDrawerHandle   = { open: () => {}, close: () => {}, refresh: () => {} };\n  let designControlsHandle = { setStatus: () => {} };\n  let pricingHandle        = { update:    () => {} };\n  let stepperHandle        = { setStep:   () => {} };\n  // Upgrade add-ons (soft-close etc.) live in the Shopify cart, applied inside\n  // the basket. The embedded advanced cart pushes their running total here so\n  // the header price includes them and matches the basket footer.\n  let plannerAddonTotalGbp = 0;\n\n  // Viewport mode is decoupled from the stepper: 2D plan or 3D viewport.\n  // Switched by the toggle button overlaid on #btk-kp-main. Default 2D.\n  let viewMode = '2d';   // '2d' | '3d'\n  // What a 3D click picks, and the stage that works on it. Customise opens the\n  // properties panel only for its own kinds; everything else keeps its menu.\n  const PICK_STAGE = {\n    'cabinet':            'add-units',\n    'end-panel':          'add-units',\n    'worktop-item':       'add-units',\n    'sink-set':           'add-units',\n    'worktop':            'style-colours',\n    'splashback-section': 'style-colours',\n    'trim-segment':       'style-colours'\n  };\n  // Furniture opens its own menu on either stage, so it has no PICK_STAGE of its own.\n  const CUSTOMISE_PICKS = new Set(\n    Object.keys(PICK_STAGE).filter(k => PICK_STAGE[k] === 'style-colours').concat('furniture'));\n  let viewBtnMode = '2d';     // which toggle BUTTON is lit\n  // Update EVERY view toggle (the main viewport one AND the basket mini-view\n  // one) so both stay in sync whichever the user clicks.\n  function syncViewToggleButtons() {\n    root.querySelectorAll('[data-btk-kp-view-toggle] [data-btk-kp-view-mode]').forEach(b => {\n      const isActive = b.dataset.btkKpViewMode === viewBtnMode;\n      b.classList.toggle('is-active', isActive);\n      b.setAttribute('aria-pressed', isActive ? 'true' : 'false');\n    });\n  }\n  root.classList.add('btk-kp-view-2d');\n\n  // 2D layer visibility - toggled from the cog overlay in 2D mode.\n  // Applied as classes on #btk-kp-main so a CSS rule can hide each\n  // group (see .btk-kp-canvas.is-hide-* in base.css).\n  let viewLayers = { floor: true, wall: true, worktops: true };\n  // \"Hide units\" tick-box (Room Setup only) - clears the placed units off the\n  // 2D plan so the room shape is easy to see while building it. Applied as a\n  // class on #btk-kp-main; only takes effect while on the Room Setup stage.\n  // Default ON (the shell checkbox is `checked`) so Room Setup shows a clean\n  // room shell; the user can untick to see their units.\n  let hideUnits = true;\n  // Auto-add end panels + fillers to exposed ends (the default). When the user\n  // turns this OFF (View options cog), autoDetectEndPanels becomes a no-op so\n  // they add/remove end panels + fillers manually via the selection panel.\n  // Persisted with the plan.\n  let autoEndPanels = true;\n  // One-time \"what is the planning style\" intro, shown on Room Setup when the\n  // plan has no style set up yet (or only the website-passed kitchen style).\n  // Persisted in localStorage so it shows once, ever.\n  let styleIntroDone = false;\n  try { styleIntroDone = !!localStorage.getItem('btk_kp_style_intro_seen_v2'); } catch (e) {}\n  // Nudge: open the Room Shape popup once when Room Setup loads with the default\n  // (untouched) room, to steer the user to set their room shape first.\n  //\n  // Pre-armed when the URL opens an EXISTING plan (?plan=...): that plan already\n  // has a room, so the nudge is never wanted there. It has to be suppressed HERE,\n  // at boot, rather than after the plan loads - the stepper's first onChange runs\n  // while the plan is still loading, so a later flag arrives to find the popup\n  // already open (it showed behind the preloader, then sat there once Add Units\n  // came up). Read before the deep-link handler scrubs the query string.\n  const _bootPlanParam = (() => {\n    try { return (new URLSearchParams(window.location.search).get('plan') || '').trim(); }\n    catch (e) { return ''; }\n  })();\n  // Remembered per browser, like the Style Setup intro: the room-shape steer\n  // is for someone planning their FIRST room, so it should not greet a\n  // returning customer every time they open the planner.\n  const ROOM_SHAPE_PROMPT_KEY = 'btk_kp_room_shape_prompted_v1';\n  let roomShapePrompted = !!_bootPlanParam;\n  try { if (localStorage.getItem(ROOM_SHAPE_PROMPT_KEY)) roomShapePrompted = true; } catch (e) {}\n  // Same arrival, same reason: an opened plan should not flash the Welcome page\n  // on its way in. The deep-link handler calls hideWelcome() too, but that only\n  // runs once the plan has loaded - by then the flash has already happened.\n  // ?open= from the introduction page (below) skips the Welcome page too.\n  if ((_bootPlanParam || /[?&]open=(new|saved|resume)(&|$)/.test(window.location.search)) && root) {\n    const _bootWelcome = root.querySelector('[data-btk-kp-welcome]');\n    if (_bootWelcome) _bootWelcome.hidden = true;\n  }\n  let dimsHandle           = null;\n  let clearanceHandle      = null;\n  let clearanceCtx         = null;   // { gridEl, pxPerMm }\n  let worktops2dHandle     = null;   // hoisted so drag handlers can live-refresh the outlines\n  let worktops2dCtx        = null;   // { gridEl, pxPerMm }\n  let renderHandles        = [];\n\n  // ---- 2D canvas view (scroll-wheel zoom) ----\n  // The grid is rebuilt on every state change, so the zoom/pan state\n  // lives here and is reapplied to the fresh grid element by\n  // rerender(). zoom 1 = the fitted view; pan is a screen-px offset of\n  // the grid centre, used to anchor zoom at the cursor.\n  // The design's content at the last successful transfer. Equal to the current\n  // one means the saved plan and basket are already up to date, whatever the\n  // view has been doing since.\n  //\n  // The signature is undoSnapshot(), which the undo stack already uses for\n  // exactly this question - pushUndoSnapshot compares it to decide \"nothing\n  // actually changed\". currentDesign() carries no timestamp and no thumbnail,\n  // which is what makes it stable between calls; the thumbnail lives in\n  // currentDesignWithThumb().\n  let transferredSignature = null;\n  // Start Planning's background save (saveJourneyPlanInBackground). Declared\n  // up here because autosave and the basket, which wait on it, are too.\n  let journeySaveInFlight = null;\n  const view2d = { zoom: 1, panX: 0, panY: 0 };\n  // The main plan's renderCabinets handle, and the badges' on-screen scale for\n  // a plan scale at the current zoom - the same sum as --btk-kp-chrome below.\n  // When a zoom settles the item numbers are laid out again at that size\n  // (relayoutBadges), so they sit by their own pieces at every zoom\n  // (Arden, 2026-10-21).\n  let mainCabsHandle = null;\n  let _badgeLayoutZoom = 1;\n  let _badgeRelayoutTimer = null;\n  function badgeScaleFor(pxPerMm) {\n    const fit = Math.max(0.5, Math.min(1, (pxPerMm || 0.16) / 0.16));\n    const z = view2d.zoom || 1;\n    return Math.min(1, fit * z) / z;\n  }\n  function relayoutBadgesSoon() {   // (also after a line is excluded - see refreshHiddenPlanNumbers)\n    clearTimeout(_badgeRelayoutTimer);\n    _badgeRelayoutTimer = setTimeout(() => {\n      try {\n        if (!mainCabsHandle || !mainCabsHandle.relayoutBadges || !lastGrid) return;\n        mainCabsHandle.relayoutBadges(badgeScaleFor(lastGrid.pxPerMm));\n        // The new badges carry no selection ring yet.\n        selectedCabinetIds.forEach(id => root.querySelectorAll(`.btk-kp-cabinet-number[data-cabinet-id=\"${id}\"]`)\n          .forEach(el => el.classList.add('btk-kp-cabinet-number--active')));\n        if (selectedItem?.kind === 'end-panel') root.querySelector(\n          `.btk-kp-cabinet-number--endpanel[data-ep-face=\"${selectedItem.cabinetId}:${selectedItem.side}\"]`)\n          ?.classList.add('btk-kp-cabinet-number--active');\n        if (selectedItem?.kind === 'rail') root.querySelector(\n          `.btk-kp-cabinet-number--rail[data-rail-face=\"${selectedItem.cabinetId}:${selectedItem.side}\"]`)\n          ?.classList.add('btk-kp-cabinet-number--active');\n        if (selectedItem?.kind === 'cpost') root.querySelector(\n          `.btk-kp-cabinet-number[data-cpost-face=\"${selectedItem.cabinetId}:${selectedItem.side}:${selectedItem.pos}\"]`)\n          ?.classList.add('btk-kp-cabinet-number--active');\n      } catch (e) { console.error('[BTK badges]', e); }\n    }, 140);\n  }\n  const ZOOM_MIN = 1, ZOOM_MAX = 6;\n  let currentGridEl = null;\n  // Last rendered grid handle (el + pxPerMm). Needed by overlays drawn outside\n  // rerender, like the opening panel's wall-span highlight.\n  let lastGrid = null;\n\n  function applyView2dTransform() {\n    if (!currentGridEl) return;\n    if (window.BTK_PLANNER_V11) {\n      // v1.1: real layout at the zoom level instead of enlarging a finished\n      // picture. CSS zoom also scales this element's own translate, so the\n      // pan is divided back to screen pixels.\n      const _vz = view2d.zoom || 1;\n      currentGridEl.style.zoom = String(_vz);\n      currentGridEl.style.transform =\n        `translate(calc(-50% + ${view2d.panX / _vz}px), calc(-50% + ${view2d.panY / _vz}px))`;\n    } else {\n    currentGridEl.style.transform =\n      `translate(calc(-50% + ${view2d.panX}px), calc(-50% + ${view2d.panY}px)) ` +\n      `scale(${view2d.zoom})`;\n    }\n    // Counter-scale the grid's background-dot radius so the dots stay\n    // ~1px on screen at every zoom. Without this, the radial-gradient\n    // disc (a CSS-space value) grows with the wrapper's scale \u2192 at\n    // zoom 6 a 1px-radius disc becomes a 12px blob. 0.5px target \u00D7 a\n    // small floor so the dot doesn't disappear at high zoom (browsers\n    // get inconsistent below ~0.2px on the gradient stop).\n    const TARGET_SCREEN_PX = 0.5;\n    const dotPx = window.BTK_PLANNER_V11 ? TARGET_SCREEN_PX / view2d.zoom : Math.max(0.2, TARGET_SCREEN_PX / view2d.zoom);\n    currentGridEl.style.setProperty('--btk-kp-grid-dot-px', `${dotPx}px`);\n    // Badges, labels and outline strokes are chrome, not plan: they must not\n    // swell with the zoom like the units do. Some were label-scaled, some a\n    // fixed 12px, and the transform then multiplied them all, so zoomed in\n    // they came out in clashing sizes over each other (Arden, 2026-10-13).\n    // --btk-kp-chrome replaces the plan-fit label scale while zoomed: at the\n    // fitted view it IS the label scale; zooming in, the on-screen size grows\n    // to full size and then holds. It never exceeds the label scale in plan\n    // space, so nothing overlaps that didn't already at the fitted view.\n    // --btk-kp-line keeps 1px strokes 1px on screen (SVG strokes and\n    // box-shadows only - Chrome rounds a CSS border up to 1px before the\n    // transform, so borders can't be thinned this way).\n    const fit = lastGrid && lastGrid.pxPerMm\n      ? Math.max(0.5, Math.min(1, lastGrid.pxPerMm / 0.16)) : 1;\n    const z = view2d.zoom || 1;\n    currentGridEl.style.setProperty('--btk-kp-chrome', String(Math.min(1, fit * z) / z));\n    currentGridEl.style.setProperty('--btk-kp-line', String(1 / z));\n    // The badge size changed with the zoom: re-place the numbers once it settles.\n    if (z !== _badgeLayoutZoom) { _badgeLayoutZoom = z; relayoutBadgesSoon(); }\n  }\n\n  // Zoom + pan the 2D plan so one unit fills/centres the view - the 2D\n  // counterpart of handle3D.focusOnCabinet, used when a basket line is\n  // clicked while the (mini or main) view is in 2D. Centring is done by\n  // measuring the unit's on-screen rect after applying the zoom, so it's\n  // immune to the grid's rotation/scale maths (panX/panY are screen px).\n  let embedPrev2dView = null;\n  function focusUnitIn2D(cabId, targetZoom) {\n    if (!currentGridEl) return;\n    if (!embedPrev2dView) {\n      embedPrev2dView = { zoom: view2d.zoom, panX: view2d.panX, panY: view2d.panY };\n    }\n    view2d.zoom = Math.max(ZOOM_MIN, Math.min(ZOOM_MAX, targetZoom || 2.2));\n    applyView2dTransform();\n    requestAnimationFrame(() => {\n      if (!currentGridEl) return;\n      const esc = (window.CSS && CSS.escape) ? CSS.escape(String(cabId)) : String(cabId);\n      const el   = currentGridEl.querySelector(`[data-cabinet-id=\"${esc}\"]`);\n      // The visible viewport in BOTH the mini basket box and the full canvas.\n      const host = document.getElementById('btk-kp-main');\n      if (!el || !host) return;\n      const r  = el.getBoundingClientRect();\n      const cr = host.getBoundingClientRect();\n      view2d.panX += (cr.left + cr.width  / 2) - (r.left + r.width  / 2);\n      view2d.panY += (cr.top  + cr.height / 2) - (r.top  + r.height / 2);\n      applyView2dTransform();\n    });\n  }\n  // Glide the 2D plan back to the pre-focus zoom/pan (mirror of resetView).\n  function resetView2D() {\n    if (!embedPrev2dView) return;\n    view2d.zoom = embedPrev2dView.zoom;\n    view2d.panX = embedPrev2dView.panX;\n    view2d.panY = embedPrev2dView.panY;\n    embedPrev2dView = null;\n    applyView2dTransform();\n  }\n\n  // Live-refresh the dimension stack without a full canvas re-render.\n  // Drag handlers pass the moving item's live array so the lines track\n  // the drag (same pattern as grid.updatePerimeterItems / updateOpenings).\n  // refreshDims is hit on EVERY mousemove during a drag (the live\n  // cabinets array is projected onto every wall + per-cab end-panel\n  // synth projections for L-shape / diag corner units). At 12+ cabs\n  // each call costs a few ms which backs up the mousemove queue \u2014\n  // the browser then coalesces mousemoves, the cab visually lags,\n  // and computeAutoRotation can miss the \"just inside the wall\"\n  // window because the cab skips through it in one big jump.\n  //\n  // Throttle via requestAnimationFrame so we run AT MOST once per\n  // paint. The latest call's overrides win (drag only ever cares\n  // about the most recent position). Same handle.update() is also\n  // called outside of drag (cab spawn / delete / settle); those\n  // paths get the rAF treatment too - sub-frame delay there is\n  // imperceptible.\n  let _refreshDimsRAF = null;\n  let _refreshDimsLastOverrides = null;\n  function refreshDims(overrides = {}) {\n    if (!dimsHandle) return;\n    _refreshDimsLastOverrides = overrides;\n    if (_refreshDimsRAF !== null) return;\n    _refreshDimsRAF = requestAnimationFrame(() => {\n      _refreshDimsRAF = null;\n      const ov = _refreshDimsLastOverrides || {};\n      _refreshDimsLastOverrides = null;\n      if (!dimsHandle) return;\n      dimsHandle.update({\n        wallOpenings:   ov.wallOpenings   || roomConfig.wallOpenings   || [],\n        perimeterItems: ov.perimeterItems || roomConfig.perimeterItems || [],\n        cabinets:       ov.cabinets       || cabinets,\n        // Hide the per-unit dim tiers when units are hidden on Room Setup.\n        hideUnits:      hideUnits && currentStep === 'room-setup',\n        wallSpans:      (wi) => wallDimSpans(wi, ov)\n      });\n    });\n  }\n\n  // Clearance zones + worktop overlays are the HEAVY part of a drag frame - they\n  // were re-rendered on every raw pointermove (only dims was throttled). Coalesce\n  // them to at most once per animation frame; the drop's full rerender is\n  // authoritative, so a frame of lag mid-drag is imperceptible.\n  let _dragHeavyRAF = null, _dragHeavyArgs = null;\n  // Live door / window warning WHILE dragging (Arden, 2026-09-25). The full\n  // warnings pass belongs to rerender, which is the commit point, so it only\n  // ran on release; the opening rule alone is cheap enough to run per frame.\n  // Every opening is set or cleared each pass, so backing out of an approach\n  // zone clears it again. rerender's applyWarnings takes over on drop.\n  function refreshOpeningWarnings(liveCabs) {\n    const ops = (roomConfig && roomConfig.wallOpenings) || [];\n    if (!ops.length) return;\n    const flagged = new Set();\n    for (const w of computeOpeningWarnings({ cabinets: liveCabs, room, wallOpenings: ops })) {\n      for (const id of (w.itemIds || [])) flagged.add(id);\n    }\n    for (const op of ops) {\n      const el = root.querySelector(`[data-opening-id=\"${op.id}\"]`);\n      if (el) el.classList.toggle('btk-kp-warn', flagged.has(op.id));\n    }\n  }\n\n  function scheduleDragHeavy(liveCabs, movedId) {\n    _dragHeavyArgs = { liveCabs, movedId };\n    if (_dragHeavyRAF !== null) return;\n    _dragHeavyRAF = requestAnimationFrame(() => {\n      _dragHeavyRAF = null;\n      const a = _dragHeavyArgs; _dragHeavyArgs = null;\n      if (!a) return;\n      try { refreshClearance(a.liveCabs, [a.movedId]); } catch (e) {}\n      try { refreshWorktops(a.liveCabs); } catch (e) {}\n      try { refreshOpeningWarnings(a.liveCabs); } catch (e) {}\n    });\n  }\n\n  // World-aligned bounding box that accounts for cabinet rotation.\n  // For rotation 0\u00B0 / 180\u00B0 the bbox is the same as the raw\n  // (cab.x, cab.y, +widthMm, +depthMm). For 90\u00B0 / 270\u00B0 the visual\n  // is rotated around the cabinet's centre so the bbox's width and\n  // depth SWAP (e.g. a 300\u00D710 filler rotated 90\u00B0 has a 10\u00D7300 visual\n  // bbox). Using this for collision avoids treating a rotated thin\n  // cabinet as if it still spanned its native width - which was\n  // making the radius-assembly stop ~100mm from a vertical wall\n  // because the filler's unrotated 300mm-wide bbox couldn't push\n  // through.\n  function visualBbox(cab) {\n    const w = cab.widthMm || 0;\n    const d = cab.depthMm || 0;\n    const rot = (((cab.rotationDeg || 0) % 360) + 360) % 360;\n    const cx = (cab.x || 0) + w / 2;\n    const cy = (cab.y || 0) + d / 2;\n    // Fast path for the common axis-aligned rotations.\n    if (rot === 0 || rot === 90 || rot === 180 || rot === 270) {\n      const swap = rot === 90 || rot === 270;\n      const vw = swap ? d : w;\n      const vh = swap ? w : d;\n      return {\n        x0: cx - vw / 2, y0: cy - vh / 2,\n        x1: cx + vw / 2, y1: cy + vh / 2,\n        w:  vw,           h:  vh\n      };\n    }\n    // Arbitrary rotation (e.g. radius assembly snapped flush to an\n    // angled wall) - fall back to the rotated-corner extent.\n    const th = rot * Math.PI / 180;\n    const cs = Math.cos(th), sn = Math.sin(th);\n    let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;\n    for (const [lx, ly] of [[-w/2,-d/2],[w/2,-d/2],[w/2,d/2],[-w/2,d/2]]) {\n      const wx = cx + lx * cs - ly * sn;\n      const wy = cy + lx * sn + ly * cs;\n      if (wx < minX) minX = wx; if (wx > maxX) maxX = wx;\n      if (wy < minY) minY = wy; if (wy > maxY) maxY = wy;\n    }\n    return {\n      x0: minX, y0: minY,\n      x1: maxX, y1: maxY,\n      w:  maxX - minX, h: maxY - minY\n    };\n  }\n\n  // Peninsula placement for a blank-panel corner unit (placement\n  // 'peninsulaIn'): the VOID END butts the nearest wall and the run turns\n  // 90\u00B0 out into the room. Returns { rotationDeg, wall } - the rotation to\n  // apply and the room-bbox wall to flush the unit against - or null when\n  // the unit isn't near a wall (so a mid-room drop just stays put).\n  function cornerUnitPeninsulaPlacement(cab, x, y, mode) {\n    if (!cab || !cab.cornerUnit) return null;\n    const rb = getBoundingBox(room);\n    if (!rb) return null;\n    const cx = x + (cab.widthMm || 0) / 2;\n    const cy = y + (cab.depthMm || 0) / 2;\n    // Nearest axis-aligned room-bbox wall to the unit centre.\n    const near = [\n      { wall: 'minX', g: Math.abs(cx - rb.minX), out: [-1, 0] },\n      { wall: 'maxX', g: Math.abs(rb.maxX - cx), out: [ 1, 0] },\n      { wall: 'minY', g: Math.abs(cy - rb.minY), out: [ 0, -1] },\n      { wall: 'maxY', g: Math.abs(rb.maxY - cy), out: [ 0,  1] }\n    ].sort((a, b) => a.g - b.g)[0];\n    if (near.g > ROTATION_PROXIMITY_MM) return null;   // not near a wall\n\n    // The void sits at cabinet-local -X (left hand) / +X (right hand);\n    // rotate so that direction points along the wall-outward vector.\n    const voidLocal = (cab.cornerUnit.hand === 'left') ? [-1, 0] : [1, 0];\n    const aVoid = Math.atan2(voidLocal[1], voidLocal[0]);\n    const aWall = Math.atan2(near.out[1], near.out[0]);\n    let deg = Math.round((aWall - aVoid) * 180 / Math.PI / 90) * 90;\n    deg = ((deg % 360) + 360) % 360;\n    return { rotationDeg: deg, wall: near.wall };\n  }\n\n  // Translate a cab so its wall-side bounding-box edge sits flush against\n  // the given room-bbox wall (used after a peninsula rotation).\n  function flushCabToWall(cab, x, y, wall) {\n    const rb = getBoundingBox(room);\n    if (!rb) return { x, y };\n    const vb = visualBbox({ ...cab, x, y });\n    let nx = x, ny = y;\n    if      (wall === 'minY') ny += rb.minY - vb.y0;\n    else if (wall === 'maxY') ny += rb.maxY - vb.y1;\n    else if (wall === 'minX') nx += rb.minX - vb.x0;\n    else if (wall === 'maxX') nx += rb.maxX - vb.x1;\n    return { x: nx, y: ny };\n  }\n\n  // Re-render the 2D worktop outline polygons against the supplied\n  // (live or committed) cabinet array. Without this, dragging a unit\n  // moves the cabinet div via CSS but the worktop SVG stays put,\n  // visibly trailing the unit until drop. Destroy + recreate is fine\n  // because the SVG is tiny - a handful of polygons.\n  function refreshWorktops(liveCabs) {\n    if (!worktops2dCtx) return;\n    if (worktops2dHandle) { worktops2dHandle.destroy(); worktops2dHandle = null; }\n    const arr = liveCabs || cabinets;\n    const slabs = computeWorktops({\n      cabinets:     arr,\n      roomVertices: room?.vertices || [],\n      perimeterItems: roomConfig.perimeterItems || [],\n      worktopCornerRadii\n    }).slabs;\n    // Waterfall sides draw as a green band on the edge they drop from.\n    stampWaterfalls(slabs, arr);\n    const opts = worktopRenderOpts(arr);\n    opts.waterfallBands = slabs.flatMap(s => waterfallBands(s, worktopThicknessFor(worktopMaterialForSlab(s))));\n    worktops2dHandle = renderWorktops(\n      worktops2dCtx.gridEl, slabs, worktops2dCtx.pxPerMm, opts\n    );\n  }\n\n  // Selection-ring path strings for the worktop SVG. For each radius\n  // assembly group that has a selected member, emit a path tracing\n  // JUST that group's perimeter - combined visual bbox with the\n  // quarter-circle substituted at the corner where the radius unit's\n  // curve sits. We DON'T stroke the worktop slab's polygon directly\n  // because a slab can span multiple cabinets / runs and the user\n  // wants the blue outline limited to the radius assembly itself.\n  function worktopRenderOpts(arr) {\n    const selectedGroupIds = new Set();\n    for (const id of selectedCabinetIds) {\n      const cab = arr.find(c => c.id === id);\n      if (cab && cab.groupId) selectedGroupIds.add(cab.groupId);\n    }\n    const selectionRingPaths = [];\n    for (const gid of selectedGroupIds) {\n      const members = arr.filter(c => c.groupId === gid);\n      if (!members.some(m => m.radiusUnit)) continue;\n      // Only outline the WHOLE assembly when it's ALL selected. Radius members\n      // are individually selectable now, so with just one member picked (e.g.\n      // the backing) the normal per-cabinet highlight shows THAT member - an\n      // assembly-wide ring here would wrongly light up the filler too.\n      if (!members.every(m => selectedCabinetIds.has(m.id))) continue;\n      const d = radiusGroupOutlinePath(members, worktops2dCtx ? worktops2dCtx.pxPerMm : 0);\n      if (d) selectionRingPaths.push(d);\n    }\n    return { selectionRingPaths };\n  }\n\n  // Build an SVG path string (pixel coords) for a radius assembly's\n  // outline: rectangle around the combined visual bbox of all group\n  // members, with the corner where the radius unit's curve sits\n  // replaced by a 250mm quarter-circle. The corner mapping accounts\n  // for both the radius unit's hand AND the group's current rotation\n  // (the assembly is rotated 90/180/270\u00B0 to face wall A/B/D). The\n  // outline is pushed OUTWARD by a small margin so the stroke stays\n  // fully clear of the cabinet bodies - cabinets sit above the\n  // worktop layer in z-order, so a ring drawn on the cabinet edge\n  // would be half-hidden by the cabinet body.\n  function radiusGroupOutlinePath(members, pxPerMm) {\n    if (!pxPerMm) return null;\n    const MARGIN_MM = 4;\n    let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;\n    let radius = null;\n    for (const m of members) {\n      const vb = visualBbox(m);\n      x0 = Math.min(x0, vb.x0); y0 = Math.min(y0, vb.y0);\n      x1 = Math.max(x1, vb.x1); y1 = Math.max(y1, vb.y1);\n      if (m.radiusUnit) radius = m;\n    }\n    if (!radius || !isFinite(x0)) return null;\n    x0 -= MARGIN_MM; y0 -= MARGIN_MM;\n    x1 += MARGIN_MM; y1 += MARGIN_MM;\n    const hand = radius.radiusUnit.hand || 'right';\n    const rot  = (((radius.rotationDeg || 0) % 360) + 360) % 360;\n    // Visual corner the curve lands at: rotation maps the unrot\n    // front-(hand) corner to one of the four bbox corners.\n    let corner;\n    if (hand === 'right') {\n      corner = rot === 0 ? 'TR' : rot === 90 ? 'BR' : rot === 180 ? 'BL' : 'TL';\n    } else {\n      corner = rot === 0 ? 'TL' : rot === 90 ? 'TR' : rot === 180 ? 'BR' : 'BL';\n    }\n    const R  = (radius.radiusUnit.carcaseRadiusMm || 250) + MARGIN_MM;\n    const Rp = R * pxPerMm;\n    const X0 = x0 * pxPerMm, X1 = x1 * pxPerMm;\n    const Y0 = y0 * pxPerMm, Y1 = y1 * pxPerMm;\n    switch (corner) {\n      case 'TR':\n        return `M ${X0} ${Y0} L ${X1 - Rp} ${Y0} A ${Rp} ${Rp} 0 0 1 ${X1} ${Y0 + Rp} L ${X1} ${Y1} L ${X0} ${Y1} Z`;\n      case 'BR':\n        return `M ${X0} ${Y0} L ${X1} ${Y0} L ${X1} ${Y1 - Rp} A ${Rp} ${Rp} 0 0 1 ${X1 - Rp} ${Y1} L ${X0} ${Y1} Z`;\n      case 'BL':\n        return `M ${X0} ${Y0} L ${X1} ${Y0} L ${X1} ${Y1} L ${X0 + Rp} ${Y1} A ${Rp} ${Rp} 0 0 1 ${X0} ${Y1 - Rp} Z`;\n      case 'TL':\n        return `M ${X0 + Rp} ${Y0} L ${X1} ${Y0} L ${X1} ${Y1} L ${X0} ${Y1} L ${X0} ${Y0 + Rp} A ${Rp} ${Rp} 0 0 1 ${X0 + Rp} ${Y0} Z`;\n    }\n    return null;\n  }\n\n  // Clearance dimensions for the active selection (or the units being\n  // dragged). liveCabs supplies live positions during a drag;\n  // idsOverride forces a measure set (the drag set even if it wasn't\n  // pre-selected). With nothing active the overlay is removed.\n  function refreshClearance(liveCabs, idsOverride) {\n    if (clearanceHandle) { clearanceHandle.destroy(); clearanceHandle = null; }\n    if (!clearanceCtx) return;\n    const arr = liveCabs || cabinets;\n    const ids = idsOverride || [...selectedCabinetIds];\n    if (ids.length === 0) { refreshRoomItemMeasure(); return; }\n\n    const sel = ids.map(id => arr.find(c => c.id === id)).filter(Boolean);\n    if (sel.length === 0) return;\n\n    // Floor units measure clearance to other FLOOR units; wall/bridging\n    // units to other WALL units. Pillars + room walls block both, so\n    // they're always included. Measured from the VISIBLE footprint\n    // (end panels + door/drawer face), not the bare carcase.\n    const clearGroup = c => /^(wall|bridging)/i.test(c.category || '') ? 'wall' : 'floor';\n    const selGroup = clearGroup(sel[0]);\n\n    let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;\n    for (const c of sel) {\n      const a = getVisualFootprintAABB(c, c.x, c.y);\n      minX = Math.min(minX, a.x);            minY = Math.min(minY, a.y);\n      maxX = Math.max(maxX, a.x + a.widthMm); maxY = Math.max(maxY, a.y + a.depthMm);\n    }\n    const selAABB = { x: minX, y: minY, widthMm: maxX - minX, depthMm: maxY - minY };\n\n    const selSet = new Set(ids);\n    const obstacles = arr\n      .filter(c => !selSet.has(c.id) && clearGroup(c) === selGroup)\n      .map(c => getVisualFootprintAABB(c, c.x, c.y))\n      .concat((roomConfig.perimeterItems || []).map(p => getVisualFootprintAABB(p, p.x, p.y)));\n\n    clearanceHandle = renderClearance(clearanceCtx.gridEl, {\n      selAABB, room, obstacles, pxPerMm: clearanceCtx.pxPerMm\n    });\n  }\n\n  // A clicked Other Item shows its size and where it is on its wall: the\n  // distance from each end of it to the walls at the ends (Non Urgent sheet\n  // row 28, Julian). Its popup's From Wall boxes type the same position.\n  // liveItem: the item at its dragged position, while it is being moved.\n  const MEASURED_ROOM_ITEMS = new Set(['boiler', 'consumer-unit', 'radiator',\n    'electrical-point', 'stopcock', 'cooker-alcove']);\n  function refreshRoomItemMeasure(liveItem) {\n    if (!clearanceCtx || !selectedItem || selectedItem.kind !== 'feature') return;\n    const it = liveItem || (roomConfig.perimeterItems || []).find(x => x.id === selectedItem.id);\n    if (!it || it.id !== selectedItem.id || !MEASURED_ROOM_ITEMS.has(it.type)) return;\n    if (clearanceHandle) { clearanceHandle.destroy(); clearanceHandle = null; }\n    clearanceHandle = renderClearance(clearanceCtx.gridEl, {\n      selAABB: getVisualFootprintAABB(it, it.x, it.y), room, obstacles: [],\n      pxPerMm: clearanceCtx.pxPerMm, roomItem: true\n    });\n  }\n\n  function destroyRender() {\n    for (let i = renderHandles.length - 1; i >= 0; i--) renderHandles[i].destroy();\n    renderHandles = [];\n  }\n\n  function getRoomConfig() { return roomConfig; }\n\n  // \"Bottom + panel\" stacked wall units carry an 18mm divider panel,\n  // charged as one wall end panel (\"created from an appropriate end\n  // panel\"). Resolves to the real Shopify product when the end-panel\n  // catalogue is wired; until then it's a no-op (no variant \u2192 no\n  // charge), exactly like the other planner product stubs.\n  const DIVIDER_PANEL_CODE = 'EP-WALL';\n  function dividerPanelFor(cab) {\n    if (!cab || (cab.mountAnchor || 'top') !== 'panel') return null;\n    if (!/^(wall|bridging)/i.test(cab.category || '')) return null;\n    for (const product of Catalogue.getProducts()) {\n      if (product.kbbUnitTypeCode !== DIVIDER_PANEL_CODE) continue;\n      const v = product.variants?.[0];\n      if (!v) break;\n      const info = Catalogue.getVariantInfo(v.id);\n      return {\n        variantId:  v.id,\n        priceCents: info?.priceCents ?? null,\n        name:       product.title || 'Wall End Panel',\n        code:       DIVIDER_PANEL_CODE\n      };\n    }\n    return null;\n  }\n\n  // Resolve a nested end-panel BOARD to its Shopify product/variant +\n  // price for a given kitchen style. One product per stock type\n  // (EP-BASE / EP-TALL / EP-WALL), one price per style - matched on\n  // kbbUnitTypeCode like the divider panel. Returns null until the real\n  // product exists, so the quote/total simply omit it meanwhile.\n  // MANUAL END PANEL SIZE (Arden, 2026-10-17). A base unit's plain or T&G end\n  // panel set to a size of the user's own (ep.manualDepthMm: the TOTAL depth,\n  // door face to back, up to 1200) and extended at the front or the back\n  // (ep.manualDir). Worked out HERE, once per render, and stamped on the side\n  // as ep.manual = { depthMm, frontMm, backMm, joinsMm } so the 2D, the 3D,\n  // the worktop, the cut list and the back panel all read the same answer:\n  //   frontMm / backMm - how much further the panel reaches than normal;\n  //   joinsMm          - where the joins fall, measured from the panel front:\n  //                      none when one board makes it (a base panel up to\n  //                      650, else the range's 1200-deep island panel);\n  //                      otherwise it is base panels end to end.\n  // Also on the unit: epNormalDepthMm (what the panel would be - the popup's\n  // floor for the size) and, for a back extension, epManualBack.standOffMm -\n  // where the breakfast-bar back panel's outer face now sits past the carcase\n  // back, so it and its battens follow the panel back.\n  const MANUAL_EP_MAX_MM = 1200;\n  const BASE_EP_BOARD_MM = 650;\n  // The longest single board the range sells that a deep BASE end panel can be\n  // cut from in one piece: its Island & Breakfast Bar Back Panels (900 x 1200,\n  // 2100, 2400 - parseBackPanelCode; not the Profile Height ones), or an old\n  // Island End Panel (1200). 0 = none, so a deep panel is base panels joined.\n  // Plain stands in for T&G, as the nester does.\n  const _islandSold = new Map();\n  function rangeLongestIslandBoard(styleId, finish) {\n    const k = styleId + '|' + finish;\n    if (_islandSold.has(k)) return _islandSold.get(k);\n    const fins = finish === 'tng' ? ['tng', 'plain'] : ['plain'];\n    const old  = finish === 'tng' ? ['IEPTG', 'IEPP'] : ['IEPP'];\n    let best = 0;\n    if (styleId) for (const p of (Catalogue.getProducts() || [])) {\n      if (!p || p.kitchenStyleId !== styleId) continue;\n      if (old.includes(p.kbbUnitTypeCode)) { best = Math.max(best, 1200); continue; }\n      const bb = parseBackPanelCode(p.kbbUnitTypeCode);\n      if (bb && !bb.ph && fins.includes(bb.finish)) best = Math.max(best, bb.lengthMm);\n    }\n    _islandSold.set(k, best);\n    return best;\n  }\n  function manualEndPanelUnit(c) {\n    // A reduced depth larder's panel can reach forward or back too, up to one\n    // 650mm board (bug sheet, Julian, 2026-11-05).\n    return !!(c && (/^base/i.test(c.category || '') || (/^tall/i.test(c.category || '') && c.depthMm < 570))\n      && !c.lShapeUnit && !c.diagonalCornerUnit\n      && !c.cornerUnit && !c.freestandingAppliance && !c.radiusUnit && !c.splayEnd && !c.stackOn);\n  }\n  // STEPPED OFF THE WALL (Position > step off, cab.wallSetbackMm; Arden,\n  // 2026-10-27): the unit's end panels reach back to the wall, so they cover the\n  // gap behind it too - base and tall units alike. Deeper than one board, a base\n  // panel comes off the range's island / breakfast-bar board, else base panels\n  // joined; a tall one is two tall panels joined. Blind corner and splay end\n  // units too (Arden, 2026-10-27); L-shape / diagonal corners cannot be\n  // stepped, and a radius unit's curve is a bought part.\n  function setbackEndPanelUnit(c) {\n    const cat = (c && c.category) || '';\n    return !!(c && (/^(base|tall)/i.test(cat) || (c.cornerUnit && !/wall|bridging/i.test(cat)))\n      && (Number(c.wallSetbackMm) || 0) > 0.5\n      && !c.lShapeUnit && !c.diagonalCornerUnit && !c.freestandingAppliance\n      && !c.radiusUnit && !c.stackOn);\n  }\n  // A FREESTANDING APPLIANCE stepped off the wall (Arden, 2026-10-27): its end\n  // panels - a cabinet panel, as deep as the run (stampFreestandingPanels) + door - reach\n  // back to the wall by the step, on the same boards as a base unit's. Not on\n  // an island / peninsula (its back panel closes the back) or when stacked.\n  const APPLIANCE_EP_CARCASE_MM = 570;\n  function stampApplianceStep(c, ks) {\n    const sb = Math.round(Number(c.wallSetbackMm) || 0);\n    if (!(sb > 0.5) || c.stackOn || (c.backPanel && c.backPanel.active) || !c.endPanels) return;\n    // An appliance carries no range of its own; its panels are the plan's.\n    const styleId = c.kitchenStyleId || kitchenStyleId || null;\n    const _ks = ks || (styleId && Catalogue.getKitchenStyle && Catalogue.getKitchenStyle(styleId));\n    const fwd = (_ks && _ks.doorThicknessMm) ? _ks.doorThicknessMm : 18;\n    for (const side of ['left', 'right']) {\n      const ep = c.endPanels[side];\n      if (!ep || !ep.active || ep.doorLine || ep.toFloor || !(ep.style === 'flat' || ep.style === 'tng')) continue;\n      const normal = ((c.faPanelSideMm && c.faPanelSideMm[side]) || c.faPanelCarcaseMm || APPLIANCE_EP_CARCASE_MM) + fwd;\n      const D = Math.min(MANUAL_EP_MAX_MM, normal + sb);\n      const joins = [];\n      if (D > BASE_EP_BOARD_MM + 0.5\n          && rangeLongestIslandBoard(styleId, ep.style === 'tng' ? 'tng' : 'plain') + 0.5 < D) {\n        for (let j = BASE_EP_BOARD_MM; j < D - 0.5; j += BASE_EP_BOARD_MM) joins.push(Math.round(j));\n      }\n      ep.manual = { depthMm: Math.round(D), frontMm: 0, backMm: D - normal, joinsMm: joins };\n    }\n  }\n  function stampManualEndPanels(c, ks) {\n    const eps = c && c.endPanels;\n    c.epManualBack = null;\n    c.epManualFrontMm = 0;\n    c.epNormalDepthMm = null;\n    c.bpNormalGapMm = null;\n    c.bpFullGapMm = null;\n    for (const side of ['left', 'right']) if (eps && eps[side]) eps[side].manual = null;\n    if (c.freestandingAppliance) { stampApplianceStep(c, ks); return; }\n    const ownOk  = manualEndPanelUnit(c);\n    const stepOk = setbackEndPanelUnit(c);\n    if (!ownOk && !stepOk) return;\n    const tall = /tall/i.test(c.category || '');\n    const d    = c.depthMm || 0;\n    const fwd  = (ks && ks.doorThicknessMm) ? ks.doorThicknessMm : 18;\n    const bp   = c.backPanel;\n    const T    = (bp && bp.thicknessMm) || 20;\n    // The panel's back, past the carcase back, as the 2D / 3D / worktop draw\n    // it with no manual size: the full-size board, or just over the back\n    // panel, or flush. The panel front is always on the door line.\n    const normalBack = (bp && bp.active && bp.thProfile) ? null\n      : c.useFullSizeEndPanel ? Math.max(0, BASE_EP_BOARD_MM - fwd - d)\n      : (bp && bp.active) ? T : 0;\n    if (normalBack == null) return;              // True Handleless island: fixed sizes\n    const normal = d + fwd + normalBack;\n    // How much further back than normal the panel reaches to meet the wall.\n    // The worktop already covers the gap behind a stepped unit, so this is\n    // left out of epManualBack (which moves the worktop and back panel).\n    const stepX = stepOk ? Math.max(0, Math.min(MANUAL_EP_MAX_MM - normal,\n      Math.round(Number(c.wallSetbackMm) || 0) - normalBack)) : 0;\n    // The popup's floor for an own size is the wall-reaching depth.\n    if (ownOk) c.epNormalDepthMm = Math.round(normal + stepX);\n    // STEP OFF UNIT (Breakfast Bar Back Panel popup, Arden 2026-10-22): the\n    // gap wanted between the carcase back and the back panel\n    // (backPanel.gapMm). The panel normally stands normalBack - T off (0 on a\n    // plain back, ~40mm where full-size end panels reach the 650 line -\n    // bpNormalGapMm, the popup's floor); the end panels reach back the rest of\n    // the way like a manual Extend at Back, and the back panel, its battens and\n    // the worktop follow epManualBack as they do for that.\n    const normalGap = Math.max(0, normalBack - T);\n    if (bp && bp.active) {\n      c.bpNormalGapMm = Math.round(normalGap);\n      // The gap with the full 650mm panel, on or off: what Full Depth sets.\n      c.bpFullGapMm = Math.round(Math.max(0, BASE_EP_BOARD_MM - fwd - d - T));\n    }\n    const wantGap = (bp && bp.active && bp.gapMm != null) ? Math.round(Number(bp.gapMm) || 0) : null;\n    const gap = (ownOk && wantGap != null)\n      ? Math.max(0, Math.min(MANUAL_EP_MAX_MM - normal, wantGap - normalGap)) : 0;\n    let maxBack = gap, maxFront = 0;\n    const floor = normal + stepX;\n    for (const side of ['left', 'right']) {\n      const ep = eps && eps[side];\n      // A True Handleless profile panel has no own size, but does reach the wall.\n      const plainOrTng = ep && (ep.style === 'flat' || ep.style === 'tng');\n      if (!ep || !ep.active || ep.doorLine || ep.toFloor\n          || !(plainOrTng || (stepX > 0 && /^th-/.test(String(ep.style || ''))))) continue;\n      // Beside a free standing appliance in an island the back panel runs on\n      // behind the appliance, so the panel between them only covers the unit\n      // (Arden, 2026-11-19: it went right to the back, through the service void).\n      if (ep.besideAppliance && plainOrTng) {\n        const D = d + fwd;\n        ep.manual = { depthMm: Math.round(D), frontMm: 0, backMm: D - normal, joinsMm: [] };\n        continue;\n      }\n      const want = (ownOk && plainOrTng) ? (Number(ep.manualDepthMm) || 0) : 0;\n      const front = ep.manualDir === 'front';\n      const own = (want > floor + 0.5) ? Math.min(MANUAL_EP_MAX_MM, want) - floor : 0;\n      const frontX = front ? own : 0;\n      const backX = stepX + Math.max(front ? 0 : own, gap);\n      if (!(frontX + backX > 0.5)) continue;\n      const D = Math.min(MANUAL_EP_MAX_MM, normal + frontX + backX);\n      const cutFront = frontX > 0 && !(backX > 0);\n      // One board where one covers it; else boards end to end, cut from the\n      // extended end inwards, so the join is nearest the normal panel. A tall\n      // panel is always tall panels joined.\n      const joins = [];\n      if (D > BASE_EP_BOARD_MM + 0.5\n          && (tall || rangeLongestIslandBoard(c.kitchenStyleId, ep.style === 'tng' ? 'tng' : 'plain') + 0.5 < D)) {\n        if (cutFront) { for (let j = D - BASE_EP_BOARD_MM; j > 0.5; j -= BASE_EP_BOARD_MM) joins.unshift(Math.round(j)); }\n        else          { for (let j = BASE_EP_BOARD_MM; j < D - 0.5; j += BASE_EP_BOARD_MM) joins.push(Math.round(j)); }\n      }\n      ep.manual = { depthMm: Math.round(D), frontMm: frontX, backMm: D - normal - frontX, joinsMm: joins };\n      maxFront = Math.max(maxFront, frontX);\n      maxBack = Math.max(maxBack, D - normal - frontX - stepX);\n    }\n    c.epManualFrontMm = maxFront;\n    if (maxBack > 0) c.epManualBack = { extraMm: maxBack, standOffMm: normalBack + maxBack };\n  }\n\n  function endPanelBoardProduct(board, styleId) {\n    if (!board) return null;\n    // The nester stamps each board with an ORDERED list of real product codes\n    // (base / island / tall / wall / breakfast-bar \u00D7 plain / T&G, plus the\n    // filler codes) - see boardProductCodes. Walk them and take the first that\n    // exists IN THIS BOARD'S OWN STYLE. Never fall back to another style's\n    // product: the same panel differs by up to 5x in price between ranges.\n    const codes = (board.productCodes && board.productCodes.length)\n      ? board.productCodes\n      : (board.code ? [board.code] : []);\n    const wantStyle = board.styleId || styleId || kitchenStyleId || null;\n    const all = Catalogue.getProducts();\n    for (const code of codes) {\n      const p = all.find(pr => pr.kbbUnitTypeCode === code && pr.kitchenStyleId === wantStyle);\n      if (!p) continue;\n      const v = p.variants && p.variants[0];\n      if (!v) continue;\n      const info = Catalogue.getVariantInfo(v.id);\n      return { variantId: v.id, priceCents: info?.priceCents ?? null,\n               name: p.title || code, handle: p.handle || null, code,\n               compareAtCents: info?.variant?.compareAtPrice ?? null };\n    }\n    if (typeof window !== 'undefined' && window.BTK_FILLER_DEBUG) {\n      console.warn('[BTK_EP_DEBUG] board', board.itemNumber, board.type, board.code,\n        'finish', board.finish, 'style', wantStyle,\n        '\u2192 no product for any of', codes);\n    }\n    return null;\n  }\n\n  // Better Bedrooms: the worktop is the range's own Bedroom Worktop Panel, so the\n  // pickers list only the current range's (each material's `range` is its\n  // range handle - see the catalogue snippet).\n  function rangeWorktopMaterials() {\n    const all = (Catalogue.getWorktopMaterials && Catalogue.getWorktopMaterials()) || [];\n    return all.filter(m => m.range === kitchenStyleId);\n  }\n\n  // ---- Bespoke worktops (made-to-measure quartz / porcelain) --------------\n  //\n  // Two kinds of basket line: the SLABS the layout nests onto (full 3200 x 1600\n  // and half 3200 x 800 variants of the chosen colour and thickness), and ONE\n  // \"Manufacture, Template & Install\" line - every process the job needs,\n  // added up from the prices Odoo publishes, rounded UP to the next fixed-price\n  // band variant. The pricing engine explains why the price is a variant.\n  //\n  // Options, one set per plan:\n  //   thicknessMm - null = the thinnest the colour is sold in\n  //   edgeKey     - Odoo Planner Key of the edge profile, charged per metre\n  //   zone        - templating zone; 'a' until postcode zoning exists\n  //   extras      - { worktopId: { featureKey: qty } } from the Worktops popup\n  function normaliseBespokeOptions(v) {\n    const o = (v && typeof v === 'object') ? v : {};\n    return {\n      thicknessMm: (typeof o.thicknessMm === 'number' && o.thicknessMm > 0) ? o.thicknessMm : null,\n      edgeKey:     (typeof o.edgeKey === 'string' && o.edgeKey) ? o.edgeKey : 'edge_double_chamfer',\n      zone:        (typeof o.zone === 'string' && /^[abc]$/i.test(o.zone)) ? o.zone.toLowerCase() : 'a',\n      extras:      (o.extras && typeof o.extras === 'object') ? JSON.parse(JSON.stringify(o.extras)) : {},\n      // A templating & fitting price our team quoted for a postcode area\n      // outside the zones (Price on Request): { area: 'EH', priceGbp }. It\n      // only counts while the plan's postcode is still in that area.\n      quoted:      (o.quoted && typeof o.quoted.area === 'string' && o.quoted.area && Number(o.quoted.priceGbp) > 0)\n        ? { area: o.quoted.area.toUpperCase(), priceGbp: Math.round(Number(o.quoted.priceGbp) * 100) / 100 }\n        : null,\n      // When the customer asked for that price (the basket's Request a Price),\n      // and for which worktop: { key, at }. Kept with the plan.\n      requested:   (o.requested && typeof o.requested.key === 'string' && typeof o.requested.at === 'string')\n        ? { key: o.requested.key, at: o.requested.at, ticket: (typeof o.requested.ticket === 'string' && o.requested.ticket) || null }\n        : null,\n      // Worktop to follow (Arden, 2026-11-06): the customer chose to order the\n      // kitchen now and this worktop separately once it is priced - { key, at },\n      // key as above, so a changed worktop asks again before checkout.\n      deferred:    (o.deferred && typeof o.deferred.key === 'string' && typeof o.deferred.at === 'string')\n        ? { key: o.deferred.key, at: o.deferred.at }\n        : null,\n      // The surface finish chosen (Polished, Suede, Matt ...) for a colour made\n      // in several. Null = the colour's first.\n      finish:      (typeof o.finish === 'string' && o.finish) ? o.finish : null,\n      // A Price on Application colour (Silestone, DEKTON): the whole job's\n      // price our team quoted, { key, priceGbp } - key is the job it was quoted\n      // for (bespokeJob().requestKey), so it stops counting once the worktop\n      // changes and the basket asks for an updated price.\n      poaQuote:    (o.poaQuote && typeof o.poaQuote.key === 'string' && o.poaQuote.key && Number(o.poaQuote.priceGbp) > 0)\n        ? { key: o.poaQuote.key, priceGbp: Math.round(Number(o.poaQuote.priceGbp) * 100) / 100 }\n        : null,\n    };\n  }\n\n  // What the plan puts INTO its worktops: sinks (and how each is mounted),\n  // hobs, taps and curves. One source for bespoke pricing and the Worktops\n  // popup, so the two can never count differently.\n  //   Sinks: a sink base with a sink chosen says how it is mounted; one with\n  //   none chosen yet still needs a cut-out, counted as the dearer polished\n  //   (undermount) one so a bespoke quote can only come down once it's picked.\n  //   Taps: every sink needs a tap hole, even before a tap is chosen.\n  //   Belfast sink units too (Planner Bugs 31, Arden 2026-10-26): they were\n  //   not counted, so a stone worktop over one was quoted with no cut-out and\n  //   no tap hole. A Belfast (or none chosen yet) is a polished cut-out - the\n  //   U-notch shows its cut edge; an apron-front sits on its rim on the\n  //   worktop, so an unpolished one. Both take a tap hole in the stone.\n  function worktopPlanCounts(slabs) {\n    // With part of the plan in another worktop (Change Worktop), only what is\n    // IN the stone counts: a sink under a laminate part is not cut in it.\n    const partial = !!slabs && (cabinets || []).some(c => c && c.worktopMaterialHandle);\n    const stone = partial ? slabs.filter(s => { const m = Catalogue.getWorktopMaterial(worktopMaterialForSlab(s)); return m && m.pricingModel === 'bespoke'; }) : null;\n    const inCabs = stone ? new Set(stone.flatMap(s => s.cabinetIds || [])) : null;\n    const onStone = (it) => !stone || stone.some(s => s && s.polygon && s.polygon.length > 2\n      && pointInPlanPolygon((it.x || 0) + (it.widthMm || 0) / 2, (it.y || 0) + (it.depthMm || 0) / 2, s.polygon));\n    const sinks = [];\n    for (const c of (cabinets || [])) {\n      if (!c || !(c.sinkBase || c.belfastSink)) continue;\n      if (inCabs && !inCabs.has(c.id)) continue;\n      const sk = (c.plannerSinkHandle && typeof Catalogue.getPlannerSink === 'function')\n        ? Catalogue.getPlannerSink(c.plannerSinkHandle) : null;\n      sinks.push({ installType: (c.belfastSink && sk && sk.installType) || sinkMountFor(c, sk) || (c.belfastSink ? 'belfast' : 'undermount') });\n    }\n    const items = (worktopItems || []).filter(it => it && onStone(it));\n    for (const it of items) {\n      if (!it || it.kind !== 'sink') continue;\n      const _sk = (it.handle && Catalogue.getPlannerSink) ? Catalogue.getPlannerSink(it.handle) : null;\n      sinks.push({ installType: (_sk && sinkMountFor(it, _sk)) || it.installType || 'undermount' });\n    }\n    const hobCount = items.filter(it => it && it.kind === 'hob').length;\n    // A tap hole is cut in the stone only where the sink has no deck of its\n    // own: an undermount or a belfast (Arden, 2026-09-23). An inset sink's\n    // tap sits on the sink itself, so it asks nothing of the worktop.\n    const needsTapHole = sinks.filter(s => /under|belfast|butler|apron/i.test(String(s.installType || ''))).length;\n    const tapCount = Math.max(items.filter(it => it && it.kind === 'tap').length, needsTapHole);\n    return { sinks, hobCount, tapCount, corners: bespokeCornerCounts(stone || slabs || [], worktopCornerRadii || {}) };\n  }\n  function pointInPlanPolygon(x, y, poly) {\n    let inside = false;\n    for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {\n      const a = poly[i], b = poly[j];\n      if (((a.y > y) !== (b.y > y)) && (x < (b.x - a.x) * (y - a.y) / ((b.y - a.y) || 1e-9) + a.x)) inside = !inside;\n    }\n    return inside;\n  }\n\n  // Is the plan's worktop stone (heat-safe behind a hob)? See worktopIsHeatSafe.\n  function planWorktopHeatSafe() {\n    const h = worktopMaterialForSlab();\n    return worktopIsHeatSafe(h ? Catalogue.getWorktopMaterial(h) : null);\n  }\n\n  // The upstand / splashback / hob splashback strips along the worktops, as\n  // the 2D plan and the 3D view draw them. `settings` (optional) asks what\n  // they WOULD be with other settings - the Worktops popup counts a supply-only\n  // upstand for a plan that has none switched on yet. Never throws.\n  function splashbackStripsFor(slabs, settings) {\n    try {\n      return computeSplashbackStrips({\n        cabinets, worktopItems, worktopSlabs: slabs || buildWorktops() || [], room,\n        perimeterItems: roomConfig.perimeterItems,\n        wallOpenings: roomConfig.wallOpenings, settings: settings || roomConfig.splashbacks\n      }).strips || [];\n    } catch (e) { return []; }\n  }\n  // The strips cut from the worktop's own stone: the ones set to match it.\n  function stoneStripParts(slabs, withMedia = true) {\n    return splashbackStripsFor(slabs)\n      .filter(st => st.material === 'match-worktop' && st.lengthMm > 0 && st.heightMm > 0)\n      .map(st => ({ part: st.kind, lengthMm: st.lengthMm, heightMm: st.heightMm }))\n      // Media Wall rear panels in the worktop: cut from the same slabs. A slab\n      // is 1600 deep, so a taller panel is cut on its side where it is no\n      // wider than that, else in rows.\n      .concat((withMedia ? mediaWorktopPieces() : []).flatMap(p => (p.heightMm > 1600 && p.lengthMm <= 1600)\n        ? [{ part: 'splashback', lengthMm: p.heightMm, heightMm: p.lengthMm }]\n        : mediaWorktopRows([p], 1600).map(r => ({ part: 'splashback', ...r }))));\n  }\n  // Window boards set to \"Match Worktop\" (on the window itself, in Doors &\n  // Windows or its panel): each is cut from the worktop, so it is a run of its\n  // own in the cutting plan - `part: 'cill'`, a plain rectangle, front and both\n  // ends on show. Numbered by the window's place among the windows.\n  // A window set to Worktop in to Window has no board of its own once the\n  // worktop reaches it - the worktop IS the board, already in the plan. With\n  // no worktop under it (nothing reached the window) it keeps its board.\n  function windowCills() {\n    const out = [];\n    let n = 0;\n    const intoWorktop = new Set();\n    if ((roomConfig.wallOpenings || []).some(windowTakesWorktop)) {\n      for (const s of (buildWorktops() || [])) {\n        for (const t of (s.windowTabs || [])) intoWorktop.add(t.openingId);\n      }\n    }\n    for (const op of (roomConfig.wallOpenings || [])) {\n      if (!op || op.type !== 'window') continue;\n      n++;\n      if (op.boardColourCode !== 'worktop') continue;\n      if (intoWorktop.has(op.id)) continue;\n      const size = windowCillSize(op);\n      if (size) out.push({ id: op.id, n, ...size });\n    }\n    return out;\n  }\n  function windowCillRuns() {\n    return windowCills().map(c => ({\n      id: null, part: 'cill', rotationDeg: 0, cabinetIds: [],\n      exposedLeft: true, exposedRight: true, exposedBack: false,\n      polygon: [{ x: 0, y: 0 }, { x: c.lengthMm, y: 0 }, { x: c.lengthMm, y: c.depthMm }, { x: 0, y: c.depthMm }]\n    }));\n  }\n\n  // Everything about the plan's bespoke job, or null when its material isn't\n  // bespoke. Never throws: pricing must never break the quote.\n  function bespokeJob(wtSlabs) {\n    try {\n      // EVERY made-to-measure stone on the plan, the plan's own first, then\n      // any chosen for part of it (Change Worktop): ONE job - one templating\n      // visit, one price - with each colour cut from its own slabs and listed\n      // on the job for the supplier to quote (Arden, 2026-11-17).\n      const all = (wtSlabs || buildWorktops() || []).filter(Boolean);\n      const isStone = (h) => { const m = h && Catalogue.getWorktopMaterial(h); return !!(m && m.pricingModel === 'bespoke'); };\n      const planH = worktopMaterialForSlab();\n      const stoneHandles = [...new Set([planH, ...all.map(x => worktopMaterialForSlab(x))].filter(isStone))];\n      const rawAll = buildWorktops() || [];\n      const colours = [];\n      for (const h of stoneHandles) {\n        const slabsH = all.filter(x => worktopMaterialForSlab(x) === h);\n        if (!slabsH.length) continue;\n        const ths = Catalogue.getBespokeThicknesses(h);\n        const t = ths.includes(worktopBespoke.thicknessMm) ? worktopBespoke.thicknessMm : (ths[0] || null);\n        // The finish: one of those this colour is made in at that thickness.\n        const fins = (typeof Catalogue.getBespokeFinishes === 'function') ? Catalogue.getBespokeFinishes(h, t) : [];\n        const fin = fins.includes(worktopBespoke.finish) ? worktopBespoke.finish : (fins[0] || null);\n        const st = Catalogue.getBespokeStock(h, t, fin);\n        if (!st) { if (typeof console !== 'undefined') console.warn('[BTK bespoke] no slabs published for', h, t, fin); continue; }\n        colours.push({ handle: h, mat: Catalogue.getWorktopMaterial(h), thicknessMm: t, thicknesses: ths, finish: fin, finishes: fins,\n                       stock: st, slabs: slabsH, raw: rawAll.filter(x => worktopMaterialForSlab(x) === h), isPlan: h === planH });\n      }\n      if (!colours.length) return null;\n      const main = colours[0];\n      const handle = main.handle, mat = main.mat, thicknesses = main.thicknesses, thicknessMm = main.thicknessMm;\n      const finishes = main.finishes, finish = main.finish, stock = main.stock;\n      const hs = new Set(colours.map(c => c.handle));\n      const slabs = all.filter(x => hs.has(worktopMaterialForSlab(x)));\n      // The worktops, the window boards set to match them and the upstands /\n      // splashbacks set to match them, all cut from the same slabs.\n      // \u26A0 THE SAME PIECES THE LAYOUT DRAWS, already merged and already\n      // classified. Handing it the raw runs instead made it merge a second\n      // time, off unmarked points, so every edge on the Cutting Plan was\n      // re-guessed from its position on the slab and every joint came back\n      // polished (Arden, 2026-09-30). mergeRuns: false because they are\n      // merged already; doing it twice would throw the marks away again.\n      // Waterfall sides are cut from the same slabs too. Taken from the\n      // worktops as built (not the merged pieces), because that is where the\n      // sides were chosen.\n      // Window boards and Media Wall panels set to match the worktop are the\n      // PLAN's worktop, so they are cut only from the plan's own stone.\n      for (const c of colours) {\n        c.bill = computeBespokeSlabs(\n          bespokePlanPieces(c.slabs).concat(c.isPlan ? windowCillRuns() : []), c.stock,\n          { parts: stoneStripParts(c.slabs, c.isPlan).concat(waterfallParts(c.raw)), mergeRuns: false });\n        c.material = /porcelain/i.test(String((c.mat && c.mat.type) || '')) ? 'porcelain' : 'quartz';\n        c.colourName = (c.mat && (c.mat.colour || c.mat.title)) || '';\n        c.worktopNos = c.slabs.map(x => slabs.indexOf(x) + 1);\n        if (colours.length > 1) c.bill = { ...c.bill, slabs: c.bill.slabs.map(sl => ({ ...sl, colourName: c.colourName, colourHandle: c.handle })) };\n      }\n      const sumOf = (k) => colours.reduce((n, c) => n + (Number(c.bill[k]) || 0), 0);\n      const bill = colours.length === 1 ? main.bill : {\n        lines: colours.flatMap(c => c.bill.lines || []), slabs: colours.flatMap(c => c.bill.slabs || []),\n        pieces: colours.flatMap(c => c.bill.pieces || []), unplaced: colours.flatMap(c => c.bill.unplaced || []),\n        fullCount: sumOf('fullCount'), halfCount: sumOf('halfCount'), exposedEdgeMm: sumOf('exposedEdgeMm'), topEdgeMm: sumOf('topEdgeMm'),\n      };\n      const material = main.material;\n\n      const { sinks, hobCount, tapCount, corners } = worktopPlanCounts(slabs);\n\n      // Extras chosen per worktop in the Worktops popup, summed for the job.\n      // A worktop that no longer exists takes its extras with it.\n      const extras = {};\n      const liveIds = new Set(slabs.map(s => s.id));\n      for (const [wid, byKey] of Object.entries(worktopBespoke.extras || {})) {\n        if (!liveIds.has(wid)) continue;\n        for (const [k, n] of Object.entries(byKey || {})) {\n          const q = Math.max(0, Math.floor(Number(n) || 0));\n          if (q) extras[k] = (extras[k] || 0) + q;\n        }\n      }\n      // A flush mount hob is on or off: one per hob on the plan, on top of\n      // that hob's cut-out (bug sheet row 66 - it could be added over and\n      // over, PLN100058 had 4 for its 1 hob).\n      if (extras.hob_flush_mount) {\n        if (hobCount) extras.hob_flush_mount = hobCount; else delete extras.hob_flush_mount;\n      }\n      const pricing = Catalogue.getBespokePricing();\n      // The templating zone is never chosen: it comes from the logged-in\n      // customer's saved postcode (the cheapest zone when there is none). A\n      // postcode we do not cover makes the job Price on Request - it is still\n      // worked out, but nothing is charged, so no line reaches the basket.\n      const templating = templatingZoneFor(Catalogue.getCustomerPostcode(), Catalogue.getWorktopZones(),\n                                           pricing && pricing.processes);\n      // Waterfall mitres. Each waterfall is mitred onto its worktop along the\n      // edge it drops from, and an end waterfall meeting a breakfast bar one\n      // is mitred down the corner as well - charged per metre (edge_mitre).\n      // That worktop edge is a MITRE, not a shaped and polished edge, so it\n      // comes off the edge profile's metres, which still count every open\n      // edge of the waterfalls themselves.\n      // Each colour's own slabs, edges and mitres; what the plan cuts into\n      // the stone (sinks, hobs, taps, corners), the extras and the one\n      // templating visit go on the job once.\n      const qty = new Map();\n      colours.forEach((c, i) => {\n        let mitreMm = 0, mitredEdgeMm = 0;\n        for (const s of c.raw) {\n          if (!s || !(s.waterfalls || []).length) continue;\n          const info = worktopWaterfallInfo(s, c.thicknessMm);\n          if (!info) continue;\n          const along = info.sides.filter(x => x.on).reduce((n, x) => n + x.lengthMm, 0);\n          mitredEdgeMm += along;\n          mitreMm += along + info.verticalMitres * info.heightMm;\n        }\n        const own = bespokeProcessQuantities({\n          material: c.material, fullCount: c.bill.fullCount, halfCount: c.bill.halfCount,\n          exposedEdgeMm: Math.max(0, c.bill.exposedEdgeMm - mitredEdgeMm), stripTopEdgeMm: c.bill.topEdgeMm,\n          edgeKey: worktopBespoke.edgeKey, mitreMm,\n          ...(i === 0 ? { sinks, tapCount, hobCount, corners, extras } : {}),\n          zone: templating.zone || 'a'\n        });\n        for (const q of own) {\n          if (i > 0 && /^templating_zone_/.test(q.key)) continue;\n          qty.set(q.key, (qty.get(q.key) || 0) + q.qty);\n        }\n      });\n      const quantities = [...qty].map(([key, n]) => ({ key, qty: n }));\n      // A postcode outside the zones: we still template and fit there, but our\n      // team prices the trip (Arden, 2026-10-14). No zone's templating is\n      // charged; until a price is quoted (worktopBespoke.quoted, set by staff\n      // for that postcode area) the job is a PRICE REQUEST - shown in the\n      // basket with a Request a Price button, and checkout waits for it.\n      const outside = templating.covered === false;\n      const jobQuantities = outside ? quantities.filter(q => !/^templating_zone_/.test(q.key)) : quantities;\n      const priced = priceBespokeProcesses(jobQuantities, pricing);\n      const quote = worktopBespoke.quoted;\n      const quoted = (outside && quote && quote.area === templating.area) ? quote : null;\n      if (quoted) {\n        const cents = Math.round(quoted.priceGbp * 100);\n        priced.lines.push({ key: 'templating_quoted', name: `Templating & fitting, quoted for ${quoted.area}`,\n                            unit: 'job', qty: 1, unitCents: cents, cents });\n        priced.totalCents += cents;\n      }\n      // What the price depends on - the colour, thickness, finish, slabs and\n      // every process with its quantity, in that area. A request or a quote is\n      // for exactly this; once it changes, the basket asks again. (The finish\n      // only joins the key where there is one, so requests made before finishes\n      // existed still match.)\n      const requestKey = JSON.stringify([handle, thicknessMm, ...(finish ? [finish] : []), bill.fullCount, bill.halfCount,\n        jobQuantities.map(q => q.key + ':' + q.qty).sort(), templating.area || '',\n        ...(colours.length > 1 ? [colours.slice(1).map(c => [c.handle, c.thicknessMm, c.finish || ''])] : [])]);\n      // PRICE ON APPLICATION (Silestone, DEKTON - Arden, 2026-10-30): the job is\n      // laid out and specified as usual, but nothing is charged from published\n      // prices. It is a price request until our team quotes the whole job -\n      // slabs, manufacture, templating and fitting, wherever the postcode is.\n      const poa = colours.some(c => c.mat && c.mat.poa === true);\n      const pq = (poa && worktopBespoke.poaQuote && worktopBespoke.poaQuote.key === requestKey) ? worktopBespoke.poaQuote : null;\n      let charged = priced;\n      if (poa) {\n        const cents = pq ? Math.round(pq.priceGbp * 100) : 0;\n        charged = { lines: pq ? [{ key: 'poa_quoted', name: 'Supply, manufacture, template & install, as quoted',\n                                   unit: 'job', qty: 1, unitCents: cents, cents }] : [],\n                    totalCents: cents, missing: [] };\n      }\n      const priceRequest = poa ? !pq : (outside && !quoted);\n      // ONE line for the whole job (Arden 2026-09-20: \"the customer is really\n      // only concerned about the total price for bespoke worktops\"), so the\n      // slabs are charged through the price band too, not as lines of their\n      // own. The slab detail still travels on the line as the breakdown.\n      const slabCents = poa ? 0 : (bill.lines || []).reduce(\n        (n, l) => n + (Number(l.qty) || 0) * Number((l.slab && l.slab.priceCents) || 0), 0);\n      const jobCents = charged.totalCents + slabCents;\n      const bands = (pricing && !priceRequest) ? pickPriceBands(jobCents, pricing.bands)\n                            : { lines: [], chargedCents: 0, roundingCents: 0 };\n      return { handle, mat, material, thicknessMm, thicknesses, finish, finishes, stock, bill, slabs,\n               colours: colours.map(c => ({ handle: c.handle, mat: c.mat, material: c.material, colourName: c.colourName,\n                                            thicknessMm: c.thicknessMm, finish: c.finish, worktopNos: c.worktopNos })),\n               quantities: jobQuantities, pricing, priced: charged, slabCents, jobCents, bands, templating,\n               quoted: poa ? null : quoted, priceRequest, poa, poaQuote: pq, requestKey };\n    } catch (e) {\n      if (typeof console !== 'undefined') console.warn('[BTK bespoke] could not price the job', e);\n      return null;\n    }\n  }\n\n  function bespokeColoursText(job, withMaterial) {\n    const cs = (job && job.colours && job.colours.length) ? job.colours\n      : [{ colourName: job && job.mat && (job.mat.colour || job.mat.title), finish: job && job.finish, thicknessMm: job && job.thicknessMm, material: job && job.material }];\n    return cs.map(c => [c.colourName, c.finish, c.thicknessMm ? c.thicknessMm + 'mm' : '', withMaterial ? c.material : '']\n      .filter(Boolean).join(', ')).join(' + ');\n  }\n\n  // Worktop charges for the current layout - one entry per slab-tier\n  // material group (ceramic / quartz), each { handle, bill, variant }.\n  // Grouped by material so two colours never share a slab. Shared by the\n  // running total AND the basket assembly so the two never diverge.\n  // Best-effort: returns [] on any error (worktop pricing must never break\n  // the quote). Blank / unassigned worktops yield no charge here.\n  // A price band's was (compare-at) price. The pricing table bands are picked\n  // from carries only each band's price; Shopify holds the compare-at on the\n  // variant itself, so read it the way the basket does (/variants/<id>.js),\n  // once per band, and redraw the Worktops popup when it lands. Until then (or\n  // if it cannot be read) the line shows its price alone.\n  const bandCompareAt = new Map();   // variantId -> cents, or null while asking / none\n  function bandCompareAtCents(variantId) {\n    if (variantId == null) return null;\n    if (bandCompareAt.has(variantId)) return bandCompareAt.get(variantId);\n    bandCompareAt.set(variantId, null);\n    if (typeof fetch === 'function') {\n      fetch('/variants/' + encodeURIComponent(variantId) + '.js', { headers: { Accept: 'application/json' } })\n        .then(r => (r.ok ? r.json() : null))\n        .then(v => {\n          const cents = v ? Number(v.compare_at_price) : 0;\n          if (cents > 0) {\n            bandCompareAt.set(variantId, cents);\n            if (worktopsPopupHandle) worktopsPopupHandle.refreshIfOpen();\n          }\n        })\n        .catch(() => {});\n    }\n    return null;\n  }\n\n  // A board worktop's window boards set to \"Match Worktop\" are cut from the\n  // same boards, so they join the plan material's group - the board count, and\n  // so the price, covers them. (A made-to-measure stone takes them in\n  // bespokeJob instead.)\n  // Can this material be cut as a DOGLEG - an L in one piece?\n  //\n  // Faced boards (round and square edge laminate, bonded FENIX) cannot: the\n  // corner is a joint, and an L bounding box asks for a board that is not\n  // sold. Real wood can physically, but its grain has to run one way, so it is\n  // treated the same (Arden, 2026-09-30). Compact laminate, solid FENIX and\n  // solid surface are cut from the sheet and CAN dogleg - but only when that\n  // works out cheaper, so a 900 board never gets bought to save a joint that\n  // two 600s would have made anyway.\n  const materialCanDogleg = (m) => !!m && m.construction === 'solid' && m.type !== 'Real Wood';\n\n  // How a board material is CUT: rectangles, or (where the material allows a\n  // dogleg and it comes out cheaper) the slabs as they are fitted. One\n  // decision, used by the price, the cut list and the Worktop Plan drawing, so\n  // the three can never disagree.\n  // A mason's mitre (butt and scribe) needs more length than a square cut:\n  // 40mm, once per joint, on ONE of the two pieces. The materials that get one\n  // are the ones that cannot dogleg - the faced laminates, bonded FENIX and\n  // real wood (Arden, 2026-09-29/30).\n  const MITRE_ALLOWANCE_MM = 40;\n\n  // A diagonal corner is filled with strips parallel to its 45, at a board's\n  // width each. The narrowest stocked width is used: these are short pieces,\n  // and buying a wide board to cover one is money for nothing. Cut AFTER the\n  // mitres, so the notches its neighbours take are already in the shape and\n  // carry into whichever strip holds them.\n  // Is this piece the worktop over a diagonal corner unit?\n  function isDiagonalCornerPiece(r) {\n    const ids = new Set(r.cabinetIds || []);\n    if (!ids.size) return false;\n    return (cabinets || []).some(c => c && ids.has(c.id) && c.diagonalCornerUnit);\n  }\n\n  function withDiagonalStrips(rects, boards) {\n    const widths = [...new Set((boards || []).map(b => Number(b.widthMm) || 0).filter(w => w > 0))]\n      .sort((a, b) => a - b);\n    const w = widths[0] || 600;\n    const out = [];\n    for (const r of rects) {\n      // Only a DIAGONAL CORNER is filled in strips, and that is decided by the\n      // unit under it, not by the shape. A splay unit also has a long angled\n      // edge, but that edge is its short side, not a front to run strips off -\n      // its front is the line its neighbours set, so it stays one piece\n      // (Arden, 2026-09-30).\n      const strips = (r && isDiagonalCornerPiece(r)) ? diagonalStrips(r, w) : null;\n      if (strips && strips.length) out.push(...strips); else out.push(r);\n    }\n    return out;\n  }\n\n  // Every width the RANGE is made in, not just this colour's: a run that\n  // measures 672 is bought as a 670 whether or not this particular colour\n  // stocks one, and should say 670.\n  // The widths the worktop range is actually made in, measured off the live\n  // catalogue 2026-09-30: 600 (83 variants), 635 (29), 645 (13), 670 (51),\n  // 900 (76). Seeded rather than derived alone, because a piece measuring 672\n  // is bought as a 670 even when the colour on the plan does not stock one and\n  // the browser's own catalogue therefore never mentions it.\n  const WT_RANGE_WIDTHS = [600, 635, 645, 670, 900];\n  // Worked out once: it walks every worktop material in the catalogue, and the\n  // catalogue does not change while the planner is open. It is asked for on\n  // every price recalculation, which is every click.\n  let _stockedWidths = null;\n  function stockedWidths() {\n    if (_stockedWidths) return _stockedWidths;\n    const out = new Set(WT_RANGE_WIDTHS);\n    for (const m of (Catalogue.getWorktopMaterials?.() || [])) {\n      for (const b of (Catalogue.getWorktopBoards?.(m.handle) || [])) {\n        if (b && b.widthMm > 0) out.add(b.widthMm);\n      }\n    }\n    _stockedWidths = [...out];\n    return _stockedWidths;\n  }\n\n  // Sinks and hobs, as spans along the run they sit on, so a joint is never\n  // put through one. Run-local mm, measured the same way the billing measures\n  // a run (slabOutline's frame: x along the run from its start).\n  const CUTOUT_CLEAR_MM = 50;\n  function cutoutSpans(slabs) {\n    const out = [];\n    for (const it of (worktopItems || [])) {\n      if (!it || !/^(sink|hob)$/.test(String(it.kind || ''))) continue;\n      const w = Number(it.widthMm) || 600;\n      for (const s of (slabs || [])) {\n        const deg = (s.rotationDeg || 0) * Math.PI / 180;\n        const cs = Math.cos(deg), sn = Math.sin(deg);\n        const L = (p) => ({ x: p.x * cs + p.y * sn, y: -p.x * sn + p.y * cs });\n        const pts = (s.polygon || []).map(L);\n        if (pts.length < 3) continue;\n        const xs = pts.map(p => p.x), ys = pts.map(p => p.y);\n        const x0 = Math.min(...xs), x1 = Math.max(...xs);\n        const y0 = Math.min(...ys), y1 = Math.max(...ys);\n        const c = L({ x: (Number(it.x) || 0) + w / 2, y: (Number(it.y) || 0) + (Number(it.depthMm) || 600) / 2 });\n        if (c.x < x0 - 50 || c.x > x1 + 50 || c.y < y0 - 50 || c.y > y1 + 50) continue;\n        out.push({\n          slabId: s.id,\n          fromMm: (c.x - x0) - w / 2 - CUTOUT_CLEAR_MM,\n          toMm:   (c.x - x0) + w / 2 + CUTOUT_CLEAR_MM,\n        });\n      }\n    }\n    return out;\n  }\n\n  // ---- Worktop in to Window: the tab rides through the cutting ------------\n  // Every step that divides the worktops into pieces (corner stitching, board\n  // rectangles, mitres, diagonal strips, slab-length splits) works on the runs\n  // WITHOUT their window tabs, exactly as it always has; the tabs are cut back\n  // into whichever finished piece lies against the window afterwards. So a\n  // run with a window in it is still one piece - one board deep enough to take\n  // the reveal, or one templated stone - and none of those steps has to know\n  // a tab exists.\n  function windowTabSpecs(slabs) {\n    const byId = new Map();\n    for (const s of (slabs || [])) {\n      for (const t of ((s && s.windowTabs) || [])) {\n        if (!byId.has(t.openingId)) { const { pts, ...spec } = t; byId.set(t.openingId, spec); }\n      }\n    }\n    return [...byId.values()];\n  }\n  function withoutWindowTabs(slabs, specs) {\n    if (!specs.length) return slabs;\n    return (slabs || []).map(s => (s && s.windowTabs)\n      ? { ...s, polygon: stripWindowTabs(s.polygon, specs), windowTabs: [] } : s);\n  }\n  function withWindowTabs(pieces, specs) {\n    if (!specs.length) return pieces;\n    return (pieces || []).map(p => {\n      if (!p || p.part) return p;          // a cill or a strip is never a worktop\n      const { polygon, tabs } = insertWindowTabs(stripWindowTabs(p.polygon, specs), specs);\n      return tabs.length ? { ...p, polygon, windowTabs: tabs } : p;\n    });\n  }\n\n  function boardCutSlabs(mat, group, boards, opts) {\n    const specs = windowTabSpecs(group);\n    // A solid worktop (real wood too) is cut from one board with a Belfast\n    // sink notched out of it - no strip behind the sink, no joints beside it.\n    const keepNotches = !!(mat && mat.construction === 'solid');\n    const rects = snapPieceDepths(rectangleSlabs(withoutWindowTabs(group, specs), { keepNotches }), stockedWidths());\n    // Mitred materials: rectangles with the mitre CUT INTO them - the butting\n    // piece grows its tongue, the piece it meets is notched to take it. One\n    // set of pieces for the price, the cut list and the drawing, so every one\n    // of them measures the same board (Arden, 2026-09-30).\n    if (!materialCanDogleg(mat)) {\n      return withWindowTabs(withDiagonalStrips(mitreShapes(rects, MITRE_ALLOWANCE_MM), boards), specs);\n    }\n    const cut = withWindowTabs(withDiagonalStrips(rects, boards), specs);\n    const asIs = computeBoardBilling(group, boards, opts);\n    // A run with no board wide enough prices at NOTHING, which is not\n    // \"cheaper\" - it is missing. Only a fully priced dogleg can win.\n    if (asIs.unpriced.length) return cut;\n    const rectBill = computeBoardBilling(cut, boards, opts);\n    return (asIs.totalCents < rectBill.totalCents) ? group : cut;\n  }\n\n  // Bill a board material, cut the way that material is cut. The pieces it\n  // was cut into come back on the bill, because a caller that wants to say\n  // anything about a piece (which wall it is against, say) needs the piece it\n  // was actually cut from, not the run it started as.\n  function billBoards(mat, group, boards, opts) {\n    const cut = boardCutSlabs(mat, group, boards, opts);\n    const bill = computeBoardBilling(cut, boards, opts);\n    bill.cutSlabs = cut;\n    return bill;\n  }\n\n  // The worktops as the PIECES they are cut into, for the Worktop Plan\n  // drawing. A made-to-measure stone is templated in one go, so it keeps its\n  // fitted shapes; a board kitchen shows what is actually bought.\n  // ---- made to measure: the pieces the fabricator will actually cut --------\n  // The Layout has to show THESE, not the runs they were built from, or the\n  // customer is looking at one division of their kitchen while the Cutting\n  // Plan bills another (Arden, 2026-09-30: \"D, E and F as one piece ... isn't\n  // shown on the layout\").\n  function bespokePlanPieces(slabs) {\n    const handle = worktopMaterialForSlab();\n    const ths = Catalogue.getBespokeThicknesses(handle) || [];\n    const th = ths.includes(worktopBespoke.thicknessMm) ? worktopBespoke.thicknessMm : (ths[0] || null);\n    const stock = Catalogue.getBespokeStock(handle, th);\n    if (!stock || !stock.full) return slabs;\n    // Window tabs come off for the merging and splitting and go back on the\n    // pieces that result (see withWindowTabs).\n    const tabSpecs = windowTabSpecs(slabs);\n    const merged = mergeAdjacentRuns(withoutWindowTabs(slabs, tabSpecs), stock.full.lengthMm, stock.full.widthMm);\n    // \u26A0 EVERY PIECE THAT IS CUT IS ITS OWN SECTION, with its own letter. A run\n    // too long for a slab is two pieces, and calling them \"B 1/2\" and \"B 2/2\"\n    // described the run rather than the things being made - so the letters on\n    // the two drawings could not line up either (Arden, 2026-09-30: \"section b\n    // for example should have their own letter\"). Split here, once, and both\n    // views letter the same list.\n    const L = stock.full.lengthMm;\n    const out = [];\n    for (const sp of merged) {\n      const d = slabDims(sp);\n      if (!d || !(d.lengthMm > L + 1e-6)) { out.push(sp); continue; }\n      const n = Math.ceil(d.lengthMm / L - 1e-6);\n      const even = d.lengthMm / n;\n      const deg = (sp.rotationDeg || 0) * Math.PI / 180;\n      const cs = Math.cos(deg), sn = Math.sin(deg);\n      const toLocal = (q) => ({ x: q.x * cs + q.y * sn, y: -q.x * sn + q.y * cs });\n      const toWorld = (q) => ({ x: q.x * cs - q.y * sn, y: q.x * sn + q.y * cs });\n      const local = (sp.polygon || []).map(q => ({ ...q, ...toLocal(q) }));\n      const minX = Math.min(...local.map(q => q.x)), minY = Math.min(...local.map(q => q.y));\n      const based = local.map(q => ({ ...q, x: q.x - minX, y: q.y - minY }));\n      for (let i = 0; i < n; i++) {\n        const cut = clipOutlineX(based, i * even, (i + 1) * even);\n        if (!cut || cut.length < 3) continue;\n        const poly = cut.map(q => ({ ...q, ...toWorld({ x: q.x + i * even + minX, y: q.y + minY }) }));\n        // \u26A0 EACH PART NEEDS ITS OWN FRAME. It inherits the merged piece's\n        // rotation, in which the part may well be taller than it is wide -\n        // and slabOutline returns NULL for that, so the piece loses its\n        // outline, nests as a plain rectangle and buys a slab it need not.\n        const f = bestFrame(poly, [sp.rotationDeg || 0, 0]);\n        out.push({\n          ...sp,\n          id: `${sp.id}#${i + 1}`,\n          rotationDeg: f ? f.rotationDeg : (sp.rotationDeg || 0),\n          polygon: poly,\n        });\n      }\n    }\n    return markStoneEdges(withWindowTabs(out, tabSpecs), (room && room.vertices) || [],\n                          waterfallMitreLines(buildWorktops()));\n  }\n\n  // Classify every segment ONCE, here in the room, and write the answer onto\n  // the point it starts at. Two reasons it has to be done here and carried:\n  // the Cutting Plan sees a piece lying on a slab and cannot tell which of its\n  // edges met a wall, and a merged outline has far more segments than the four\n  // sides any position test can name - so the drawing fell back to \"polished\"\n  // and put an edge charge on every joint (Arden, 2026-09-30).\n  function markStoneEdges(pieces, roomVerts, mitreLines) {\n    const distTo = (A, B, p) => {\n      const dx = B.x - A.x, dy = B.y - A.y, L2 = dx * dx + dy * dy;\n      let t = L2 ? ((p.x - A.x) * dx + (p.y - A.y) * dy) / L2 : 0;\n      t = Math.max(0, Math.min(1, t));\n      return Math.hypot(p.x - (A.x + t * dx), p.y - (A.y + t * dy));\n    };\n    // A worktop edge with a waterfall mitred onto it: both ends of the segment\n    // lie on that side of the worktop.\n    const onMitre = (P, Q) => (mitreLines || []).some(([A, B]) =>\n      distTo(A, B, P) <= 2 && distTo(A, B, Q) <= 2);\n    return pieces.map(sp => {\n      const pts = (sp.polygon || []).map(q => ({ ...q }));\n      for (let i = 0; i < pts.length; i++) {\n        const P = pts[i], Q = pts[(i + 1) % pts.length];\n        let k = slabEdgeKind(sp, P, Q, { room: roomVerts, joints: [], bespoke: true });\n        if (k !== 'raw' && onMitre(P, Q)) { P.k = 'mitre'; continue; }\n        if (k !== 'raw') {\n          // Where it runs along another piece it is a JOINT between them, not\n          // an edge anybody polishes and not an edge anybody is charged for.\n          //\n          // \u26A0 25mm, NOT \"touching\". Worktop runs are modelled with the cutting\n          // allowance between them, so the faces that meet sit 10mm apart, or\n          // 20mm where two allowances meet. A 2mm test found NOTHING and every\n          // interface in the kitchen stayed polished (Arden, 2026-09-30).\n          // Measured on a real plan: interfaces 10-20mm, the next nearest\n          // segment 150mm+, so there is no ambiguity in between.\n          const mid = { x: (P.x + Q.x) / 2, y: (P.y + Q.y) / 2 };\n          for (const other of pieces) {\n            if (other === sp) continue;\n            const op = other.polygon || [];\n            let hit = false;\n            for (let j = 0; j < op.length; j++) {\n              if (distTo(op[j], op[(j + 1) % op.length], mid) <= 25) { hit = true; break; }\n            }\n            if (hit) { k = 'joint'; break; }\n          }\n        }\n        P.k = k;\n      }\n      return { ...sp, polygon: pts };\n    });\n  }\n\n  // ---- a corner unit belongs to two runs, so stitch the second one back ---\n  //\n  // A run is a straight line of units with ONE direction, and an L-shape\n  // corner unit faces two ways. It carries a single rotationDeg, so it joins\n  // the run along one of its arms and the neighbour against its OTHER arm\n  // reads as perpendicular and starts a run of its own. On 'New Cliant' that\n  // left a 280mm stub beside the corner, boxed in by a full-height fridge\n  // (Arden, 2026-10-01: \"why does B and D exist as separate sections when they\n  // should be in the same run\").\n  //\n  // Fixed AFTER the runs are built rather than inside runAdjacent: the run's\n  // own direction stays unambiguous, and nothing in the 3D build, the end\n  // panels or the grouping has to change. Two runs are stitched only when one\n  // of a run's rectangles lines up with one of the other's - same depth band,\n  // touching end to end - which is the geometric way of saying \"these two are\n  // the same stretch of wall\".\n  function runWorldRects(run) {\n    const deg = (run.rotationDeg || 0) * Math.PI / 180;\n    const cs = Math.cos(deg), sn = Math.sin(deg);\n    const local = (run.polygon || []).map(q => ({ x: q.x * cs + q.y * sn, y: -q.x * sn + q.y * cs }));\n    if (!local.length) return [];\n    const minX = Math.min(...local.map(q => q.x)), minY = Math.min(...local.map(q => q.y));\n    const back = (lx, ly) => ({ x: (lx + minX) * cs - (ly + minY) * sn,\n                                y: (lx + minX) * sn + (ly + minY) * cs });\n    const bands = slabToRects(run);\n    const boxOf = (pts) => {\n      const xs = pts.map(q => q.x), ys = pts.map(q => q.y);\n      return { x0: Math.min(...xs), x1: Math.max(...xs), y0: Math.min(...ys), y1: Math.max(...ys) };\n    };\n    if (!bands || !bands.length) return [boxOf(run.polygon || [])];\n    return bands.map(b => boxOf([back(b.x0, b.y0), back(b.x1, b.y0), back(b.x1, b.y1), back(b.x0, b.y1)]));\n  }\n  function sameStretch(P, Q, tol) {\n    const near = (u, v) => Math.abs(u - v) <= tol;\n    const touchX = Math.max(P.x0, Q.x0) - Math.min(P.x1, Q.x1) <= tol;\n    const touchY = Math.max(P.y0, Q.y0) - Math.min(P.y1, Q.y1) <= tol;\n    // Same depth band across, and end to end along.\n    if (near(P.y0, Q.y0) && near(P.y1, Q.y1) && touchX) return true;\n    if (near(P.x0, Q.x0) && near(P.x1, Q.x1) && touchY) return true;\n    return false;\n  }\n  // Stitched without their window tabs, which go back on afterwards (see\n  // withWindowTabs) - the union welds points 25mm apart, which would fold a\n  // shallow reveal flat.\n  function mergeCornerRuns(runs, tolMm) {\n    const specs = windowTabSpecs(runs);\n    if (!specs.length) return mergeCornerRunsBare(runs, tolMm);\n    return withWindowTabs(mergeCornerRunsBare(withoutWindowTabs(runs, specs), tolMm), specs);\n  }\n  function mergeCornerRunsBare(runs, tolMm) {\n    const tol = tolMm == null ? 25 : tolMm;\n    let list = (runs || []).filter(Boolean).slice();\n    // \u26A0 ONLY AT A CORNER UNIT. The fault being fixed is specific: a unit that\n    // faces two ways can only join one run. Two ordinary runs meeting at an\n    // ordinary corner must stay apart - they are joined with a mason's mitre,\n    // and merging them makes that corner internal and the mitre disappears.\n    // Without this the chipboard plan lost the mitre between its left and\n    // bottom runs (Arden, 2026-10-01).\n    const cornerCabs = new Set();\n    for (const c of (cabinets || [])) {\n      if (c && (c.lShapeUnit || c.cornerUnit)) cornerCabs.add(c.id);\n    }\n    if (!cornerCabs.size) return list;\n    const hasCorner = (r) => (r.cabinetIds || []).some(id => cornerCabs.has(id));\n    const areaOf = (r) => {\n      const pts = r.polygon || [];\n      return Math.abs(pts.reduce((t, q, i) => {\n        const n = pts[(i + 1) % pts.length];\n        return t + (q.x * n.y - n.x * q.y);\n      }, 0) / 2);\n    };\n    for (let pass = 0; pass < 8; pass++) {\n      let did = false;\n      const rects = list.map(runWorldRects);\n      outer:\n      for (let i = 0; i < list.length; i++) {\n        for (let j = i + 1; j < list.length; j++) {\n          // Exactly one of them is the corner run; the other is the stranded\n          // neighbour. Two corner runs, or two plain runs, are left alone.\n          if (hasCorner(list[i]) === hasCorner(list[j])) continue;\n          // Two worktop materials are never stitched into one (row 100).\n          if ((list[i].altMaterial || null) !== (list[j].altMaterial || null)) continue;\n          let hit = false;\n          for (const P of rects[i]) { for (const Q of rects[j]) if (sameStretch(P, Q, tol)) { hit = true; break; } if (hit) break; }\n          if (!hit) continue;\n          const u = unionOutlines([list[i].polygon || [], list[j].polygon || []]);\n          if (!u || u.length < 3) continue;\n          // Keep the bigger run's identity and frame: it owns the corner.\n          const keep = areaOf(list[i]) >= areaOf(list[j]) ? i : j;\n          const drop = keep === i ? j : i;\n          const merged = {\n            ...list[keep],\n            polygon: u,\n            cabinetIds: (list[keep].cabinetIds || []).concat(list[drop].cabinetIds || []),\n          };\n          // Only if it still decomposes into boards; otherwise leave them be.\n          if (!slabToRects(merged)) continue;\n          list[keep] = merged;\n          list.splice(drop, 1);\n          did = true;\n          break outer;\n        }\n      }\n      if (!did) break;\n    }\n    return list;\n  }\n\n  // forHandle: only that material's worktops (row 100); none = the plan's\n  // material, drawn over every worktop as before.\n  function worktopPlanPieces(forHandle) {\n    try {\n      const all = mergeCornerRuns(buildWorktops() || []);\n      const slabs = forHandle ? all.filter(s => worktopMaterialForSlab(s) === forHandle) : all;\n      const handle = forHandle || worktopMaterialForSlab();\n      const mat = handle && Catalogue.getWorktopMaterial(handle);\n      if (mat && mat.pricingModel === 'bespoke') return bespokePlanPieces(slabs);\n      if (!mat || mat.pricingModel === 'slab-tier') return slabs;\n      const boards = Catalogue.getWorktopBoards(handle);\n      const opts = {\n        canRip: mat.construction === 'solid' || mat.profile !== 'rounded',\n        reuseOffcuts: true,\n      };\n      // No dimensioned boards yet: rectangles are still the honest picture.\n      if (!boards.length) return rectangleSlabs(slabs, { keepNotches: mat.construction === 'solid' });\n      const cut = boardCutSlabs(mat, slabs, boards, opts);\n      return withCutDetail(cut, boards, { ...opts, cutouts: cutoutSpans(cut) });\n    } catch (e) { return []; }\n  }\n\n  // Any worktop edge lying ON a wall is a cut, unfinished edge: the board's own\n  // raw back or one sawn on site, never a finished one (Arden, 2026-09-30).\n  // Applied HERE, where the piece is still in world coordinates, so the\n  // Layout, the Cutting Plan and the order all say the same thing - the\n  // drawing alone cannot know it once a piece is laid on a board.\n  function edgeOnWall(A, B) {\n    const verts = (room && room.vertices) || [];\n    if (verts.length < 2) return false;\n    const mid = { x: (A.x + B.x) / 2, y: (A.y + B.y) / 2 };\n    for (let i = 0; i < verts.length; i++) {\n      const P = verts[i], Q = verts[(i + 1) % verts.length];\n      const dx = Q.x - P.x, dy = Q.y - P.y;\n      const len2 = dx * dx + dy * dy;\n      if (!(len2 > 0)) continue;\n      let on = true;\n      for (const pt of [A, B, mid]) {\n        const t = ((pt.x - P.x) * dx + (pt.y - P.y) * dy) / len2;\n        const d = Math.abs((pt.x - P.x) * dy - (pt.y - P.y) * dx) / Math.sqrt(len2);\n        if (t < -0.001 || t > 1.001 || d > 12) { on = false; break; }\n      }\n      if (on) return true;\n    }\n    return false;\n  }\n  // The four sides of a run, in world mm, so each can be tested against a wall.\n  function wallAdjustedEdges(slab, edges) {\n    if (!slab || !edges) return edges;\n    const deg = (slab.rotationDeg || 0) * Math.PI / 180;\n    const cs = Math.cos(deg), sn = Math.sin(deg);\n    const L = (p) => ({ x: p.x * cs + p.y * sn, y: -p.x * sn + p.y * cs });\n    const W = (q) => ({ x: q.x * cs - q.y * sn, y: q.x * sn + q.y * cs });\n    const pts = (slab.polygon || []).map(L);\n    if (pts.length < 3) return edges;\n    const xs = pts.map(q => q.x), ys = pts.map(q => q.y);\n    const x0 = Math.min(...xs), x1 = Math.max(...xs);\n    const y0 = Math.min(...ys), y1 = Math.max(...ys);\n    const side = {\n      front: [W({ x: x0, y: y0 }), W({ x: x1, y: y0 })],\n      back:  [W({ x: x0, y: y1 }), W({ x: x1, y: y1 })],\n      left:  [W({ x: x0, y: y0 }), W({ x: x0, y: y1 })],\n      right: [W({ x: x1, y: y0 }), W({ x: x1, y: y1 })],\n    };\n    const out = { ...edges };\n    for (const k of Object.keys(side)) {\n      if (edgeOnWall(side[k][0], side[k][1])) out[k] = 'raw';\n    }\n    return out;\n  }\n\n  // What the billing knows and the drawing needs: how each edge of a piece is\n  // finished, and where a run too long for a board is JOINED. A 3.5m run on a\n  // 3m board is one worktop in the kitchen and two boards on the order, and\n  // the layout should say so (Arden, 2026-09-30).\n  function withCutDetail(cut, boards, opts) {\n    const bill = computeBoardBilling(cut, boards, opts);\n    const bySlab = new Map();\n    for (const b of bill.boards) {\n      for (const pc of b.pieces) {\n        if (pc.slabId == null) continue;\n        if (!bySlab.has(pc.slabId)) bySlab.set(pc.slabId, []);\n        bySlab.get(pc.slabId).push(pc);\n      }\n    }\n    return cut.map(r => {\n      const all = (bySlab.get(r.id) || []).slice();\n      if (!all.length) return r;\n      // \u26A0 TWO DIFFERENT KINDS OF PART SHARE A SLAB ID and they compose\n      // differently. A run longer than a board is split along its LENGTH; a\n      // run deeper than a board is joined along its DEPTH into bands. Treating\n      // a band as a length split put the join line off the far end of the\n      // piece and took the back edge off the FRONT band, so the back of a\n      // breakfast bar drew as a joint (Arden, 2026-09-30).\n      const bands = new Map();\n      for (const pc of all) {\n        const k = pc.joinStrip || 1;\n        if (!bands.has(k)) bands.set(k, []);\n        bands.get(k).push(pc);\n      }\n      const keys = [...bands.keys()].sort((a, b) => a - b);\n      for (const k of keys) bands.get(k).sort((a, b) => (a.joinIndex || 0) - (b.joinIndex || 0));\n      const firstBand = bands.get(keys[0]);\n      const lastBand  = bands.get(keys[keys.length - 1]);\n      const first = firstBand[0], last = firstBand[firstBand.length - 1];\n      // Where the joins fall along the run, measured within ONE band: every\n      // band is the same length and breaks in the same places.\n      const splits = [];\n      let run = 0;\n      for (let i = 0; i < firstBand.length - 1; i++) { run += firstBand[i].lengthMm; splits.push(run); }\n      // And where they fall across the depth: the band boundaries.\n      const depthSplits = [];\n      let acc = 0;\n      for (let i = 0; i < keys.length - 1; i++) { acc += bands.get(keys[i])[0].depthMm; depthSplits.push(acc); }\n      return {\n        ...r,\n        edges: wallAdjustedEdges(r, {\n          // The outer edges of the WHOLE section: its front off the front\n          // band, its back off the back one.\n          front: (first.edges || {}).front,\n          back:  ((lastBand[0] || {}).edges || {}).back,\n          left:  (first.edges || {}).left,\n          right: (last.edges  || {}).right,\n        }),\n        splitsMm: splits,\n        depthSplitsMm: depthSplits,\n      };\n    });\n  }\n\n  // How those pieces meet, for the drawing: [{ points, kind }] in world mm.\n  // A material that takes a mason's mitre gets the mitre's own shape; anything\n  // else gets the straight butt line across the end of the butting piece.\n  function worktopPlanJoints(forHandle) {\n    try {\n      const handle = forHandle || worktopMaterialForSlab();\n      const mat = handle && Catalogue.getWorktopMaterial(handle);\n      if (!mat || mat.pricingModel === 'bespoke' || mat.pricingModel === 'slab-tier') return [];\n      // From the UNSHAPED rectangles: once the mitre is cut into the pieces\n      // their bounding boxes carry the tongue, and a line measured off those\n      // would sit 40mm out. Measured here it lands exactly on the shaped\n      // outline, which is the point of drawing it.\n      // \u26A0 THE SAME STITCHED RUNS the pieces are built from. Left on the raw\n      // runs, this re-found the joint that stitching had just removed and\n      // drew a mason's mitre across a worktop that is now continuous (Arden,\n      // 2026-10-01).\n      // A solid worktop keeps a Belfast sink notch in one piece, as the cut\n      // does (boardCutSlabs) - so no mitre is drawn either side of the sink.\n      const _all = mergeCornerRuns(buildWorktops() || []);\n      const pieces = rectangleSlabs(forHandle ? _all.filter(s => worktopMaterialForSlab(s) === forHandle) : _all, { keepNotches: mat.construction === 'solid' });\n      const mitred = !materialCanDogleg(mat);\n      return pieceJoints(pieces).map(j => {\n        // From the interface the two really meet on, the same as the cut.\n        const pts = mitred\n          ? mitreLine(j.butt, j.atEnd, MITRE_ALLOWANCE_MM, j.atX)\n          : mitreLine(j.butt, j.atEnd, 0, j.atX);   // no roll: a straight butt\n        return pts ? { points: pts, kind: mitred ? 'mitre' : 'butt' } : null;\n      }).filter(Boolean);\n    } catch (e) { return []; }\n  }\n\n  function addBoardCills(groups) {\n    const cills = windowCillRuns();\n    if (!cills.length) return;\n    const handle = worktopMaterialForSlab();\n    const mat = handle && Catalogue.getWorktopMaterial(handle);\n    if (!mat || mat.pricingModel === 'slab-tier' || mat.pricingModel === 'bespoke') return;\n    if (!groups.has(handle)) groups.set(handle, []);\n    groups.get(handle).push(...cills);\n  }\n  // WATERFALL SIDES ON A BOARD WORKTOP (laminate, wood, FENIX - sales sheet\n  // row 139): each is cut from its worktop's boards, as a made-to-measure\n  // stone's are from its slabs (waterfallParts), so the Cut List shows it and\n  // the boards bought include it. One rectangle per waterfall, its length by\n  // its drop, laid shorter side across the board. Its id is the waterfall's,\n  // so the Cut List names it with the waterfall's own section letter. Each is\n  // placed well away from the room and from the others, so nothing that\n  // compares pieces by position (corner arms, joints) can tie it to a worktop.\n  function addBoardWaterfalls(groups) {\n    const built = buildWorktops() || [];\n    const byId = new Map(built.filter(Boolean).map(s => [s.id, s]));\n    let j = 0;\n    for (const w of worktopWaterfallList(built)) {\n      const s = byId.get(w.slabId);\n      const h = s && worktopMaterialForSlab(s);\n      if (!h || !groups.has(h)) continue;         // board materials only\n      const L = Math.max(w.lengthMm, w.heightMm), D = Math.min(w.lengthMm, w.heightMm);\n      if (!(L > 0 && D > 0)) continue;\n      const ox = 1e6 + (j++) * 1e4;\n      groups.get(h).push({\n        id: w.id, part: 'waterfall', rotationDeg: 0, cabinetIds: [],\n        exposedLeft: true, exposedRight: true, exposedBack: false,\n        polygon: [{ x: ox, y: 0 }, { x: ox + L, y: 0 }, { x: ox + L, y: D }, { x: ox, y: D }]\n      });\n    }\n  }\n\n  // The bespoke job as a LIST for Odoo's line note.\n  //\n  // \u26A0 IT READS LIKE THE CUSTOMISE PANEL, because that is what the customer\n  // chose and signed off. The first version listed `job.priced.lines`, whose\n  // names are the PRICING TABLE's product names - \"Bespoke Worktop - Edge:\n  // Double Chamfer, standard: 9m\", \"Bespoke Worktop - Templating Zone B x 1\" -\n  // which meant nothing to the supplier, repeated the templating zone, and\n  // left out the cut-outs and tap holes the panel shows (Arden, 2026-09-26).\n  // worktopsPopupHandle.specRows() returns the panel's own [label, value]\n  // pairs, so the note and the panel can never drift apart.\n  //\n  // sale.order.line.item_note is fields.Text and Odoo's PO report renders it\n  // with t-field, whose text converter turns newlines into <br> - so ONE LINE\n  // PER ITEM prints as a list. bk_stock's _prepare_purchase_order_line copies\n  // item_note onto the PO line, which is why this is the vehicle: only five\n  // sale-line fields can ever reach a printed PO.\n  //\n  // NO MONEY and NO BOARD QUANTITIES. This travels to the supplier, who\n  // templates on site and nests the job their own way.\n  // `slabs` is passed straight through to specRows so the popup does not\n  // rebuild the worktop layout that this caller has already built.\n  function bespokeSpecLines(job, slabs) {\n    if (!job) return [];\n    const out = [];\n    try {\n      const rows = (worktopsPopupHandle && typeof worktopsPopupHandle.specRows === 'function')\n        ? worktopsPopupHandle.specRows({ job, slabs: job.slabs || slabs }) : [];\n      // Two stones: each colour's own line (below) says its colour and\n      // thickness, so the panel's single ones would only mislead.\n      const multiColour = !!(job.colours && job.colours.length > 1);\n      for (const r of rows) {\n        if (!r || !r[0]) continue;\n        if (multiColour && /^(Colour \\/ Finish|Thickness|Finish)$/.test(r[0])) continue;\n        const val = String(r[1] == null ? '' : r[1]).trim();\n        if (!val || val === '-') continue;\n        out.push(r[0] + ': ' + val);\n      }\n    } catch (e) { /* fall back to the head line below */ }\n    // The panel does not show the templating zone - it is not the customer's\n    // choice - but the supplier needs it.\n    if (job.poa) {\n      // Priced by our team as a whole: say so, and what was quoted.\n      out.push('Price on application: ' + (job.poaQuote ? 'quoted \u00A3' + job.poaQuote.priceGbp.toFixed(2) : 'price on request')\n        + (job.templating && job.templating.postcode ? ' (' + job.templating.postcode + ')' : ''));\n    } else if (job.templating && job.templating.zone) {\n      out.push('Templating zone: ' + String(job.templating.zone).toUpperCase());\n    } else if (job.templating && job.templating.covered === false) {\n      // Outside the zones: priced by our team for the postcode area.\n      out.push('Templating: ' + (job.quoted\n        ? `quoted for ${job.quoted.area}, \u00A3${job.quoted.priceGbp.toFixed(2)}`\n        : `price on request (${job.templating.area})`));\n    }\n    // Nothing from the panel (it has never been opened this session): fall back\n    // to what the job itself knows, so the note is never empty.\n    const multi = !!(job.colours && job.colours.length > 1);\n    if (!multi && (!out.length || out.length === 1)) {\n      const colour = (job.mat && (job.mat.colour || job.mat.title)) || '';\n      const head = [colour, job.finish, job.thicknessMm ? job.thicknessMm + 'mm' : '',\n                    job.material === 'porcelain' ? 'porcelain' : 'quartz'].filter(Boolean);\n      if (head.length) out.unshift(head.join(', '));\n    }\n    // More than one stone: each colour, and the worktops (as numbered on the\n    // Layout) cut from it, first - the supplier quotes each colour.\n    if (multi) {\n      out.unshift(...job.colours.map((c, i) => 'Colour ' + (i + 1) + ': '\n        + [c.colourName, c.finish, c.thicknessMm ? c.thicknessMm + 'mm' : '', c.material].filter(Boolean).join(', ')\n        + ' - worktop' + (c.worktopNos.length > 1 ? 's ' : ' ') + c.worktopNos.join(', ')));\n    }\n    return out;\n  }\n  // The last billing run's depth bands that no stock board could take, for the\n  // popup to report. Stashed rather than recomputed: billBoards is not cheap\n  // and computeWorktopCharges already runs it.\n  let lastUnpriced = null;\n  function computeWorktopCharges() {\n    lastWorktopPriceRequest = null;\n    try {\n      // Buying them elsewhere: the plan draws them, nothing is charged.\n      if (worktopsNotPriced) return [];\n      // Stitched, so the price counts the same sections the drawing shows.\n      const wtSlabs = mergeCornerRuns(buildWorktops() || []);\n      // A Pastry Bench shelf matched to the plan worktop is one more piece of it.\n      wtSlabs.push(...pastryShelfSlabs());\n      const out = [];\n\n      // --- slab-tier (templated & installed ceramic / quartz) --------------\n      // Priced by how many standard slabs the layout nests onto \u2192 one tier\n      // variant, quantity one.\n      const billing = computeWorktopBillingByMaterial(wtSlabs, (s) => {\n        const h = worktopMaterialForSlab(s);\n        const m = h && Catalogue.getWorktopMaterial(h);\n        return (m && m.pricingModel === 'slab-tier') ? h : null;\n      });\n      for (const handle of Object.keys(billing)) {\n        const bill = billing[handle];\n        const variant = Catalogue.resolveWorktopVariant(handle, bill.tierKey);\n        if (variant && typeof variant.priceCents === 'number') {\n          out.push({ handle, bill, variant, qty: 1, label: bill.tierLabel });\n        }\n      }\n\n      // --- bespoke (made-to-measure quartz / porcelain) -------------------\n      // The slabs, then ONE band line carrying manufacture, templating and\n      // fitting. A job above the dearest band takes more than one band line.\n      const job = bespokeJob(wtSlabs);\n      if (job) {\n        // The slabs are NOT basket lines of their own - their value is inside\n        // the band line - but they are the first thing the breakdown lists, so\n        // the customer (and the order import) can still see what was bought.\n        const slabRows = (job.bill.lines || []).map(line => {\n          const sl = line.slab;\n          return {\n            name: (sl.colour || sl.name || 'Slab') + ', ' + (line.kind === 'half' ? 'half' : 'full')\n                  + ' slab ' + sl.lengthMm + ' \\u00d7 ' + sl.widthMm + ' \\u00d7 ' + sl.thicknessMm + 'mm',\n            qty: line.qty, cents: (sl.priceCents || 0) * (line.qty || 1),\n            slab: true, variantId: sl.variantId, sku: sl.sku,\n          };\n        });\n        for (const b of job.bands.lines) {\n          out.push({\n            handle: job.handle, bill: job.bill, qty: b.qty, bespoke: 'band',\n            label: 'Supply, manufacture, template & install',\n            // What the basket shows after the product name: which worktop.\n            detail: bespokeColoursText(job, false),\n            breakdown: slabRows.concat(job.priced.lines),\n            // The same breakdown as a printable list, for the Odoo line note.\n            spec: bespokeSpecLines(job, wtSlabs),\n            variant: {\n              variantId: b.variantId, priceCents: b.priceCents, compareAtCents: bandCompareAtCents(b.variantId),\n              name: 'Manufacture, Template & Install Bespoke Worktop', materialHandle: null, url: null,\n            }\n          });\n        }\n        // Outside the templating zones, or a Price on Application colour, and\n        // not yet quoted: no band line, but the worktop is still on the plan,\n        // so the basket shows it as a price request (buildQuote ->\n        // basket.priceRequest).\n        if (job.priceRequest) {\n          const spec = bespokeSpecLines(job, wtSlabs);\n          const mat = job.mat || {};\n          lastWorktopPriceRequest = {\n            // What the price depends on - the colour, thickness, slabs and every\n            // process with its quantity, in that area. NOT the spec text, which\n            // reads differently once the Worktops popup has been opened.\n            key: job.requestKey,\n            // Price on Application: the whole job is priced by our team (not\n            // just templating for the area), and the basket says so.\n            poa: !!job.poa,\n            area: job.templating.area || '',\n            postcode: job.templating.postcode || '',\n            handle: job.handle,\n            title: (job.colours && job.colours.length > 1) ? 'Bespoke worktops' : (mat.title || mat.colour || 'Bespoke worktop'),\n            detail: bespokeColoursText(job, true),\n            image: mat.swatchUrl || null,\n            spec,\n          };\n        }\n        if (typeof console !== 'undefined') {\n          if (!job.pricing) console.warn('[BTK bespoke] prices not published yet (btk.bespoke_worktop_pricing)');\n          else if (job.priced.missing.length) console.warn('[BTK bespoke] no price for', job.priced.missing);\n        }\n      }\n\n      // --- board materials (laminate, real wood, FENIX, solid surface) -----\n      // (billBoards below decides rectangles vs doglegs per material.)\n      // Sold as physical boards, so the layout resolves to a QUANTITY of each\n      // stock size rather than a single tier variant. Grouped by material\n      // first for the same reason slabs are: two colours can't share a board.\n      const boardGroups = new Map();\n      for (const s of wtSlabs) {\n        const h = worktopMaterialForSlab(s);\n        const m = h && Catalogue.getWorktopMaterial(h);\n        if (!m || m.pricingModel === 'slab-tier') continue;\n        if (!boardGroups.has(h)) boardGroups.set(h, []);\n        boardGroups.get(h).push(s);\n      }\n      addBoardCills(boardGroups);\n      addBoardWaterfalls(boardGroups);\n      for (const [handle, group] of boardGroups) {\n        const mat    = Catalogue.getWorktopMaterial(handle);\n        const boards = Catalogue.getWorktopBoards(handle);\n        if (!boards.length) continue;              // no dimensioned variants yet\n        const bill = billBoards(mat, group, boards, {\n          cutouts: cutoutSpans(group),\n          // Rippable = the cut long edge can be finished afterwards: solid\n          // material always, and square-edge boards because the installer can\n          // edge the new edge. A postformed bullnose cannot be recreated.\n          canRip: mat.construction === 'solid' || mat.profile !== 'rounded',\n          // ASSUMPTION (flagged to Arden, 2026-09-17): a length off-cut may\n          // serve another run in the same kitchen, i.e. one 4000 board yields\n          // a 2400 and a 1600 run. Switch to false to give each run its own\n          // board - note that also costs segmentation independence.\n          reuseOffcuts: true\n        });\n        for (const line of bill.lines) {\n          const b = line.board;\n          out.push({\n            handle,\n            bill,\n            qty: line.qty,\n            label: `${b.lengthMm} \u00D7 ${b.widthMm}${b.thicknessMm ? ' \u00D7 ' + b.thicknessMm : ''}mm`,\n            variant: {\n              variantId:      b.variantId,\n              priceCents:     b.priceCents,\n              compareAtCents: b.compareAtCents,\n              sku:            b.sku,\n              materialHandle: b.materialHandle,\n              name:           b.name,\n              colour:         b.colour,\n              range:          b.range,\n              url:            b.url,\n              profile:        b.profile,\n              thicknessMm:    b.thicknessMm,\n            }\n          });\n        }\n        // A run deeper than any board this material is sold in. It is left out\n        // of the boards AND out of the price, and it disappears from the\n        // Cutting Plan with it, so the customer sees a drawing and a total that\n        // quietly omit part of their kitchen. A console warning is no use to\n        // them: record it so the popup can say so (Arden, 2026-09-30).\n        if (bill.unpriced.length) {\n          lastUnpriced = { handle, bands: bill.unpriced.slice() };\n          if (typeof console !== 'undefined') {\n            console.warn('[BTK worktop] no board wide enough for', handle, bill.unpriced);\n          }\n        } else if (lastUnpriced && lastUnpriced.handle === handle) {\n          lastUnpriced = null;\n        }\n      }\n\n      // --- the board's matching upstand / splashback ----------------------\n      // Switched on in the Worktops popup: the plan draws it (roomConfig\n      // .splashbacks) and it is bought as its own product, by the length or\n      // the sheet. Priced HERE so it behaves like the worktop - in the running\n      // total, in the popup's footer, and in the basket when the plan is.\n      // Every BOARD material on the plan prices its own (bug sheet row 100):\n      // the plan's, with the part chosen in the popup, and any material set on\n      // part of the plan (Change Worktop), with that worktop's own matching\n      // part (altWorktopPartsFor). Each counts the strips along its own\n      // worktops only.\n      const planHandle = worktopMaterialForSlab();\n      const boardHandles = [...new Set(wtSlabs.filter(s => !s.pastryShelf).map(s => worktopMaterialForSlab(s)).filter(Boolean))]\n        .filter(h => { const m = Catalogue.getWorktopMaterial(h); return m && m.pricingModel !== 'bespoke' && m.pricingModel !== 'slab-tier'; });\n      const sp = roomConfig.splashbacks || {};\n      for (const partHandle of boardHandles) {\n        const isPlan = partHandle === planHandle;\n        const ownSlabs = wtSlabs.filter(s => !s.pastryShelf && worktopMaterialForSlab(s) === partHandle);\n        const parts = isPlan ? worktopParts : altWorktopPartsFor(partHandle);\n        for (const [part, kind] of [['upstand', 'upstand'], ['splashback', 'splashback']]) {\n          const info = parts && parts[part];\n          const slot = sp[part] || {};\n          const planOn = !!slot.enabled && (slot.material || 'match-worktop') === 'match-worktop';\n          // Media Wall rear panels in the worktop are bought as its splashback.\n          const mediaRows = (isPlan && part === 'splashback' && info) ? mediaWorktopRows(mediaWorktopPieces(), info.widthMm) : [];\n          if (!planOn && !mediaRows.length) continue;\n          const strips = planOn ? splashbackStripsFor(ownSlabs)\n            .filter(st => st.kind === kind && st.material === 'match-worktop') : [];\n          if (!info || !info.variantId) {\n            if (strips.length && !isPlan && typeof console !== 'undefined') {\n              console.warn('[BTK worktop] ' + part + ' along ' + partHandle + ' has no matching product (yet) - not charged');\n            }\n            continue;\n          }\n          const count = countStripStock(strips.map(st => ({ lengthMm: st.lengthMm, heightMm: st.heightMm })).concat(mediaRows),\n                                        { lengthMm: info.lengthMm, widthMm: info.widthMm });\n          if (!count.qty) continue;\n          out.push({\n            handle: partHandle, qty: count.qty, part,\n            label: info.variantTitle || `${info.lengthMm} \u00D7 ${info.widthMm}mm`,\n            detail: info.variantTitle || '',\n            variant: {\n              variantId: info.variantId, priceCents: info.priceCents || 0,\n              compareAtCents: info.compareAtCents || null,\n              name: info.name || (part === 'upstand' ? 'Upstand' : 'Splashback'),\n              url: info.url || null, materialHandle: null,\n            }\n          });\n        }\n\n        // --- edging strip for the sawn edges the room can see -------------\n        // Not a toggle and not a tile: a faced board arrives raw on every\n        // sawn edge, so the strip that covers them is part of buying it. It\n        // is charged here, with the boards, so it is in the running total,\n        // the popup footer and the basket without anyone having to remember\n        // it (Arden, 2026-09-30). worktopEdgingRuns explains why no material\n        // whitelist is needed. Each board material edges its own worktops.\n        const edging = edgingStripFor(partHandle);\n        const edgeRuns = worktopEdgingRuns().get(partHandle) || [];\n        if (edging && edging.variantId && edgeRuns.length && edging.lengthMm > 0) {\n          const count = countStripStock(edgingPieces(edgeRuns, edging),\n                                        { lengthMm: edging.lengthMm, widthMm: edgingWidthMm(edging, edgeRuns) });\n          if (count.qty) {\n            out.push({\n              handle: partHandle, qty: count.qty, part: 'edging',\n              label: edging.variantTitle || `${edging.lengthMm}mm`,\n              detail: edging.variantTitle || '',\n              variant: {\n                variantId: edging.variantId, priceCents: edging.priceCents || 0,\n                compareAtCents: edging.compareAtCents || null,\n                name: edging.name || 'Edging strip',\n                url: edging.url || null, materialHandle: null,\n              }\n            });\n          }\n        } else if (edgeRuns.length && typeof console !== 'undefined') {\n          // Louder than charging nothing: this worktop cannot be fitted\n          // without strip, so a missing product is a data gap to fix, not a\n          // saving. The popup says so on screen too (see getEdgingNeed).\n          console.warn('[BTK worktop] ' + edgeRuns.length + ' sawn edge(s) need edging strip but no'\n            + ' strip matched this worktop:', partHandle,\n            '- add a worktop_edging metaobject whose decor_code matches the board SKU');\n        }\n      }\n      return out;\n    } catch (e) { return []; }\n  }\n\n  // ---- Worktop cut list --------------------------------------------------\n  //\n  // Every stock board the plan buys, with the parts nested on it and each edge\n  // classified. Separate from computeWorktopCharges because that emits one\n  // entry per BASKET LINE (a quantity of one board size) whereas the cut list\n  // wants one entry per PHYSICAL board with its own parts on it.\n  function worktopCutList() {\n    try {\n      const wtSlabs = mergeCornerRuns(buildWorktops() || []);\n      const byMaterial = new Map();\n      for (const s of wtSlabs) {\n        const h = worktopMaterialForSlab(s);\n        const m = h && Catalogue.getWorktopMaterial(h);\n        if (!m || m.pricingModel === 'slab-tier') continue;\n        if (!byMaterial.has(h)) byMaterial.set(h, []);\n        byMaterial.get(h).push(s);\n      }\n      addBoardCills(byMaterial);\n      addBoardWaterfalls(byMaterial);\n      const out = [];\n      for (const [handle, group] of byMaterial) {\n        const mat    = Catalogue.getWorktopMaterial(handle);\n        const boards = Catalogue.getWorktopBoards(handle);\n        if (!boards.length) continue;\n        const bill = billBoards(mat, group, boards, {\n          cutouts: cutoutSpans(group),\n          // Rippable = the cut long edge can be finished. Solid material is\n          // finished wherever cut; a SQUARE EDGE board can be ripped and edged\n          // on site (Arden, 2026-09-18). Only a postformed bullnose can't be\n          // recreated on a sawn edge.\n          canRip: mat.construction === 'solid' || mat.profile !== 'rounded',\n          reuseOffcuts: true\n        });\n        for (const b of bill.boards) {\n          // Same wall rule as the Layout: a side buried against a wall is a\n          // cut edge, whatever the board itself arrived with.\n          const bySlab = new Map((bill.cutSlabs || group).map(sl => [sl.id, sl]));\n          out.push({\n            materialName: mat.colour || mat.title, handle, ...b,\n            pieces: (b.pieces || []).map(pc => ({\n              ...pc,\n              edges: wallAdjustedEdges(bySlab.get(pc.slabId), pc.edges),\n            })),\n          });\n        }\n      }\n      // Bespoke slabs: pieces sit side by side ACROSS the slab too, so each\n      // carries a y as well as an x. `kind` marks them as slabs, not boards.\n      const job = bespokeJob(wtSlabs);\n      if (job) {\n        for (const sl of job.bill.slabs) {\n          out.push({\n            materialName: sl.colourName || job.mat.colour || job.mat.title, handle: sl.colourHandle || job.handle, kind: sl.kind,\n            board: { ...sl.slab, construction: 'solid' },\n            usedLengthMm: sl.pieces.reduce((t, pc) => Math.max(t, (pc.x || 0) + pc.lengthMm), 0),\n            usedWidthMm: sl.usedWidthMm, pieces: sl.pieces\n          });\n        }\n      }\n      return out;\n    } catch (e) { return []; }\n  }\n\n  // ---- Edging strip ------------------------------------------------------\n  //\n  // A FACED board - round edge laminate, square edge laminate, bonded FENIX -\n  // is finished only on the edges it arrives with, and raw wherever it is\n  // sawn. Every sawn edge the room can see has to be covered with matching\n  // edging strip, so on these materials the strip is not an optional extra:\n  // it is part of buying the worktop, and how much of it comes from the plan\n  // (Arden, 2026-09-30).\n  //\n  // Driven by the cut list's OWN edge states rather than a list of material\n  // names, which is what makes it exactly right. 'onsite' is only ever\n  // returned for a faced board: solid material (compact laminate, solid\n  // FENIX, solid surface) and real wood come back 'factory' on a sawn edge\n  // because they are finished wherever they are cut, so they ask for no strip\n  // and need no special case here. Change classifyPieceEdges and this follows.\n  function worktopEdgingRuns() {\n    const byHandle = new Map();\n    // Every board material on the plan, each from its own worktops (row 100).\n    const handles = [...new Set((mergeCornerRuns(buildWorktops() || []) || []).map(s => worktopMaterialForSlab(s)).filter(Boolean))];\n    if (!handles.length && worktopMaterialForSlab()) handles.push(worktopMaterialForSlab());\n    for (const h of handles) edgingRunsInto(byHandle, h);\n    return byHandle;\n  }\n  function edgingRunsInto(byHandle, handle) {\n    const mat = handle && Catalogue.getWorktopMaterial(handle);\n    if (!mat || mat.pricingModel === 'bespoke' || mat.pricingModel === 'slab-tier') return byHandle;\n    // The SAME pieces the Worktops popup draws, classified by the SAME\n    // function, so the strip that is charged is exactly what is drawn red.\n    // Counting a cut piece's four sides instead missed every angled return\n    // and stepped end: six red edges on Arden's plan came out as two.\n    const runs = onsiteEdgeRuns(worktopPlanPieces(handle), {\n      room: (room && room.vertices) || [],\n      joints: worktopPlanJoints(handle),\n      solid: mat.construction === 'solid',\n    });\n    if (!runs.length) return byHandle;\n    const boards = Catalogue.getWorktopBoards(handle) || [];\n    const thicknessMm = Number((boards[0] || {}).thicknessMm) || 0;\n    byHandle.set(handle, runs.map(r => ({ lengthMm: r.lengthMm, heightMm: thicknessMm })));\n    return byHandle;\n  }\n\n  // What the Worktops popup needs to SAY about edging, whether or not a strip\n  // product has been found: how many edges, how much strip, and the quantity\n  // of the product when there is one. `resolved` false with edges > 0 is the\n  // case worth shouting about - the worktop needs edging that nothing is\n  // charging for.\n  function worktopEdgingNeed(handle) {\n    const h = handle || worktopMaterialForSlab() || null;\n    const runs = (h && worktopEdgingRuns().get(h)) || [];\n    const info = edgingStripFor(h);\n    const totalMm = runs.reduce((t, r) => t + r.lengthMm, 0);\n    const out = { handle: h, edges: runs.length, totalMm, qty: 0, resolved: false, label: '' };\n    if (!runs.length || !info || !info.variantId || !(info.lengthMm > 0)) return out;\n    out.resolved = true;\n    out.label = info.variantTitle || (info.lengthMm + 'mm');\n    out.qty = countStripStock(edgingPieces(runs, info),\n                              { lengthMm: info.lengthMm, widthMm: edgingWidthMm(info, runs) }).qty;\n    return out;\n  }\n\n  // ---- which strip matches this worktop ----------------------------------\n  //\n  // THE DECOR CODE, which both SKUs already carry: board WS-CL-WT-12-F9669 is\n  // edged with strip FW-WA-LA-ES-2000-26-F9669. FENIX uses a four-letter\n  // colour instead (ES-LA-FNX-1500-43-BEAZ). Never the product title, and not\n  // complementary products either - Search & Discovery has none of the 250\n  // boards linked, so that route resolved nothing (Arden, 2026-09-30).\n  //\n  // The map is the worktop_edging metaobjects, rendered into the page by\n  // sections/btk-kitchen-planner.liquid.\n  // Three shapes in the live data: F9669 / PP5932 (letters + digits), BEAZ\n  // (FENIX's four-letter colour) and a bare 17175 / 4632. The bare form is\n  // accepted so those ranges can be fixed by hand with a worktop_edging entry;\n  // a size that happens to look like one simply finds no entry.\n  const DECOR_RE = /-([A-Z]{1,3}\\d{3,5}|[A-Z]{4}|\\d{4,5})-V\\d+$/;\n  const decorCodeOf = (sku) => {\n    const m = DECOR_RE.exec(String(sku || '').toUpperCase());\n    return m ? m[1] : null;\n  };\n  function edgingStripFor(handle) {\n    // A part set by hand in the popup still wins, so one worktop can be\n    // corrected without touching the data.\n    if (worktopParts.edging && worktopParts.edging.variantId\n        && (!handle || handle === worktopMaterialForSlab())) return worktopParts.edging;\n    if (!handle) return null;\n    const list = (typeof window !== 'undefined' && window.BTK_KP_EDGING) || [];\n    if (!list.length) return null;\n    const codes = new Set();\n    for (const b of (Catalogue.getWorktopBoards(handle) || [])) {\n      const c = decorCodeOf(b.sku);\n      if (c) codes.add(c);\n    }\n    if (!codes.size) return null;\n    // A decor sold in two lengths gives two entries; take the LONGEST, since\n    // fewer lengths means fewer joins in the finished edge.\n    let best = null;\n    for (const e of list) {\n      if (!e || !e.variantId || e.available === false || !codes.has(e.code)) continue;\n      if (!best || (Number(e.lengthMm) || 0) > (Number(best.lengthMm) || 0)) best = e;\n    }\n    if (!best) return null;\n    return {\n      variantId: best.variantId,\n      priceCents: Number(best.priceCents) || 0,\n      compareAtCents: best.compareAtCents == null ? null : Number(best.compareAtCents),\n      lengthMm: Number(best.lengthMm) || 0,\n      widthMm: Number(best.widthMm) || 0,\n      name: best.title || 'Edging strip',\n      variantTitle: best.variantTitle || '',\n      url: best.url || null,\n    };\n  }\n  // A strip covers the board's thickness. 15 strips carry no width in their\n  // SKU, so the metaobject's width is blank for them - fall back to the\n  // board's own thickness, because countStripStock counts NOTHING when the\n  // stock width is zero, and silently charging for no edging is the one\n  // outcome worth guarding against.\n  function edgingWidthMm(info, runs) {\n    const w = Number(info && info.widthMm) || 0;\n    if (w > 0) return w;\n    for (const r of (runs || [])) if (r.heightMm > 0) return r.heightMm;\n    return 0;\n  }\n  // Each run is as tall as the board is thick; where a board carries no\n  // thickness metafield, fall back to the strip's own width.\n  function edgingPieces(runs, info) {\n    return runs.map(r => ({\n      lengthMm: r.lengthMm, heightMm: r.heightMm || Number(info.widthMm) || 0,\n    }));\n  }\n\n  // Edge colours - Arden's key (corrected 2026-09-30, the note here had\n  // factory and on-site the wrong way round): BLUE factory finished, RED\n  // finished on site by the installer, BLACK raw cut edge that is never seen,\n  // GREEN a mason's mitre. A joint between two pieces of one long run is none\n  // of those, so it reads as a grey dashed line.\n  // What a part is when it is not a worktop, for its label in the cut list.\n  const CUTLIST_PART = { cill: 'Window cill', upstand: 'Upstand', splashback: 'Splashback', 'hob-splashback': 'Hob splashback',\n                         waterfall: 'Waterfall side' };\n  const CUTLIST_EDGE = {\n    factory: { colour: '#1560d1', label: 'Factory finished edge' },\n    onsite:  { colour: '#d11', label: 'Edged on site by installer' },\n    // Solid material only. It has no facing to protect and takes no edging\n    // strip, so every edge the room can see is worked and polished in place.\n    // Purple, because the four colours already in use are spoken for and this\n    // has to be told apart from the red it replaces (Arden, 2026-09-30).\n    polished: { colour: '#7a3aa8', label: 'Polished on site by installer' },\n    // Made to measure only: shaped and polished to the chosen profile in the\n    // workshop, before it is delivered. Charged per metre, so it is its own\n    // state rather than borrowing the board's 'factory'.\n    profiled: { colour: '#0f7b8a', label: 'Shaped and polished to your edge profile' },\n    raw:     { colour: '#111', label: 'Raw cut edge (hidden)' },\n    joint:   { colour: '#9a9a9a', label: 'Joint between parts', dash: '9 7' },\n    mitre:   { colour: '#2d7a3a', label: \"Mason's mitre (butt and scribe)\" }\n  };\n\n  // One cut piece drawn to scale: its REAL outline (a curved end, a rounded\n  // corner, an L-shaped island) filled, then every edge of that outline stroked\n  // in its edge colour. Shared by the popup and the compact list under the mini\n  // plan so the two can never draw a piece differently.\n  //\n  // Each outline segment is classified by WHERE it lies, in piece-local mm:\n  //   along y = 0            front edge      pc.edges.front\n  //   along y = back         back edge       pc.edges.back\n  //   along x = 0            left end        pc.edges.left  (joint if interior)\n  //   along x = length       right end       pc.edges.right (joint if interior)\n  //   anything else          a CURVE (or an L-shaped step). A curve is always a\n  //                          fresh cut, so it's finished on site on laminate and\n  //                          factory quality on solid - the same logic as the\n  //                          ripping rule, not a new one.\n  // With no outline (older data, or an odd frame) it falls back to a rectangle,\n  // which classifies to exactly the four straight edges it always had.\n  function cutListPieceSVG(pc, board, PX, strokeW, originPx) {\n    const e = pc.edges || {};\n    const curveState = (board && board.construction === 'solid') ? 'factory' : 'onsite';\n    const L = pc.lengthMm;\n    const rect = [{ x: 0, y: 0 }, { x: L, y: 0 },\n                  { x: L, y: Math.min(pc.depthMm, board.widthMm) },\n                  { x: 0, y: Math.min(pc.depthMm, board.widthMm) }];\n    const pts = (Array.isArray(pc.outline) && pc.outline.length >= 3) ? pc.outline : rect;\n    let backY = 0;\n    for (const q of pts) if (q.y > backY) backY = q.y;\n    const X = (x) => (originPx + x * PX).toFixed(1);\n    const Y = (y) => (y * PX).toFixed(1);\n    const TOL = 0.5;                               // mm\n    const on = (a, b) => Math.abs(a - b) < TOL;\n    let edges = '';\n    for (let i = 0; i < pts.length; i++) {\n      const P = pts[i], Q = pts[(i + 1) % pts.length];\n      let st;\n      // BOTH sides of a mason's mitre are the mitre. The male side is the\n      // piece's end (e.left / e.right already say 'mitre'); the female side is\n      // a NOTCH in the long edge of the piece it butts into, which is neither\n      // an end nor the full front or back - it hugs one face for the depth of\n      // the rolled edge. That is the test: a segment whose ends both sit\n      // within the mitre's own depth of the SAME face is part of it. Without\n      // this the female half drew black and its 45 drew red (Arden,\n      // 2026-09-30).\n      // The point itself says so: mitreShapes marks the point each mitre\n      // segment starts at, and that mark survives the piece being re-framed,\n      // split across boards or cut into diagonal strips - which a test on the\n      // shape cannot (Arden, 2026-09-30).\n      // The segment was classified in the ROOM and the answer written onto\n      // this point; a piece lying on a slab cannot work it out again.\n      if (P.k)                                      st = P.k;\n      else if (P.m)                                 st = 'mitre';\n      else if (on(P.y, 0) && on(Q.y, 0))            st = e.front;\n      else if (on(P.y, backY) && on(Q.y, backY))    st = e.back;\n      else if (on(P.x, 0) && on(Q.x, 0))            st = e.left;\n      else if (on(P.x, L) && on(Q.x, L))            st = e.right;\n      // Anything else is square to nothing: the 45 of a mason's mitre, the\n      // sloped end of a diagonal strip, a splay's short side. It belongs to\n      // the END it is nearest, which already carries the right answer -\n      // 'mitre' where one was cut, 'raw' where it is buried. Calling every\n      // such segment a mitre painted a diagonal strip green all round and\n      // disagreed with the Layout (Arden, 2026-09-30).\n      else st = ((P.x + Q.x) / 2 < L / 2) ? e.left : e.right;\n      const c = (CUTLIST_EDGE[st] || CUTLIST_EDGE.raw).colour;\n      const dash = st === 'joint' ? ` stroke-dasharray=\"${CUTLIST_EDGE.joint.dash}\"` : '';\n      edges += `<line x1=\"${X(P.x)}\" y1=\"${Y(P.y)}\" x2=\"${X(Q.x)}\" y2=\"${Y(Q.y)}\" `\n             + `stroke=\"${c}\" stroke-width=\"${strokeW}\" stroke-linecap=\"round\"${dash}/>`;\n    }\n    const d = 'M' + pts.map(q => X(q.x) + ',' + Y(q.y)).join(' L') + ' Z';\n    return `<path class=\"btk-kp-cutlist-shape\" d=\"${d}\" fill=\"rgba(45,122,58,0.10)\" stroke=\"none\"/>${edges}`;\n  }\n\n  // Warning panel for the cut list popup: shown ONLY when the plan's worktop is\n  // a bullnose (postformed) laminate AND something makes it curve. Square edge\n  // and solid worktops take curves properly, so they never see it. Same test\n  // and same wording as the dialog, so the popup can't disagree with it.\n  function cutListWarningHTML(handle) {\n    if (!isPostformedMaterial(handle) || !planHasCurvedWorktop()) return '';\n    return `<div class=\"btk-kp-cutlist-warning\" role=\"note\">` +\n             `<div class=\"btk-kp-warnings-head\">${escForKp(BULLNOSE_CURVE_TITLE)}</div>` +\n             `<p>${escForKp(BULLNOSE_CURVE_TEXT)}</p>` +\n           `</div>`;\n  }\n\n  // ---- Bespoke worktops: a PLAN, not a nesting diagram ----------------------\n  // A made-to-measure job goes to the fabricator as shapes and sizes; they\n  // optimise the slabs themselves, so board nesting would be noise here\n  // (Arden 2026-09-20). Two panes behind a toggle: Worktop Plan and Worktop\n  // Details, the same spec that travels to the supplier with the order.\n  let wtPopupView = 'plan';\n\n  function bespokeWorktopPlan() {\n    try {\n      const all = mergeCornerRuns(buildWorktops() || []);\n      const job = bespokeJob(all);\n      if (!job) return null;\n      const hs = new Set((job.colours || [{ handle: job.handle }]).map(c => c.handle));\n      const mine = all.filter(s => hs.has(worktopMaterialForSlab(s)));\n      return mine.length ? { job, slabs: mine } : null;\n    } catch (e) { return null; }\n  }\n\n  // A worktop's real size: its own pieces, joined along the run.\n  function bespokePieceSize(job, slab) {\n    const pcs = ((job && job.bill && job.bill.pieces) || [])\n      .filter(p => String(p.slabId) === String(slab.id));\n    if (!pcs.length) return null;\n    const len = Math.round(pcs.reduce((t, p) => t + (p.lengthMm || 0), 0));\n    const dep = Math.round(pcs.reduce((t, p) => Math.max(t, p.depthMm || 0), 0));\n    return (len && dep) ? [len, dep] : null;\n  }\n\n  function bespokePlanSVG(d) {\n    let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;\n    for (const s of d.slabs) for (const p of (s.polygon || [])) {\n      minX = Math.min(minX, p.x); maxX = Math.max(maxX, p.x);\n      minY = Math.min(minY, p.y); maxY = Math.max(maxY, p.y);\n    }\n    if (!isFinite(minX)) return '<p class=\"btk-kp-panel-note\">No worktops on the plan yet.</p>';\n    const span = Math.max(maxX - minX, maxY - minY);\n    const pad = span * 0.12 + 200;\n    const fs = Math.max(70, span * 0.032);\n    const vb = [minX - pad, minY - pad, (maxX - minX) + pad * 2, (maxY - minY) + pad * 2]\n      .map(v => v.toFixed(0)).join(' ');\n    const shapes = d.slabs.map((s, i) => {\n      const pts = s.polygon || [];\n      if (pts.length < 3) return '';\n      const xs = pts.map(p => p.x), ys = pts.map(p => p.y);\n      const cx = xs.reduce((t, v) => t + v, 0) / xs.length;\n      const cy = ys.reduce((t, v) => t + v, 0) / ys.length;\n      const bw = Math.round(Math.max.apply(null, xs) - Math.min.apply(null, xs));\n      const bh = Math.round(Math.max.apply(null, ys) - Math.min.apply(null, ys));\n      const dims = bespokePieceSize(d.job, s) || (bw >= bh ? [bw, bh] : [bh, bw]);\n      return `<g>\n          <polygon points=\"${pts.map(p => p.x.toFixed(0) + ',' + p.y.toFixed(0)).join(' ')}\"\n                   fill=\"#f4f4f1\" stroke=\"#111\" stroke-width=\"${Math.max(8, fs * 0.08).toFixed(0)}\"/>\n          <text x=\"${cx.toFixed(0)}\" y=\"${(cy - fs * 0.1).toFixed(0)}\" text-anchor=\"middle\"\n                font-size=\"${fs.toFixed(0)}\" font-weight=\"800\" fill=\"#111\">${i + 1}</text>\n          <text x=\"${cx.toFixed(0)}\" y=\"${(cy + fs).toFixed(0)}\" text-anchor=\"middle\"\n                font-size=\"${(fs * 0.74).toFixed(0)}\" fill=\"#333\">${dims[0]} &#215; ${dims[1]}mm</text>\n        </g>`;\n    }).join('');\n    return `<svg viewBox=\"${vb}\" width=\"100%\" style=\"max-height:60vh;overflow:visible;\">${shapes}</svg>`;\n  }\n\n  function bespokeDetailsHTML(d) {\n    const m = Catalogue.getWorktopMaterial(d.job.handle) || {};\n    const tz = d.job.templating || {};\n    const zone = tz.covered !== false ? 'Zone ' + String(tz.zone || 'a').toUpperCase()\n      : d.job.quoted ? 'Priced for your postcode'\n      : 'Outside our standard area, price on request';\n    const spec = [\n      ['Material', [m.colour || m.title, m.range, m.type].filter(Boolean).join(' \u00B7 ')],\n      ['Thickness', d.job.thicknessMm ? d.job.thicknessMm + 'mm' : ''],\n      ['Worktop pieces', String(d.slabs.length)],\n      ['Slabs allowed for', `${d.job.bill.fullCount} full, ${d.job.bill.halfCount} half`],\n      ['Templating zone', zone],\n    ].filter(r => r[1]);\n    const sizes = d.slabs.map((s, i) => {\n      const dims = bespokePieceSize(d.job, s);\n      return `<tr><td>Worktop ${i + 1}</td><td>${dims ? dims[0] + ' \u00D7 ' + dims[1] + 'mm' : '-'}</td></tr>`;\n    }).join('');\n    // Every row carries a count, including the single ones: a blank cell reads\n    // as missing data rather than \"one of these\" (Arden 2026-09-20).\n    const work = (d.job.priced.lines || [])\n      .map(l => `<tr><td>${escForKp(String(l.name).replace(/^Bespoke Worktop - /, ''))}</td>`\n              + `<td>\u00D7 ${Math.max(1, Number(l.qty) || 1)}</td></tr>`).join('');\n    // Each heading + table is one block so the two columns can only break\n    // BETWEEN sections, never through a table (Arden: use the width, lose the\n    // scroll).\n    const block = (title, body) => `<section class=\"btk-kp-cutlist-block\">\n        <h3>${title}</h3><table class=\"btk-kp-cutlist-spec\">${body}</table></section>`;\n    return `<div class=\"btk-kp-cutlist-details\">\n        ${block('Worktop details', spec.map(r =>\n          `<tr><td>${escForKp(r[0])}</td><td>${escForKp(String(r[1]))}</td></tr>`).join(''))}\n        ${block('Sizes from your plan (approximate)', sizes)}\n        ${work ? block('Manufacture, template &amp; install', work) : ''}\n      </div>`;\n  }\n\n  function renderBespokeWorktopPopup(d, host) {\n    // The popup is titled for what it shows: bespoke worktops are never cut\n    // from boards, so \"Cut List\" would be wrong on every surface.\n    const title = document.getElementById('btk-kp-cutlist-title');\n    if (title) title.textContent = 'Worktop Plan';\n    // Two plain menu buttons, not a segmented toggle (Arden 2026-09-20). Same\n    // component as every other left-hand menu in the planner.\n    const tab = (id, label, icon) => `<button type=\"button\" class=\"btk-kp-action-btn${\n      wtPopupView === id ? ' is-active' : ''}\" data-btk-kp-wtview=\"${id}\" aria-pressed=\"${wtPopupView === id}\">\n        <span class=\"btk-kp-action-btn-icon\" aria-hidden=\"true\">${icon}</span>\n        <span class=\"btk-kp-action-btn-label\">${label}</span>\n      </button>`;\n    const ICON_PLAN = '<svg viewBox=\"0 0 24 24\" width=\"16\" height=\"16\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\">'\n      + '<rect x=\"3\" y=\"3\" width=\"18\" height=\"18\" rx=\"2\"/><path d=\"M3 9h18M9 21V9\"/></svg>';\n    const ICON_LIST = '<svg viewBox=\"0 0 24 24\" width=\"16\" height=\"16\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\">'\n      + '<path d=\"M8 6h13M8 12h13M8 18h13M3 6h.01M3 12h.01M3 18h.01\"/></svg>';\n    host.innerHTML = `\n      <div class=\"btk-kp-cutlist-wrap\">\n        <aside class=\"btk-kp-cutlist-rail\">\n          <div class=\"btk-kp-cutlist-views\">\n            ${tab('plan', 'Worktop Plan', ICON_PLAN)}${tab('details', 'Worktop Details', ICON_LIST)}\n          </div>\n          <div class=\"btk-kp-cutlist-terms\">\n            <strong>For pricing only</strong>\n            <p>Sizes are taken from your plan so we can price the job.</p>\n            <p>Your worktops are made from a template taken on site once the\n               units are fitted, and the fabricator sets the final sizes.</p>\n          </div>\n        </aside>\n        <div class=\"btk-kp-cutlist-boards\">${\n          wtPopupView === 'details' ? bespokeDetailsHTML(d) : bespokePlanSVG(d)}</div>\n      </div>`;\n    host.querySelectorAll('[data-btk-kp-wtview]').forEach(b => {\n      b.addEventListener('click', () => {\n        wtPopupView = b.dataset.btkKpWtview === 'details' ? 'details' : 'plan';\n        renderWorktopCutList();\n      });\n    });\n  }\n\n  function renderWorktopCutList() {\n    const host = document.querySelector('[data-btk-kp-cutlist-body]');\n    if (!host) return;\n    const bespoke = bespokeWorktopPlan();\n    if (bespoke) return renderBespokeWorktopPopup(bespoke, host);\n    const list = worktopCutList();\n    if (!list.length) {\n      host.innerHTML = '<p class=\"btk-kp-panel-note btk-kp-panel-note--muted\">'\n        + 'No worktops in the plan yet, or the chosen material is a templated '\n        + 'quartz / ceramic (priced by slab, not cut from boards).</p>';\n      return;\n    }\n    const PX_PER_MM = 0.2;          // 4100mm board \u2248 820px\n    const EW        = 4;            // edge stroke width\n    const boardsHTML = list.map((bd, i) => {\n      const L = bd.board.lengthMm, D = bd.board.widthMm;\n      const w = Math.round(L * PX_PER_MM), h = Math.round(D * PX_PER_MM);\n      const parts = bd.pieces.map(pc => {\n        const px = pc.x * PX_PER_MM;\n        const pw = pc.lengthMm * PX_PER_MM;\n        const ph = Math.min(pc.depthMm, D) * PX_PER_MM;\n        const label = [CUTLIST_PART[pc.part] || '', pc.joinCount > 1 ? `${pc.joinIndex + 1}/${pc.joinCount}` : '']\n          .filter(Boolean).join(' \u00B7 ');\n        // The POPUP is a read-only diagram. Finding a part in the plan lives in\n        // the compact cut list under the mini plan (lineCutListHTML), so these\n        // carry no click hook and don't look clickable.\n        const py = (pc.y || 0) * PX_PER_MM;   // bespoke slabs nest across the width too\n        return `<g class=\"btk-kp-cutlist-part--static\" transform=\"translate(0 ${py.toFixed(1)})\">\n            ${cutListPieceSVG(pc, bd.board, PX_PER_MM, EW, px)}\n            <text x=\"${(px + pw / 2).toFixed(1)}\" y=\"${(ph / 2 + 4).toFixed(1)}\" text-anchor=\"middle\"\n                  font-size=\"11\" fill=\"#333\">${Math.round(pc.lengthMm)}${label ? ' \u00B7 ' + label : ''}</text>\n          </g>`;\n      }).join('');\n      return `<div class=\"btk-kp-cutlist-board\">\n          <div class=\"btk-kp-cutlist-board-head\">\n            <strong>${bd.kind ? (bd.kind === 'half' ? 'Half slab' : 'Full slab') : 'Board'} ${i + 1}</strong> \u00B7 ${escForKp(bd.materialName)} \u00B7\n            ${L} \u00D7 ${D}${bd.board.thicknessMm ? ' \u00D7 ' + bd.board.thicknessMm : ''}mm \u00B7\n            used ${Math.round(bd.usedLengthMm)}mm\n          </div>\n          <svg viewBox=\"0 0 ${w} ${h}\" width=\"100%\" height=\"${h}\" style=\"max-width:${w}px;overflow:visible;\">\n            <rect x=\"0\" y=\"0\" width=\"${w}\" height=\"${h}\" fill=\"rgba(0,0,0,0.04)\" stroke=\"rgba(0,0,0,0.15)\" stroke-dasharray=\"4 3\"/>\n            ${parts}\n          </svg>\n        </div>`;\n    }).join('');\n    const keyHTML = Object.keys(CUTLIST_EDGE).map(k => {\n      const c = CUTLIST_EDGE[k];\n      const dash = k === 'joint' ? 'border-top-style:dashed;' : '';\n      return `<li><span style=\"display:inline-block;width:26px;border-top:4px solid ${c.colour};${dash}\n                   vertical-align:middle;margin-right:8px;\"></span>${c.label}</li>`;\n    }).join('');\n    // Identify the material at the TOP of the left rail, key at the BOTTOM,\n    // boards on the right - so the eye lands on \"which worktop is this\" first.\n    const mat  = Catalogue.getWorktopMaterial(list[0].handle);\n    const sw   = mat && mat.swatchUrl;\n    const meta = mat ? [mat.range, mat.type].filter(Boolean).join(' \u00B7 ') : '';\n    host.innerHTML = `\n      <div class=\"btk-kp-cutlist-wrap\">\n        <aside class=\"btk-kp-cutlist-rail\">\n          <div class=\"btk-kp-cutlist-material\">\n            ${sw ? `<img src=\"${escForKp(sw)}\" alt=\"\">` : '<div class=\"btk-kp-cutlist-material-noimg\"></div>'}\n            <div class=\"btk-kp-cutlist-material-text\">\n              <div class=\"btk-kp-cutlist-material-name\">${escForKp(mat ? (mat.colour || mat.title) : list[0].materialName)}</div>\n              ${meta ? `<div class=\"btk-kp-cutlist-material-meta\">${escForKp(meta)}</div>` : ''}\n            </div>\n          </div>\n          ${cutListWarningHTML(list[0].handle)}\n          <div class=\"btk-kp-cutlist-key\">\n            <h3>Key</h3>\n            <ul>${keyHTML}</ul>\n            <div class=\"btk-kp-cutlist-terms\">\n              <strong>For pricing only</strong>\n              <p>Shows how your worktops nest onto boards to work out the price.\n                 Not a cutting list.</p>\n              <p>Final sizes are set on site from the installer&rsquo;s survey.</p>\n            </div>\n          </div>\n        </aside>\n        <div class=\"btk-kp-cutlist-boards\">${boardsHTML}</div>\n      </div>`;\n\n  }\n\n  // Compact cut list for ONE basket line, drawn in the details panel under the\n  // mini-3D when a worktop line is selected. No key and no dimensions here -\n  // the popup carries those; this is purely \"which bits are on this board\",\n  // clickable, and small enough not to bury the 3D.\n  function lineCutListHTML(p) {\n    try {\n      // A cut list belongs ONLY to a worktop line. The basket tells us outright\n      // via the line's quote group - matching on the product TITLE was fragile\n      // (the line carries the full product title, the cut list the colour) and\n      // failed silently, drawing nothing at all.\n      if (!p) return '';\n      if (p.cabId || p.epFaces) return '';\n      const group = String(p.group || '').toLowerCase();\n      if (group !== 'worktops') return '';\n      const list = worktopCutList();\n      if (!list.length) return '';\n      // Resolve by VARIANT ID ONLY - the line's own board variant, which is\n      // exact and picks out this line's board size. No fallback to matching\n      // the product title, and no \"there's only one material so it must be\n      // that\" guess: both are the easy route that has already produced wrong\n      // answers. If the id doesn't resolve, showing nothing is correct.\n      if (!p.variantId) return '';\n      const mine = list.filter(b => String(b.board.variantId) === String(p.variantId));\n      if (!mine.length) return '';\n      const PX = 0.11;                        // half the popup's scale\n      const svgs = mine.map((bd, i) => {\n        const w = Math.round(bd.board.lengthMm * PX), h = Math.round(bd.board.widthMm * PX);\n        const parts = bd.pieces.map(pc => {\n          const wt = pc.slabId || '';\n          return `<g class=\"btk-kp-cutlist-part\" data-btk-kp-cutlist-focus=\"${escForKp(wt)}\"\n                     transform=\"translate(0 ${((pc.y || 0) * PX).toFixed(1)})\"\n                     style=\"cursor:${wt ? 'pointer' : 'default'};\">\n              ${cutListPieceSVG(pc, bd.board, PX, 3, pc.x * PX)}\n            </g>`;\n        }).join('');\n        return `<svg viewBox=\"0 0 ${w} ${h}\" width=\"${w}\" height=\"${h}\" style=\"max-width:100%;\">\n            <rect x=\"0\" y=\"0\" width=\"${w}\" height=\"${h}\" fill=\"rgba(0,0,0,0.04)\" stroke=\"rgba(0,0,0,0.15)\" stroke-dasharray=\"3 2\"/>\n            ${parts}\n          </svg>`;\n      }).join('');\n      return `<div class=\"btk-kp-cutlist-mini\">${svgs}</div>`;\n    } catch (e) { return ''; }\n  }\n\n  // Shared click wiring - the popup and the mini panel both use it.\n  function bindCutListFocus(scope) {\n    if (!scope) return;\n    scope.querySelectorAll('[data-btk-kp-cutlist-focus]').forEach(g => {\n      const worktopId = g.dataset.btkKpCutlistFocus;\n      if (!worktopId) return;\n      g.addEventListener('click', (e) => {\n        // A part is a piece of ONE worktop slab, so highlight that worktop -\n        // not the first cabinet under it. selectItem drives the 2D + 3D\n        // highlight (applySelectionVisual); in 3D the camera then frames the\n        // slab. Deliberately NOT routed through __btkPlannerLineSelected: that\n        // clears the details panel and spins to a unit, which is exactly what\n        // made the camera jump to a single cabinet.\n        e.stopPropagation();\n        try { selectItem({ kind: 'worktop', worktopId }); } catch (err) {}\n        if (viewMode !== '2d') { try { handle3D?.focusOnWorktop?.(worktopId); } catch (err) {} }\n        // Show which part was picked, in whichever cut list was clicked.\n        scope.querySelectorAll('.btk-kp-cutlist-part.is-picked').forEach(x => x.classList.remove('is-picked'));\n        g.classList.add('is-picked');\n      });\n    });\n  }\n\n  // Opened by the basket's Worktops section header button (the basket is a\n  // separate module, so it reaches the planner through this).\n  window.BTKWorktopCutList = {\n    open() {\n      renderWorktopCutList();\n      const popup = document.querySelector('[data-btk-kp-popup=\"worktop-cutlist\"]');\n      if (popup) popup.hidden = false;\n    },\n    hasBoards() { return worktopCutList().length > 0; },\n    // Bespoke worktops are not cut from boards, so the basket button says what\n    // the popup actually shows (Arden 2026-09-20).\n    label() { return bespokeWorktopPlan() ? 'Worktop Plan' : 'Cut List'; }\n  };\n\n  // Trims (plinth / cornice / pelmet) total in GBP, using the SAME charges the\n  // basket builds from, so header and basket agree line-for-line.\n  function computeTrimsTotalGbp() {\n    try {\n      let t = 0;\n      for (const ch of computeTrimCharges()) {\n        const cents = (ch.product && ch.product.priceCents) || 0;\n        t += (cents / 100) * (ch.qty || 1);\n      }\n      return t;\n    } catch (e) { return 0; }\n  }\n  // Handles total in GBP - mirrors the basket's handle accumulation (aggregated\n  // per product, skipping handleless styles) so the figures line up.\n  // ---- Automatic items (Arden, 2026-10-22) ---------------------------------\n  // What the planner basket adds by itself, from the planner_auto_item\n  // metaobjects (window.BTK_KP_AUTO_ITEMS, sections/btk-kitchen-planner.liquid):\n  // touch up paint for a painted kitchen, the fittings pack for the units, a\n  // fitting / joining kit with a worktop. Charged like any line; a customer\n  // can take one out in Exclude Items from Quote, which warns them first.\n  //\n  //   trigger 'Kitchen units'        - the units on the quote\n  //   trigger 'Painted door colours' - units in a range that has one of the\n  //                                    rule's products (each product names its\n  //                                    range), one line per door colour\n  //   trigger 'Worktop material'     - the worktop types listed, counted in\n  //                                    pieces as cut (the cut list) and joints\n  //                                    (pieces - 1 on each worktop: a run cut\n  //                                    in two, an L, a U's corners)\n  //\n  // Returns [{ key, rule, product, qty, group, colour, style, detail }]; key is\n  // the basket line's id without its 'q:', so an exclusion holds across rebuilds.\n  function computeAutoItemCharges() {\n    const rules = (typeof window !== 'undefined' && Array.isArray(window.BTK_KP_AUTO_ITEMS)) ? window.BTK_KP_AUTO_ITEMS : [];\n    if (!rules.length) return [];\n    const units = (cabinets || []).filter(c => c && c.variantId && !c.endPanelUnit && !c.endPanelFiller\n      && !c.excludeFromQuote && !c.freestandingAppliance);\n    // Worktop pieces and joints per worktop TYPE, only for materials actually\n    // on the quote (a worktop bought elsewhere brings no kit).\n    let tally = null;\n    const worktopTally = () => {\n      if (tally) return tally;\n      tally = {};\n      try {\n        const ex = quoteExcludedLines || {};\n        const charged = new Set(computeWorktopCharges().map(ch => ch.handle).filter(h => h\n          && !Object.keys(ex).some(k => k.indexOf('q:wt:' + h + ':') === 0)));\n        const perWorktop = new Map();   // type -> Map(worktop -> pieces)\n        for (const b of worktopCutList()) {\n          if (b.kind || !charged.has(b.handle)) continue;   // bespoke slabs: no kit rules there\n          const m = Catalogue.getWorktopMaterial(b.handle);\n          const type = m && m.type;\n          if (!type) continue;\n          if (!perWorktop.has(type)) perWorktop.set(type, new Map());\n          const per = perWorktop.get(type);\n          for (const pc of (b.pieces || [])) {\n            if (pc.part === 'cill') continue;   // window boards are not worktops\n            const wt = String(pc.slabId || '').split('#')[0] || ('?' + per.size);\n            per.set(wt, (per.get(wt) || 0) + 1);\n          }\n        }\n        // Joints = pieces less one per WORKTOP, where a worktop is every run\n        // touching another of the same type - two runs meeting at a corner are\n        // one worktop with a joint, even when they are drawn as two.\n        const boxes = new Map();\n        for (const sl of mergeCornerRuns(buildWorktops() || [])) {\n          const xs = (sl.polygon || []).map(p => p.x), ys = (sl.polygon || []).map(p => p.y);\n          if (xs.length) boxes.set(String(sl.id).split('#')[0], { x0: Math.min(...xs), x1: Math.max(...xs), y0: Math.min(...ys), y1: Math.max(...ys) });\n        }\n        const touch = (A, B) => A && B && A.x0 <= B.x1 + 5 && B.x0 <= A.x1 + 5 && A.y0 <= B.y1 + 5 && B.y0 <= A.y1 + 5;\n        for (const [type, per] of perWorktop) {\n          const ids = [...per.keys()];\n          const root = new Map(ids.map(i => [i, i]));\n          const find = (i) => { while (root.get(i) !== i) i = root.get(i); return i; };\n          for (let i = 0; i < ids.length; i++) for (let j = i + 1; j < ids.length; j++) {\n            if (touch(boxes.get(ids[i]), boxes.get(ids[j]))) root.set(find(ids[i]), find(ids[j]));\n          }\n          let pieces = 0;\n          for (const n of per.values()) pieces += n;\n          const worktops = new Set(ids.map(find)).size;\n          tally[type] = { pieces, joints: Math.max(0, pieces - worktops) };\n        }\n      } catch (e) { /* no worktops yet */ }\n      return tally;\n    };\n    const out = [];\n    for (const r of rules) {\n      const prods = (r.products || []).filter(p => p && p.variantId);\n      if (!prods.length) continue;\n      const per = Math.max(1, Number(r.perN) || 1);\n      const push = (p, qty, extra) => {\n        if (!(qty > 0)) return;\n        const x = extra || {};\n        out.push({ key: 'auto:' + r.key + ':' + p.handle + (x.colour ? ':' + x.colour : ''),\n                   rule: r, product: p, qty, group: x.group || 'other',\n                   colour: x.colour || null, style: x.style || null, detail: x.detail || '' });\n      };\n      if (r.trigger === 'Kitchen units') {\n        if (!units.length) continue;\n        push(prods[0], r.countBy === 'Per order' ? 1 : Math.ceil(units.length / per),\n             { detail: 'For ' + units.length + ' unit' + (units.length === 1 ? '' : 's') });\n      } else if (r.trigger === 'Painted door colours') {\n        // A range is painted when the rule has a product for it.\n        const seen = new Map();   // style|colour -> { product, colour, style }\n        for (const c of units) {\n          const style = c.kitchenStyleId || kitchenStyleId || null;\n          const p = style && prods.find(x => x.style === style);\n          const colour = c.doorColourHandle || globalDoorColourHandle || null;\n          if (!p || !colour) continue;\n          const k = style + '|' + (r.countBy === 'Per order' ? '' : colour);\n          if (!seen.has(k)) seen.set(k, { product: p, colour, style });\n        }\n        for (const s of seen.values()) push(s.product, 1, { colour: s.colour, style: s.style });\n      } else if (r.trigger === 'Worktop material') {\n        const t = worktopTally();\n        let pieces = 0, joints = 0;\n        for (const type of (r.worktopTypes || [])) {\n          if (t[type]) { pieces += t[type].pieces; joints += t[type].joints; }\n        }\n        if (!pieces) continue;\n        const qty = r.countBy === 'Per worktop piece' ? pieces\n          : r.countBy === 'Per N joints' ? Math.ceil(joints / per)\n          : 1;\n        const detail = r.countBy === 'Per N joints'\n          ? (joints + ' joint' + (joints === 1 ? '' : 's'))\n          : (pieces + ' worktop piece' + (pieces === 1 ? '' : 's'));\n        push(prods[0], qty, { group: 'worktops', detail });\n      } else if (r.trigger === 'Unit types') {\n        // Units that bring a kit of their own (Planner Bugs row 351): each\n        // Frame Shelf Unit brings its H\u00E4fele frame set. With one product per\n        // width, a unit takes the one whose title has its width (\"600mm ...\",\n        // \"900mm ...\"); a single product suits every width.\n        const want = new Set(r.unitTypes || []);\n        const byWidth = new Map();\n        for (const c of units) {\n          if (!want.has(c.unitTypeId)) continue;\n          const w = Math.round(c.widthMm || 0);\n          byWidth.set(w, (byWidth.get(w) || 0) + 1);\n        }\n        const widthOf = (p) => { const m = /(\\d+)\\s*mm/i.exec(p.title || ''); return m ? +m[1] : null; };\n        for (const [w, n] of byWidth) {\n          const p = prods.length === 1 ? prods[0] : prods.find(x => widthOf(x) === w);\n          if (!p) continue;\n          push(p, r.countBy === 'Per order' ? 1 : n,\n               { detail: 'For ' + n + ' unit' + (n === 1 ? '' : 's') });\n        }\n      }\n    }\n    return out;\n  }\n  // Their part of the running total - leaving out any the customer excluded,\n  // as the basket does. `compare` adds the RRP uplift instead.\n  // Furniture bought as a product (a bar stool): one line per product, however\n  // many are on the plan.\n  function computeFurnitureCharges() {\n    const byProduct = new Map();\n    for (const f of furnitureItems) {\n      if (!f.productHandle) continue;\n      const product = (Catalogue.getFurniture?.() || []).find(e => e.id === f.productHandle);\n      if (!product || !product.variantId) continue;\n      const ch = byProduct.get(f.productHandle) || { key: 'fu:' + f.productHandle, product, qty: 0 };\n      ch.qty++;\n      byProduct.set(f.productHandle, ch);\n    }\n    return [...byProduct.values()];\n  }\n  function computeFurnitureTotalGbp(compare) {\n    const ex = quoteExcludedLines || {};\n    let t = 0;\n    for (const ch of computeFurnitureCharges()) {\n      if (ex['q:' + ch.key]) continue;\n      const p = ch.product, sale = p.priceCents || 0;\n      if (compare) { const cmp = p.compareAtCents || 0; if (cmp > sale) t += ((cmp - sale) / 100) * ch.qty; }\n      else t += (sale / 100) * ch.qty;\n    }\n    return t;\n  }\n\n  function computeAutoItemsTotalGbp(compare) {\n    const ex = quoteExcludedLines || {};\n    let t = 0;\n    for (const ch of computeAutoItemCharges()) {\n      if (ex['q:' + ch.key]) continue;\n      const p = ch.product, sale = p.priceCents || 0;\n      if (compare) { const cmp = p.compareAtCents || 0; if (cmp > sale) t += ((cmp - sale) / 100) * ch.qty; }\n      else t += (sale / 100) * ch.qty;\n    }\n    return t;\n  }\n\n  function computeHandlesTotalGbp() {\n   try {\n    const PAN_MIN = 200;\n    const norm = (t) => String(t || '').toLowerCase().replace(/[\\s_-]/g, '');\n    const acc = new Map();\n    for (const c of cabinets) {\n      if (!c || c.excludeFromQuote || !c.variantId) continue;\n      if (c.carcaseOnly) continue;   // no fronts, so no handles\n      const ks = Catalogue.getKitchenStyle?.(c.kitchenStyleId);\n      if ((Catalogue.isStyleHandleless?.(ks)) ?? ks?.doorGeometry?.hasIntegratedHandle) continue;\n      const openings = (c.cutoutSchema && c.cutoutSchema.openings) || [];\n      // A base pull-out's door front takes a drawer handle (pullOutFrontIsDrawer).\n      const _poDrawer = !!(Catalogue.pullOutFrontIsDrawer && Catalogue.pullOutFrontIsDrawer(c.cutoutSchema));\n      for (const op of openings) {\n        if (op.handle === false) continue;\n        // An L-shape's bi-fold pair takes ONE handle, on the leaf not hinged\n        // to the carcase (opening 1) - matches the 3D (Arden, 2026-10-26).\n        if (c.lShapeUnit && op === openings[0] && openings.length > 1) continue;\n        const t = norm(op.type);\n        let frontType = null;\n        if (_poDrawer && t === 'door') frontType = ((Number(op.height) || 0) >= PAN_MIN) ? 'pan' : 'drawer';\n        else if (t === 'door' || t === 'glass' || t === 'bifoldh' || t === 'bifoldv') frontType = 'door';\n        else if (t === 'drawer' || t === 'topdrawer') frontType = ((Number(op.height) || 0) >= PAN_MIN) ? 'pan' : 'drawer';\n        else continue;\n        const eff = effectiveHandle(c, frontType);\n        const product = eff && eff.product;\n        if (!product || !product.variantId) continue;\n        const key = String(product.variantId);\n        const prev = acc.get(key) || { product, qty: 0 };\n        prev.qty += 1; acc.set(key, prev);\n      }\n    }\n    let t = 0;\n    for (const { product, qty } of acc.values()) {\n      const cents = (typeof product.price === 'number') ? product.price : 0;\n      t += (cents / 100) * qty;\n    }\n    return t;\n   } catch (e) { return 0; }\n  }\n\n  // Units-only total in GBP - the cabinets and nothing else (no panels,\n  // trims, worktops, handles, appliances or upgrades). This is what the\n  // planner TOP BAR shows as the running price while designing, so the figure\n  // the customer watches climb is purely \"kitchen units\". The full quote is\n  // broken down by group in the basket's Pricing bar and totalled in its\n  // footer; computeTotal below is still the FULL figure (PDF report, saved-plan\n  // price) and must stay that way.\n  // A unit's price NOW: the live catalogue's, which already has any extra\n  // discount in it (the catalogue applies btk.extra_discounts), and only the\n  // price stored on the unit when it was placed if the catalogue does not have\n  // it. The stored one alone froze every unit at the price of the day it went\n  // in: switching the extra 10% on changed nothing on a plan (Arden, 2026-10-10).\n  // \u2500\u2500\u2500 CARCASE ONLY (Arden, 2026-11-16, sales bug sheet row 131) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n  // Staff can sell any kitchen unit without its doors and drawer fronts. Odoo\n  // pushes one HIDDEN product per unit type, 'carcase-only-<unit type>', whose\n  // variants end in the same Odoo id as the unit's own (bk_shopify_export\n  // _shopify_carcase_only_products), priced as the carcase plus its hinges and\n  // drawer boxes. A carcase-only cab (cab.carcaseOnly = { token, expiresAt })\n  // is drawn without fronts or handles and goes in the basket as that variant,\n  // carrying staff's permission for Odoo's Import Check.\n  const _carcaseOnlyProducts = new Map();   // unit type -> Map(odoo id -> variant) | null (none)\n  const _carcaseOnlyInflight = new Map();\n  const _carcaseOnlyFailedAt = new Map();   // a failed load is not retried on every redraw\n  const odooIdOfSku = (sku) => {\n    const segs = String(sku || '').split('-').filter(s => /^\\d{5,}$/.test(s));\n    return segs.length === 1 ? segs[0] : null;\n  };\n  function ensureCarcaseOnlyProduct(ut) {\n    if (!ut || _carcaseOnlyProducts.has(ut)) return Promise.resolve(_carcaseOnlyProducts.get(ut) || null);\n    if (_carcaseOnlyInflight.has(ut)) return _carcaseOnlyInflight.get(ut);\n    const p = fetch('/products/carcase-only-' + encodeURIComponent(ut) + '.js', { credentials: 'same-origin' })\n      .then(r => (r.ok ? r.json() : (r.status === 404 ? null : Promise.reject(new Error('carcase only ' + r.status)))))\n      .then(prod => {\n        const byId = new Map();\n        ((prod && prod.variants) || []).forEach(v => {\n          const id = odooIdOfSku(v.sku);\n          if (id) byId.set(id, { variantId: v.id, title: prod.title, variantTitle: v.title || '',\n            priceCents: v.price, compareAtCents: (typeof v.compare_at_price === 'number') ? v.compare_at_price : null });\n        });\n        _carcaseOnlyProducts.set(ut, prod ? byId : null);\n        return _carcaseOnlyProducts.get(ut);\n      })\n      .catch((e) => { _carcaseOnlyFailedAt.set(ut, Date.now()); throw e; })\n      .finally(() => _carcaseOnlyInflight.delete(ut));\n    _carcaseOnlyInflight.set(ut, p);\n    return p;\n  }\n  // The carcase-only variant for a carcase-only cab: undefined while its\n  // product is loading (a load is started), null when there is none.\n  function carcaseOnlyVariant(c) {\n    if (!c || !c.carcaseOnly || !c.variantId) return null;\n    const info = Catalogue.getVariantInfo(c.variantId);\n    const id = info && info.variant && odooIdOfSku(info.variant.sku);\n    if (!id) return info ? null : undefined;\n    if (!_carcaseOnlyProducts.has(c.unitTypeId)) {\n      const failed = _carcaseOnlyFailedAt.get(c.unitTypeId);\n      if (!failed || Date.now() - failed > 20000) {\n        ensureCarcaseOnlyProduct(c.unitTypeId).then(() => refreshQuoteLocally()).catch(() => {});\n      }\n      return undefined;\n    }\n    const byId = _carcaseOnlyProducts.get(c.unitTypeId);\n    return (byId && byId.get(id)) || null;\n  }\n  // \u2500\u2500 Sink Units (Arden, 2026-11-16) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n  // A sink goes IN a unit, never loose on the plan. Sink base units always\n  // are one (unit_type sink_base, or Belfast). These door units can be made\n  // one with the Sink Unit switch in their panel: cab.sinkBase becomes\n  // { designated: true }, so the sink picker, 3D sink, worktop cut-out, sink\n  // line and taps treat it exactly as a sink base. A 2 drawer base unit with\n  // a sink also takes a Steel Under-Sink Drawer Insert, its own basket line.\n  const SINK_UNIT_TYPES = new Set([\n    'single-highline-base-unit', 'double-highline-base-unit',\n    'true-handleless-single-highline-base-unit', 'true-handleless-double-highline-base-unit',\n    'highline-corner-base-unit', 'highline-corner-base-unit-2-doors', 'true-handleless-highline-corner-base-unit',\n    'l-shape-corner-base-unit', 'true-handleless-l-shape-corner-base-unit',\n    '2-drawer-base-unit', 'true-handleless-2-drawer-base-unit'\n  ]);\n  const SINK_INSERT_TYPES = new Set(['2-drawer-base-unit', 'true-handleless-2-drawer-base-unit']);\n  const SINK_INSERT_HANDLE = 'steel-under-sink-drawer-insert';\n  const isSinkUnit = (c) => !!(c && (c.sinkBase || c.belfastSink));\n  // Can this unit be switched to a Sink Unit (it isn't a sink base already)?\n  // Too narrow for a sink (sales row 138: a 150 single unit took a 600 sink):\n  // a straight unit under 500mm can't be a Sink Unit. Corners are always wide\n  // enough.\n  const SINK_UNIT_MIN_WIDTH_MM = 500;\n  function sinkUnitAllowed(c) {\n    return !!c && !c.belfastSink && !(c.sinkBase && !c.sinkBase.designated)\n      && SINK_UNIT_TYPES.has(String(c.unitTypeId || ''))\n      && !!(c.cornerUnit || c.lShapeUnit || (c.widthMm || 0) >= SINK_UNIT_MIN_WIDTH_MM);\n  }\n  // Where a corner Sink Unit's sink sits (sales row 138). Every sink position\n  // is \"plannerSinkXOffsetMm along a line through the unit\": for most units\n  // that line is the unit's own run, through its centre. An L-shape's sink is\n  // on ONE of its legs - Left or Right as you face into the corner\n  // (cab.plannerSinkLeg, Make Sink Unit) - so its line runs along that leg,\n  // through the leg's middle, turned to face out of it. Cab-local plan mm from\n  // the unit's centre (y = towards the back); rot in degrees, clockwise on\n  // the plan. The 2D plan and the 3D renderer carry the same rule.\n  function sinkFrameOf(cab) {\n    const ls = cab && cab.lShapeUnit;\n    if (!ls) return { x: 0, y: 0, rot: 0, len: (cab && cab.widthMm) || 0 };\n    const W = cab.widthMm || 0, D = cab.depthMm || 0, arm = ls.armDepthMm || 570;\n    const hand = String(ls.hand || 'NE').toUpperCase();\n    const outerLeft = hand === 'NE' || hand === 'SE', outerBottom = hand === 'NE' || hand === 'NW';\n    const fx = outerLeft ? -1 : 1, fy = outerBottom ? 1 : -1;\n    const horizIsLeft = (-fx * fy) > 0;\n    const horiz = (String(cab.plannerSinkLeg || 'left') !== 'right') === horizIsLeft;\n    return horiz\n      ? { x: 0, y: (outerBottom ? 1 : -1) * (D / 2 - arm / 2), rot: outerBottom ? 0 : 180, len: W }\n      : { x: (outerLeft ? -1 : 1) * (W / 2 - arm / 2), y: 0, rot: outerLeft ? 90 : -90, len: D };\n  }\n  // A point on the sink's line (sx along it, sy towards its back) in the\n  // unit's own plan frame.\n  function sinkFramePoint(cab, sx, sy) {\n    const f = sinkFrameOf(cab), r = f.rot * Math.PI / 180, cs = Math.cos(r), sn = Math.sin(r);\n    return { x: f.x + sx * cs - sy * sn, y: f.y + sx * sn + sy * cs, rot: f.rot };\n  }\n  // How far along that line the sink may go: a blank corner's own cabinet\n  // (never over its void), an L-shape's leg, else the unit.\n  function sinkRunRange(cab) {\n    const W = cab.widthMm || 0;\n    const cu = cab.cornerUnit;\n    if (cu && cu.cabinetMm > 0) {\n      return cu.hand === 'left' ? [W / 2 - cu.cabinetMm, W / 2] : [-W / 2, -W / 2 + cu.cabinetMm];\n    }\n    const len = sinkFrameOf(cab).len || W;\n    return [-len / 2, len / 2];\n  }\n  // A corner unit's door centre on that line, or null for any other unit.\n  function sinkDoorCentre(cab) {\n    const W = cab.widthMm || 0;\n    const cu = cab.cornerUnit;\n    if (cu && cu.doorMm > 0) return cu.hand === 'left' ? W / 2 - cu.doorMm / 2 : -W / 2 + cu.doorMm / 2;\n    const ls = cab.lShapeUnit;\n    if (!ls) return null;\n    const D = cab.depthMm || 0, arm = ls.armDepthMm || 570;\n    const hand = String(ls.hand || 'NE').toUpperCase();\n    const outerLeft = hand === 'NE' || hand === 'SE', outerBottom = hand === 'NE' || hand === 'NW';\n    const f = sinkFrameOf(cab), r = f.rot * Math.PI / 180;\n    // The door is on the leg's free end, between the other leg and the end.\n    const horiz = f.rot === 0 || f.rot === 180;\n    const dc = horiz ? { x: (outerLeft ? 1 : -1) * arm / 2, y: f.y }\n                     : { x: f.x, y: (outerBottom ? -1 : 1) * (D > 0 ? arm / 2 : 0) };\n    return (dc.x - f.x) * Math.cos(r) + (dc.y - f.y) * Math.sin(r);\n  }\n  // Make Sink Unit > Sink Side on an L-shape: Left or Right leg. The sink\n  // starts over that leg's door again.\n  function handleSetCabinetSinkLeg(cabinetId, leg) {\n    const idx = cabinets.findIndex(c => c.id === cabinetId);\n    if (idx === -1) return;\n    const cab = cabinets[idx];\n    const want = leg === 'right' ? 'right' : 'left';\n    if (!cab.lShapeUnit || (cab.plannerSinkLeg || 'left') === want) return;\n    const _taps = tapsOnCabinet(cabinetId).map(t => t.id);\n    let next = { ...cab, plannerSinkLeg: want };\n    const sk = next.plannerSinkHandle && Catalogue.getPlannerSink ? Catalogue.getPlannerSink(next.plannerSinkHandle) : null;\n    if (sk) next.plannerSinkXOffsetMm = sinkOffsetNearest(next, sk, sinkStartOffset(next, sk)) ?? 0;\n    cabinets[idx] = next;\n    reseatTapsOn(cabinetId, _taps);\n    rerender();\n    if (selectionPanelHandle && typeof selectionPanelHandle.refresh === 'function') selectionPanelHandle.refresh();\n  }\n  let _sinkInsert;            // undefined: not loaded; null: none; else the line's product\n  let _sinkInsertLoading = null;\n  function ensureSinkInsert() {\n    if (_sinkInsert !== undefined || _sinkInsertLoading) return;\n    _sinkInsertLoading = fetch('/products/' + SINK_INSERT_HANDLE + '.js', { credentials: 'same-origin' })\n      .then(r => (r.ok ? r.json() : null))\n      .then(p => {\n        const v = p && p.variants && p.variants[0];\n        _sinkInsert = v ? { variantId: v.id, title: p.title, priceCents: v.price,\n          compareAtCents: (typeof v.compare_at_price === 'number') ? v.compare_at_price : null } : null;\n      })\n      .catch(() => { _sinkInsert = undefined; })\n      .finally(() => { _sinkInsertLoading = null; rerender(); refreshQuoteLocally(); });\n  }\n  // The drawer insert this unit's sink needs, or null (none needed / not loaded yet).\n  function sinkInsertFor(c) {\n    if (!c || !c.plannerSinkHandle || !c.sinkBase || !c.sinkBase.designated\n      || !SINK_INSERT_TYPES.has(String(c.unitTypeId || ''))) return null;\n    if (_sinkInsert === undefined) { ensureSinkInsert(); return null; }\n    return _sinkInsert;\n  }\n  // The panel's Sink Unit switch. Off takes the sink and its taps away.\n  function handleSetCabinetSinkUnit(cabinetId, on) {\n    const idx = cabinets.findIndex(c => c.id === cabinetId);\n    if (idx === -1) return;\n    const cab = cabinets[idx];\n    if (on) {\n      if (cab.sinkBase || !sinkUnitAllowed(cab)) return;\n      cabinets[idx] = { ...cab, sinkBase: { designated: true }, plannerSinkHandle: null, plannerSinkXOffsetMm: 0 };\n    } else {\n      if (!cab.sinkBase || !cab.sinkBase.designated) return;\n      const taps = new Set(tapsOnCabinet(cabinetId).map(t => t.id));\n      if (taps.size) worktopItems = worktopItems.filter(it => !taps.has(it.id));\n      cabinets[idx] = { ...cab, sinkBase: null, plannerSinkHandle: null, plannerSinkXOffsetMm: 0,\n        plannerSinkFitting: null, plannerSinkMount: null, plannerSinkDrainerSide: null, plannerSinkLeg: null };\n    }\n    rerender();\n    if (selectionPanelHandle && typeof selectionPanelHandle.refresh === 'function') selectionPanelHandle.refresh();\n  }\n  // Add Sinks & Taps > a sink: into a Sink Unit - the selected one, else the\n  // plan's only one, else the customer picks (two) or selects one (more).\n  async function fitSinkFromPicker(entry) {\n    const dlg = window.BTKKPDialog;\n    const say = (msg, title) => (dlg ? dlg.alert(msg, { title }) : window.alert(msg));\n    const fits = (c) => {\n      const f = cabinetsHandle && cabinetsHandle.sinkFitsUnit;\n      return typeof f === 'function' ? f(entry.handle, c) : true;\n    };\n    const units = cabinets.filter(c => isSinkUnit(c) && !c.excludeFromQuote)\n      .sort((a, b) => (a.displayNumber ?? 1e9) - (b.displayNumber ?? 1e9));\n    const label = (c) => (c.displayNumber != null ? 'Unit ' + c.displayNumber : 'the sink unit');\n    if (!units.length) {\n      say('A sink goes in a sink unit. Add a sink base unit, or select a base unit and switch on Sink Unit in its panel, then add your sink.', 'Choose a Sink Unit');\n      return;\n    }\n    const picked = units.filter(c => selectedCabinetIds.has(c.id));\n    let target = picked.length === 1 ? picked[0] : (units.length === 1 ? units[0] : null);\n    if (!target) {\n      const ok = units.filter(fits);\n      if (ok.length === 1) target = ok[0];\n      else if (ok.length === 2 && dlg) {\n        const r = await dlg.confirm('Which sink unit should this sink go in?', {\n          title: 'Choose a Sink Unit', confirmText: label(ok[0]), alt: { text: label(ok[1]), value: 'alt' }, cancelText: 'Cancel' });\n        target = r === 'alt' ? ok[1] : (r === true ? ok[0] : null);\n        if (!target) return;\n      } else if (ok.length > 2) {\n        say('This plan has more than one sink unit. Select the unit you want the sink in, then add it again.', 'Choose a Sink Unit');\n        return;\n      }\n    }\n    if (!target || !fits(target)) {\n      say(`This sink doesn't suit ${label(target || units[0])}: a Belfast sink goes in a Belfast unit, and a standard sink in a sink unit.`, 'Sink Doesn\u2019t Fit');\n      return;\n    }\n    handleSetCabinetPlannerSink(target.id, entry.handle);\n  }\n\n  function carcaseOnlyPending() {\n    return (cabinets || []).some(c => c && c.carcaseOnly && !c.excludeFromQuote && carcaseOnlyVariant(c) === undefined);\n  }\n\n  function unitPriceCents(c, info) {\n    if (c && c.carcaseOnly) {\n      const co = carcaseOnlyVariant(c);\n      return co ? co.priceCents : null;\n    }\n    const i = (info !== undefined) ? info : (c && c.variantId ? Catalogue.getVariantInfo(c.variantId) : null);\n    if (i && typeof i.priceCents === 'number') return i.priceCents;\n    return (c && typeof c.priceCents === 'number') ? c.priceCents : null;\n  }\n  // The unit's compare-at (RRP) in pence, the carcase-only one for a\n  // carcase-only cab.\n  function unitCompareAtCents(c, info) {\n    if (c && c.carcaseOnly) {\n      const co = carcaseOnlyVariant(c);\n      return co ? co.compareAtCents : null;\n    }\n    return (info && info.variant && typeof info.variant.compareAtPrice === 'number')\n      ? info.variant.compareAtPrice : null;\n  }\n  function computeUnitsTotal() {\n    let total = 0;\n    cabinets.forEach(c => {\n      // Same set the basket's unit lines are built from (quoteItems), so the\n      // top-bar figure and the basket's \"Units\" group always agree:\n      // free-placed end panels / fillers are panels, not units (and are charged\n      // per BOARD, not per placement), and a unit the customer has X'd out of\n      // the quote is priced at nothing even though it stays in the 3D plan.\n      if (c.endPanelUnit || c.excludeFromQuote) return;\n      const cents = unitPriceCents(c);\n      if (typeof cents === 'number') total += cents / 100;\n      // A built-under double oven's fitting-panel pair - its own basket line.\n      const _kit = fittingKitFor(c);\n      if (_kit) total += _kit.priceCents / 100;\n    });\n    return total;\n  }\n\n  // Compare-at (RRP) counterpart of computeUnitsTotal: the units total plus\n  // each cabinet's compare-at UPLIFT wherever a higher RRP exists.\n  function computeUnitsCompareTotal() {\n    let total = computeUnitsTotal();\n    cabinets.forEach(c => {\n      if (!c.variantId || c.endPanelUnit || c.excludeFromQuote) return;\n      const info = Catalogue.getVariantInfo(c.variantId);\n      const saleCents = unitPriceCents(c, info);\n      const cmp = unitCompareAtCents(c, info);\n      if (typeof cmp === 'number' && typeof saleCents === 'number' && cmp > saleCents) {\n        total += (cmp - saleCents) / 100;\n      }\n    });\n    return total;\n  }\n\n  function computeTotal() {\n    let total = 0;\n    cabinets.forEach(c => {\n      // Free-placed end panels / fillers are charged as part of the BOARD they\n      // are cut from (see the end-panel board loop below), so counting their\n      // own product price here would bill them twice.\n      if (c.endPanelUnit) return;\n      const cents = unitPriceCents(c);\n      if (typeof cents === 'number') total += cents / 100;\n      // A built-under double oven's fitting-panel pair - its own basket line.\n      const _kit = fittingKitFor(c);\n      if (_kit) total += _kit.priceCents / 100;\n      // A Pastry Bench Set's fronts, plinth frame and shelf.\n      for (const ch of pastryCharges(c)) total += ((ch.priceCents || 0) / 100) * (ch.qty || 1);\n    });\n    // Nested end-panel boards - one charge per physical board (incl. the\n    // stacked-unit under panels, which are now tall end-panel boards).\n    const epStyle = kitchenStyleId || null;\n    for (const board of (endPanelLayout?.boards || [])) {\n      const prod = endPanelBoardProduct(board, epStyle);\n      if (prod && typeof prod.priceCents === 'number') total += prod.priceCents / 100;\n    }\n    // Worktops - slab-tier materials (ceramic / quartz) charged by the number\n    // of standard slabs the layout nests onto \u2192 tier variant; board materials\n    // (laminate, real wood, FENIX, solid surface) charged per stock board, so\n    // the charge carries a QUANTITY.\n    for (const ch of computeWorktopCharges()) total += (ch.variant.priceCents / 100) * (ch.qty || 1);\n    // Trims + handles (same categories the basket adds), plus any upgrade\n    // add-ons applied inside the basket, so the header matches the footer.\n    total += computeTrimsTotalGbp();\n    total += computeRailTotalGbp();      // True Handleless profiles (the basket's Profiles section)\n    total += computeHandlesTotalGbp();\n    total += plannerAddonTotalGbp;\n    total += computeAutoItemsTotalGbp();   // automatic items (touch up paint, fitting kits)\n    total += computeFurnitureTotalGbp();   // bar stools\n    return total;\n  }\n\n  // Compare-at (RRP) total - per cabinet, use the variant's compare-at\n  // price when it's higher than the sale price, else fall back to the\n  // sale price. Mirrors computeTotal so the two stay aligned.\n  function computeCompareTotal() {\n    // Full RRP = the full sale total (all categories + add-ons) plus the\n    // compare-at UPLIFT wherever a higher RRP exists (cabinets + trims).\n    let total = computeTotal();\n    cabinets.forEach(c => {\n      if (!c.variantId) return;\n      const info = Catalogue.getVariantInfo(c.variantId);\n      const saleCents = unitPriceCents(c, info);\n      const cmp = unitCompareAtCents(c, info);\n      if (typeof cmp === 'number' && typeof saleCents === 'number' && cmp > saleCents) {\n        total += (cmp - saleCents) / 100;\n      }\n    });\n    for (const ch of [...computeTrimCharges(), ...computeRailCharges()]) {\n      const p = ch.product || {};\n      const sale = p.priceCents || 0;\n      const cmp = p.compareAtCents || 0;\n      if (cmp > sale) total += ((cmp - sale) / 100) * (ch.qty || 1);\n    }\n    total += computeAutoItemsTotalGbp(true);\n    total += computeFurnitureTotalGbp(true);\n    return total;\n  }\n\n  // Total linear mm per trim feature, derived from the perimeter\n  // tracer in the trim engine. Front runs + side returns to back of\n  // unit are summed; co-linear runs across adjacent same-band\n  // cabinets are merged into single segments before summing.\n  // Skipped (mm = 0) when the feature is set to \"None\".\n  // Worktop slabs for the current layout - one continuous slab per\n  // run of base units, 10mm overhang auto-suppressed at walls / tall\n  // units. Recomputed per render (cheap; mirrors the trim engine).\n  // How the 3D view draws a bespoke edge profile (its three looks: square,\n  // chamfered, rounded - see worktopExtrudeSettings in the renderer). The\n  // chamfers read as chamfered, every rounded profile (pencil, full radius,\n  // bullnose, shark's nose, ogee) as rounded, a built-up edge as square.\n  function bespokeEdgeLook(edgeKey) {\n    const k = String(edgeKey || 'edge_double_chamfer');\n    if (/chamfer/.test(k)) return 'chamfered';\n    if (/pencil|radius|bullnose|sharks|ogee/.test(k)) return 'rounded';\n    return 'square';\n  }\n\n  function buildWorktops(cabs = cabinets) {\n    // A window set to Worktop in to Window takes the worktop under it back\n    // across its reveal, as part of the same piece - cut into the slab here so\n    // the plan, the 3D, the upstands and the cutting plans all see it.\n    const slabs = addWorktopWindowReveals(computeWorktops({\n      cabinets: cabs,\n      roomVertices: room?.vertices || [],\n      perimeterItems: roomConfig.perimeterItems || [],\n      worktopCornerRadii\n    }).slabs, roomConfig.wallOpenings, room?.vertices || []);\n    // Stamp the plan-wide worktop material onto each slab so the 3D render\n    // picks up its real thickness, swatch texture + edge profile (the render\n    // reads these off the slab). Cushion tops keep their fabric look/height.\n    // Each worktop takes its OWN material: the plan's, or one chosen for its\n    // units (Change Worktop, bug sheet row 100).\n    {\n      for (const s of slabs) {\n        if (s.cushionTop) continue;\n        const matHandle = worktopMaterialForSlab(s);\n        const mat = matHandle ? Catalogue.getWorktopMaterial(matHandle) : null;\n        if (!mat) continue;\n        s.thicknessMm    = worktopThicknessFor(matHandle);\n        // 3D texture only - never the picker's photo fallback (a lifestyle\n        // image tiled at 600mm intervals is worse than no texture at all).\n        s.swatchUrl      = mat.textureUrl || null;\n        // A made-to-measure stone's edge is the profile chosen in Customise\n        // Worktop (a window board set to Match Worktop follows it too).\n        s.profile        = mat.pricingModel === 'bespoke' ? bespokeEdgeLook(worktopBespoke.edgeKey) : (mat.profile || 'square');\n        s.materialHandle = mat.handle;\n        // Better Bedrooms: a Bedroom Worktop Panel is made in the door colour, so\n        // it renders in the door colour of the first unit under it.\n        s.colourHex = null;\n        if (mat.type === 'Worktop Panels') {\n          const _wc = cabs.find(c => (s.cabinetIds || []).includes(c.id));\n          const _wh = (_wc && _wc.doorColourHandle) || globalDoorColourHandle;\n          s.colourHex = (_wh && Catalogue.getMasterDoorColour && (Catalogue.getMasterDoorColour(_wh) || {}).hex) || null;\n        }\n        // Stone is heat-safe behind a hob; laminate, wood and solid surface\n        // are not (engine-splashbacks, the hob heat rule).\n        s.heatSafe       = worktopIsHeatSafe(mat);\n        // Board edges in 3D (stone keeps its Customise Worktop profile instead):\n        //  - round edge laminate: the factory round on the front (and an island's\n        //    back) only; sawn ends, radius corners and cut-outs are edged square\n        //    on site, with a glue line;\n        //  - real wood and solid surface: a 2 mm chamfer on every exposed edge\n        //    (they are shaped and polished on site);\n        //  - everything else (square edge and solid laminate, FENIX): a 1 mm\n        //    round on every exposed edge, just to take the hard edge off.\n        // Edges against a wall or the next worktop stay square.\n        s.edgeTreatment = null;\n        if (mat.pricingModel !== 'bespoke') {\n          const range = String(mat.range || '').toLowerCase();\n          if (mat.construction === 'faced' && mat.profile === 'rounded') {\n            s.edgeTreatment = { profile: 'rounded', mm: 0, edges: 'factory', glueLines: true };\n          } else if (/wood|solid surface/.test(range)) {\n            s.edgeTreatment = { profile: 'chamfered', mm: 2, edges: 'exposed', glueLines: false };\n          } else {\n            s.edgeTreatment = { profile: 'rounded', mm: 1, edges: 'exposed', glueLines: false };\n          }\n        }\n        // A bespoke swatch is a photograph of a WHOLE SLAB, so it must map at\n        // slab size. Tiled at the default 600mm it would squeeze the entire\n        // pattern into a 600mm square and repeat it, which reads as busy noise\n        // rather than stone. Boards keep the 600mm default (their swatches are\n        // seamless patterns) unless the texture is a manufacturer's full-sheet\n        // photo, which carries its own sheet size from the catalogue.\n        s.textureMm = null;\n        if (mat.pricingModel === 'bespoke' && mat.textureUrl) {\n          const stock = Catalogue.getBespokeStock(mat.handle, worktopThicknessFor(mat.handle));\n          if (stock && stock.full && stock.full.lengthMm > 0 && stock.full.widthMm > 0) {\n            s.textureMm = { lengthMm: stock.full.lengthMm, widthMm: stock.full.widthMm };\n          }\n        } else if (mat.textureUrl && mat.textureMm) {\n          s.textureMm = { lengthMm: mat.textureMm.lengthMm, widthMm: mat.textureMm.widthMm };\n        }\n      }\n    }\n    stampWaterfalls(slabs, cabs);\n    return slabs;\n  }\n\n  // Waterfall sides: which sides COULD take one (s.waterfallSides), and which\n  // have one (s.waterfalls). The 2D and 3D draw from `waterfalls`, the cutting\n  // plan cuts from it. A side that has stopped being possible (the run now\n  // ends against a wall) simply stops being drawn or cut.\n  function stampWaterfalls(slabs, cabs) {\n    const cabById = new Map((cabs || []).map(c => [c.id, c]));\n    const t = waterfallThicknessMm();\n    for (const s of (slabs || [])) {\n      const sides = worktopWaterfallSides(s, cabById);\n      s.waterfallSides = sides.map(x => x.side);\n      s.waterfalls = sides.filter(x => x.on).map(x => x.side);\n      s.waterfallReachMm = Object.fromEntries(sides.filter(x => x.reachMm).map(x => [x.side, x.reachMm]));\n      // A waterfall END is the worktop's own thickness, butted to the unit's\n      // side, with the worktop stopping flush with its face (Arden, 2026-10-20:\n      // it came out thicker than the worktop). The engine still builds this\n      // end with the panel's reach (panel + its 10mm overhang - see unitRect),\n      // so the worktop's id, colours and corner radii do not move when a panel\n      // is swapped for a waterfall; the end is brought to one thickness past\n      // the unit here instead, after the id is set.\n      for (const x of sides) {\n        if (!x.on || !x.reachMm || (x.side !== 'left' && x.side !== 'right')) continue;\n        moveSlabEnd(s, x.side, t - x.reachMm);\n        s.waterfallReachMm[x.side] = t;\n      }\n    }\n    return slabs;\n  }\n  // Move one END of a worktop along its run by `deltaMm` (+ longer, - shorter):\n  // every outline point on that end's edge. 'left' is the run's +X end.\n  function moveSlabEnd(s, side, deltaMm) {\n    if (!(Math.abs(deltaMm) > 0.25)) return;\n    const f = worktopLocalFrame(s);\n    if (!f) return;\n    const edge = side === 'left' ? f.x1 : f.x0;\n    const by = side === 'left' ? deltaMm : -deltaMm;\n    s.polygon = f.pts.map(p => f.toWorld(Math.abs(p.x - edge) < 0.5 ? { x: p.x + by, y: p.y } : p));\n  }\n\n  // ---- Waterfall sides --------------------------------------------------\n  //\n  // A waterfall carries the worktop's own material down to the floor, mitred\n  // where it meets the worktop. It goes on a side that has an END PANEL (an\n  // open end of the run) or a BREAKFAST BAR (the back panel of an island).\n  //\n  // Sides are named as the customer stands at the FRONT of the worktop, the\n  // way end panels are: 'left' is the run's local +X end, 'right' its -X end,\n  // 'back' its +Y edge. (The slab's own exposedLeft / exposedRight flags are\n  // the -X / +X ends, i.e. the other way round - so they are mapped here.)\n  const WATERFALL_SIDES = ['left', 'right', 'back'];\n  function worktopLocalFrame(s) {\n    const th = ((s && s.rotationDeg) || 0) * Math.PI / 180;\n    const cs = Math.cos(th), sn = Math.sin(th);\n    const toLocal = (p) => ({ x: p.x * cs + p.y * sn, y: -p.x * sn + p.y * cs });\n    const pts = ((s && s.polygon) || []).map(toLocal);\n    if (pts.length < 3) return null;\n    const xs = pts.map(p => p.x), ys = pts.map(p => p.y);\n    return {\n      th, cs, sn, toLocal, pts,\n      toWorld: (p) => ({ x: p.x * cs - p.y * sn, y: p.x * sn + p.y * cs }),\n      x0: Math.min(...xs), x1: Math.max(...xs), y0: Math.min(...ys), y1: Math.max(...ys),\n    };\n  }\n  // The unit at one end of a worktop and the side of it that faces out of\n  // that end: { c, key } or null. A unit turned the same way as the run has its\n  // user-left on the run's +X; turned round, its user-right is.\n  function worktopEndUnit(s, cabById, plusX) {\n    const f = worktopLocalFrame(s);\n    if (!f) return null;\n    let best = null;\n    for (const id of (s.cabinetIds || [])) {\n      const c = cabById.get(id);\n      if (!c) continue;\n      const centre = { x: (c.x || 0) + (c.widthMm || 0) / 2, y: (c.y || 0) + (c.depthMm || 0) / 2 };\n      const along = Math.cos(((c.rotationDeg || 0) * Math.PI / 180) - f.th);\n      const lx = f.toLocal(centre).x;\n      if (!best || (plusX ? lx > best.lx : lx < best.lx)) best = { c, lx, along };\n    }\n    if (!best || Math.abs(best.along) < 0.5) return null;\n    return { c: best.c, key: ((best.along > 0) === plusX) ? 'left' : 'right' };\n  }\n  // The unit sides an END waterfall covers besides its own unit's: every other\n  // unit under the same worktop whose side stands at that end - the back row of\n  // a back-to-back island (Sales row 149, PLN101452: the waterfall dropped the\n  // island's full depth, but the 300 deep back units kept their own end panels\n  // inside it). As 'cabId:side'. autoDetectEndPanels takes their panels off,\n  // and taking the waterfall off puts them back.\n  const WATERFALL_COVER_TOL_MM = 30;\n  function waterfallCoveredEndSides(cabs = cabinets) {\n    const out = new Set();\n    const hasWf = (c) => !!(c && c.endPanels && ((c.endPanels.left || {}).waterfall || (c.endPanels.right || {}).waterfall));\n    if (!(cabs || []).some(hasWf)) return out;\n    let slabs;\n    try { slabs = buildWorktops(cabs); } catch (e) { return out; }\n    const cabById = new Map((cabs || []).map(c => [c.id, c]));\n    for (const s of (slabs || [])) {\n      const f = worktopLocalFrame(s);\n      if (!f) continue;\n      // How far along the run a unit reaches, at the +X or -X end.\n      const reach = (c, plusX) => {\n        const a = ((c.rotationDeg || 0) * Math.PI / 180) - f.th;\n        const half = (Math.abs(Math.cos(a)) * (c.widthMm || 0) + Math.abs(Math.sin(a)) * (c.depthMm || 0)) / 2;\n        const lx = f.toLocal({ x: (c.x || 0) + (c.widthMm || 0) / 2, y: (c.y || 0) + (c.depthMm || 0) / 2 }).x;\n        return plusX ? lx + half : lx - half;\n      };\n      for (const side of (s.waterfalls || [])) {\n        if (side !== 'left' && side !== 'right') continue;\n        const plusX = side === 'left';\n        const end = worktopEndUnit(s, cabById, plusX);\n        if (!end) continue;\n        const endReach = reach(end.c, plusX);\n        for (const id of (s.cabinetIds || [])) {\n          const c = cabById.get(id);\n          if (!c || c.id === end.c.id) continue;\n          const along = Math.cos(((c.rotationDeg || 0) * Math.PI / 180) - f.th);\n          if (Math.abs(along) < 0.5) continue;\n          if (Math.abs(reach(c, plusX) - endReach) > WATERFALL_COVER_TOL_MM) continue;\n          out.add(c.id + ':' + (((along > 0) === plusX) ? 'left' : 'right'));\n        }\n      }\n    }\n    return out;\n  }\n  // [{ side, on }] for every side of a worktop that can take a waterfall.\n  //   An END: an open end of the run whose end unit has an end panel there, or\n  //     already has the waterfall that replaced it. The waterfall lives ON THE\n  //     UNIT (endPanels[side].waterfall, with the panel itself off), so the\n  //     End Panels popup and this worktop's popup are the same switch, and the\n  //     panel leaves the plan, the 3D and the quote. A radius panel curves the\n  //     worktop, so it cannot take one.\n  //   The BACK: a breakfast bar - see worktopBarUnits. Its waterfall lives on\n  //     those units too (breakfastBarBack.waterfall), so the Breakfast Bar Back\n  //     Panel popup and this worktop's popup are the same switch. The back\n  //     panel keeps its place (the worktop is built over it, so it does not\n  //     move), but with a waterfall it is not drawn and not charged - see\n  //     isBarWaterfall.\n  function worktopWaterfallSides(s, cabById) {\n    if (!s || s.cushionTop) return [];\n    const out = [];\n    const endSide = (side, plusX, exposed) => {\n      if (!exposed) return;\n      const u = worktopEndUnit(s, cabById, plusX);\n      // The same units the End Panels popup offers Waterfall End on.\n      if (!u || !/^base/i.test(u.c.category || '') || u.c.lShapeUnit || u.c.diagonalCornerUnit) return;\n      const ep = (u.c.endPanels || {})[u.key];\n      if (!ep) return;\n      // How far the worktop's end stands past the unit: the panel's reach the\n      // worktop keeps (see unitRect) plus its 10mm end overhang. The 3D fills\n      // the waterfall back across that, to the unit's side.\n      const reachMm = endPanelThickMm(ep) + 10;\n      if (!ep.active && ep.waterfall) out.push({ side, on: true, reachMm });\n      else if (ep.active && ep.style !== 'radius') out.push({ side, on: false, reachMm });\n    };\n    endSide('left',  true,  s.exposedRight !== false);\n    endSide('right', false, s.exposedLeft  !== false);\n    const bar = worktopBarUnits(s, cabById);\n    if (bar.length) out.push({ side: 'back', on: bar.some(c => c.breakfastBarBack && c.breakfastBarBack.waterfall) });\n    return out;\n  }\n  // The units under a worktop whose breakfast bar back panel its back\n  // waterfall would replace: facing the same way as the run, back panel on,\n  // on a worktop whose back is open to the room. A True Handleless island's\n  // back is its own rail-and-post build, so it never takes one.\n  function worktopBarUnits(s, cabById) {\n    const f = worktopLocalFrame(s);\n    if (!f || !s.exposedBack || s.cushionTop) return [];\n    const out = [];\n    for (const id of (s.cabinetIds || [])) {\n      const c = cabById.get(id);\n      if (!c || !c.backPanel || !c.backPanel.active || c.backPanel.thProfile) continue;\n      if (Math.cos(((c.rotationDeg || 0) * Math.PI / 180) - f.th) > 0.5) out.push(c);\n    }\n    return out;\n  }\n  // A waterfall as drawn on the 2D plan: a band the waterfall's thickness wide\n  // along the worktop edge it drops from (it stands under that edge, its face\n  // flush with the worktop's), in world mm.\n  function waterfallBands(s, thicknessMm) {\n    return ((s && s.waterfalls) || []).map(k => waterfallBand(s, k, thicknessMm)).filter(Boolean);\n  }\n  function waterfallBand(s, side, thicknessMm) {\n    const f = worktopLocalFrame(s);\n    if (!f) return null;\n    const t = Math.max(6, Number(thicknessMm) || 20);\n    // An end fills back to the unit, as the 3D draws it (waterfallReachMm).\n    const reach = s.waterfallReachMm || {};\n    const endT = (k) => Math.max(t, Number(reach[k]) || 0);\n    const quad = (ax, bx, ay, by) => [f.toWorld({ x: ax, y: ay }), f.toWorld({ x: bx, y: ay }),\n                                      f.toWorld({ x: bx, y: by }), f.toWorld({ x: ax, y: by })];\n    if (side === 'left')  return quad(f.x1 - endT('left'), f.x1, f.y0, f.y1);\n    if (side === 'right') return quad(f.x0, f.x0 + endT('right'), f.y0, f.y1);\n    if (side === 'back')  return quad(f.x0, f.x1, f.y1 - t, f.y1);\n    return null;\n  }\n  // The thickness a waterfall is cut at: the worktop's own, which for a\n  // made-to-measure stone is the thickness picked (worktopThicknessMm).\n  function waterfallThicknessMm() {\n    try { return worktopThicknessMm(); } catch (e) { return 20; }\n  }\n  // EVERY WATERFALL IN THE PLAN, in one order, each its own SECTION of the\n  // job: the Layout letters them after the worktop pieces, the Cutting Plan\n  // names its pieces by the same id, and the key lists their sizes. One list\n  // so the three can never disagree.\n  //   { id, slabId, side, label, lengthMm, heightMm,\n  //     band   - its footprint on the plan, world mm\n  //     out    - the unit direction away from the worktop, for its letter }\n  function worktopWaterfallList(slabs) {\n    const out = [];\n    const t = waterfallThicknessMm();\n    for (const s of (slabs || buildWorktops() || [])) {\n      if (!s || !(s.waterfalls || []).length) continue;\n      const info = worktopWaterfallInfo(s, t);\n      if (!info) continue;\n      const f = info.frame;\n      const dir = { left: { x: 1, y: 0 }, right: { x: -1, y: 0 }, back: { x: 0, y: 1 } };\n      for (const x of info.sides) {\n        if (!x.on) continue;\n        out.push({ id: `wf|${s.id}|${x.side}`, slabId: s.id, side: x.side, label: x.label,\n                   lengthMm: x.lengthMm, heightMm: info.heightMm,\n                   band: waterfallBand(s, x.side, t), out: f.toWorld(dir[x.side]) });\n      }\n    }\n    return out;\n  }\n  // Everything the popup, the cut list and (later) the price need to know\n  // about one worktop's waterfalls, in the worktop's own frame:\n  //   sides     every side that can take one: { side, label, lengthMm, on }\n  //   heightMm  floor to worktop top - the worktop's rest height plus its\n  //             thickness (870 + 20 on a standard base run), because the mitre\n  //             means the drop is cut to the full height including the top.\n  //   mitreMm   the mitre joints: one along the top of each waterfall, and a\n  //             vertical one where an end waterfall meets a breakfast bar one.\n  function worktopWaterfallInfo(s, thicknessMm) {\n    const f = worktopLocalFrame(s);\n    if (!f) return null;\n    const on = new Set(s.waterfalls || []);\n    const t = Number(thicknessMm) || s.thicknessMm || 20;\n    const heightMm = Math.round((s.restMm || 0) + t);\n    const len = { left: f.y1 - f.y0, right: f.y1 - f.y0, back: f.x1 - f.x0 };\n    const LABEL = { left: 'Left end', right: 'Right end', back: 'Breakfast bar side' };\n    const sides = (s.waterfallSides || []).map(k => ({\n      side: k, label: LABEL[k], lengthMm: Math.round(len[k]), on: on.has(k),\n    }));\n    const vertical = on.has('back') ? ['left', 'right'].filter(k => on.has(k)).length : 0;\n    const horizontal = sides.filter(x => x.on).reduce((n, x) => n + x.lengthMm, 0);\n    return { frame: f, sides, heightMm, thicknessMm: t, verticalMitres: vertical,\n             mitreMm: horizontal + vertical * heightMm };\n  }\n  // The waterfall pieces to cut, from the same slabs as the worktops. A piece\n  // lies on the slab as the waterfall stands: its length is the side's length,\n  // its depth the drop. Its top edge is the mitre onto the worktop, its foot\n  // stands on the floor; an end meets the breakfast bar waterfall in a mitre,\n  // is buried against a wall, or is on show and polished.\n  function waterfallParts(slabs) {\n    const out = [];\n    const bySlab = new Map((slabs || []).filter(Boolean).map(s => [s.id, s]));\n    for (const w of worktopWaterfallList(slabs)) {\n      const s = bySlab.get(w.slabId);\n      if (!s) continue;\n      const on = new Set(s.waterfalls);\n      let ends;\n      if (w.side === 'back') {\n        // Its two ends are the worktop's ends: as seen from the back, the\n        // run's right end is on the left.\n        const endOf = (k, exposed) => (on.has(k) ? 'mitre' : exposed ? 'profiled' : 'raw');\n        ends = { left: endOf('right', s.exposedLeft !== false), right: endOf('left', s.exposedRight !== false) };\n      } else {\n        // Front end on show; back end meets the breakfast bar waterfall, or\n        // the back of the run (open on an island, on a wall otherwise).\n        ends = { left: 'profiled', right: on.has('back') ? 'mitre' : (s.exposedBack ? 'profiled' : 'raw') };\n      }\n      // slabId is the WATERFALL's id, so the Cutting Plan finds its letter.\n      out.push({ part: 'waterfall', side: w.side, slabId: w.id,\n                 lengthMm: w.lengthMm, heightMm: w.heightMm,\n                 edges: { front: 'mitre', back: 'raw', ...ends } });\n    }\n    return out;\n  }\n  // The worktop edges a waterfall is mitred onto, in world mm, so the cutting\n  // plan draws them as the mitre they are rather than a polished edge.\n  function waterfallMitreLines(slabs) {\n    const out = [];\n    for (const s of (slabs || [])) {\n      if (!s || !(s.waterfalls || []).length) continue;\n      const f = worktopLocalFrame(s);\n      if (!f) continue;\n      for (const k of s.waterfalls) {\n        const a = k === 'left' ? { x: f.x1, y: f.y0 } : k === 'right' ? { x: f.x0, y: f.y0 } : { x: f.x0, y: f.y1 };\n        const b = k === 'left' ? { x: f.x1, y: f.y1 } : k === 'right' ? { x: f.x0, y: f.y1 } : { x: f.x1, y: f.y1 };\n        out.push([f.toWorld(a), f.toWorld(b)]);\n      }\n    }\n    return out;\n  }\n  function handleSetWorktopWaterfall(worktopId, side, on) {\n    if (!worktopId || !WATERFALL_SIDES.includes(side)) return;\n    if (side !== 'back') {\n      // An end: switch it on the end unit, exactly as the End Panels popup\n      // does - the waterfall replaces the end panel, and taking it off puts the\n      // panel back as it was (its style is still on the side).\n      const s = (buildWorktops() || []).find(x => x && x.id === worktopId);\n      const u = s && worktopEndUnit(s, new Map((cabinets || []).map(c => [c.id, c])), side === 'left');\n      if (!u) return;\n      handleUpdateCabinetEndPanel(u.c.id, u.key, on\n        ? { active: false, userOff: true, waterfall: true, toFloor: false, doorLine: false }\n        : { active: true, userOff: false, waterfall: false });\n      return;\n    }\n    // The back: one waterfall along the whole worktop, so every breakfast bar\n    // unit under it is switched together.\n    const s = (buildWorktops() || []).find(x => x && x.id === worktopId);\n    const ids = new Set(s ? worktopBarUnits(s, new Map((cabinets || []).map(c => [c.id, c]))).map(c => c.id) : []);\n    if (!ids.size) return;\n    cabinets = cabinets.map(c => ids.has(c.id)\n      ? { ...c, breakfastBarBack: { ...(c.breakfastBarBack || {}), waterfall: !!on } } : c);\n    rerender();\n    scheduleBasketResync();\n  }\n  // The Breakfast Bar Back Panel popup's Waterfall choice: the back waterfall\n  // of the worktop this unit sits under.\n  function handleSetCabinetBarWaterfall(cabinetId, on) {\n    const s = (buildWorktops() || []).find(x => x && (x.cabinetIds || []).includes(cabinetId)\n      && (x.waterfallSides || []).includes('back'));\n    if (s) handleSetWorktopWaterfall(s.id, 'back', on);\n  }\n  // Whether this unit can have one (its worktop has a breakfast bar side).\n  // ROUND EDGE LAMINATE TAKES NO WATERFALL (Arden, 2026-11-18, sales sheet row\n  // 139): a postformed bullnose board can't be mitred down to the floor. The\n  // same test the board cut uses for \"can't be ripped\" (canRip): a rounded\n  // profile on a board that isn't solid. Solid laminate, square edge, wood,\n  // FENIX and stone keep their waterfalls. Waterfalls already on such a plan\n  // stay drawn, and waterfallMaterialWarnings says so - nothing placed is\n  // taken away on its own.\n  function waterfallBarredMaterial(handle) {\n    const m = handle && Catalogue.getWorktopMaterial(handle);\n    return !!(m && m.profile === 'rounded' && m.construction !== 'solid'\n      && m.pricingModel !== 'bespoke' && m.pricingModel !== 'slab-tier');\n  }\n  function waterfallBarredForSlab(s) {\n    return !!s && waterfallBarredMaterial(worktopMaterialForSlab(s));\n  }\n  // The worktop over this unit is round edge laminate.\n  function cabinetWaterfallBarred(cabinetId) {\n    try {\n      return (buildWorktops() || []).some(x => x && (x.cabinetIds || []).includes(cabinetId) && waterfallBarredForSlab(x));\n    } catch (e) { return false; }\n  }\n  function waterfallMaterialWarnings() {\n    const out = [];\n    for (const s of (buildWorktops() || [])) {\n      if (!s || !(s.waterfalls || []).length || !waterfallBarredForSlab(s)) continue;\n      const ids = (s.cabinetIds || []).filter(id => cabinets.some(c => c.id === id));\n      const m = Catalogue.getWorktopMaterial(worktopMaterialForSlab(s)) || {};\n      const nums = ids.map(id => cabinets.find(c => c.id === id)).map(c => c && c.displayNumber).filter(n => n != null);\n      out.push({\n        ruleId: 'waterfall-round-edge', severity: 'warning', itemIds: ids,\n        message: `${m.colour || m.title || 'This worktop'} is a round edge laminate, which can't have a waterfall${nums.length ? ` (worktop over unit${nums.length > 1 ? 's' : ''} #${nums.join(', #')})` : ''}. Change the worktop, or put the end panel or back panel back.`,\n        _signature: 'waterfall-round-edge|' + s.id + '|' + (s.waterfalls || []).join(',') + '|' + worktopMaterialForSlab(s)\n      });\n    }\n    return out;\n  }\n  // WORKTOP PANTRY UNIT (row 142): it stands on the worktop, so beside a wall\n  // or tall unit its top is higher by the worktop's thickness and the cornice\n  // steps there. Arden: say so, nothing moves.\n  function pantryTopStepWarnings() {\n    const out = [];\n    for (const c of cabinets) {\n      if (!c || !isPantryCab(c)) continue;\n      const own = planFootprintAABB(c);\n      const top = unitVerticalRange(c).top;\n      for (const o of cabinets) {\n        if (!o || o === c || isPantryCab(o)) continue;\n        if (!/^(wall|tall)/i.test(o.category || '') || o.asBase) continue;\n        if (!footprintsOverlap(own, planFootprintAABB(o), -80)) continue;   // beside it, past an end panel + filler\n        const step = Math.round(top - unitVerticalRange(o).top);\n        if (Math.abs(step) < 3) continue;\n        out.push({\n          ruleId: 'pantry-top-step', severity: 'warning', itemIds: [c.id, o.id],\n          message: `The Worktop Pantry Unit${c.displayNumber != null ? ` #${c.displayNumber}` : ''} stands on the worktop, so its top is ${Math.abs(step)}mm ${step > 0 ? 'higher' : 'lower'} than unit${o.displayNumber != null ? ` #${o.displayNumber}` : ''} beside it, and the cornice steps there.`,\n          _signature: 'pantry-top-step|' + c.id + '|' + o.id + '|' + step\n        });\n      }\n    }\n    return out;\n  }\n  function cabinetCanBarWaterfall(cabinetId) {\n    return (buildWorktops() || []).some(x => x && (x.cabinetIds || []).includes(cabinetId)\n      && (x.waterfallSides || []).includes('back'));\n  }\n\n  // What collectEndPanelFaces needs to know about the range: its door\n  // thickness, which panel products it sells, and its own back panel sizes.\n  // Shared by the layout pass and the Breakfast Bar Back Panel preview.\n  function panelFaceOpts() {\n    const epStyle = kitchenStyleId ? Catalogue.getKitchenStyle(kitchenStyleId) : null;\n    const doorThicknessMm = (epStyle && epStyle.doorThicknessMm) || undefined;\n    // Which end-panel PRODUCTS this range actually sells. Drives the\n    // back-panel run fallback: an island back long enough to need a 2400\n    // uses one, but a range that does not sell a 2400 gets a 1200 + a wall\n    // panel instead, and a range with neither gets base panels. Cached\n    // because a run asks per kind and getProducts() is the whole catalogue.\n    const panelProductCache = new Map();\n    const hasPanelProduct = (kind, finish, styleId) => {\n      const want = styleId || kitchenStyleId || null;\n      const key = kind + '|' + finish + '|' + want;\n      if (panelProductCache.has(key)) return panelProductCache.get(key);\n      const codes = panelOwnCodes(kind, finish);\n      const all = Catalogue.getProducts();\n      const found = codes.some(code =>\n        all.some(pr => pr.kbbUnitTypeCode === code && pr.kitchenStyleId === want));\n      panelProductCache.set(key, found);\n      return found;\n    };\n    // The range's own Island & Breakfast Bar back panels, read from their\n    // codes (BBEPP2400, BBEPTG2100, BBEPGR1200, BBEPP-PH-1200 ...), so a back\n    // panel run is built from the sizes this range really sells.\n    const backPanelStockCache = new Map();\n    const backPanelStock = (styleId) => {\n      const want = styleId || kitchenStyleId || null;\n      if (backPanelStockCache.has(want)) return backPanelStockCache.get(want);\n      const out = [], seen = new Set();\n      for (const pr of Catalogue.getProducts()) {\n        if (pr.kitchenStyleId !== want) continue;\n        const p = parseBackPanelCode(pr.kbbUnitTypeCode);\n        if (!p || seen.has(p.code)) continue;\n        seen.add(p.code);\n        out.push(p);\n      }\n      backPanelStockCache.set(want, out);\n      return out;\n    };\n    return { doorThicknessMm, hasPanelProduct, backPanelStock };\n  }\n\n  // ---- Breakfast Bar Back Panel popup (Arden, 2026-10-22) -----------------\n  // The units the back waterfall of this unit's worktop would cover.\n  function barWaterfallUnitIds(cabinetId) {\n    const s = (buildWorktops() || []).find(x => x && (x.cabinetIds || []).includes(cabinetId)\n      && (x.waterfallSides || []).includes('back'));\n    return s ? worktopBarUnits(s, new Map((cabinets || []).map(c => [c.id, c]))).map(c => c.id) : [];\n  }\n  // The popup's staged choice laid onto a list of units, without touching it:\n  // the finish across the panel's whole run (one run is one panel), or the\n  // worktop's back waterfall in its place, and the extensions on the run's two\n  // end units. `staged` = { finish: 'plain'|'tng'|'grooved'|'acoustic'|\n  // 'waterfall', acousticHandle, extLeft, extRight } - left / right as you\n  // face the panel, which is the run's lo / hi end (backPanelUserExt).\n  function withBackPanelStaged(list, cabinetId, staged) {\n    if (!staged || !staged.finish) return list;\n    const run = backPanelRunOf(list, cabinetId);\n    const runIds = new Set(run ? run.map(u => u.id) : [cabinetId]);\n    const wfIds = new Set(barWaterfallUnitIds(cabinetId));\n    const wantWf = staged.finish === 'waterfall';\n    let out = list.map(c => {\n      if (!c) return c;\n      const bb = c.breakfastBarBack || {};\n      if (wantWf) {\n        return (wfIds.has(c.id) && !bb.waterfall)\n          ? { ...c, breakfastBarBack: { ...bb, waterfall: true } } : c;\n      }\n      // Taking the waterfall off puts a panel back on every unit it covered.\n      if (runIds.has(c.id) || (wfIds.has(c.id) && bb.waterfall)) {\n        const next = { ...bb, finish: staged.finish, tng: staged.finish === 'tng', waterfall: false };\n        // True Handleless back finish (Plain Panel / Match Drawer Fronts).\n        if (staged.thDrawerFronts != null) next.thDrawerFronts = !!staged.thDrawerFronts;\n        if (staged.finish === 'acoustic') next.acousticHandle = staged.acousticHandle || bb.acousticHandle || null;\n        // ...and its style: Standard (floor to worktop) or Profiled.\n        if (staged.thProfile != null && c.backPanel)\n          return { ...c, breakfastBarBack: next, backPanel: { ...c.backPanel, thProfile: !!staged.thProfile } };\n        return { ...c, breakfastBarBack: next };\n      }\n      return c;\n    });\n    if (!wantWf) {\n      const r = backPanelRunOf(out, cabinetId);\n      const setExt = (id, key, v) => {\n        if (v == null) return;\n        const mm = Math.max(0, Math.min(BACK_PANEL_EXT_MAX_MM, Math.round(Number(v) || 0)));\n        out = out.map(c => (c && c.id === id)\n          ? { ...c, backPanel: { ...(c.backPanel || {}), userExtMm: { ...((c.backPanel && c.backPanel.userExtMm) || {}), [key]: mm } } }\n          : c);\n      };\n      if (r && r.length) {\n        setExt(r[0].id, 'lo', staged.extLeft);\n        setExt(r[r.length - 1].id, 'hi', staged.extRight);\n        if (staged.gapMm != null) {\n          const ids = new Set(r.map(u => u.id));\n          const g = Math.max(0, Math.round(Number(staged.gapMm) || 0));\n          out = out.map(c => (c && ids.has(c.id) && c.backPanel)\n            ? { ...c, backPanel: { ...c.backPanel, gapMm: g } } : c);\n        }\n        if (staged.fullDepth != null) {\n          const ids = new Set(r.map(u => u.id));\n          out = out.map(c => (c && ids.has(c.id))\n            ? { ...c, useFullSizeEndPanel: !!staged.fullDepth, fullSizeEndPanelUserSet: true } : c);\n        }\n      }\n    }\n    return out;\n  }\n  // How far one end of a run's back panel can go before it meets a wall, a\n  // unit or a room feature standing on the floor: measured along the back\n  // line, just behind the carcase where the panel stands, from the end unit's\n  // back corner. null when nothing is in the way.\n  function backPanelEndGap(u, end, skipIds) {\n    const W = u.widthMm || 0, Dp = u.depthMm || 0;\n    const th = ((u.rotationDeg || 0) * Math.PI) / 180;\n    const ax = Math.cos(th), ay = Math.sin(th);      // the unit's own +X: lo -> hi\n    const nx = -Math.sin(th), ny = Math.cos(th);     // out of its back\n    const k = end === 'hi' ? 1 : -1;\n    const cx = (u.x || 0) + W / 2, cy = (u.y || 0) + Dp / 2;\n    const ex = cx + k * (W / 2) * ax + (Dp / 2) * nx;\n    const ey = cy + k * (W / 2) * ay + (Dp / 2) * ny;\n    const dir = { x: k * ax, y: k * ay };\n    const segs = [];\n    for (const w of getWalls(room)) segs.push([w.from, w.to]);\n    const rectSegs = (x, y, w, d, deg) => {\n      const r = ((deg || 0) * Math.PI) / 180, cs = Math.cos(r), sn = Math.sin(r);\n      const mx = x + w / 2, my = y + d / 2;\n      const p = [[-w / 2, -d / 2], [w / 2, -d / 2], [w / 2, d / 2], [-w / 2, d / 2]]\n        .map(([lx, ly]) => ({ x: mx + lx * cs - ly * sn, y: my + lx * sn + ly * cs }));\n      for (let i = 0; i < 4; i++) segs.push([p[i], p[(i + 1) % 4]]);\n    };\n    for (const o of cabinets) {\n      if (!o || skipIds.has(o.id) || isWallMounted(o)) continue;\n      rectSegs(o.x || 0, o.y || 0, o.widthMm || 0, o.depthMm || 0, o.rotationDeg);\n    }\n    for (const p of (roomConfig.perimeterItems || [])) {\n      if (!p || p.type === 'beam' || p.type === 'sloped-ceiling' || p.type === 'vaulted-ceiling') continue;\n      if (p.type === 'free-block' && (Number(p.restMm) || 0) > 600) continue;   // overhead\n      if (!(p.widthMm > 0) || !(p.depthMm > 0)) continue;\n      rectSegs(p.x || 0, p.y || 0, p.widthMm, p.depthMm, p.rotationDeg);\n    }\n    let best = Infinity;\n    for (const off of [2, 10, 18]) {   // across the panel's thickness\n      const ox = ex + nx * off, oy = ey + ny * off;\n      for (const [a, b] of segs) {\n        const qx = b.x - a.x, qy = b.y - a.y;\n        const den = dir.x * qy - dir.y * qx;\n        if (Math.abs(den) < 1e-9) continue;\n        const wx = a.x - ox, wy = a.y - oy;\n        const t = (wx * qy - wy * qx) / den;\n        const v = (wx * dir.y - wy * dir.x) / den;\n        if (v < -1e-6 || v > 1 + 1e-6 || t < -0.5) continue;\n        if (t < best) best = t;\n      }\n    }\n    return Number.isFinite(best) ? Math.max(0, Math.round(best)) : null;\n  }\n  // The popup's view of a unit's back panel run: its two ends - how far the\n  // panel is extended past each now, and how far it could go to the nearest\n  // wall or unit - and whether it can be extended at all.\n  function getBackPanelRunInfo(cabinetId) {\n    const run = backPanelRunOf(cabinets, cabinetId);\n    if (!run || !run.length) return null;\n    const skip = new Set(run.map(u => u.id));\n    const first = run[0], last = run[run.length - 1];\n    return {\n      ids: run.map(u => u.id),\n      canExtend: !(run.seed && run.seed.backPanel && run.seed.backPanel.thProfile),\n      maxMm: BACK_PANEL_EXT_MAX_MM,\n      left:  { mm: backPanelUserExt(first, 'lo'), gapMm: backPanelEndGap(first, 'lo', skip) },\n      right: { mm: backPanelUserExt(last, 'hi'),  gapMm: backPanelEndGap(last, 'hi', skip) },\n      // Step Off Unit: the gap between the units and the panel as it is now,\n      // the least it can be (where the panel normally stands) and the most\n      // (end panels top out at MANUAL_EP_MAX_MM).\n      ...(() => {\n        const reals = run.map(u => cabinets.find(c => c && c.id === u.id)).filter(Boolean);\n        const T = (u) => (u.backPanel && u.backPanel.thicknessMm) || 20;\n        const normalGap = (u) => (typeof u.bpNormalGapMm === 'number') ? u.bpNormalGapMm : 0;\n        const nowGap = (u) => u.epManualBack ? Math.max(0, Math.round(u.epManualBack.standOffMm - T(u))) : normalGap(u);\n        // The run can switch Full Depth when every unit has a plain or T&G end:\n        // then any gap is allowed, and one under gapFullMm turns Full Depth off.\n        const rounded = (u) => ['left', 'right'].some(s => ['radius', 'square'].includes(u.endPanels && u.endPanels[s] && u.endPanels[s].style));\n        const fullSwitch = reals.length > 0 && reals.every(u => typeof u.bpFullGapMm === 'number' && !rounded(u));\n        const gapFullMm = Math.max(0, ...reals.map(u => u.bpFullGapMm || 0));\n        const fullDepth = reals.length > 0 && reals.every(u => !!u.useFullSizeEndPanel);\n        const gapMinMm = fullSwitch ? 0 : Math.max(0, ...reals.map(normalGap));\n        const gapMaxMm = Math.max(gapMinMm, Math.min(600, ...reals.map(u =>\n          (typeof u.epNormalDepthMm === 'number') ? normalGap(u) + MANUAL_EP_MAX_MM - u.epNormalDepthMm : 600)));\n        return { gapMm: Math.max(gapMinMm, ...reals.map(nowGap)), gapMinMm, gapMaxMm, gapFullMm, fullDepth, fullSwitch };\n      })(),\n    };\n  }\n  // Confirm: the staged choice onto the plan as one edit.\n  function handleApplyBackPanel(cabinetId, staged) {\n    const next = withBackPanelStaged(cabinets, cabinetId, staged);\n    if (next === cabinets) return;\n    cabinets = next;\n    rerender();\n    scheduleBasketResync();\n  }\n  // The popup's live render: the kitchen with the staged choice, on the Stack\n  // popup's own renderer, looking at the back of the run. The units are\n  // copies, their back panels too (the segments are stamped onto them), so\n  // nothing on the plan changes until Confirm.\n  async function renderBackPanelPreview(slot, cabId, staged) {\n    const seq = ++_stackPreviewSeq;\n    const r = await stackPreviewRenderer();\n    if (!r) return false;\n    if (seq !== _stackPreviewSeq || !slot || !slot.isConnected) return true;\n    if (!cabinets.some(c => c && c.id === cabId)) return false;\n    if (r.el.parentNode !== slot) slot.appendChild(r.el);\n    const copies = cabinets.map(o => (o ? {\n      ...o,\n      backPanel: o.backPanel ? { ...o.backPanel } : o.backPanel,\n      endPanels: o.endPanels ? { ...o.endPanels,\n        left: o.endPanels.left ? { ...o.endPanels.left } : o.endPanels.left,\n        right: o.endPanels.right ? { ...o.endPanels.right } : o.endPanels.right } : o.endPanels\n    } : o));\n    const mini = withBackPanelStaged(copies, cabId, staged);\n    // The staged gap reaches the end panels, the back panel and the worktop\n    // through the manual end panel stamp, as the layout pass does it.\n    stampFreestandingPanels(mini);\n    for (const o of mini) if (o) stampManualEndPanels(o, Catalogue.getKitchenStyle && Catalogue.getKitchenStyle(o.kitchenStyleId));\n    stampBackPanelSegments(mini, collectEndPanelFaces(mini, panelFaceOpts()));\n    const h = r.handle;\n    h.setWallColour(getWallColour(wallColourHandle).hex);\n    applyFeatureWallsTo3D(h);\n    applyFloorTo3D(h);\n    h.setActive(true);\n    h.render({ room, roomConfig, cabinets: mini, baseRoom, featureStyles, railFinishHandle, segmentColours,\n               worktops: buildWorktops(mini), worktopColourHex, worktopColours, worktopCornerRadii,\n               worktopItems: [], furnitureItems: [], handleGroups, lights: [], lightsOn: false });\n    h.resize();\n    frameBackPanelPreview(h, mini, cabId);\n    return true;\n  }\n  // Three-quarters on to the back of the run, extensions and all. A unit's\n  // back faces (-sin, cos) of its rotation on the plan; plan x/y are world x/z.\n  function frameBackPanelPreview(h, mini, cabId) {\n    const run = backPanelRunOf(mini, cabId) || mini.filter(o => o && o.id === cabId);\n    if (!run.length) return;\n    const th = ((run[0].rotationDeg || 0) * Math.PI) / 180;\n    const ax = Math.cos(th), ay = Math.sin(th);\n    let minX = Infinity, maxX = -Infinity, minZ = Infinity, maxZ = -Infinity, top = 0;\n    const take = (x, z) => { minX = Math.min(minX, x); maxX = Math.max(maxX, x); minZ = Math.min(minZ, z); maxZ = Math.max(maxZ, z); };\n    for (const o of run) {\n      const b = stackPreviewFootprint(o);\n      take(b.minX, b.minY); take(b.maxX, b.maxY);\n      top = Math.max(top, unitVerticalRange(o).top);\n    }\n    // Out to the ends of the extended panel.\n    const endAt = (u, k, ext) => {\n      const b = stackPreviewFootprint(u), reach = (u.widthMm || 0) / 2 + ext;\n      take((b.minX + b.maxX) / 2 + k * ax * reach, (b.minY + b.maxY) / 2 + k * ay * reach);\n    };\n    endAt(run[0], -1, backPanelUserExt(run[0], 'lo'));\n    endAt(run[run.length - 1], 1, backPanelUserExt(run[run.length - 1], 'hi'));\n    top += 150;\n    const bx = -Math.sin(th), bz = Math.cos(th);\n    // Far enough back for the whole run and its extensions in the portrait box.\n    const swing = 0.55;\n    const dx = bx * Math.cos(swing) - bz * Math.sin(swing);\n    const dz = bx * Math.sin(swing) + bz * Math.cos(swing);\n    const cx = (minX + maxX) / 2, cz = (minZ + maxZ) / 2, cy = top / 2;\n    const size = Math.max(top, maxX - minX, maxZ - minZ);\n    const dist = size * 2.6;\n    h.setCameraState({ pos: [cx + dx * dist, cy + size * 0.5, cz + dz * dist], target: [cx, cy * 0.8, cz] });\n  }\n  // The worktop round a unit, for its overhang diagram: the worktop's outline\n  // in mm about the unit's centre (plan axes), and the corners of it that are\n  // this unit's to round - a corner of the worktop nearer this unit than any\n  // other on it, on a side with an overhang set, standing at least 50mm past\n  // the carcase. Each corner's largest radius\n  // is how far it stands past the carcase, at most 300mm (Arden, 2026-10-09).\n  // Corners are the plan's own (applyCornerRadii); one already rounded is\n  // always listed so it can be changed or removed.\n  function getCabinetWorktopShape(cabinetId) {\n    try {\n      const c = (cabinets || []).find(x => x && x.id === cabinetId);\n      if (!c) return null;\n      const s = (buildWorktops() || []).find(x => x && (x.cabinetIds || []).includes(cabinetId));\n      if (!s || !s.polygon || s.polygon.length < 3) return null;\n      const rectOf = (k) => {\n        const w = k.widthMm || 0, d = k.depthMm || 0;\n        return { cx: k.x + w / 2, cy: k.y + d / 2, hw: w / 2, hd: d / 2, th: ((k.rotationDeg || 0) * Math.PI) / 180 };\n      };\n      // How far a point stands past a unit's carcase, along the unit's own axes.\n      const past = (r, p) => {\n        const dx = p.x - r.cx, dy = p.y - r.cy;\n        const cs = Math.cos(-r.th), sn = Math.sin(-r.th);\n        const lx = dx * cs - dy * sn, ly = dx * sn + dy * cs;\n        return { gx: Math.max(0, Math.abs(lx) - r.hw), gy: Math.max(0, Math.abs(ly) - r.hd), lx, ly };\n      };\n      const me = rectOf(c);\n      const others = (cabinets || []).filter(k => k && k.id !== cabinetId && (s.cabinetIds || []).includes(k.id)).map(rectOf);\n      const xs = s.polygon.map(p => p.x), ys = s.polygon.map(p => p.y);\n      const x0 = Math.min(...xs), x1 = Math.max(...xs), y0 = Math.min(...ys), y1 = Math.max(...ys);\n      const at = { tl: { x: x0, y: y0 }, tr: { x: x1, y: y0 }, bl: { x: x0, y: y1 }, br: { x: x1, y: y1 } };\n      const radii = worktopCornerRadii[s.id] || {};\n      const corners = {};\n      for (const k of ['tl', 'tr', 'bl', 'br']) {\n        const p = at[k];\n        const v = Number(radii[k]) || 0;\n        // A square corner has to be a real corner of the outline.\n        if (!v && !s.polygon.some(q => Math.abs(q.x - p.x) < 1 && Math.abs(q.y - p.y) < 1)) continue;\n        const g = past(me, p);\n        // Only where the customer has set an overhang on one of the corner's\n        // two sides - a worktop that already runs past the carcase (an island\n        // void, a breakfast bar back) offered radii with nothing entered\n        // (Arden, 2026-10-09). The unit's left is its local +X, its front -Y.\n        const ext = c.worktop || {};\n        const sideX = g.lx > 0 ? 'left' : 'right', sideY = g.ly < 0 ? 'front' : 'back';\n        if (!v && !((Number(ext[sideX]) || 0) > 0 || (Number(ext[sideY]) || 0) > 0)) continue;\n        const dMe = Math.hypot(g.gx, g.gy);\n        if (others.some(r => { const o = past(r, p); return Math.hypot(o.gx, o.gy) < dMe; })) continue;\n        let max = Math.min(300, Math.round(Math.max(g.gx, g.gy)));\n        // A radius longer than either edge at the corner cannot be cut\n        // (roundCornerInPolygon leaves it square), so it is not offered.\n        const vi = s.polygon.findIndex(q => Math.abs(q.x - p.x) < 1 && Math.abs(q.y - p.y) < 1);\n        if (vi >= 0) {\n          const n = s.polygon.length, a = s.polygon[(vi - 1 + n) % n], b = s.polygon[(vi + 1) % n];\n          max = Math.min(max, Math.floor(Math.hypot(p.x - a.x, p.y - a.y)), Math.floor(Math.hypot(p.x - b.x, p.y - b.y)));\n        }\n        if (!v && max < 50) continue;\n        corners[k] = { max: Math.max(max, v), value: v };\n      }\n      return { worktopId: s.id, corners,\n               outline: s.polygon.map(q => ({ x: q.x - me.cx, y: q.y - me.cy })) };\n    } catch (e) { return null; }\n  }\n  // The worktop a unit sits under (its slab), for the unit's Customise\n  // Worktop popup. null when it has none.\n  function getCabinetWorktopId(cabinetId) {\n    try {\n      const s = (buildWorktops() || []).find(x => x && (x.cabinetIds || []).includes(cabinetId));\n      return s ? s.id : null;\n    } catch (e) { return null; }\n  }\n  // For the selection panel's popup: one worktop's waterfall picture.\n  // The selected worktop's outline as it sits on the PLAN (seen from above,\n  // top of the plan at the top), in mm from its top-left - for the Corner\n  // Radius popup, whose corners are the plan's own (applyCornerRadii).\n  function getWorktopPlanOutline(worktopId) {\n    try {\n      const s = (buildWorktops() || []).find(x => x && x.id === worktopId);\n      if (!s || !s.polygon || s.polygon.length < 3) return null;\n      const xs = s.polygon.map(p => p.x), ys = s.polygon.map(p => p.y);\n      const x0 = Math.min(...xs), y0 = Math.min(...ys);\n      return { worktopId, outline: s.polygon.map(p => ({ x: p.x - x0, y: p.y - y0 })),\n               widthMm: Math.max(...xs) - x0, depthMm: Math.max(...ys) - y0 };\n    } catch (e) { return null; }\n  }\n\n  function getWorktopWaterfallInfo(worktopId) {\n    try {\n      const s = (buildWorktops() || []).find(x => x && x.id === worktopId);\n      if (!s) return null;\n      const info = worktopWaterfallInfo(s, waterfallThicknessMm());\n      if (!info) return null;\n      // The outline as the customer sees it from the front: back at the top,\n      // their left on the left (local +X), in mm from the top-left corner.\n      const f = info.frame;\n      const outline = f.pts.map(p => ({ x: f.x1 - p.x, y: f.y1 - p.y }));\n      return { worktopId, outline, widthMm: f.x1 - f.x0, depthMm: f.y1 - f.y0,\n               sides: info.sides, heightMm: info.heightMm, thicknessMm: info.thicknessMm,\n               verticalMitres: info.verticalMitres, mitreMm: info.mitreMm,\n               // Round edge laminate: no waterfall can be added (see waterfallBarredMaterial).\n               barred: waterfallBarredForSlab(s) };\n    } catch (e) { return null; }\n  }\n\n  function computeLinearTotals() {\n    const fs = featureStyles || {};\n    const trim = computeTrimRuns({\n      cabinets,\n      featureStyles: fs,\n      roomVertices: room?.vertices || [],\n      perimeterItems: roomConfig?.perimeterItems || [],\n      doorThicknessMm: 18\n    });\n    const out = {};\n    // Plinth: every group of the plan's kind - including sections only set to\n    // another position - bills as the plan's plinth.\n    const _planPlinthKind = (trim.plinth && trim.plinth.kind) || null;\n    for (const key of ['plinth', 'cornice', 'pelmet']) {\n      const d = trim[key] || { totalMm: 0, style: fs[key] || 'none' };\n      out[key] = {\n        mm: Math.round(d.totalMm || 0),\n        style: d.style && d.style !== 'none' ? d.style : (fs[key] || (key === 'plinth' ? 'standard' : 'modern'))\n      };\n    }\n    // Sections set to the other plinth kind (plain / skirting): style = that kind.\n    if (_planPlinthKind) {\n      out.plinth.mm = Math.round(plinthRunsOfKind(trim, _planPlinthKind).reduce((n, d) => n + plinthStockMm(d), 0));\n      const altKind = _planPlinthKind === 'plain' ? 'skirting' : 'plain';\n      const mm = plinthRunsOfKind(trim, altKind).reduce((n, d) => n + plinthStockMm(d), 0);\n      if (mm > 0) out.plinthAlt = { mm: Math.round(mm), style: altKind };\n    }\n    return out;\n  }\n\n  // Trim \u2192 chargeable basket lines.\n  //\n  // Two billing shapes, told apart by the trim variant's `custom.length_mm`:\n  //   \u2022 LENGTH stock (e.g. a 3m plinth) - the run is cut from stock lengths,\n  //     so quantity is ceil(total run / stock length). Off-cuts aren't credited,\n  //     which matches how the trade actually sells it.\n  //   \u2022 PER PIECE (no length_mm) - the External Curved Plinth is a moulded\n  //     piece, one per external curve, not something cut from a length.\n  //\n  // The curved plinth is deliberately NOT a picker choice: you don't select it,\n  // you get one wherever the kitchen curves. So it's matched by product code\n  // (like end-panel boards) rather than by a chosen profile.\n  const TRIM_CURVED_PLINTH_CODE = 'EXTCURVPLIN';\n  // Resolve the Radius / Square product for a style. Lives at module level\n  // because computeEndFeatureCharges() below is the only caller and runs\n  // outside the basket builder - it was defined inside it, which threw a\n  // ReferenceError the moment a plan had an end feature.\n  const endFeatureProduct = (kind, styleId) => {\n    const codes = EP_FEATURE_CODES[kind] || [];\n    const want  = styleId || kitchenStyleId || null;\n    const all   = Catalogue.getProducts();\n    for (const code of codes) {\n      const p = all.find(pr => pr.kbbUnitTypeCode === code && pr.kitchenStyleId === want);\n      if (!p) continue;\n      const v = p.variants && p.variants[0];\n      if (!v) continue;\n      const info = Catalogue.getVariantInfo(v.id);\n      // lengthMm = the STOCK LENGTH of one piece (variant custom.length_mm).\n      const lenMm = (typeof v.lengthMm === 'number' && v.lengthMm > 0) ? v.lengthMm\n                  : (typeof info?.variant?.lengthMm === 'number' ? info.variant.lengthMm : null);\n      return { variantId: v.id, priceCents: info?.priceCents ?? null,\n               name: p.title || code, handle: p.handle || null, code, lengthMm: lenMm,\n               compareAtCents: info?.variant?.compareAtPrice ?? null };\n    }\n    return null;\n  };\n\n  // TRUE HANDLELESS EXTERNAL CORNER POSTS - the 46x46 L-post at each outer\n  // corner of a TH end panel (front, plus the back on an island). The numbering\n  // pass gave each its own number (cab.cornerPostNumbers) but nothing billed\n  // them, so those numbers were missing from the quote (Arden, 2026-10-21:\n  // \"External Corner Posts, not Adjustable corner posts\" - the range's own\n  // product). A base unit takes the 685 post (TH base height), else the range's\n  // standard one. One line per post, with the number the plan shows on it.\n  const EXT_CORNER_POST_CODES = { base: ['EXTCP685', 'EXTCP'], other: ['EXTCP', 'EXTCP685'] };\n  const extCornerPostProduct = (cab) => {\n    const codes = /^base/i.test(cab.category || '') ? EXT_CORNER_POST_CODES.base : EXT_CORNER_POST_CODES.other;\n    const want = cab.kitchenStyleId || kitchenStyleId || null;\n    const all = Catalogue.getProducts();\n    for (const code of codes) {\n      const p = all.find(pr => pr.kbbUnitTypeCode === code && pr.kitchenStyleId === want);\n      const v = p && p.variants && p.variants[0];\n      if (!v) continue;\n      const info = Catalogue.getVariantInfo(v.id);\n      return { variantId: v.id, priceCents: info?.priceCents ?? null, name: p.title || code,\n               handle: p.handle || null, code, compareAtCents: info?.variant?.compareAtPrice ?? null };\n    }\n    return null;\n  };\n  function computeCornerPostCharges() {\n    try {\n      const out = [];\n      for (const c of (cabinets || [])) {\n        const nums = c && c.cornerPostNumbers;\n        if (!nums) continue;\n        const prod = extCornerPostProduct(c);\n        for (const key of Object.keys(nums)) {\n          const [side, pos] = key.split(':');\n          if (!prod || !prod.variantId) {\n            console.warn('[BTK corner posts] no External Corner Post for %s - post %s NOT charged', c.kitchenStyleId, nums[key]);\n            continue;\n          }\n          out.push({ product: prod, qty: 1, name: prod.name,\n            detail: `${side === 'left' ? 'Left' : 'Right'} end, ${pos === 'back' ? 'back' : 'front'} corner`,\n            ownerCabId: c.id, number: nums[key], side, pos,\n            faces: [`${c.id}:${side}:cpost${pos === 'back' ? '-back' : ''}`] });\n        }\n      }\n      return out;\n    } catch (err) {\n      console.error('[BTK] corner post charges failed', err);\n      return [];\n    }\n  }\n\n  // END FEATURES (Radius / Square) are sold in LENGTHS and cut to fit, so they\n  // are pooled per style + kind and packed - NOT billed one per end.\n  //   base 720 carcase + 150 legs = 870   tall carcase + 150   wall carcase + 70\n  // An off-cut only serves another end if a WHOLE end fits in it, so five 870\n  // ends off a 2400 length need THREE lengths, where a running total says two.\n  function computeEndFeatureCharges() {\n    try {\n      return _computeEndFeatureCharges();\n    } catch (err) {\n      // Never let an end-feature charge take the whole basket down - the plan\n      // must still add, even if one line cannot be priced.\n      console.error('[BTK] end-feature charges failed', err);\n      return [];\n    }\n  }\n  function _computeEndFeatureCharges() {\n    const bins = (endPanelLayout && endPanelLayout.endFeatureBins) || [];\n    if (bins.length) {\n      const out = [];\n      for (const bin of bins) {\n        const prod = endFeatureProduct(bin.kind, bin.styleId);\n        if (!prod || !prod.variantId) {\n          console.warn('[BTK end features] %s: no product in %s - %d end(s) NOT charged',\n            bin.kind, bin.styleId || kitchenStyleId, bin.items.length);\n          continue;\n        }\n        const cuts = bin.items.map(i => Math.round(i.lengthMm)).join(' + ');\n        const detail = bin.stockMm\n          ? `${bin.stockMm}mm length \u00B7 cut into ${bin.items.length} `\n            + `end${bin.items.length > 1 ? 's' : ''} (${cuts}mm`\n            + (bin.remaining > 0 ? `, ${Math.round(bin.remaining)}mm off-cut)` : ')')\n          : `1 end (${cuts}mm) - no stock length set on the product`;\n        out.push({ product: prod, qty: 1, name: prod.name, detail, kind: bin.kind,\n                   colour: bin.colour || null,\n                   ownerCabId: bin.ownerCabId, number: bin.number,\n                   faces: bin.items.map(i => i.focusKey || i.faceKey).filter(Boolean) });\n      }\n      return out;\n    }\n    return [];\n  }\n\n  // Radius ends that a CORNICE crosses - wall, bridging and tall - each of\n  // which needs one curved cornice BLOCK on top. Square ends are cut square\n  // and the straight cornice simply returns, so they take no block.\n  // A PROFILED (skirting / decorative) plinth cannot follow a curve: it is not\n  // offered while the plan has a radius end post on a unit the plinth runs\n  // under (base / tall), or a curved base unit (Arden, 2026-10-07).\n  // -> { posts, curves }, counts of each.\n  // cabIds: only those units (a plinth section). Otherwise the units following\n  // the plan's plinth - a unit set to Plain on its own takes no skirting. A\n  // FLUSH skirting butts a radius end post, so posts block only a proud one\n  // (Arden, 2026-10-27); radiusPosts counts them either way, for the note.\n  function profiledPlinthBlockers(cabIds = null) {\n    const ids = cabIds ? new Set(cabIds) : null;\n    const live = (cabinets || []).filter(c => c && !c.excludeFromQuote\n      && (ids ? ids.has(c.id) : c.plinthType !== 'plain'));\n    const radiusPosts = live\n      .filter(c => /^(base|tall)/i.test(c.category || ''))\n      .reduce((n, c) => n + ['left', 'right'].filter(side => {\n        const ep = (c.endPanels || {})[side];\n        return ep && ep.active && ep.style === 'radius';\n      }).length, 0);\n    const curves = live.filter(c => c.radiusUnit && c.radiusUnit.kind !== 'end-wall'\n      && !/^wall/i.test(c.category || '')).length;\n    const posts = live.filter(c => plinthPositionOf(c) === 'proud')\n      .filter(c => /^(base|tall)/i.test(c.category || ''))\n      .reduce((n, c) => n + ['left', 'right'].filter(side => {\n        const ep = (c.endPanels || {})[side];\n        return ep && ep.active && ep.style === 'radius';\n      }).length, 0);\n    return { posts, curves, radiusPosts };\n  }\n  // A unit's skirting position: its section's own, else the plan's.\n  function plinthPositionOf(c) {\n    const p = c && c.plinthPosition;\n    if (p === 'proud' || p === 'flush') return p;\n    return (featureStyles || {}).plinthPosition === 'flush' ? 'flush' : 'proud';\n  }\n  // The plinth runs of one kind across the plan's group and the sections set\n  // otherwise (engine 'plinth' / 'plinthAlt' / 'plinthAlt2').\n  // A plinth taller than the 150mm stock (row 95) is cut from end panels\n  // instead (tallPlinthFaces), so its runs leave the plinth lines.\n  function plinthRunIsTall(run) {\n    return Number(run && run.plinthMm) > PLINTH_STD_MM;\n  }\n  function plinthStockMm(d) {\n    return ((d && d.runs) || []).filter(r => !plinthRunIsTall(r))\n      .reduce((n, r) => n + (r.segments || []).reduce((m, sg) => m + (sg.lengthMm || 0), 0), 0);\n  }\n  // Tall plinth pieces as end panel cut-list faces: each run's length in pieces\n  // no longer than a Tall End Panel board (2400), as wide as the plinth is high.\n  const TALL_PLINTH_PIECE_MAX_MM = 2400;\n  function tallPlinthFaces(list) {\n    const live = (list || []).filter(c => c && !c.excludeFromQuote);\n    if (!live.some(c => Number(c.plinthShiftMm) < 0)) return [];\n    const fs = featureStyles || {};\n    const trim = computeTrimRuns({ cabinets: live, featureStyles: fs, roomVertices: room?.vertices || [],\n      perimeterItems: roomConfig?.perimeterItems || [], doorThicknessMm: 18 });\n    const out = [];\n    for (const k of ['plinth', ...PLINTH_ALT_FEATURES]) {\n      for (const run of ((trim[k] && trim[k].runs) || [])) {\n        if (!plinthRunIsTall(run)) continue;\n        for (const sg of run.segments || []) {\n          if (!(sg.lengthMm >= 1)) continue;\n          const cab = live.find(c => (sg.cabinetIds || []).includes(c.id)) || null;\n          const n = Math.ceil(sg.lengthMm / TALL_PLINTH_PIECE_MAX_MM);\n          for (let i = 0; i < n; i++) {\n            out.push({ id: `${sg.id}:plinth${i}`, role: 'tall', depthMm: Math.round(run.plinthMm),\n                       heightMm: Math.ceil(sg.lengthMm / n), side: 'front', cabIds: sg.cabinetIds || [],\n                       styleId: (cab && cab.kitchenStyleId) || kitchenStyleId || null,\n                       colour: (cab && cab.plinthColour) || fs.plinthColour || (cab && cab.doorColourHandle) || null, finish: 'plain',\n                       tallPlinth: true, px: sg.midX, py: sg.midY });\n          }\n        }\n      }\n    }\n    return out;\n  }\n  function plinthRunsOfKind(trim, kind) {\n    return ['plinth', ...PLINTH_ALT_FEATURES].map(k => trim && trim[k])\n      .filter(d => d && d.kind === kind);\n  }\n\n  // PLAIN or SKIRTING plinth for a plinth section (Arden, 2026-10-27). The plan's\n  // plinth is the default; a section picked in the 3D can take the other kind,\n  // stored on the units it runs under (cab.plinthType) so it survives the run\n  // being redrawn. Choosing the plan's own kind hands them back to the plan.\n  function plinthSectionInfo(cabIds) {\n    const fs = featureStyles || {};\n    if (!fs.plinth || fs.plinth === 'none') return null;\n    const planKind = plinthKindOf(fs.plinth);\n    const styleId = planTrimStyle().styleId;\n    const sold = ((Catalogue.getTrimForStyle?.(styleId) || {}).plinth || []).filter(p => p.available !== false);\n    const has = (k) => sold.some(p => plinthKindOf(p.name) === k);\n    if (!has('plain') || !has('skirting')) return null;\n    const cabs = (cabinets || []).filter(c => c && (cabIds || []).includes(c.id));\n    if (!cabs.length) return null;\n    const kinds = new Set(cabs.map(c => (c.plinthType === 'plain' || c.plinthType === 'skirting') ? c.plinthType : planKind));\n    const positions = new Set(cabs.map(plinthPositionOf));\n    const b = profiledPlinthBlockers(cabs.map(c => c.id));\n    const skirtingWhy = b.curves > 0 ? 'Not with curves' : '';\n    // A radius end post: the skirting runs up to it Flush, so Proud is not offered.\n    const proudWhy = b.radiusPosts > 0 ? 'This section has a radius end, so its skirting plinth sits Flush.' : '';\n    return {\n      current: kinds.size === 1 ? [...kinds][0] : null, planKind,\n      position: positions.size === 1 ? [...positions][0] : null,\n      planPosition: fs.plinthPosition === 'flush' ? 'flush' : 'proud',\n      skirtingWhy, proudWhy\n    };\n  }\n  // PROUD or FLUSH for one skirting section (Arden, 2026-10-27), over the\n  // plan's position. The plan's own position hands it back to the plan.\n  function handleSetPlinthPosition(cabIds, pos) {\n    if (pos !== 'proud' && pos !== 'flush') return;\n    const info = plinthSectionInfo(cabIds);\n    if (!info || (pos === 'proud' && info.proudWhy)) return;\n    const ids = new Set(cabIds || []);\n    cabinets = cabinets.map(c => {\n      if (!c || !ids.has(c.id)) return c;\n      const next = { ...c };\n      if (pos === info.planPosition) delete next.plinthPosition; else next.plinthPosition = pos;\n      return next;\n    });\n    rerender();\n    scheduleBasketResync();\n  }\n  function handleSetPlinthType(cabIds, kind) {\n    if (kind !== 'plain' && kind !== 'skirting') return;\n    const info = plinthSectionInfo(cabIds);\n    if (!info || (kind === 'skirting' && info.skirtingWhy)) return;\n    const ids = new Set(cabIds || []);\n    cabinets = cabinets.map(c => {\n      if (!c || !ids.has(c.id)) return c;\n      const next = { ...c };\n      if (kind === info.planKind) delete next.plinthType; else next.plinthType = kind;\n      if (kind === 'skirting' && info.proudWhy && info.planPosition !== 'flush') next.plinthPosition = 'flush';\n      return next;\n    });\n    rerender();\n    scheduleBasketResync();\n  }\n\n  // A unit's own Plinth popup (Arden, 2026-10-28) - offered on unit types whose\n  // default plinth is None (the Media Base Units, often wall-hung). None =\n  // floating: no plinth or legs, with its Height from floor. Otherwise the\n  // plinth kinds the range sells, and Proud / Flush for a skirting one, as the\n  // plinth section panel has. Not while the unit is stacked (Stack popup).\n  function unitPlinthInfo(cabId) {\n    const c = (cabinets || []).find(x => x && x.id === cabId);\n    const ut = c && c.unitTypeId ? Catalogue.getUnitType(c.unitTypeId) : null;\n    if (!c || !ut || (ut.defaultPlinth !== 'none' && !ut.mediaWall) || isStacked(c) || isUnderWorktopUnit(c) || isHungBetweenUnit(c)) return null;\n    const fs = featureStyles || {};\n    const planKind = (fs.plinth && fs.plinth !== 'none') ? plinthKindOf(fs.plinth) : 'plain';\n    const sold = ((Catalogue.getTrimForStyle?.(planTrimStyle().styleId) || {}).plinth || []).filter(p => p.available !== false);\n    const kinds = ['plain', 'skirting'].filter(k => sold.some(p => plinthKindOf(p.name) === k));\n    const sect = c.plinthType === 'none' ? null : plinthSectionInfo([c.id]);\n    const plinthMm = ut.plinthHeightMm || 150;\n    return {\n      current: c.plinthType === 'none' ? 'none'\n        : ((c.plinthType === 'plain' || c.plinthType === 'skirting') ? c.plinthType : planKind),\n      kinds: kinds.length ? kinds : [planKind],\n      position: plinthPositionOf(c),\n      skirtingWhy: (sect && sect.skirtingWhy) || '',\n      proudWhy: (sect && sect.proudWhy) || '',\n      floatHeightMm: floatHeightMmOf(c, plinthMm)\n    };\n  }\n  function handleSetUnitPlinth(cabId, kind) {\n    if (kind !== 'none' && kind !== 'plain' && kind !== 'skirting') return;\n    if (!unitPlinthInfo(cabId)) return;\n    if (kind !== 'none' && plinthSectionInfo([cabId])) {\n      // Back on a plinth, and the range sells both kinds: the section rules.\n      cabinets = cabinets.map(c => (c && c.id === cabId) ? { ...c, plinthType: undefined } : c);\n      handleSetPlinthType([cabId], kind);\n      return;\n    }\n    cabinets = cabinets.map(c => {\n      if (!c || c.id !== cabId) return c;\n      const next = { ...c };\n      if (kind === 'none') { next.plinthType = 'none'; delete next.plinthPosition; } else delete next.plinthType;\n      return next;\n    });\n    rerender();\n    scheduleBasketResync();\n  }\n  // THE ISLAND DESIGNER'S PLINTH (Arden, 2026-11-19): the kitchen's plinth and\n  // the kinds the range sells, for its End Panels & Plinth step; and its\n  // choice laid on each island unit standing on a plinth, as the plinth\n  // section and the unit's Position menu would (the kitchen's own clears it).\n  function islandPlinthInfo() {\n    const fs = featureStyles || {};\n    if (!fs.plinth || fs.plinth === 'none') return { planKind: null };\n    const sold = ((Catalogue.getTrimForStyle?.(planTrimStyle().styleId) || {}).plinth || []).filter(p => p.available !== false);\n    return {\n      planKind: plinthKindOf(fs.plinth),\n      kinds: ['plain', 'skirting'].filter(k => sold.some(p => plinthKindOf(p.name) === k)),\n      planPosition: fs.plinthPosition === 'flush' ? 'flush' : 'proud',\n      planMm: clampPlinthMm(fs.plinthHeightMm) || PLINTH_STD_MM,\n      // The Island Designer's plinth page (Arden, 2026-11-20): one tile per\n      // sold profile (the plan's own profile for its kind), None's picture,\n      // the kitchen's plinth colour and a preview drawn with the island's\n      // choices.\n      planProfile: fs.plinth,\n      profiles: sold.map(p => ({ name: p.name, label: p.friendlyName || p.name, imageUrl: p.tileImageUrl || null, kind: plinthKindOf(p.name) })),\n      noneImage: (Catalogue.getTrimNoneImage && Catalogue.getTrimNoneImage('plinth')) || null,\n      planColour: fs.plinthColour || null,\n      preview: (st) => renderTrimPreview('plinth', st)\n    };\n  }\n  function islandPlinthOn(c, p) {\n    if (!p || !hasPlinthBand(c) || isPastrySet(c)) return c;\n    const info = islandPlinthInfo();\n    if (!info.planKind) return c;\n    const next = { ...c };\n    const kind = p.kind === 'none' ? 'none'\n      : (p.kind === 'plain' || p.kind === 'skirting') && info.kinds.length > 1 ? p.kind : info.planKind;\n    if (kind === info.planKind) delete next.plinthType; else next.plinthType = kind;\n    // The island's own plinth colour (null = the kitchen's plinth colour, or\n    // the units' doors when it has none).\n    if (kind !== 'none' && p.colour) next.plinthColour = p.colour; else delete next.plinthColour;\n    if (kind === 'skirting' && (p.position === 'proud' || p.position === 'flush') && p.position !== info.planPosition) next.plinthPosition = p.position;\n    else delete next.plinthPosition;\n    const mm = p.heightMm == null ? null : clampPlinthMm(p.heightMm);\n    if (mm == null || mm === info.planMm) delete next.plinthMm; else next.plinthMm = mm;\n    return next;\n  }\n  // A unit's own plinth height (row 95); null or the plan's height hands it\n  // back to the plan (Customise > Cornice, Pelmet & Plinth).\n  function handleSetCabinetPlinthHeight(cabId, mm) {\n    const planMm = clampPlinthMm((featureStyles || {}).plinthHeightMm) || PLINTH_STD_MM;\n    const v = mm == null ? null : clampPlinthMm(mm);\n    cabinets = cabinets.map(c => {\n      if (!c || c.id !== cabId) return c;\n      const next = { ...c };\n      if (v == null || v === planMm) delete next.plinthMm; else next.plinthMm = v;\n      return next;\n    });\n    rerender();\n    scheduleBasketResync();\n  }\n  function handleSetUnitFloatHeight(cabId, mm) {\n    const v = Math.round(Number(mm));\n    if (!Number.isFinite(v)) return;\n    cabinets = cabinets.map(c => (c && c.id === cabId) ? { ...c, floatHeightMm: Math.max(0, Math.min(2400, v)) } : c);\n    rerender();\n  }\n\n  // ---- Media Wall popup (Arden, 2026-10-28) ----------------------------\n  // The Media units' own popup: Plinth (above), a Rear Panel behind the unit\n  // to a custom width and height, and a TV. Stored on the unit as\n  // cab.mediaWall = { panel: { material, acousticHandle, widthMm, heightMm },\n  //                   tv: { inches, widthMm, heightMm, bottomMm } }.\n  // The panel stands on the top of the unit's worktop (stampMediaPanelBottoms; Arden, 2026-10-28), centred on the unit, its face 20mm off\n  // the unit's back line. Tall End Panel = the range's 2400 x 650 boards in\n  // the unit's door colour (nested in the end panel cut list); Worktop = the\n  // plan's worktop, priced as its matching splashback; Acoustic = the AURORA\n  // panels (2400 x 600), like the breakfast bar back. The TV is not priced.\n  const MEDIA_PANEL_MAX_TOP_MM = 2400;      // one board / acoustic panel long\n  const MEDIA_PANEL_MAX_WIDTH_MM = 4000;\n  function mediaPanelOf(c) {\n    const p = c && c.mediaWall && c.mediaWall.panel;\n    return (p && ['panel', 'worktop', 'acoustic'].includes(p.material) && p.widthMm > 0 && p.heightMm > 0) ? p : null;\n  }\n  // Where each rear panel stands: on the top of its unit's worktop (the unit's\n  // top where it carries none). Stamped every render, after the stack anchors\n  // (a floating unit's top moves with its Height from floor), and read by the\n  // runs, the 3D and the preview.\n  function stampMediaPanelBottoms(list) {\n    for (const c of (list || [])) {\n      if (!c) continue;\n      c.mediaPanelBottomMm = mediaPanelOf(c) ? Math.round(unitTopY(c) + (carriesWorktop(c) ? worktopThicknessForCab(c) : 0)) : null;\n    }\n  }\n  // End panel cut-list pieces for the rear panels, from the combined runs\n  // (computeMediaRuns): a run of Tall End Panel is cut evenly into pieces no\n  // wider than a 650 board, joins wherever that puts them; an acoustic run is\n  // one back, billed like the breakfast bar's. A Worktop run is priced with\n  // the worktops (mediaWorktopPieces). Keyed to the run's first unit, as the\n  // 3D draws and selects it.\n  function mediaPanelFaces(list) {\n    const out = [];\n    const live = (list || []).filter(c => c && !c.excludeFromQuote);\n    for (const r of computeMediaRuns(live)) {\n      if (r.material === 'worktop') continue;\n      const at = (m) => ({ x: m * r.ax + r.off * r.nx, y: m * r.ay + r.off * r.ny });\n      for (const pc of r.pieces) {\n        // Each piece's own height: the panel stops under any wall unit in front.\n        const H = Math.min(MEDIA_PANEL_MAX_TOP_MM, Math.round(pc.heightMm));\n        const mid = at(pc.startMm + pc.widthMm / 2);\n        if (r.material === 'acoustic') {\n          out.push({ id: `${r.ownerId}:${pc.side}`, role: 'media', acoustic: true, acousticHandle: r.acousticHandle,\n                     runMm: Math.round(pc.widthMm), panelHeightMm: H, side: pc.side, cabIds: [r.ownerId],\n                     styleId: r.styleId, px: mid.x, py: mid.y });\n        } else {\n          out.push({ id: `${r.ownerId}:${pc.side}`, role: 'tall', depthMm: Math.ceil(pc.widthMm), heightMm: H,\n                     side: pc.side, cabIds: [r.ownerId], styleId: r.styleId,\n                     colour: r.colour, finish: 'plain', px: mid.x, py: mid.y });\n        }\n      }\n    }\n    return out;\n  }\n  // Worktop rear panels as splashback pieces: each stretch's length x height.\n  function mediaWorktopPieces() {\n    return computeMediaRuns((cabinets || []).filter(c => c && !c.excludeFromQuote))\n      .filter(r => r.material === 'worktop')\n      .flatMap(r => r.pieces.map(pc => ({ lengthMm: Math.round(pc.widthMm), heightMm: Math.round(pc.heightMm) })));\n  }\n  // A splashback product comes in sheets no taller than its width, so a taller\n  // panel is bought as rows of strips, each the panel's width.\n  function mediaWorktopRows(pieces, sheetWidthMm) {\n    const out = [];\n    const W = Number(sheetWidthMm) || 0;\n    for (const p of pieces) {\n      let rem = p.heightMm;\n      if (!(W > 0)) { out.push(p); continue; }\n      while (rem > 1) { const h = Math.min(W, rem); out.push({ lengthMm: p.lengthMm, heightMm: h }); rem -= h; }\n    }\n    return out;\n  }\n  // Can a Worktop rear panel be priced now? A stone worktop nests it with the\n  // slabs; a board needs its matching splashback product, which is chosen in\n  // the Worktops popup.\n  function mediaWorktopPriceable() {\n    const h = worktopMaterialForSlab();\n    const m = h && Catalogue.getWorktopMaterial(h);\n    if (!m) return false;\n    if (m.pricingModel === 'bespoke' || m.pricingModel === 'slab-tier') return true;\n    return !!(worktopParts.splashback && worktopParts.splashback.variantId);\n  }\n  // The staged popup choice laid onto a list of units, without touching it.\n  // staged = { plinth: 'none'|'plain'|'skirting', position, floatHeightMm,\n  //            panel: {material, acousticHandle, widthMm, heightMm} | null,\n  //            tv: {inches, widthMm, heightMm, bottomMm} | null }\n  function withMediaStaged(list, cabId, staged) {\n    if (!staged) return list;\n    const fs = featureStyles || {};\n    const planKind = (fs.plinth && fs.plinth !== 'none') ? plinthKindOf(fs.plinth) : 'plain';\n    const planPos = fs.plinthPosition === 'flush' ? 'flush' : 'proud';\n    const clampInt = (v, lo, hi) => Math.max(lo, Math.min(hi, Math.round(Number(v) || 0)));\n    return list.map(c => {\n      if (!c || c.id !== cabId) return c;\n      const next = { ...c };\n      const k = staged.plinth;\n      if (k === 'none') { next.plinthType = 'none'; delete next.plinthPosition; }\n      else if (k === 'plain' || k === 'skirting') {\n        if (k === planKind) delete next.plinthType; else next.plinthType = k;\n        if (k === 'skirting' && (staged.position === 'proud' || staged.position === 'flush') && staged.position !== planPos) next.plinthPosition = staged.position;\n        else delete next.plinthPosition;\n      }\n      if (staged.floatHeightMm != null) next.floatHeightMm = clampInt(staged.floatHeightMm, 0, 2400);\n      const sp = staged.panel, st = staged.tv;\n      const panel = (sp && ['panel', 'worktop', 'acoustic'].includes(sp.material)) ? {\n        material: sp.material,\n        acousticHandle: sp.material === 'acoustic' ? (sp.acousticHandle || null) : null,\n        widthMm: clampInt(sp.widthMm, 100, MEDIA_PANEL_MAX_WIDTH_MM),\n        heightMm: clampInt(sp.heightMm, 100, sp.material === 'worktop' ? 3000 : MEDIA_PANEL_MAX_TOP_MM)\n      } : null;\n      const tv = st ? {\n        inches: st.inches ? clampInt(st.inches, 10, 120) : null,\n        widthMm: clampInt(st.widthMm, 200, 3000),\n        heightMm: clampInt(st.heightMm, 100, 2000),\n        bottomMm: clampInt(st.bottomMm, 0, 2700),\n        offsetMm: clampInt(st.offsetMm || 0, -3000, 3000)\n      } : null;\n      next.mediaWall = (panel || tv) ? { panel, tv } : null;\n      return next;\n    });\n  }\n  // What the popup needs to draw its choices.\n  function getMediaInfo(cabId) {\n    const c = (cabinets || []).find(x => x && x.id === cabId);\n    const plinth = unitPlinthInfo(cabId);\n    if (!c || !plinth) return null;\n    const ut = c.unitTypeId ? Catalogue.getUnitType(c.unitTypeId) : null;\n    const carcaseMm = Math.max(0, (c.heightMm || 0) - ((ut && ut.plinthHeightMm) || 150));\n    return {\n      plinth,\n      fs: { planPosition: (featureStyles || {}).plinthPosition === 'flush' ? 'flush' : 'proud' },\n      unitWidthMm: c.widthMm || 0,\n      carcaseMm,\n      plinthMm: (ut && ut.plinthHeightMm) || 150,\n      mediaWall: c.mediaWall || null,\n      acoustic: ((typeof window !== 'undefined' && window.BTKAcousticPanels) || [])\n        .map(p => ({ handle: p.handle, label: p.label || p.title })),\n      worktopPriceable: mediaWorktopPriceable(),\n      maxTopMm: MEDIA_PANEL_MAX_TOP_MM,\n      maxWidthMm: MEDIA_PANEL_MAX_WIDTH_MM\n    };\n  }\n  function handleApplyMedia(cabId, staged) {\n    if (!unitPlinthInfo(cabId)) return;\n    cabinets = withMediaStaged(cabinets, cabId, staged);\n    rerender();\n    scheduleBasketResync();\n  }\n  // The popup's live render: the unit with the staged choice, front on, on\n  // the Stack popup's renderer. Copies only - nothing changes until Confirm.\n  async function renderMediaPreview(slot, cabId, staged) {\n    const seq = ++_stackPreviewSeq;\n    const r = await stackPreviewRenderer();\n    if (!r) return false;\n    if (seq !== _stackPreviewSeq || !slot || !slot.isConnected) return true;\n    if (!cabinets.some(c => c && c.id === cabId)) return false;\n    if (r.el.parentNode !== slot) slot.appendChild(r.el);\n    const target = cabinets.find(c => c && c.id === cabId);\n    const own = stackPreviewFootprint(target);\n    const mini = withMediaStaged(cabinets.filter(o => o && (o.id === cabId || (!isWallMounted(o)\n      && footprintsOverlap(own, stackPreviewFootprint(o))))).map(o => ({ ...o })), cabId, staged);\n    resolveStackAnchors(mini, stackAnchorOpts());\n    stampMediaPanelBottoms(mini);\n    const h = r.handle;\n    h.setWallColour(getWallColour(wallColourHandle).hex);\n    applyFeatureWallsTo3D(h);\n    applyFloorTo3D(h);\n    h.setActive(true);\n    h.render({ room, roomConfig, cabinets: mini, baseRoom, featureStyles, railFinishHandle, segmentColours,\n               worktops: buildWorktops(mini), worktopColourHex, worktopColours, worktopCornerRadii,\n               worktopItems: [], furnitureItems: [], handleGroups, lights: [], lightsOn: false });\n    h.resize();\n    frameMediaPreview(h, mini, cabId);\n    return true;\n  }\n  // Straight on to the front, wide and tall enough for the panel and the TV.\n  function frameMediaPreview(h, mini, cabId) {\n    const cab = mini.find(o => o && o.id === cabId);\n    if (!cab) return;\n    const mw = cab.mediaWall || {};\n    const p = mw.panel, tv = mw.tv;\n    const top = Math.max(unitVerticalRange(cab).top + 100, p ? (cab.mediaPanelBottomMm || 0) + p.heightMm + 100 : 0, tv ? tv.bottomMm + tv.heightMm + 100 : 0);\n    const wide = Math.max(cab.widthMm || 0, p ? p.widthMm : 0, tv ? tv.widthMm + 2 * Math.abs(tv.offsetMm || 0) : 0) + 300;\n    const th = ((cab.rotationDeg || 0) * Math.PI) / 180;\n    const fx = Math.sin(th), fz = -Math.cos(th);\n    const b = stackPreviewFootprint(cab);\n    const cx = (b.minX + b.maxX) / 2, cz = (b.minY + b.maxY) / 2, cy = top / 2;\n    const size = Math.max(top, wide);\n    const swing = 0.35;\n    const dx = fx * Math.cos(swing) - fz * Math.sin(swing);\n    const dz = fx * Math.sin(swing) + fz * Math.cos(swing);\n    const dist = size * 1.45;\n    h.setCameraState({ pos: [cx + dx * dist, cy + size * 0.15, cz + dz * dist], target: [cx, cy, cz] });\n  }\n\n  function radiusBlockEndCount() {\n    return (cabinets || []).filter(c =>\n      c && !c.excludeFromQuote\n      && (/^wall/i.test(c.category || '') || /^bridging/i.test(c.category || '')\n          || /^tall/i.test(c.category || '')))\n      .reduce((n, c) => n + ['left', 'right'].filter(side => {\n        const ep = (c.endPanels || {})[side];\n        return ep && ep.active && ep.style === 'radius';\n      }).length, 0);\n  }\n\n  // The block is profile-specific and coverage is patchy (31 products across the\n  // ranges: mostly Tangent, a few Universal, Seaton the only Classic), so a\n  // range that doesn't sell the block for a profile gets nothing rather than a\n  // substituted - wrong - moulding.\n  //\n  // \u26A0 These are NOT in the three trim collections, so getTrimAccessoryProduct\n  // cannot see them: a block is merchandised with the END FEATURES it caps\n  // (kitchen-units-doors-panels-end-posts-pilasters + accessories). Resolve it\n  // off the general product list by kbb code + style, the same way the radius\n  // and square end features themselves resolve. The trim-collection lookup is\n  // kept as a fallback in case a range files one under cornice instead.\n  function radiusCorniceBlockProduct(profileName, styleId) {\n    const pname = String(profileName || '').toLowerCase();\n    const key   = Object.keys(EP_RADIUS_CORNICE_BLOCK).find(k => pname.indexOf(k) >= 0);\n    if (!key) return null;\n    const code = EP_RADIUS_CORNICE_BLOCK[key];\n    const want = styleId || kitchenStyleId || null;\n    if (!want) return null;\n    const p = (Catalogue.getProducts() || [])\n      .find(pr => pr.kbbUnitTypeCode === code && pr.kitchenStyleId === want);\n    const v = p && p.variants && p.variants[0];\n    if (v) {\n      const info = Catalogue.getVariantInfo(v.id);\n      return { variantId: v.id, priceCents: info?.priceCents ?? null,\n               name: p.title || code, title: p.title || code,\n               handle: p.handle || null, code,\n               compareAtCents: info?.variant?.compareAtPrice ?? null };\n    }\n    return Catalogue.getTrimAccessoryProduct?.(code, want) || null;\n  }\n\n  // ---- True Handleless profiles \u2192 chargeable basket lines ----\n  // Everything the 3D view draws on True Handleless units, in the kitchen's\n  // Profile Finish (Arden, 2026-10-08). The pieces, corners and end caps come\n  // from the same engine functions the 3D view places them with, so the\n  // basket can never charge for something that is not drawn, or miss one that\n  // is. Products are matched by their data (custom.th_part + Profile Finish +\n  // the variant's custom.length_mm), never by title.\n  //   Top / Mid profile   - each straight piece cut from the cheapest mix of\n  //                         the stock lengths (4000 / 2300 / 1600mm); one\n  //                         length can feed several pieces (cutRailPieces).\n  //   Corner joints       - one per corner drawn, internal or external.\n  //   End plates          - one per capped end drawn.\n  //   Vertical profiles   - one per TH tall unit: Single Opening (lateral), or\n  //                         Double Opening for a grip-to-grip pair (counted\n  //                         once, on the unit that draws the shared rail).\n  //   30mm spacer set     - one per vertical profile (each needs one).\n  //   Appliance spacer    - one per appliance opening in a TH tall unit.\n  // Quick Fix Brackets are NOT added: they come with the units.\n  function computeRailCharges() {\n    try {\n      return _computeRailCharges();\n    } catch (err) {\n      // A profile charge must never take the basket down.\n      console.error('[BTK] profile charges failed', err);\n      return [];\n    }\n  }\n  function _computeRailCharges() {\n    const all = cabinets || [];\n    if (!all.some(c => c && c.isTrueRail === true)) return [];\n    const finish = (railFinishHandle && Catalogue.getRailFinish && Catalogue.getRailFinish(railFinishHandle))\n      || ((Catalogue.getRailFinishes && Catalogue.getRailFinishes()) || [])[0] || null;\n    const fh = finish ? finish.handle : null;\n    const prods = (part) => (Catalogue.getRailProducts ? Catalogue.getRailProducts(part, fh) : []);\n    const asProduct = (p) => ({\n      variantId: p.variantId, priceCents: (typeof p.price === 'number') ? p.price : null,\n      compareAtCents: (typeof p.compareAtPrice === 'number') ? p.compareAtPrice : null,\n      name: p.title, title: p.title, handle: p.handle || null,\n      url: p.handle ? ('/products/' + p.handle) : null, imageUrl: p.imageUrl || null\n    });\n    const out = [];\n    const add = (part, qty, detail, product) => {\n      if (!(qty > 0)) return;\n      const p = product || prods(part)[0];\n      if (!p) {\n        console.warn('[BTK profiles] no \"%s\" product in finish %s - %d NOT charged', part, fh, qty);\n        return;\n      }\n      out.push({ product: asProduct(p), qty, name: p.title, detail, part });\n    };\n    const trim = computeTrimRuns({\n      cabinets: all,\n      featureStyles: { ...(featureStyles || {}), railtop: 'rail', railmid: 'rail' },\n      roomVertices: room?.vertices || [],\n      perimeterItems: roomConfig?.perimeterItems || [],\n      doorThicknessMm: 18\n    });\n    for (const [feature, prefix, label] of [['railtop', 'top', 'top profile'], ['railmid', 'mid', 'mid profile']]) {\n      const segs = railActiveSegments(trim[feature], all);\n      const pieces = segs.map(s => s.lengthMm || 0).filter(L => L >= 1);\n      if (!pieces.length) continue;\n      // Lengths: group the cut lengths by stock size, one line each.\n      const stock = prods(prefix + '-profile').filter(p => p.lengthMm > 0 && typeof p.price === 'number')\n        .map(p => ({ lengthMm: p.lengthMm, priceCents: p.price, p }));\n      const { bars, uncut } = cutRailPieces(pieces, stock);\n      const bySize = new Map();\n      for (const b of bars) {\n        const k = b.stock.lengthMm;\n        if (!bySize.has(k)) bySize.set(k, { stock: b.stock, cuts: [] });\n        bySize.get(k).cuts.push(...b.cuts);\n      }\n      for (const [len, g] of [...bySize.entries()].sort((a, b) => b[0] - a[0])) {\n        const n = bars.filter(b => b.stock.lengthMm === len).length;\n        add(prefix + '-profile', n,\n          `${n} \u00D7 ${len}mm length${n > 1 ? 's' : ''} \u00B7 cut ${g.cuts.map(c => Math.round(c)).join(' + ')}mm`, g.stock.p);\n      }\n      if (uncut.length) {\n        console.warn('[BTK profiles] no %s lengths in finish %s - %dmm NOT charged', label, fh,\n          Math.round(uncut.reduce((t, x) => t + x, 0)));\n      }\n      // Corner joints + end plates, as the 3D view places them.\n      const fit = railFittings(segs);\n      const intN = fit.corners.filter(k => !k.isExt).length;\n      const extN = fit.corners.filter(k => k.isExt).length;\n      add(prefix + '-internal-corner', intN, `${intN} internal corner${intN > 1 ? 's' : ''}`);\n      add(prefix + '-external-corner', extN, `${extN} external corner${extN > 1 ? 's' : ''}`);\n      // TOP end plates come as a SET - a left-hand and a right-hand plate - so\n      // a run's two open ends take ONE set, not two (Arden, 2026-10-21; bug\n      // sheet row 327 \"adds more than the customer needs\"). Each open end is\n      // handed as you face the profile (its outward normal nx/ny): sets = the\n      // larger of the left-hand and right-hand counts. Mid end plates are sold\n      // singly - one per open end. Ends at a wall or a tall unit keep their\n      // plate (Arden: both need one).\n      if (prefix === 'top') {\n        let nL = 0, nR = 0;\n        for (const cap of fit.endCaps) {\n          const s = cap.s, pt = cap.pt;\n          const other = (pt === s.p1) ? s.p2 : s.p1;\n          const rx = (s.ny || 0), ry = -(s.nx || 0);   // facing the profile (-n), your right\n          if ((pt.x - other.x) * rx + (pt.y - other.y) * ry > 0) nR++; else nL++;\n        }\n        const sets = Math.max(nL, nR);\n        add(prefix + '-end-plate', sets,\n          `${fit.endCaps.length} open end${fit.endCaps.length > 1 ? 's' : ''} (${nL} left, ${nR} right) \u00B7 sold as left & right pairs`);\n      } else {\n        add(prefix + '-end-plate', fit.endCaps.length,\n          `${fit.endCaps.length} open end${fit.endCaps.length > 1 ? 's' : ''}`);\n      }\n    }\n    // Vertical profiles on TH tall units (the 3D view's buildVerticalRails) -\n    // ONE line per profile, carrying the number the plan draws on it, its\n    // unit (the line sits with that unit in the quote) and its face key\n    // (\"cabId:rail-left\") so the plan number and the line select each other\n    // (Arden, 2026-10-21: the numbers weren't clickable or in the quote list;\n    // they were billed as one \"N tall units\" line under Profiles). A unit with\n    // no grip side draws no profile and is no longer charged one.\n    const sideWord = (s) => (s === 'left' ? 'Left' : 'Right');\n    const addRail = (part, c, number, side, faces, detail) => {\n      const p = prods(part)[0];\n      if (!p) {\n        console.warn('[BTK profiles] no \"%s\" product in finish %s - profile %s NOT charged', part, fh, number);\n        return;\n      }\n      out.push({ product: asProduct(p), qty: 1, name: p.title, detail, part,\n        ownerCabId: c.id, number: number != null ? number : null, side, faces });\n    };\n    let vertN = 0, ovens = 0;\n    for (const c of all) {\n      if (!c || c.isTrueRail !== true || !/^tall/i.test(c.category || '')) continue;\n      const shared = (c.railType || 'lateral') === 'intermediate';\n      if (c.railGripSide && (!shared || c.railOwnsShared)) {\n        const faces = [`${c.id}:rail-${c.railGripSide}`];\n        const partner = shared ? all.find(x => x && x.id === c.railPartnerId) : null;\n        if (partner && partner.railGripSide) faces.push(`${partner.id}:rail-${partner.railGripSide}`);\n        addRail(shared ? 'vertical-double' : 'vertical-single', c, c.railNumber, c.railGripSide, faces,\n          shared ? 'Shared between two tall units' : `${sideWord(c.railGripSide)} side`);\n        vertN++;\n      }\n      if (c.railSecondSide) {   // \"Add Rail to both sides\" - always a Lateral\n        addRail('vertical-single', c, c.railSecondNumber, c.railSecondSide, [`${c.id}:rail-${c.railSecondSide}`],\n          `${sideWord(c.railSecondSide)} side - second profile`);\n        vertN++;\n      }\n      ovens += ((c.cutoutSchema && c.cutoutSchema.openings) || []).filter(o => o && o.type === 'oven').length;\n    }\n    add('vertical-spacer-set', vertN, `1 per vertical profile`);\n    add('appliance-spacer', ovens, `${ovens} appliance${ovens > 1 ? 's' : ''} in tall housings`);\n    return out;\n  }\n  function computeRailTotalGbp() {\n    try {\n      let t = 0;\n      for (const ch of computeRailCharges()) t += ((ch.product.priceCents || 0) / 100) * (ch.qty || 1);\n      return t;\n    } catch (e) { return 0; }\n  }\n\n  // A trim charge's basket line id, without its 'q:' (derivedId).\n  const trimLineKey = (ch) => 'tr:' + ch.product.variantId + ':' + (ch.colour || '') + ':' + (ch.detail || '');\n  function computeTrimCharges() {\n    // The plan's own range, only for a part with no range of its own - never\n    // the active planning style, which is just what the next unit added will\n    // be. With Perlo left active on a plan with no Perlo units, the Wrenwood\n    // Tangent cornice was billed as Perlo's Modern cornice (PLN100723).\n    const styleId = planTrimStyle().styleId || null;\n    if (!styleId || !Catalogue.getTrimForStyle) return [];\n    const fs     = featureStyles || {};\n    const totals = computeLinearTotals();\n    const charges = [];\n\n    // COLOUR. Each trim type is one colour for the whole kitchen when one is\n    // chosen in Customise > Cornice, Pelmet & Plinth (fs[feature + 'Colour']);\n    // otherwise each run matches the units it is fitted to - what the 3D draws.\n    // So a type is billed as one line PER COLOUR: an island in another colour\n    // gets its own plinth line instead of being charged in the kitchen's main\n    // colour (Arden, 2026-10-06).\n    const typeColour = (feature) => fs[(feature === 'plinthAlt' ? 'plinth' : feature) + 'Colour'] || null;\n    const doorOfCab = (cabId) => ((cabinets || []).find(c => c.id === cabId) || {}).doorColourHandle || null;\n    let _trimRuns = null;\n    const trimRunsFor = (feature) => {\n      if (!_trimRuns) _trimRuns = computeTrimRuns({\n        cabinets, featureStyles: fs, roomVertices: room?.vertices || [],\n        perimeterItems: roomConfig?.perimeterItems || [], doorThicknessMm: 18 });\n      // A plinth line covers every section of its kind (see computeLinearTotals).\n      if (feature === 'plinth' || feature === 'plinthAlt') {\n        const planK = _trimRuns.plinth && _trimRuns.plinth.kind;\n        if (planK) {\n          const k = feature === 'plinth' ? planK : (planK === 'plain' ? 'skirting' : 'plain');\n          return plinthRunsOfKind(_trimRuns, k).flatMap(d => d.runs || []).filter(r => !plinthRunIsTall(r));\n        }\n      }\n      return (_trimRuns[feature] && _trimRuns[feature].runs) || [];\n    };\n    // RANGE. A plan can hold units in two ranges - Caswood Lacquered Oak base\n    // and tall units under Caswood F&B wall units (Karen Pratt, WKIT-SO300088).\n    // The trim over each part is billed on the product of the range ITS units\n    // are in: the cornice and pelmet on her Strong White wall units were billed\n    // as the Lacquered Oak cornice and pelmet painted Strong White, a product\n    // that isn't made (Arden, 2026-10-30). A colour chosen for the whole trim\n    // type is billed in the range that sells it, the plan's style first.\n    const styleOfCab = (cabId) => ((cabinets || []).find(c => c.id === cabId) || {}).kitchenStyleId || styleId;\n    const planStyles = [...new Set([styleId, ...(cabinets || []).map(c => c && c.kitchenStyleId).filter(Boolean)])];\n    // (An F&B / RAL paint is listed in its range as the range's base colour.)\n    const styleForColour = (h) => {\n      const bp = Catalogue.getBespokePaint ? Catalogue.getBespokePaint(h) : null;\n      const want = (bp && bp.baseHandle) || h;\n      return planStyles.find(s =>\n        (Catalogue.getDoorColoursForStyle?.(s) || []).some(x => x.handle === want)) || styleId;\n    };\n    // The profile a range supplies for this trim: the chosen one by name (or,\n    // for the other plinth kind, the first of that kind), else that range's\n    // own first one. Never another range's product: a Perlo larder under a\n    // Tangent cornice Perlo doesn't sell was billed as Wrenwood's Tangent\n    // cornice in Perlo's oak, which isn't made (Arden, 2026-11-09).\n    const profileIn = (s, feature, sel, isAlt) => {\n      const sold = ((Catalogue.getTrimForStyle(s) || {})[isAlt ? 'plinth' : feature] || [])\n        .filter(p => p.available !== false);\n      return (isAlt ? sold.find(p => plinthKindOf(p.name) === sel)\n        : sold.find(p => (p.name || '').toLowerCase() === String(sel).toLowerCase())) || sold[0] || null;\n    };\n    // The run total split by range and colour in proportion to its pieces, so\n    // the total billed is unchanged - only who it is billed as.\n    const ownPlinthColour = (feature, cabId) => /^plinth/.test(feature)\n      ? (((cabinets || []).find(c => c.id === cabId) || {}).plinthColour || null) : null;\n    const anyOwnPlinthColour = (cabinets || []).some(c => c && c.plinthColour);\n    const splitByColour = (feature, mm) => {\n      const fixed = typeColour(feature);\n      if (fixed && !(/^plinth/.test(feature) && anyOwnPlinthColour)) return [{ style: styleForColour(fixed), colour: fixed, mm }];\n      const by = new Map();\n      let sum = 0;\n      for (const run of trimRunsFor(feature)) for (const seg of (run.segments || [])) {\n        const L = seg.lengthMm || 0;\n        if (!(L > 0) || seg._suppress) continue;\n        const cabId = (seg.cabinetIds || [])[0];\n        const own = ownPlinthColour(feature, cabId);\n        const h = own || fixed || doorOfCab(cabId) || globalDoorColourHandle || null;\n        const s = (own || !fixed) ? styleOfCab(cabId) : styleForColour(fixed);\n        const k = s + '|' + h;\n        if (!by.has(k)) by.set(k, { style: s, colour: h, L: 0 });\n        by.get(k).L += L;\n        sum += L;\n      }\n      const entries = [...by.values()];\n      if (!(sum > 0) || entries.length <= 1) {\n        return [entries.length ? { style: entries[0].style, colour: entries[0].colour, mm }\n          : { style: styleId, colour: globalDoorColourHandle || null, mm }];\n      }\n      let left = mm;\n      return entries.map((e, i) => {\n        const part = (i === entries.length - 1) ? left : Math.round(mm * e.L / sum);\n        left -= part;\n        return { style: e.style, colour: e.colour, mm: part };\n      }).filter(p => p.mm > 0);\n    };\n    const colourNameOf = (h, s) =>\n      ((Catalogue.getDoorColoursForStyle?.(s || styleId) || []).find(x => x.handle === h) || {}).name || h || '';\n\n    for (const feature of ['plinth', 'plinthAlt', 'cornice', 'pelmet']) {\n      const isAlt = feature === 'plinthAlt';\n      const sel = isAlt ? (totals.plinthAlt && totals.plinthAlt.style) : fs[feature];\n      if (!sel || sel === 'none' || sel === CEILING_FILLER) continue;\n      const mmTotal = (totals[feature] && totals[feature].mm) || 0;\n      if (mmTotal <= 0) continue;\n      const parts = splitByColour(feature, mmTotal);\n      for (const { style, colour, mm } of parts) {\n      // This part's own range's profile. A RUN is metres of straight trim, so\n      // it can ONLY be priced from the straight product. If the range doesn't\n      // sell one for this profile, charge nothing and say so - substituting\n      // the external-curve moulding billed a whole run as curves.\n      const ps   = style || styleId;\n      const pr   = profileIn(ps, feature, sel, isAlt);\n      const prod = pr && pr.product;\n      if (!prod || !prod.variantId) {\n        console.warn('[BTK trims] %s \"%s\" has no straight product in %s. Run NOT charged.', feature, sel, ps);\n        continue;\n      }\n      const lenMm = (typeof prod.lengthMm === 'number' && prod.lengthMm > 0) ? prod.lengthMm : 0;\n      const qty   = lenMm ? Math.max(1, Math.ceil(mm / lenMm)) : 1;\n      if (typeof window !== 'undefined' && window.BTK_FILLER_DEBUG) {\n        console.log('[BTK_TRIM_DEBUG] %s run %.2fm \u2192 profile \"%s\" \u2192 %s (%s), length_mm=%s, qty=%d%s',\n          feature, mm / 1000, pr.name || pr.handle,\n          prod.kbbUnitTypeCode || '(no code)', prod.title || '',\n          lenMm || 'unset', qty,\n          pr.curveProduct ? ('  [curve piece available: ' + (pr.curveProduct.kbbUnitTypeCode || '?') + ']') : '');\n      }\n      charges.push({\n        product: prod,\n        name:    prod.title || pr.name || feature,\n        detail:  (lenMm\n          ? `${(mm / 1000).toFixed(2)}m run \u00B7 ${qty} \u00D7 ${(lenMm / 1000).toFixed(1)}m length`\n          : `${(mm / 1000).toFixed(2)}m run`)\n          + (parts.length > 1 ? ` \u00B7 ${colourNameOf(colour, ps)}` : ''),\n        qty, colour, style: ps, feature\n      });\n      }\n    }\n\n    // EXTERNAL CURVES - the moulded piece fitted where a run turns a curve, one\n    // per curve, from the CHOSEN profile's own curve product. Plinth curves come\n    // off curved BASE units; cornice + pelmet curves off curved WALL units.\n    // Nothing is charged when the plan has no curves, which is what stops a\n    // straight kitchen showing curved trim lines at all.\n    {\n      const curvedBase = (cabinets || []).filter(c =>\n        c && !c.excludeFromQuote && c.radiusUnit && c.radiusUnit.kind !== 'end-wall'\n        && !/^wall/i.test(c.category || ''));\n      const curvedWall = (cabinets || []).filter(c =>\n        c && !c.excludeFromQuote && c.radiusUnit && /^wall/i.test(c.category || ''));\n      for (const feature of ['plinth', 'cornice', 'pelmet']) {\n        const sel = fs[feature];\n        if (!sel || sel === 'none') continue;\n        const curved = (feature === 'plinth') ? curvedBase : curvedWall;\n        if (!curved.length) continue;\n        // One line per range and colour, as the straight runs.\n        const byCol = new Map();\n        for (const c of curved) {\n          const fixed = typeColour(feature);\n          const own = feature === 'plinth' ? (c.plinthColour || null) : null;\n          const h = own || fixed || c.doorColourHandle || globalDoorColourHandle || null;\n          const s = (fixed && !own) ? styleForColour(fixed) : (c.kitchenStyleId || styleId);\n          const k = s + '|' + h;\n          if (!byCol.has(k)) byCol.set(k, { style: s, colour: h, n: 0 });\n          byCol.get(k).n++;\n        }\n        for (const { style, colour, n } of byCol.values()) {\n          const ps = style;\n          const prof = profileIn(ps, feature, sel, false);\n          const piece = prof && prof.curveProduct;\n          if (!piece || !piece.variantId) continue;\n          charges.push({\n            product: piece,\n            name:    piece.title || `External Curved ${feature}`,\n            detail:  `${n} external curve${n > 1 ? 's' : ''}` + (byCol.size > 1 ? ` \u00B7 ${colourNameOf(colour, ps)}` : ''),\n            qty:     n, colour, style: ps, feature\n          });\n        }\n      }\n    }\n\n    // RADIUS END CORNICE BLOCKS - the curved moulded block that caps a radius\n    // end where the cornice reaches it. One PIECE per radius end top (not a\n    // run), on the cabs a cornice actually crosses: wall, bridging and tall.\n    // Square ends take no block - they are cut square and the straight cornice\n    // simply returns.\n    //\n    // The block is profile-specific and coverage is patchy (Universal 7 ranges\n    // / Tangent 23 / Classic 1), so a range that does not sell the block for\n    // its chosen profile gets NO block line and a console warning, rather than\n    // a substituted block that would be the wrong moulding.\n    if (fs.cornice && fs.cornice !== 'none' && fs.cornice !== CEILING_FILLER) {\n      const blockEnds = radiusBlockEndCount();\n      if (blockEnds > 0) {\n        // Each block in the cornice colour, else its radius end's colour - and\n        // in its unit's range, as the runs.\n        const byCol = new Map();\n        for (const c of (cabinets || [])) {\n          if (!c || c.excludeFromQuote) continue;\n          if (!(/^wall/i.test(c.category || '') || /^bridging/i.test(c.category || '') || /^tall/i.test(c.category || ''))) continue;\n          for (const side of ['left', 'right']) {\n            const ep = (c.endPanels || {})[side];\n            if (!(ep && ep.active && ep.style === 'radius')) continue;\n            const fixed = typeColour('cornice');\n            const h = fixed || (c.endPanelColours && c.endPanelColours[side])\n              || c.doorColourHandle || globalDoorColourHandle || null;\n            const s = fixed ? styleForColour(fixed) : (c.kitchenStyleId || styleId);\n            const k = s + '|' + h;\n            if (!byCol.has(k)) byCol.set(k, { style: s, colour: h, n: 0 });\n            byCol.get(k).n++;\n          }\n        }\n        for (const { style, colour, n } of byCol.values()) {\n          const ps = style;\n          const prof = profileIn(ps, 'cornice', fs.cornice, false);\n          const piece = radiusCorniceBlockProduct(prof && prof.name, ps);\n          if (!piece || !piece.variantId) {\n            console.warn('[BTK trims] no radius cornice block for profile \"%s\" in %s - '\n              + '%d radius end%s NOT charged a block.',\n              (prof && prof.name) || fs.cornice, ps, n, n > 1 ? 's' : '');\n            continue;\n          }\n          charges.push({\n            product: piece,\n            name:    piece.name || piece.title || 'Radius Cornice Block',\n            detail:  `${n} radius end${n > 1 ? 's' : ''}` + (byCol.size > 1 ? ` \u00B7 ${colourNameOf(colour, ps)}` : ''),\n            qty:     n, colour, style: ps, feature: 'cornice'\n          });\n        }\n      }\n    }\n\n    // (The old hard-coded External Curved Plinth block lived here. It resolved\n    // EXTCURVPLIN by code whatever plinth was chosen, and would now DOUBLE\n    // CHARGE against the profile-driven curve pass above - which also picks the\n    // right curve for a decorative plinth, e.g. CURVTORPLIN.)\n    return charges;\n  }\n  // Debug: run window.__btkBlockCheck() to see why a radius cornice block is\n  // (not) charged - the ends counted, and per cornice profile whether the range\n  // sells the straight length and the block.\n  try {\n    if (typeof window !== 'undefined') window.__btkBlockCheck = () => {\n      const forStyle = Catalogue.getTrimForStyle?.(kitchenStyleId) || {};\n      const rows = (forStyle.cornice || []).map(p => ({\n        profile: p.name,\n        inRange: p.available !== false,\n        block: (() => {\n          const b = radiusCorniceBlockProduct(p.name, kitchenStyleId);\n          return b ? (b.code + ' ' + (b.variantId || '')) : 'NONE';\n        })()\n      }));\n      const ends = (cabinets || []).filter(c => c && !c.excludeFromQuote)\n        .flatMap(c => ['left', 'right']\n          .filter(sd => { const ep = (c.endPanels || {})[sd]; return ep && ep.active && ep.style === 'radius'; })\n          .map(sd => ({ cab: c.code, category: c.category, side: sd })));\n      console.log('style', kitchenStyleId, '| cornice =', featureStyles && featureStyles.cornice);\n      console.log('radius ends in plan:', ends);\n      console.log('counted for blocks (wall/bridging/tall):', radiusBlockEndCount());\n      console.table(rows);\n      return { style: kitchenStyleId, ends, counted: radiusBlockEndCount(), rows };\n    };\n  } catch (e) {}\n  // Debug: run window.__btkTrimCharges() in the console to see exactly which\n  // trim lines the basket will add (name, qty, detail) for the current plan.\n  try { if (typeof window !== 'undefined') window.__btkTrimCharges = computeTrimCharges; } catch (e) {}\n\n  // Per-worktop corner radius - corner \u2208 {'tl','tr','bl','br'},\n  // value \u2208 {0, 70, 300}. Sets / clears one corner on one worktop.\n  // ---- Curved ends on a BULLNOSE worktop -------------------------------\n  // A postformed (bullnose) laminate CAN be cut to a curve, and people do have\n  // it, but its edge profile can't follow the curve cleanly so it doesn't look\n  // good (Arden, 2026-09-18). So it is WARNED, never blocked: the customer is\n  // told once and decides. Square edge laminate and solid worktops take curves\n  // properly and are never warned.\n  function isPostformedMaterial(handle) {\n    const m = (handle && Catalogue.getWorktopMaterial) ? Catalogue.getWorktopMaterial(handle) : null;\n    return !!(m && m.profile === 'rounded');\n  }\n  // Any curved worktop in the plan. A bullnose can't follow a curve cleanly,\n  // whatever made it. Checked from the plan's own data by ID, in three ways:\n  //   1. a corner radius the customer set by hand on a worktop\n  //   2. a worktop that COVERS a curved unit (cab.radiusUnit) or a unit with a\n  //      radius end panel - the worktop over it follows the curve. Every slab\n  //      already lists the cabinets it covers, so this is an exact test.\n  //   3. the arc record (slab.radiusRounds), as a catch-all\n  // (2) is the one that matters: the arc is only recorded when a curved unit's\n  // hand matches the end of its run, so a standalone curved unit or an island\n  // curve was missed and never warned.\n  function planHasCurvedWorktop() {\n    for (const r of Object.values(worktopCornerRadii || {})) {\n      if (r && (r.tl || r.tr || r.bl || r.br)) return true;\n    }\n    let slabs = [];\n    try { slabs = buildWorktops() || []; } catch (e) {}\n    const cabById = new Map((cabinets || []).map(c => [c.id, c]));\n    const radiusPanel = (ep) => !!(ep && ep.active && ep.style === 'radius' && !ep.wtSquare);\n    for (const s of slabs) {\n      if (!s || s.cushionTop) continue;\n      if (Array.isArray(s.radiusRounds) && s.radiusRounds.length) return true;\n      // A Radius-end island's own rounded corners (a breakfast bar's).\n      if (Array.isArray(s.islandCornerRadii) && s.islandCornerRadii.length) return true;\n      for (const id of (s.cabinetIds || [])) {\n        const c = cabById.get(id);\n        if (!c) continue;\n        if (c.radiusUnit) return true;\n        const ep = c.endPanels || {};\n        if (radiusPanel(ep.left) || radiusPanel(ep.right)) return true;\n      }\n    }\n    return false;\n  }\n  // ONE source for the wording, shared by the dialog and the cut list popup's\n  // warning panel, so the two can never say different things.\n  const BULLNOSE_CURVE_TITLE = 'Curved ends on a bullnose worktop';\n  const BULLNOSE_CURVE_TEXT =\n    'A rounded edge (bullnose) laminate can be cut to a curve, but its edge ' +\n    'profile cannot follow the curve cleanly, so the finish will not look as ' +\n    'neat as a straight end. Square edge laminate or a solid worktop gives a ' +\n    'better curved finish.';\n  // The units a ROUND EDGE (bullnose) worktop runs over that make it curve - a\n  // curved unit, or a unit with a radius end post - for the Advisory and the\n  // Checklist card (Arden, 2026-10-12: the warning above only ever showed\n  // when a corner was rounded by hand, or in the cut list). The same test as\n  // planHasCurvedWorktop, unit by unit. A corner rounded by hand counts too,\n  // with no unit to name.\n  function bullnoseCurveUnits() {\n    const out = { cabs: [], corners: false, material: null };\n    const handle = worktopMaterialForSlab();\n    if (!isPostformedMaterial(handle)) return out;\n    out.material = handle;\n    for (const r of Object.values(worktopCornerRadii || {})) {\n      if (r && (r.tl || r.tr || r.bl || r.br)) { out.corners = true; break; }\n    }\n    let slabs = [];\n    try { slabs = buildWorktops() || []; } catch (e) {}\n    if (slabs.some(sl => sl && !sl.cushionTop && Array.isArray(sl.islandCornerRadii) && sl.islandCornerRadii.length)) out.corners = true;\n    const cabById = new Map((cabinets || []).map(c => [c.id, c]));\n    const radiusEnd = (ep) => !!(ep && ep.active && ep.style === 'radius' && !ep.wtSquare);\n    const seen = new Set();\n    for (const sl of slabs) {\n      if (!sl || sl.cushionTop) continue;\n      for (const id of (sl.cabinetIds || [])) {\n        const c = cabById.get(id);\n        if (!c || seen.has(id) || c.excludeFromQuote) continue;\n        const ep = c.endPanels || {};\n        if (c.radiusUnit || radiusEnd(ep.left) || radiusEnd(ep.right)) { seen.add(id); out.cabs.push(c); }\n      }\n    }\n    out.cabs.sort((a, b) => (a.displayNumber ?? 9e9) - (b.displayNumber ?? 9e9));\n    return out;\n  }\n  // Console aid: why the round edge advisory does or does not show.\n  try {\n    window.__btkBullnoseCheck = () => {\n      const h = worktopMaterialForSlab();\n      const m = (h && Catalogue.getWorktopMaterial) ? Catalogue.getWorktopMaterial(h) : null;\n      let slabs = []; try { slabs = buildWorktops() || []; } catch (e) {}\n      const b = bullnoseCurveUnits();\n      return { material: h, profile: m && m.profile, slabs: slabs.map(sl => (sl.cabinetIds || []).join('+')),\n               flagged: b.cabs.map(c => c.id), corners: b.corners };\n    };\n  } catch (e) {}\n  function bullnoseCurveWarning() {\n    const b = bullnoseCurveUnits();\n    if (!b.material || (!b.cabs.length && !b.corners)) return null;\n    const nums = b.cabs.map(c => '#' + (c.displayNumber ?? '?'));\n    const what = b.cabs.length\n      ? (b.cabs.length === 1 ? `Unit ${nums[0]} is curved or has a radius end, and your round edge laminate worktop runs over it.`\n                             : `Units ${nums.join(', ')} are curved or have a radius end, and your round edge laminate worktop runs over them.`)\n      : 'A worktop corner is rounded, and your worktop is a round edge laminate.';\n    return { ruleId: 'bullnose-curve', severity: 'warning', itemIds: b.cabs.map(c => c.id),\n             message: what + ' ' + BULLNOSE_CURVE_TEXT,\n             _signature: b.material + '|' + b.cabs.map(c => c.id).sort().join(',') + (b.corners ? '|corners' : '') };\n  }\n  // ---- Belfast sink: worktop round both sides (Planner Bugs 37) ----\n  // The worktop wraps the sides of a Belfast sink, so it has to carry on past\n  // the unit on both sides. Where it stops at the unit's side - the end of a\n  // run, a tall unit or a tall end panel beside it, a wall - all that is left\n  // on that edge is a strip too thin to fit, so that side has no worktop\n  // (Arden, 2026-10-26). Measured off the worktop the plan actually has.\n  const BELFAST_WORKTOP_PROBE_MM = 60;\n  function belfastWorktopWarnings() {\n    const belfasts = cabinets.filter(c => c && c.belfastSink && !c.excludeFromQuote);\n    if (!belfasts.length) return [];\n    let slabs;\n    try { slabs = (buildWorktops() || []).filter(w => w && !w.cushionTop && Array.isArray(w.polygon) && w.polygon.length > 2); }\n    catch (e) { return []; }\n    if (!slabs.length) return [];\n    const inside = (poly, x, y) => {\n      let hit = false;\n      for (let a = 0, b = poly.length - 1; a < poly.length; b = a++) {\n        const pa = poly[a], pb = poly[b];\n        if (((pa.y > y) !== (pb.y > y)) && (x < (pb.x - pa.x) * (y - pa.y) / ((pb.y - pa.y) || 1e-9) + pa.x)) hit = !hit;\n      }\n      return hit;\n    };\n    const onWorktop = (x, y) => slabs.some(s => inside(s.polygon, x, y));\n    const out = [];\n    for (const c of belfasts) {\n      const w = c.widthMm || 0, d = c.depthMm || 0;\n      const cx = c.x + w / 2, cy = c.y + d / 2;\n      const th = ((c.rotationDeg || 0) * Math.PI) / 180, cs = Math.cos(th), sn = Math.sin(th);\n      const at = (lx, ly) => ({ x: cx + lx * cs - ly * sn, y: cy + lx * sn + ly * cs });\n      for (const [side, sign] of [['left', 1], ['right', -1]]) {\n        // No worktop over this side of the unit at all (worktop switched off) - nothing to say.\n        const own = at(sign * (w / 2 - 10), 0);\n        if (!onWorktop(own.x, own.y)) continue;\n        const carriesOn = [-d / 6, d / 6].every(ly => { const p = at(sign * (w / 2 + BELFAST_WORKTOP_PROBE_MM), ly); return onWorktop(p.x, p.y); });\n        if (carriesOn) continue;\n        out.push({\n          ruleId: 'belfast-worktop-edge', severity: 'warning', itemIds: [c.id],\n          _unit: c.displayNumber ?? '?', _side: side,\n          message: `The worktop on the ${side} of the Belfast sink on unit #${c.displayNumber ?? '?'} would be too thin to fit, so that side would have no worktop. ` +\n                   'The worktop wraps round both sides of a Belfast sink, so it needs a base unit beside it on that side - not the end of a run, a tall unit or a tall end panel.'\n        });\n      }\n    }\n    return out;\n  }\n  function confirmBullnoseCurve() {\n    const d = window.BTKKPDialog;\n    if (!d || typeof d.confirm !== 'function') return Promise.resolve(true);\n    return d.confirm(BULLNOSE_CURVE_TEXT,\n      { title: BULLNOSE_CURVE_TITLE, confirmText: 'Continue anyway', cancelText: 'Cancel' });\n  }\n\n  // ---- Faced laminate worktops and sinks ----\n  // A square or round edge laminate worktop is a faced board: cut it for an\n  // undermount or a Belfast sink and its core shows. So the two never go\n  // together (Arden, 2026-10-15: \"a hard no for laminates\"). Solid laminate,\n  // solid surface, real wood, FENIX and stone are solid all the way through\n  // and take either. Checked wherever a worktop or a sink is chosen, and the\n  // pickers grey out what the plan cannot have.\n  function isFacedLaminate(handle) {\n    const m = handle && Catalogue.getWorktopMaterial(handle);\n    const type = String((m && m.type) || '');\n    return !!(m && m.pricingModel !== 'bespoke' && m.construction !== 'solid'\n      && /laminate/i.test(type) && !/solid|compact/i.test(type));\n  }\n  // An undermount or a Belfast sink - what a faced laminate cannot take.\n  const sinkNeedsSolidWorktop = (installType) => /under|belfast|butler/i.test(String(installType || ''))\n    && !/inset-or-under|either/i.test(String(installType || ''));\n  const sinkWords = (installType) => (/belfast|butler/i.test(String(installType || '')) ? 'a Belfast sink' : 'an undermount sink');\n  // What on the plan rules out a faced laminate, in words ('a Belfast sink\n  // unit', 'an undermount sink'), or [] when nothing does. A Belfast sink unit\n  // always does; a sink base only once an undermount or Belfast sink is chosen\n  // for it (it may yet get an inset one); a free-placed sink by its own type.\n  // cabIds: just those units (Change Worktop on part of the plan); without,\n  // the units on the plan's own worktop.\n  function sinksNeedingSolidWorktop(cabIds) {\n    const out = [];\n    for (const c of (cabinets || [])) {\n      if (!c) continue;\n      if (cabIds ? !cabIds.includes(c.id) : !!c.worktopMaterialHandle) continue;\n      // An apron front sink sits ON the worktop, so a Belfast unit with one\n      // takes any worktop, laminates included (Arden, 2026-10-24).\n      if (c.belfastSink) {\n        const _bsk = (c.plannerSinkHandle && Catalogue.getPlannerSink) ? Catalogue.getPlannerSink(c.plannerSinkHandle) : null;\n        if (!(_bsk && isApronFrontSink(_bsk.installType))) out.push('a Belfast sink unit');\n        continue;\n      }\n      const sk = (c.sinkBase && c.plannerSinkHandle && Catalogue.getPlannerSink) ? Catalogue.getPlannerSink(c.plannerSinkHandle) : null;\n      // An Inset or Undermount sink left to the worktop goes Inset on a\n      // laminate by itself (sinkMountFor), so it never stands in the way.\n      if (sk && Catalogue.plannerSinkMountInfo(sk).either && !c.plannerSinkFitting) continue;\n      const _m = sinkMountFor(c, sk);\n      if (_m && sinkNeedsSolidWorktop(_m)) out.push(sinkWords(_m));\n    }\n    for (const it of (cabIds ? [] : (worktopItems || []))) {\n      if (!it || it.kind !== 'sink') continue;\n      const sk = (it.handle && Catalogue.getPlannerSink) ? Catalogue.getPlannerSink(it.handle) : null;\n      const type = sk ? sinkMountFor(it, sk) : it.installType;\n      if (sinkNeedsSolidWorktop(type)) out.push(sinkWords(type));\n    }\n    return [...new Set(out)];\n  }\n  // Is a faced laminate on the plan - the kitchen-wide worktop or any section's own?\n  // The fitting a sink has on this plan (sales row 133): its own when it has\n  // only one; for an Inset or Undermount sink, staff's choice on the unit\n  // (cab.plannerSinkFitting), else Undermount under a solid worktop and Inset\n  // on a faced laminate, which cannot take an undermount. 'under-mount' /\n  // 'top-mount' / 'belfast' / 'apron-front', or null with no sink.\n  function sinkMountFor(c, sk) {\n    if (!sk) return null;\n    const info = Catalogue.plannerSinkMountInfo(sk);\n    if (!info.either) return info.fixed;\n    const own = c && c.plannerSinkFitting;\n    if (own === 'under-mount' || own === 'top-mount') return own;\n    return cabWorktopFaced(c) ? 'top-mount' : 'under-mount';\n  }\n  // Is the worktop over this unit a faced laminate - its own (Change\n  // Worktop), else the plan's?\n  function cabWorktopFaced(c) {\n    const own = c && c.worktopMaterialHandle;\n    return own ? isFacedLaminate(own) : planHasFacedLaminate();\n  }\n  function planHasFacedLaminate() {\n    return [worktopMaterialHandle, ...Object.values(worktopMaterialsBySection || {})].some(isFacedLaminate);\n  }\n  const FACED_SINK_TITLE = 'Not suitable together';\n  const listWords = (xs) => (xs.length > 1 ? xs.slice(0, -1).join(', ') + ' and ' + xs[xs.length - 1] : xs[0] || '');\n  // Why this worktop cannot go on the plan as it stands, or null.\n  // cabIds: for those units only (Change Worktop).\n  function worktopSinkBlock(handle, cabIds) {\n    if (!isFacedLaminate(handle)) return null;\n    const sinks = sinksNeedingSolidWorktop(cabIds);\n    return sinks.length ? `${cabIds ? 'This part of your plan has' : 'Your plan has'} ${listWords(sinks)}. Square and round edge laminate worktops cannot be cut for undermount or Belfast sinks, so choose a solid worktop, or change to an inset sink first.` : null;\n  }\n  // Why a sink of this install type cannot go on the plan as it stands, or null.\n  // cab: the unit it is going on, whose own worktop decides (Change Worktop).\n  function sinkWorktopBlock(installType, isBelfastUnit, cab) {\n    if (!(isBelfastUnit || sinkNeedsSolidWorktop(installType)) || !(cab ? cabWorktopFaced(cab) : planHasFacedLaminate())) return null;\n    return `${cab && cab.worktopMaterialHandle ? 'The worktop on this unit is' : 'Your plan has'} a square or round edge laminate worktop, which cannot be cut for ${isBelfastUnit ? 'a Belfast sink' : sinkWords(installType)}. Choose an inset sink, or change to a solid worktop first.`;\n  }\n  function alertFacedSink(text) {\n    const d = window.BTKKPDialog;\n    if (d && typeof d.alert === 'function') d.alert(text, { title: FACED_SINK_TITLE });\n  }\n\n  async function handleSetWorktopCornerRadius(worktopId, corner, value) {\n    if (!worktopId) return;\n    if (!['tl', 'tr', 'bl', 'br'].includes(corner)) return;\n    // Any radius from 50 to 300mm (Arden, 2026-10-09) - the overhang diagram\n    // keeps it within the overhang; 0 = square.\n    const n = Math.round(Number(value) || 0);\n    const v = n > 0 ? Math.max(50, Math.min(300, n)) : 0;\n    if (((worktopCornerRadii[worktopId] || {})[corner] || 0) === v) return;\n    // Warn only on the FIRST curve of a bullnose plan. If it is already curved\n    // they have accepted it, so adding more corners doesn't ask again. Every\n    // other case runs straight through with no await, exactly as before.\n    if (v > 0 && isPostformedMaterial(worktopMaterialForSlab()) && !planHasCurvedWorktop()) {\n      if (!(await confirmBullnoseCurve())) { rerender(); return; }   // put the UI back\n    }\n    const cur = worktopCornerRadii[worktopId] || { tl: 0, tr: 0, bl: 0, br: 0 };\n    const next = { ...cur, [corner]: v };\n    const allZero = !next.tl && !next.tr && !next.bl && !next.br;\n    if (allZero) {\n      const { [worktopId]: _drop, ...rest } = worktopCornerRadii;\n      worktopCornerRadii = rest;\n    } else {\n      worktopCornerRadii = { ...worktopCornerRadii, [worktopId]: next };\n    }\n    rerender();\n  }\n\n  // Worktop colour - target='section' sets just the selected\n  // worktop's override; target='all' (or unspecified) sets the global\n  // default and clears every per-section override. Rerender repaints\n  // 2D + 3D from the updated state.\n  function handleSetWorktopColour(hex, target) {\n    if (typeof hex !== 'string') return;\n    const v = hex.trim();\n    if (!/^#[0-9a-fA-F]{3,8}$/.test(v)) return;\n    if (target === 'section' && selectedItem && selectedItem.kind === 'worktop') {\n      worktopColours = { ...worktopColours, [selectedItem.worktopId]: v };\n    } else {\n      worktopColourHex = v;\n      worktopColours   = {};\n    }\n    rerender();\n  }\n\n  // Worktop material - same targeting as colour. target='section' sets\n  // just the selected worktop's override; target='all' (or unspecified)\n  // sets the global default material and clears every override. Pass\n  // handle=null / '' to clear back to \"no material\". Rerender repaints +\n  // recomputes the total (slab-tier materials are charged by tier).\n  async function handleSetWorktopMaterial(handle, target) {\n    const h = (typeof handle === 'string' && handle.trim()) ? handle.trim() : null;\n    const wasHandle = worktopMaterialForSlab();\n    // A faced laminate with an undermount or Belfast sink on the plan: never.\n    const sinkBlock = h ? worktopSinkBlock(h) : null;\n    if (sinkBlock) {\n      alertFacedSink(sinkBlock);\n      try { styleColoursHandle?.refresh?.(); } catch (e) {}\n      try { syncJourneyWorktopFromPlan(); renderJourneyWorktopTile(); } catch (e) {}\n      return;\n    }\n    // Switching TO a bullnose material while the plan already has curved ends.\n    // Re-picking another bullnose colour doesn't ask again: the curves were\n    // already accepted on a bullnose.\n    let warned = false;\n    if (h && isPostformedMaterial(h) && !isPostformedMaterial(worktopMaterialForSlab())\n          && planHasCurvedWorktop()) {\n      warned = true;\n      if (!(await confirmBullnoseCurve())) {\n        // Nothing applied: put BOTH pickers back to the plan's real material -\n        // the Customise popup and the Style Setup tile read different state.\n        try { styleColoursHandle?.refresh?.(); } catch (e) {}\n        try { syncJourneyWorktopFromPlan(); renderJourneyWorktopTile(); } catch (e) {}\n        return;\n      }\n    }\n    if (target === 'section' && selectedItem && selectedItem.kind === 'worktop') {\n      const next = { ...worktopMaterialsBySection };\n      if (h) next[selectedItem.worktopId] = h;\n      else delete next[selectedItem.worktopId];\n      worktopMaterialsBySection = next;\n    } else {\n      worktopMaterialHandle     = h;\n      worktopMaterialsBySection = {};\n    }\n    // A different worktop takes its own accessories with it.\n    if (worktopMaterialForSlab() !== wasHandle) clearWorktopAccessories(wasHandle, worktopMaterialForSlab());\n    rerender();\n    // The Style Setup stage shows this same material, and so does the mood\n    // board - so a pick in the popup (from either stage) is reflected without\n    // the user having to leave and come back.\n    try { syncJourneyWorktopFromPlan(); renderJourneyWorktopTile(); } catch (e) {}\n    // The picker redrew itself before the warning was answered, so it still\n    // shows the old choice - bring it up to date now the pick has applied.\n    if (warned) { try { styleColoursHandle?.refresh?.(); } catch (e) {} }\n  }\n  // Everything that was bought FOR the old worktop goes with it (Arden,\n  // 2026-09-24): an edging strip and a matching upstand are colour matched to\n  // the worktop they were chosen for, so even one laminate to another leaves\n  // them wrong. The basket lines go without asking, as the planner basket\n  // does everything else.\n  function clearWorktopAccessories(before, after) {\n    worktopParts = { upstand: null, splashback: null, edging: null };\n    // A strip that matches the worktop is either a product (a board's, which\n    // has just been cleared) or cut from the stone (a made-to-measure one).\n    // It only carries over between two made-to-measure stones; otherwise it\n    // would be drawn with nothing priced behind it, so it goes off and is\n    // chosen again for the new worktop. Glass ones are not ours to touch.\n    const isBespoke = (x) => {\n      const m = x && Catalogue.getWorktopMaterial(x);\n      return !!m && m.pricingModel === 'bespoke';\n    };\n    if (!(isBespoke(before) && isBespoke(after))) {\n      const sp = roomConfig.splashbacks || {};\n      const patch = {};\n      for (const slot of ['upstand', 'splashback', 'hobSplashback']) {\n        const v = sp[slot] || {};\n        if (v.enabled && v.material === 'match-worktop') patch[slot] = { enabled: false };\n      }\n      if (Object.keys(patch).length) handleUpdateSplashbacks(patch);\n    }\n    clearWorktopExtras();\n  }\n  // The worktop's own lines in the basket's Extras section - they carry the\n  // 'worktops' quote group (extrasQuoteGroup), which is what tells them from\n  // the appliances and handles added the same way.\n  // THIS plan's basket, found as transferPlanToBasket finds it: the working\n  // basket pointer, else the planner basket stamped with this plan's id.\n  // `isActive` is the website /cart's current basket, never a plan's - picking\n  // it first sent Add Other Items (and this clean-up) to the website basket\n  // instead of the plan's (Arden, 2026-10-09).\n  async function planBasketIn(project) {\n    const all = (project && project.baskets) || [];\n    let workingId = null;\n    try { workingId = planStore.getActiveBasketId ? await planStore.getActiveBasketId() : null; } catch (_) {}\n    let planId = null;\n    try { planId = currentDesign().plannerPlanId || null; } catch (_) {}\n    return all.find(b => b && workingId && b.id === workingId && !basketHoldsOtherPlan(b))\n      || all.find(b => b && b.source === 'planner' && planId\n           && b.plannerDesign && b.plannerDesign.design && b.plannerDesign.design.plannerPlanId === planId)\n      || null;\n  }\n\n  async function clearWorktopExtras() {\n    const api = window.BTKBasketAPI;\n    if (!api) return;\n    try {\n      const project = await api.getProject();\n      const basket = await planBasketIn(project);\n      if (!basket) return;\n      const section = (basket.sections || []).find(s => s.name === 'Extras');\n      if (!section || !(section.items || []).length) return;\n      const keep = section.items.filter(it => ((it.attributes && it.attributes.quoteGroup) || '') !== 'worktops');\n      if (keep.length === section.items.length) return;\n      section.items = keep;\n      api.recalculateLineNumbers(basket);\n      await api.saveBasket(basket);\n      // By id, so there is no whole-project PUT just to flag the basket, and\n      // nothing writes `isActive` onto a planner basket - which is /cart's\n      // notion of the current basket and must never be one of these. See\n      // flushCartForCheckout for the timings behind it.\n      await api.syncToShopifyCart(basket.id);\n      window.BTKCartAdvanced?.reload?.();\n    } catch (e) {\n      console.error('[BTK Kitchen Planner] clearing the worktop extras failed', e);\n    }\n  }\n\n  // Worktop material is PLAN-WIDE (a kitchen's worktop is one material), so\n  // every slab resolves to the SAME material: the global handle if set, else\n  // any per-section override. Applying it to every slab - rather than looking\n  // up each slab's own id - means a re-split run never orphans a piece from\n  // pricing (slab ids are spatial hashes that change when the layout edits),\n  // and it also covers legacy plans saved as per-section before the global\n  // handle existed, plus a stale section-storing UI.\n  function worktopMaterialForSlab(slab) {\n    // A worktop over units given a material of their own (bug sheet row 100).\n    if (slab && slab.altMaterial) return slab.altMaterial;\n    if (worktopMaterialHandle) return worktopMaterialHandle;\n    const vals = Object.values(worktopMaterialsBySection || {});\n    return vals.length ? vals[0] : null;\n  }\n\n  // The plan's worktop THICKNESS (mm) - the real figure off the picked\n  // material (custom.worktop_thickness_mm: 12mm ceramic vs 38mm\n  // laminate), falling back to the engine's placeholder, which is what\n  // actually gets drawn when no material is chosen yet. Shared by\n  // buildWorktops (which stamps it onto every slab) and the stack\n  // derive (a unit stacked on a worktopped unit rests ON the slab), so\n  // the height a stacked unit sits at always matches the slab beneath it.\n  //\n  // A made-to-measure stone comes in more than one thickness (20 / 30mm) and\n  // the customer picks one in Customise Worktop; the material's own figure is\n  // only the thinnest it comes in. So it is the PICKED one, chosen exactly as\n  // bespokeJob chooses it - otherwise the 3D, the waterfalls and the stacked\n  // units all stayed at 20mm while the slabs being priced were 30.\n  function worktopThicknessMm() {\n    return worktopThicknessFor(worktopMaterialForSlab());\n  }\n  // A unit's worktop thickness: its own material's, else the plan's.\n  function worktopThicknessForCab(c) {\n    return worktopThicknessFor((c && c.worktopMaterialHandle) || worktopMaterialForSlab());\n  }\n  function worktopThicknessFor(handle) {\n    const mat = handle ? Catalogue.getWorktopMaterial(handle) : null;\n    if (mat && mat.pricingModel === 'bespoke') {\n      const ths = (typeof Catalogue.getBespokeThicknesses === 'function'\n        ? Catalogue.getBespokeThicknesses(handle) : null) || [];\n      const t = ths.includes(worktopBespoke.thicknessMm) ? worktopBespoke.thicknessMm : ths[0];\n      if (t > 0) return t;\n    }\n    return (mat && typeof mat.thicknessMm === 'number' && mat.thicknessMm > 0)\n      ? mat.thicknessMm\n      : STACK_WORKTOP_FALLBACK_MM;\n  }\n\n  // Resolve every cabinet's stack anchor (cab.stackBottomMm /\n  // stackPlinthDropMm / stackHostId) from the units actually under\n  // them. Runs at the top of rerender so the 3D renderer, trim,\n  // worktop, placement and warning engines all read a fresh anchor -\n  // move a host, swap the worktop material or delete a unit and its\n  // riders re-resolve on the next render.\n  function syncStackAnchors() {\n    syncWalkInSets();\n    syncWorktopDressers();\n    syncAsBaseUnits();\n    syncPastrySets();\n    syncWorktopMaterials();\n    resolveStackAnchors(cabinets, stackAnchorOpts());\n    if (stackOntoColumns()) resolveStackAnchors(cabinets, stackAnchorOpts());\n    stampMediaPanelBottoms(cabinets);\n    stampPastrySets(cabinets);\n  }\n  // A unit's own worktop material (bug sheet row 100) that has become the\n  // plan's is the plan's again, so the worktop rejoins its run.\n  function syncWorktopMaterials() {\n    const plan = worktopMaterialHandle || null;\n    for (const c of cabinets) {\n      if (c && c.worktopMaterialHandle && c.worktopMaterialHandle === plan) delete c.worktopMaterialHandle;\n    }\n  }\n  // CHANGE WORKTOP (bug sheet row 100, Arden 2026-11-17): part of the plan in\n  // another worktop material, at that material's own thickness. Stored on the\n  // units (cab.worktopMaterialHandle) so it survives the worktop being\n  // redrawn; the engine keeps them out of other materials' worktops. Chosen in\n  // the Worktops popup, opened for those units (worktopTarget) from the unit\n  // panel or a worktop's panel; pricing and the cutting plan group by material.\n  let worktopTarget = null;   // { cabIds, label } while the popup is choosing for part of the plan\n  // A worktop set on part of the plan prices its own matching upstand and\n  // splashback: the same complementary products the Worktops popup offers for\n  // the plan's worktop (the btk-worktop-extras section), fetched once each.\n  const _altParts = new Map();   // handle -> { upstand, splashback } | 'loading'\n  function altWorktopPartsFor(handle) {\n    const got = _altParts.get(handle);\n    if (got && got !== 'loading') return got;\n    if (!got && typeof fetch === 'function') {\n      _altParts.set(handle, 'loading');\n      const recs = (id) => '/recommendations/products?product_id=' + encodeURIComponent(id) + '&intent=complementary&limit=10';\n      const parse = (html) => {\n        const m = String(html || '').match(/<script type=\"application\\/json\" data-btk-kp-wt-extras>([\\s\\S]*?)<\\/script>/);\n        if (!m) return [];\n        try { const j = JSON.parse(m[1]); return Array.isArray(j) ? j : []; } catch (e) { return []; }\n      };\n      fetch('/products/' + encodeURIComponent(handle) + '.js', { headers: { Accept: 'application/json' } })\n        .then(r => (r.ok ? r.json() : null))\n        .then(p => (p && p.id ? fetch(recs(p.id) + '&section_id=btk-worktop-extras', { headers: { Accept: 'text/html' } }).then(r => (r.ok ? r.text() : '')) : ''))\n        .then(html => {\n          const out = { upstand: null, splashback: null };\n          for (const p of parse(html)) {\n            for (const v of (p.variants || [])) {\n              if (!v || v.available === false || (v.part !== 'upstand' && v.part !== 'splashback') || out[v.part]) continue;\n              out[v.part] = { variantId: v.id, priceCents: Number(v.price) || 0,\n                compareAtCents: v.compare_at_price == null ? null : Number(v.compare_at_price),\n                lengthMm: Number(v.length_mm) || 0, widthMm: Number(v.width_mm) || 0, name: p.title,\n                variantTitle: v.title === 'Default Title' ? '' : (v.title || ''), url: p.handle ? '/products/' + p.handle : null };\n            }\n          }\n          _altParts.set(handle, out);\n        }, () => _altParts.set(handle, { upstand: null, splashback: null }))\n        .finally(() => { rerender(); refreshQuoteLocally(); });\n    }\n    return null;\n  }\n  function worktopPopupOpen() {\n    const el = root && root.querySelector('[data-btk-kp-popup=\"worktop\"]');\n    return !!(el && !el.hidden);\n  }\n  function worktopTargetHandle() {\n    if (!worktopTarget || !worktopPopupOpen()) return null;\n    const c = (cabinets || []).find(x => x && worktopTarget.cabIds.includes(x.id));\n    return (c && c.worktopMaterialHandle) || worktopMaterialForSlab();\n  }\n  function openWorktopForUnits(cabIds, label) {\n    const ids = (cabIds || []).filter(id => (cabinets || []).some(c => c && c.id === id));\n    if (!ids.length) return;\n    worktopTarget = { cabIds: ids, label: label || 'these units' };\n    const popup = root.querySelector('[data-btk-kp-popup=\"worktop\"]');\n    if (!popup) return;\n    popup.hidden = false;\n    worktopsPopupHandle?.open?.({ pickOnly: true });\n  }\n  function handleSetUnitsWorktop(cabIds, handle) {\n    const plan = worktopMaterialForSlab();\n    const h = (typeof handle === 'string' && handle.trim()) ? handle.trim() : null;\n    const sinkBlock = worktopSinkBlock(h || plan, cabIds);\n    if (sinkBlock) { alertFacedSink(sinkBlock); return; }\n    let changed = false;\n    for (const c of (cabinets || [])) {\n      if (!c || !cabIds.includes(c.id)) continue;\n      const next = (h && h !== plan) ? h : null;\n      if ((c.worktopMaterialHandle || null) === next) continue;\n      changed = true;\n      if (next) c.worktopMaterialHandle = next; else delete c.worktopMaterialHandle;\n    }\n    if (changed) { rerender(); refreshQuoteLocally(); }\n    if (selectionPanelHandle && typeof selectionPanelHandle.refresh === 'function') selectionPanelHandle.refresh();\n  }\n  // The worktop a unit has, for its panel: { title, own } (own = not the plan's).\n  function unitWorktopInfo(cabId) {\n    const c = (cabinets || []).find(x => x && x.id === cabId);\n    if (!c || !carriesWorktop(c)) return null;\n    const h = c.worktopMaterialHandle || worktopMaterialForSlab();\n    const m = h ? Catalogue.getWorktopMaterial(h) : null;\n    return { title: m ? m.title : null, own: !!c.worktopMaterialHandle, planChosen: !!worktopMaterialForSlab() };\n  }\n  // A worktop section's units, from its panel.\n  function worktopSectionCabIds(worktopId) {\n    const s = (mergeCornerRuns(buildWorktops() || []) || []).find(x => x && String(x.id) === String(worktopId));\n    return s ? (s.cabinetIds || []).slice() : [];\n  }\n\n  // PASTRY BENCH SET (Arden, 2026-11-17): the Pastry Bench Drawer Set with\n  // its legs, back panel, plinth frame, oak shelf and side fronts - see\n  // engine-stack pastrySetParts. The legs are its Square End Feature end\n  // panels plus the back post, held on here every render: the end panel and\n  // back panel walks leave the set alone, so nothing else can change them.\n  function syncPastrySets() {\n    for (const c of cabinets) {\n      if (!c) continue;\n      if (!isPastrySet(c)) {\n        if (c.pastrySet) { delete c.pastrySet; delete c.pastrySetBack; delete c.pastryParts; }\n        continue;\n      }\n      // Column Legs / Open Pastry Bench: its sides are the 80mm Floor\n      // Columns, bought as their own lines (no post, no board), so every\n      // engine sizes them through the end panel's own width (pastryWidthMm).\n      const kind = pastryKindOf(c);\n      const col = kind !== 'square';\n      if (col) c.pastrySet = { kind };\n      else {\n        const fp = endFeatureProduct('square', c.kitchenStyleId || kitchenStyleId || null);\n        c.pastrySet = pastryPostSection(fp ? fp.name : '');\n      }\n      const ep = c.endPanels || {}, fil = c.fillers || {};\n      const side = (s) => ({ ...(ep[s] || {}), active: true, style: 'square', inline: false,\n        toFloor: false, tng: false, doorEnd: null, manual: null, userOff: false, pastry: true,\n        pastryColumn: col || undefined, pastryWidthMm: col ? PASTRY_COLUMN_MM : undefined });\n      c.endPanels = { left: side('left'), right: side('right') };\n      c.fillers = { left: { ...(fil.left || {}), active: false }, right: { ...(fil.right || {}), active: false } };\n      // The back post's back face is panelLengthMm + 120 behind the front\n      // (2D, worktop, trim): at the carcase back + the 20mm back panel.\n      c.backEndPost = { ...(c.backEndPost || {}), active: true, panelLengthMm: Math.max(1, (c.depthMm || 0) - 100) };\n      c.backPanel = { ...(c.backPanel || {}), active: false };\n      c.useFullSizeEndPanel = false;\n    }\n  }\n  // The parts' sizes, once the unit's top is known (it hangs at the base\n  // units' top, so it moves with the plan's plinth).\n  function stampPastrySets(list) {\n    for (const c of (list || [])) {\n      if (!c || !c.pastrySet) continue;\n      const r = unitVerticalRange(c);\n      const sh = pastryShelfLook(c);\n      const parts = pastrySetParts(c.pastrySet, c.widthMm || 0, c.depthMm || 0, r.top, r.bottom, sh.thicknessMm);\n      c.pastryParts = parts;\n      c.pastrySetBack = parts.back;\n      c.pastryShelf = sh;\n    }\n  }\n  // THE SHELF (Arden, 2026-11-17): Real Wood (a real wood worktop blank,\n  // Natural Oak 22mm unless another is chosen), Carcase Material (the\n  // Pastry Bench Shelf, in the unit's carcase colour, made to the size the\n  // plan draws) or Match Plan Worktop (cut from the plan's worktop, priced\n  // with it - see pastryShelfSlabs). Stored as cab.pastryShelfChoice\n  // { kind: 'wood' | 'carcase' | 'worktop', handle }.\n  const PASTRY_SHELF_PRODUCT = 'no-door-pastry-bench-shelf';\n  // Carcase Material unless another is chosen (Arden, 2026-11-17).\n  function pastryShelfChoice(c) {\n    const ch = (c && c.pastryShelfChoice) || {};\n    if (ch.kind === 'worktop' && worktopMaterialForSlab()) return { kind: 'worktop' };\n    if (ch.kind === 'wood') {\n      const wood = ch.handle && Catalogue.getWorktopMaterial && Catalogue.getWorktopMaterial(ch.handle);\n      return { kind: 'wood', handle: wood ? ch.handle : PASTRY_SHELF_HANDLE };\n    }\n    return { kind: 'carcase' };\n  }\n  // How the 3D draws it: its thickness and finish.\n  function pastryShelfLook(c) {\n    const ch = pastryShelfChoice(c);\n    if (ch.kind === 'carcase') {\n      const cc = Catalogue.getCarcaseColour ? Catalogue.getCarcaseColour(c.carcaseColourHandle || globalCarcaseColourHandle) : null;\n      return { kind: 'carcase', thicknessMm: 18, hex: (cc && cc.hex) || '#f2f2f2', swatchUrl: null, textureMm: null };\n    }\n    if (ch.kind === 'worktop') {\n      const m = Catalogue.getWorktopMaterial(worktopMaterialForSlab());\n      return { kind: 'worktop', thicknessMm: worktopThicknessMm(), hex: worktopColourHex || null,\n               swatchUrl: (m && (m.textureUrl || m.swatchUrl)) || null, textureMm: (m && m.textureMm) || null };\n    }\n    const m = Catalogue.getWorktopMaterial ? Catalogue.getWorktopMaterial(ch.handle) : null;\n    return { kind: 'wood', handle: ch.handle, thicknessMm: (m && m.thicknessMm) || 22,\n             swatchUrl: (m && m.swatchUrl) || null, textureMm: (m && m.textureMm) || null };\n  }\n  // The Carcase Material shelf product, fetched once (it's a no-door product,\n  // not in the style catalogue the planner loads).\n  let _pbShelf;            // undefined: not loaded; null: none\n  let _pbShelfLoading = null;\n  function ensurePastryShelfProduct() {\n    if (_pbShelf !== undefined || _pbShelfLoading) return;\n    _pbShelfLoading = fetch('/products/' + PASTRY_SHELF_PRODUCT + '.js', { credentials: 'same-origin' })\n      .then(r => (r.ok ? r.json() : null))\n      .then(p => { _pbShelf = p ? { title: p.title, handle: p.handle, variants: (p.variants || []).map(v => ({ id: v.id, title: v.title,\n        priceCents: v.price, compareAtCents: (typeof v.compare_at_price === 'number') ? v.compare_at_price : null })) } : null; })\n      .catch(() => { _pbShelf = undefined; })\n      .finally(() => { _pbShelfLoading = null; rerender(); refreshQuoteLocally(); try { cabinetsHandle?.refresh?.(); } catch (e) {} });\n  }\n  // THE SET'S PRICE for an Add Units card (Arden, 2026-11-17): a Pastry Bench\n  // product goes on the plan as a whole set, so its card shows the set - the\n  // unit (nothing for the Open bench) plus its legs, back panel board, fronts\n  // or rails, plinth and the Carcase Material shelf - as the basket would\n  // charge it standing alone. Cents, or null for any other unit.\n  function pastrySetPriceCents(unitTypeId, styleId, variantId) {\n    if (!isPastrySet({ unitTypeId })) return null;\n    try {\n      const def = Catalogue.buildCabinetDefinition({ unitTypeId, variantId, kitchenStyleId: styleId });\n      if (!def) return null;\n      const info = Catalogue.getVariantInfo ? Catalogue.getVariantInfo(variantId) : null;\n      let total = Number((info && info.priceCents) || 0);\n      const c = { ...def, id: 'pastry-price', x: 0, y: 0, rotationDeg: 0, kitchenStyleId: styleId,\n                  doorColourHandle: globalDoorColourHandle || null, carcaseColourHandle: globalCarcaseColourHandle || null,\n                  pastryShelfChoice: { kind: 'carcase' } };\n      const kind = pastryKindOf(c);\n      const fp = kind === 'square' ? endFeatureProduct('square', styleId) : null;\n      c.pastrySet = kind === 'square' ? pastryPostSection(fp ? fp.name : '') : { kind };\n      const TOP = 870;\n      c.pastryParts = pastrySetParts(c.pastrySet, c.widthMm || 0, c.depthMm || 0, TOP, TOP - 145, pastryShelfLook(c).thicknessMm);\n      c.pastrySetBack = c.pastryParts.back;\n      if (_pbShelf === undefined) ensurePastryShelfProduct();\n      for (const ch of pastryCharges(c)) total += (ch.priceCents || 0) * (ch.qty || 1);\n      // Square End Feature legs: the stock lengths the four are cut from.\n      if (fp && fp.priceCents != null) {\n        const legs = [1, 2, 3, 4].map(() => c.pastryParts.legMm);\n        const n = fp.lengthMm ? packEndFeatureLengths(legs, fp.lengthMm).lengths : 4;\n        total += fp.priceCents * n;\n      }\n      // The back panel board, as the nester picks it for this set alone.\n      const faces = collectEndPanelFaces([c], panelFaceOpts()).filter(f => f.side === 'pastry-back');\n      const nested = faces.length ? nestPanels(faces, { fillerStock: [] }) : null;\n      for (const b of ((nested && nested.boards) || [])) {\n        const p = endPanelBoardProduct(b, styleId);\n        if (p && p.priceCents != null) total += p.priceCents;\n      }\n      return Math.round(total);\n    } catch (e) {\n      console.warn('[BTK pastry set] card price failed', e);\n      return null;\n    }\n  }\n  // Match Plan Worktop: the shelf as one more piece of the plan's worktop,\n  // so it is nested and priced with the rest of it (boards, slabs or the\n  // made-to-measure job). Laid flat at the unit, for the billing only.\n  function pastryShelfSlabs() {\n    const out = [];\n    for (const c of (cabinets || [])) {\n      if (!c || !c.pastryParts || c.excludeFromQuote || pastryShelfChoice(c).kind !== 'worktop') continue;\n      const L = c.pastryParts.shelf.lengthMm, D = c.pastryParts.shelf.depthMm;\n      const x0 = c.x || 0, y0 = c.y || 0;\n      out.push({ id: 'pastry-shelf|' + c.id, cabinetIds: [c.id], thicknessMm: worktopThicknessMm(), cushionTop: false,\n        restMm: 150, exposedBack: false, exposedLeft: true, exposedRight: true, rotationDeg: 0,\n        polygon: [{ x: x0, y: y0 }, { x: x0 + L, y: y0 }, { x: x0 + L, y: y0 + D }, { x: x0, y: y0 + D }],\n        worldRects: [{ x0, y0, x1: x0 + L, y1: y0 + D }], radiusRounds: [], materialHandle: worktopMaterialForSlab(),\n        pastryShelf: true });\n    }\n    return out;\n  }\n  function handleSetPastryShelf(cabinetId, choice) {\n    const c = (cabinets || []).find(x => x && x.id === cabinetId);\n    if (!c) return;\n    const k = choice && choice.kind;\n    c.pastryShelfChoice = k === 'carcase' ? { kind: 'carcase' } : k === 'worktop' ? { kind: 'worktop' }\n      : { kind: 'wood', handle: (choice && choice.handle) || PASTRY_SHELF_HANDLE };\n    rerender();\n    refreshQuoteLocally();\n    if (selectionPanelHandle && typeof selectionPanelHandle.refresh === 'function') selectionPanelHandle.refresh();\n  }\n  // What the shelf popup offers: the real wood worktops, and the plan's own\n  // worktop when it has one.\n  function pastryShelfOptions(cabinetId) {\n    const c = (cabinets || []).find(x => x && x.id === cabinetId);\n    const woods = (Catalogue.getWorktopMaterials ? Catalogue.getWorktopMaterials() : [])\n      .filter(m => m && /real wood/i.test(String(m.range || m.type || '')))\n      .map(m => ({ handle: m.handle, title: m.title, thicknessMm: m.thicknessMm }))\n      .sort((a, b) => String(a.title).localeCompare(String(b.title)));\n    const wh = worktopMaterialForSlab();\n    const wm = wh ? Catalogue.getWorktopMaterial(wh) : null;\n    return { choice: c ? pastryShelfChoice(c) : null, woods, planWorktop: wm ? { handle: wm.handle, title: wm.title } : null };\n  }\n  // A set part's product and quantity: { part, variantId, title, handle,\n  // priceCents, compareAtCents, qty, detail, colour } or null when the range\n  // doesn't sell it (the line is then left off and a warning logged).\n  const PASTRY_LINE_PARTS = ['fronts', 'plinth', 'shelf'];\n  // The column sets' legs are lines of their own (the range's Floor Column),\n  // and the Open Pastry Bench has a front rail too.\n  const pastryLineParts = (c) => {\n    const k = (c && c.pastryParts && c.pastryParts.kind) || 'square';\n    return k === 'open' ? ['legs', 'front-rail', ...PASTRY_LINE_PARTS] : k === 'column' ? ['legs', ...PASTRY_LINE_PARTS] : PASTRY_LINE_PARTS;\n  };\n  const PASTRY_SHELF_HANDLE = 'natural-oak-real-wood-worktop-22mm-thick';\n  function pastryPartCharge(c, part) {\n    const pp = c && c.pastryParts;\n    if (!pp) return null;\n    const style = c.kitchenStyleId || kitchenStyleId || null;\n    const colour = c.doorColourHandle || globalDoorColourHandle || null;\n    const vinfo = (id) => (Catalogue.getVariantInfo ? Catalogue.getVariantInfo(id) : null);\n    if (part === 'legs') {\n      // Four of the range's Floor Columns, cut to the bench's height.\n      const pr = Catalogue.getProductForUnitInStyle ? Catalogue.getProductForUnitInStyle('floor-column', style) : null;\n      const v = pr && (pr.variants || [])[0];\n      if (!v) return null;\n      const i = vinfo(v.id);\n      return { part, variantId: v.id, title: pr.title, handle: pr.handle || null,\n               priceCents: (i && i.priceCents) ?? v.price ?? 0,\n               compareAtCents: (i && i.variant && i.variant.compareAtPrice) ?? null,\n               qty: 4, colour, style,\n               detail: `Cut to ${pp.legMm}mm, 80mm off the ${pp.kind === 'open' ? 'top' : 'bottom'} \u00B7 one each corner` };\n    }\n    if (part === 'fronts' || part === 'front-rail') {\n      const need = part === 'front-rail' ? pp.frontRailMm : pp.frontMm;\n      const pr = Catalogue.getProductForUnitInStyle ? Catalogue.getProductForUnitInStyle('drawer-front-140', style) : null;\n      const vs = ((pr && pr.variants) || []).map(v => ({ v, i: vinfo(v.id) }))\n        .map(o => ({ ...o, w: Math.round(Number(o.i && o.i.widthMm) || Number((String(o.v.title || '').match(/\\d{3,4}/) || [])[0]) || 0) }))\n        .filter(o => o.w >= need).sort((a, b) => a.w - b.w);\n      const pick = vs[0];\n      if (!pick) return null;\n      // The Open Pastry Bench's rails are drawer fronts cut down to 50mm.\n      const rail = pp.kind === 'open' ? ` x ${pp.railHeightMm}mm` : 'mm';\n      // A front used at its full width (the 1000 bench's 996 front rail).\n      if (pick.w === need) return { part, variantId: pick.v.id, title: pr.title, handle: pr.handle || null,\n               priceCents: (pick.i && pick.i.priceCents) ?? pick.v.price ?? 0,\n               compareAtCents: (pick.i && pick.i.variant && pick.i.variant.compareAtPrice) ?? null,\n               qty: part === 'front-rail' ? 1 : 2, colour, style,\n               detail: `${pick.w}mm, cut to ${pp.railHeightMm}mm high \u00B7 ${part === 'front-rail' ? 'front rail' : 'one each side'}` };\n      return { part, variantId: pick.v.id, title: pr.title, handle: pr.handle || null,\n               priceCents: (pick.i && pick.i.priceCents) ?? pick.v.price ?? 0,\n               compareAtCents: (pick.i && pick.i.variant && pick.i.variant.compareAtPrice) ?? null,\n               qty: part === 'front-rail' ? 1 : 2, colour, style,\n               detail: `${pick.w}mm, cut to ${need}${rail} \u00B7 ${part === 'front-rail' ? 'front rail' : 'one each side'}` };\n    }\n    if (part === 'plinth') {\n      const sold = ((Catalogue.getTrimForStyle && Catalogue.getTrimForStyle(style)) || {}).plinth || [];\n      const ok = sold.filter(p => p && p.available !== false && p.product && p.product.variantId);\n      const pr = (ok.find(p => plinthKindOf(p.name) === 'plain') || ok[0] || {}).product;\n      if (!pr) return null;\n      const len = (typeof pr.lengthMm === 'number' && pr.lengthMm > 0) ? pr.lengthMm : 0;\n      const qty = len ? Math.max(1, packEndFeatureLengths(pp.plinthPiecesMm, len).lengths) : 1;\n      return { part, variantId: pr.variantId, title: pr.title, handle: pr.handle || null,\n               priceCents: pr.priceCents ?? 0, compareAtCents: pr.compareAtPrice ?? pr.compareAtCents ?? null,\n               qty, colour, style, detail: `Shelf frame${pp.plinthMm && pp.plinthMm !== 150 ? ', cut to ' + pp.plinthMm + 'mm high' : ''}: ${pp.plinthPiecesMm.join(' + ')}mm` };\n    }\n    if (part === 'shelf') {\n      const ch = pastryShelfChoice(c);\n      // Matched to the plan worktop: billed in the worktop lines.\n      if (ch.kind === 'worktop') return null;\n      if (ch.kind === 'carcase') {\n        if (_pbShelf === undefined) { ensurePastryShelfProduct(); return null; }\n        const L = pp.shelf.lengthMm, D = pp.shelf.depthMm;\n        const size = (v) => (String(v.title || '').match(/(\\d+)\\s*\\/\\s*(\\d+)/) || []).slice(1).map(Number);\n        const fits = ((_pbShelf && _pbShelf.variants) || []).map(v => ({ v, s: size(v) }))\n          .filter(o => o.s[0] >= L && o.s[1] >= D).sort((a, b) => (a.s[0] * a.s[1]) - (b.s[0] * b.s[1]));\n        const v = fits[0] && fits[0].v;\n        if (!v) return null;\n        return { part, variantId: v.id, title: _pbShelf.title, handle: _pbShelf.handle, priceCents: v.priceCents || 0,\n                 compareAtCents: v.compareAtCents ?? null, qty: 1, colour: null, style, carcase: true,\n                 carcaseColour: c.carcaseColourHandle || globalCarcaseColourHandle || null,\n                 detail: String(v.title || '').replace(/\\s*\\/\\s*/, ' x ') + 'mm' };\n      }\n      const m = Catalogue.getWorktopMaterial ? Catalogue.getWorktopMaterial(ch.handle) : null;\n      const vs = ((m && m.variants) || []).filter(v => v && v.available !== false\n        && (v.lengthMm || 0) >= pp.shelf.lengthMm && (v.widthMm || 0) >= pp.shelf.depthMm)\n        .sort((a, b) => (a.priceCents || 0) - (b.priceCents || 0));\n      const v = vs[0];\n      if (!v) return null;\n      return { part, variantId: v.id, title: m.title, handle: m.handle, priceCents: v.priceCents || 0,\n               compareAtCents: v.compareAtCents ?? null, qty: 1, colour: null, style: null,\n               swatchUrl: m.swatchUrl || null,\n               detail: `${v.option || ''} \u00B7 cut to ${pp.shelf.lengthMm} x ${pp.shelf.depthMm}mm` };\n    }\n    return null;\n  }\n  function pastryCharges(c) {\n    if (!c || !c.pastryParts || c.excludeFromQuote) return [];\n    const out = [];\n    for (const k of pastryLineParts(c)) {\n      const ch = pastryPartCharge(c, k);\n      if (ch) out.push(ch);\n      else if (!(k === 'shelf' && pastryShelfChoice(c).kind !== 'wood'))\n        console.warn('[BTK pastry set] no product for', k, 'in', c.kitchenStyleId);\n    }\n    return out;\n  }\n  // MEDIA WALL COLUMNS: a wall unit dropped onto a column (units set to\n  // Worktop / Wall Unit / Line Up) is set to Wall Unit, so it goes on top of\n  // the column (Arden, 2026-10-28: a third unit wouldn't go over the others).\n  function stackOntoColumns() {\n    const inColumn = (c) => c && isWallMounted(c) && ['worktop', 'on', 'align'].includes(c.mountAnchor);\n    const col = cabinets.filter(inColumn);\n    if (!col.length) return false;\n    let changed = false;\n    cabinets.forEach((c, i) => {\n      if (!c || !isWallMounted(c) || c.dresserUnit || inColumn(c) || c.mountAnchor === 'under' || c.mountAnchor === 'set') return;\n      // Over a column unit's footprint and not hanging below it: a unit set to\n      // Wall Unit would otherwise climb onto this one, so this one joins the\n      // column, last in its order.\n      const own = planFootprintAABB(c), r = wallUnitVerticalRange(c);\n      const joins = col.some(o => footprintsOverlap(own, planFootprintAABB(o))\n        && o.mountAnchor !== 'on' && r.top > wallUnitVerticalRange(o).bottom + 5);\n      if (!joins) return;\n      c.mountAnchor = 'on'; c.onSince = Date.now() + i;\n      changed = true;\n    });\n    return changed;\n  }\n  // Worktop dressers, kept right on every render rather than only on load:\n  // their unit types sit past the Liquid 250 cap and arrive from the\n  // Storefront API a moment after boot, so a saved plan can load before the\n  // catalogue knows them. Read off the cab alone, it corrects itself:\n  // category to wall-units (so it may sit over a base unit), the height its\n  // Height option is sold in once the variant is known, and the line that\n  // height is made for. Clears the flag the 2026-10-09 push wrongly put on\n  // the Larder Wall Unit.\n  // MAKE BASE UNIT (Arden, 2026-11-12): a wall unit - or a corner wall unit -\n  // set to stand on the floor on 150mm legs, with a plinth and a worktop, as a\n  // base unit does. While it is on, the unit IS a base unit to every engine\n  // (placement, plinth, worktop, end panels, cornice / pelmet): category\n  // base-units and its height plus the legs. cab.asBase keeps what it was, so\n  // turning it off hangs it back as it was. Its product is still the wall\n  // unit; a leg pack is added to the basket for it (legItemsOwnedBy).\n  const AS_BASE_LEGS_MM = 150;\n  function canMakeBaseUnit(c) {\n    return !!c && (!!c.asBase || (/^wall/i.test(c.category || '') && !c.dresserUnit && !isStacked(c)));\n  }\n  // Kept right on every render: a size or range change re-reads the unit from\n  // the catalogue (wall category, the carcase height) - the carcase is the\n  // variant's height, the legs go under it.\n  // The Walk-In Corner Larder FRAME a unit at (x, y) is over (its centre on\n  // the larder's floor), or null. Only the Frame (Arden 2026-11-12).\n  function frameLarderUnder(cab, x, y, others) {\n    if (!cab || isWalkInLarder(cab) || cab.diagonalCornerUnit) return null;\n    const mx = x + (cab.widthMm || 0) / 2, my = y + (cab.depthMm || 0) / 2;\n    return (others || []).find(o => o && isWalkInLarder(o) && /frame/i.test(String(o.unitTypeId || ''))\n      && pointOverWalkInLarder(o, mx, my)) || null;\n  }\n  // ---- WALK-IN LARDER SETS (Sales sheet line 111) ----\n  // A Walk-In Corner Larder FRAME is fitted with one of the sets in\n  // engine-walkin-sets (Full Doors / Wine Storage / Open Shelving), picked in\n  // the Customise Walk-in Larder popup - from the Frame's panel or the green +\n  // on an empty Frame. Arden 2026-11-12: no free layout inside the Frame.\n  // The set's units are real units - their own lines, numbers, colours,\n  // handles and hinges - but each one is held to its place in the larder\n  // (cab.walkInSet = { hostId, key, u, v, rel }): it moves, turns, is copied\n  // and is deleted with the larder, and cannot be dragged on its own.\n  const walkInEsc = s => String(s == null ? '' : s).replace(/[&<>\"]/g, ch => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '\"': '&quot;' }[ch]));\n  function walkInSetMembers(frameId) {\n    return cabinets.filter(c => c && c.walkInSet && c.walkInSet.hostId === frameId);\n  }\n  // Put every set unit where its place says, in its larder as it stands now.\n  // Runs at the top of every render (syncStackAnchors), so a larder that has\n  // been dragged, turned or snapped carries its units with it.\n  const walkInRefitPending = new Set();\n  function syncWalkInSets() {\n    const byId = new Map(cabinets.filter(Boolean).map(c => [c.id, c]));\n    for (const c of cabinets) {\n      if (!c || !c.walkInSet) continue;\n      const host = byId.get(c.walkInSet.hostId);\n      if (!host || !isWalkInFrame(host)) { delete c.walkInSet; continue; }\n      const p = walkInSetPose(host, c.walkInSet, c.widthMm, c.depthMm);\n      if (p) { c.x = p.x; c.y = p.y; c.rotationDeg = p.rotationDeg; }\n    }\n    // A Frame changed between Medium and High: its set is refitted in the\n    // other height's version of the same layout (after this render).\n    for (const f of cabinets) {\n      if (!f || !f.walkInSetKey || !f.walkInSetHeight || walkInRefitPending.has(f.id)) continue;\n      if (f.walkInSetHeight === walkInSetHeightKey(f) || !walkInSetMembers(f.id).length) continue;\n      walkInRefitPending.add(f.id);\n      setTimeout(() => { walkInRefitPending.delete(f.id); applyWalkInSet(f.id, f.walkInSetKey); }, 0);\n    }\n  }\n  // The set units' poses for a larder being dragged to (x, y) - so they ride\n  // with it on screen before the drop commits.\n  function walkInSetLivePoses(frame, x, y) {\n    const out = new Map();\n    for (const m of walkInSetMembers(frame.id)) {\n      const p = walkInSetPose(frame, m.walkInSet, m.widthMm, m.depthMm, x, y);\n      if (p) out.set(m.id, p);\n    }\n    return out;\n  }\n  // Where the green + goes on an EMPTY Frame (nothing fitted, nothing stood\n  // in it): its floor, between the gables. Null otherwise.\n  function walkInSetPlusAt(cab) {\n    if (!isWalkInFrame(cab) || _bootOrdered) return null;\n    if (cabinets.some(c => c && c !== cab && ((c.walkInSet && c.walkInSet.hostId === cab.id)\n      || (!isWalkInLarder(c) && pointOverWalkInLarder(cab, (c.x || 0) + (c.widthMm || 0) / 2, (c.y || 0) + (c.depthMm || 0) / 2))))) return null;\n    const b = walkInFrameBasis(cab);\n    return b ? walkInToWorld(b, 400, 400) : null;\n  }\n  // The unit a set slot asks for, in the Frame's range: matched by the\n  // variant's option values (Width / Depth / Height), which every range shares.\n  function walkInSetDef(frame, tpl) {\n    const styleId = frame.kitchenStyleId;\n    const product = Catalogue.getProductForUnitInStyle(tpl.ut, styleId);\n    if (!product) return null;\n    const want = tpl.opts.join('|');\n    const v = (product.variants || []).find(vv => {\n      const i = Catalogue.getVariantInfo(vv.id);\n      return i && ((i.variant && i.variant.options) || []).join('|') === want;\n    });\n    return v ? Catalogue.buildCabinetDefinition({ unitTypeId: tpl.ut, variantId: v.id, kitchenStyleId: styleId }) : null;\n  }\n  // Every unit standing in the Frame now: its set, and anything placed in it\n  // by hand before sets existed.\n  function walkInUnitsIn(frame) {\n    return cabinets.filter(c => c && c !== frame && ((c.walkInSet && c.walkInSet.hostId === frame.id)\n      || (!isWalkInLarder(c) && pointOverWalkInLarder(frame, (c.x || 0) + (c.widthMm || 0) / 2, (c.y || 0) + (c.depthMm || 0) / 2))));\n  }\n  // Fit the Frame with a set, in place of whatever stands in it.\n  function applyWalkInSet(frameId, key) {\n    const frame = cabinets.find(c => c.id === frameId);\n    if (!frame || !isWalkInFrame(frame) || _bootOrdered) return false;\n    const tpls = walkInSetTemplates(frame, key);\n    const defs = tpls.map(t => walkInSetDef(frame, t));\n    if (!tpls.length || defs.some(d => !d)) {\n      designControlsHandle.setStatus('This set is not available in this bedroom range.');\n      return false;\n    }\n    const out = new Set(walkInUnitsIn(frame).map(c => c.id));\n    cabinets = cabinets.filter(c => !out.has(c.id));\n    selectedCabinetIds = new Set([...selectedCabinetIds].filter(id => !out.has(id)));\n    tpls.forEach((t, i) => {\n      const id = addCabinet(defs[i], { quiet: true });\n      const cab = cabinets.find(c => c.id === id);\n      if (!cab) return;\n      Object.assign(cab, JSON.parse(JSON.stringify(t.keep)),\n        { walkInSet: { hostId: frameId, key, u: t.u, v: t.v, rel: t.rel } });\n      const p = walkInSetPose(frame, cab.walkInSet, cab.widthMm, cab.depthMm);\n      if (p) Object.assign(cab, p);\n    });\n    frame.walkInSetKey = key;\n    frame.walkInSetHeight = walkInSetHeightKey(frame);\n    syncStackAnchors();\n    autoDetectBackPanels();\n    resizeFillers();\n    rerender();\n    scheduleBasketResync();\n    return true;\n  }\n\n  // The Customise Walk-in Larder popup: one card per set, each with a live\n  // picture of the set in the plan's colours, what is in it and its price.\n  let walkInSetsPopupEl = null;\n  let walkInSetsFrameId = null;\n  function walkInSetPreviewCabs(frame, key) {\n    const tpls = walkInSetTemplates(frame, key);\n    const out = [];\n    tpls.forEach((t, i) => {\n      const d = walkInSetDef(frame, t);\n      if (!d) return;\n      const cab = Object.assign({}, d, JSON.parse(JSON.stringify(t.keep)), {\n        id: 'walkin-preview-' + i, type: 'cabinet',\n        doorColourHandle: frame.doorColourHandle || globalDoorColourHandle || null,\n        carcaseColourHandle: frame.carcaseColourHandle || globalCarcaseColourHandle || null,\n        walkInSet: { hostId: frame.id, key, u: t.u, v: t.v, rel: t.rel }\n      });\n      if (/^wall/i.test(cab.category || '') && !cab.asBase) {\n        cab.capTopMm = (frame.heightMm || 0) - WALK_IN_BOARD_MM * 2;\n      }\n      Object.assign(cab, walkInSetPose(frame, cab.walkInSet, cab.widthMm, cab.depthMm) || {});\n      out.push(cab);\n    });\n    return out;\n  }\n  function walkInSetSummary(frame, key) {\n    const tpls = walkInSetTemplates(frame, key);\n    const name = (t) => {\n      const ut = Catalogue.getUnitType ? Catalogue.getUnitType(t.ut) : null;\n      const n = String((ut && (ut.name || ut.title)) || t.ut).replace(/\\s*Wall Unit$/i, '').replace(/\\s*Unit$/i, '');\n      return /corner/i.test(n) ? n : `${t.opts[0]} ${n}`;\n    };\n    const list = (arr) => {\n      const counts = new Map();\n      // The corner unit first, then the rest in the order they stand.\n      const ordered = [...arr].sort((a, b) => (/corner/.test(b.ut) ? 1 : 0) - (/corner/.test(a.ut) ? 1 : 0));\n      for (const t of ordered) { const n = name(t); counts.set(n, (counts.get(n) || 0) + 1); }\n      return [...counts].map(([n, k]) => (k > 1 ? `${k} x ${n}` : n)).join(', ');\n    };\n    let cents = 0;\n    for (const t of tpls) {\n      const d = walkInSetDef(frame, t);\n      const info = d && Catalogue.getVariantInfo ? Catalogue.getVariantInfo(d.variantId) : null;\n      cents += (info && info.priceCents) || 0;\n    }\n    return {\n      lower: list(tpls.filter(t => t.keep.asBase)),\n      upper: list(tpls.filter(t => !t.keep.asBase)),\n      cents\n    };\n  }\n  function walkInMoney(cents) {\n    const vat = window.BTKVat;\n    return (vat && typeof vat.formatPrice === 'function')\n      ? vat.formatPrice(Math.round(cents))\n      : '\u00A3' + (Math.round(cents) / 100).toFixed(2);\n  }\n  function ensureWalkInSetsPopup() {\n    if (walkInSetsPopupEl) return walkInSetsPopupEl;\n    const wrap = document.createElement('div');\n    wrap.innerHTML = `\n      <div class=\"btk-kp-popup btk-kp-popup--wide\" data-btk-kp-popup=\"walkin-sets\" hidden>\n        <div class=\"btk-kp-popup-backdrop\" data-btk-kp-popup-close></div>\n        <div class=\"btk-kp-popup-panel\" role=\"dialog\" aria-label=\"Customise Walk-in Larder\">\n          <header class=\"btk-kp-popup-head\">\n            <h2>Customise Walk-in Larder</h2>\n            <button type=\"button\" class=\"btk-kp-popup-close\" data-btk-kp-popup-close aria-label=\"Close\">\u00D7</button>\n          </header>\n          <div class=\"btk-kp-popup-body\">\n            <p class=\"btk-kp-walkin-intro\">Choose how the inside of your walk-in larder is fitted. Each layout is made to fit the larder exactly.</p>\n            <div class=\"btk-kp-walkin-cards\" data-walkin-cards></div>\n          </div>\n        </div>\n      </div>`;\n    walkInSetsPopupEl = wrap.firstElementChild;\n    root.appendChild(walkInSetsPopupEl);\n    walkInSetsPopupEl.addEventListener('click', (e) => {\n      const btn = e.target.closest('[data-walkin-pick]');\n      if (!btn || btn.disabled) return;\n      if (applyWalkInSet(walkInSetsFrameId, btn.getAttribute('data-walkin-pick'))) {\n        walkInSetsPopupEl.hidden = true;\n        selectItem({ kind: 'cabinet', id: walkInSetsFrameId });\n      }\n    });\n    return walkInSetsPopupEl;\n  }\n  function openWalkInSetsPopup(frameId) {\n    const frame = cabinets.find(c => c.id === frameId);\n    if (!frame || !isWalkInFrame(frame) || _bootOrdered) return;\n    walkInSetsFrameId = frameId;\n    const pop = ensureWalkInSetsPopup();\n    const grid = pop.querySelector('[data-walkin-cards]');\n    grid.innerHTML = '';\n    const basis = walkInFrameBasis(frame);\n    const viewDir = basis ? { x: basis.e1x + basis.e2x, y: basis.e1y + basis.e2y } : null;\n    const height = walkInSetHeightKey(frame) === 'high' ? 'High' : 'Medium';\n    for (const opt of WALK_IN_SET_OPTIONS) {\n      const s = walkInSetSummary(frame, opt.key);\n      const fitted = frame.walkInSetKey === opt.key && walkInSetMembers(frame.id).length > 0;\n      const ok = walkInSetTemplates(frame, opt.key).every(t => walkInSetDef(frame, t));\n      const card = document.createElement('div');\n      card.className = 'btk-kp-walkin-card' + (fitted ? ' is-fitted' : '');\n      card.innerHTML = `\n        <div class=\"btk-kp-walkin-card-img\"><div class=\"btk-kp-cabinets-row-img--placeholder\"></div></div>\n        <div class=\"btk-kp-walkin-card-text\">\n          <div class=\"btk-kp-cabinets-row-name\">${walkInEsc(opt.title)}</div>\n          <div class=\"btk-kp-walkin-card-meta\">${walkInEsc(height)} walk-in larder</div>\n          <dl class=\"btk-kp-walkin-card-list\">\n            <dt>Wall level</dt><dd>${walkInEsc(s.upper)}</dd>\n            <dt>Lower level, on legs</dt><dd>${walkInEsc(s.lower)}</dd>\n          </dl>\n        </div>\n        <div class=\"btk-kp-walkin-card-side\">\n          <div class=\"btk-kp-cabinets-add-summary\"><span class=\"btk-kp-cabinets-add-summary-price\">${ok ? walkInEsc(walkInMoney(s.cents)) : ''}</span></div>\n          <button type=\"button\" class=\"btk-kp-cabinets-add\" data-walkin-pick=\"${walkInEsc(opt.key)}\" ${(!ok || fitted) ? 'disabled' : ''}>\n            <span class=\"btk-kp-cabinets-add-label\">${fitted ? 'Fitted' : (ok ? 'Choose' : 'Not available')}</span>\n          </button>\n        </div>`;\n      grid.appendChild(card);\n      const slot = card.querySelector('.btk-kp-walkin-card-img');\n      const cabs = walkInSetPreviewCabs(frame, opt.key);\n      if (cabs.length) {\n        openingThumbnailRenderer().then(h => (h && typeof h.renderGroupThumbnail === 'function')\n          ? h.renderGroupThumbnail(cabs, { width: 480, height: 360, viewDir, handleGroups })\n          : null).then(url => {\n          if (!url || walkInSetsFrameId !== frameId) return;\n          slot.innerHTML = '';\n          const img = document.createElement('img');\n          img.src = url; img.alt = opt.title;\n          slot.appendChild(img);\n        }).catch(() => {});\n      }\n    }\n    pop.hidden = false;\n  }\n  function syncAsBaseUnits() {\n    // Wall units inside a walk-in corner larder hang under its 18mm top panel\n    // (cab.capTopMm, read by engine-wall-mount wallUnitVerticalRange).\n    const larders = cabinets.filter(c => c && isWalkInLarder(c));\n    for (const c of cabinets) {\n      if (!c || isWalkInLarder(c)) continue;\n      const L = larders.length && /^(wall|bridging)/i.test(c.category || '')\n        ? larders.find(l => unitInsideWalkInLarder(c, c.x || 0, c.y || 0, l)) : null;\n      // The Frame comes with a double top panel (2 x 18mm), the larder a single.\n      if (L) c.capTopMm = (L.heightMm || 0) - WALK_IN_BOARD_MM * (/frame/i.test(String(L.unitTypeId || '')) ? 2 : 1);\n      else if (c.capTopMm != null) delete c.capTopMm;\n    }\n    // A larder with units inside draws its top see-through in 2D, so the\n    // units under its top panel show (Arden 2026-11-12).\n    for (const l of larders) {\n      const any = cabinets.some(c => c && c !== l && unitInsideWalkInLarder(c, c.x || 0, c.y || 0, l));\n      if (any) l.walkInHasUnitsInside = true;\n      else if (l.walkInHasUnitsInside) delete l.walkInHasUnitsInside;\n    }\n    for (const c of cabinets) {\n      if (!c || !c.asBase) continue;\n      const info = c.variantId && Catalogue.getVariantInfo ? Catalogue.getVariantInfo(c.variantId) : null;\n      const carcase = (info && info.heightMm > 0) ? info.heightMm : (c.asBase.heightMm || 720);\n      c.asBase.heightMm = carcase;\n      c.category = 'base-units';\n      c.heightMm = carcase + AS_BASE_LEGS_MM;\n      c.plinthHeightMm = AS_BASE_LEGS_MM;\n      if (c.plinthType === 'none') c.plinthType = null;\n    }\n  }\n  // WORKTOP PANTRY UNIT - Depth & Internals popup (Sales sheet row 142). The\n  // BACK edge stays put, so a unit against the wall stays against it.\n  function handleSetPantry(cabinetId, pick) {\n    const idx = cabinets.findIndex(c => c.id === cabinetId);\n    if (idx === -1 || !pick) return;\n    const c = cabinets[idx];\n    if (!isPantryCab(c)) return;\n    const nd = pantryDepthMm({ depthMm: pick.depthMm != null ? pick.depthMm : c.depthMm });\n    const internals = PANTRY_INTERNALS.some(p => p.key === pick.internals) ? pick.internals : pantryInternalsKey(c);\n    const th = ((c.rotationDeg || 0) * Math.PI) / 180;\n    const back = (c.depthMm - nd) / 2;\n    const ncx = c.x + c.widthMm / 2 - Math.sin(th) * back;\n    const ncy = c.y + c.depthMm / 2 + Math.cos(th) * back;\n    cabinets[idx] = { ...c, depthMm: nd, pantryInternals: internals, x: ncx - c.widthMm / 2, y: ncy - nd / 2 };\n    syncStackAnchors();\n    autoDetectEndPanels([cabinetId]);\n    rerender();\n    scheduleBasketResync();\n  }\n\n  function handleSetCabinetAsBase(cabinetId, on) {\n    const idx = cabinets.findIndex(c => c.id === cabinetId);\n    if (idx === -1) return;\n    const c = cabinets[idx];\n    if (!canMakeBaseUnit(c) || !!on === !!c.asBase) return;\n    if (on) {\n      cabinets[idx] = {\n        ...c,\n        asBase: { category: c.category, heightMm: c.heightMm, plinthHeightMm: c.plinthHeightMm != null ? c.plinthHeightMm : null,\n                  wallMountLevel: c.wallMountLevel || null, mountAnchor: c.mountAnchor || null, plinthType: c.plinthType || null },\n        category: 'base-units',\n        heightMm: (c.heightMm || 720) + AS_BASE_LEGS_MM,\n        plinthHeightMm: AS_BASE_LEGS_MM,\n        mountAnchor: null,\n        // Never floating: it stands on its legs, with a plinth.\n        plinthType: c.plinthType === 'none' ? null : (c.plinthType || null)\n      };\n    } else {\n      const a = c.asBase;\n      const { asBase, ...rest } = c;\n      cabinets[idx] = { ...rest, category: a.category || 'wall-units', heightMm: a.heightMm || ((c.heightMm || 870) - AS_BASE_LEGS_MM),\n        plinthHeightMm: a.plinthHeightMm, wallMountLevel: a.wallMountLevel || rest.wallMountLevel, mountAnchor: a.mountAnchor || null,\n        plinthType: a.plinthType || null };\n      if (cabinets[idx].plinthHeightMm == null) delete cabinets[idx].plinthHeightMm;\n    }\n    syncStackAnchors();\n    autoDetectEndPanels([cabinetId]);\n    rerender();\n    scheduleBasketResync();\n  }\n\n  function syncWorktopDressers() {\n    for (const c of cabinets) {\n      if (!c) continue;\n      // An open larder saved before it was treated as a tall unit (rows\n      // 77-78) still says Display Units: put it right, at the height its\n      // Low / Medium / High is made in.\n      if (c.category === 'glass-wall-dresser-units' && c.unitTypeId && Catalogue.behaviourCategoryOfUnitType\n          && Catalogue.behaviourCategoryOfUnitType(Catalogue.getUnitType(c.unitTypeId)) === 'tall-units') {\n        c.category = 'tall-units';\n        const oi = c.variantId && Catalogue.getVariantInfo ? Catalogue.getVariantInfo(c.variantId) : null;\n        if (oi && oi.heightMm > 0) c.heightMm = oi.heightMm;\n      }\n      if (!isWorktopDresserCab(c)) { if (c.dresserUnit) c.dresserUnit = false; continue; }\n      c.dresserUnit = true;\n      c.category = 'wall-units';\n      // Worktop Pantry Unit (row 142): always 1250 high, standing on the\n      // worktop; its depth is the customer's (200-550).\n      if (isPantryCab(c)) {\n        c.heightMm = PANTRY_HEIGHT_MM;\n        c.wallMountLevel = 'medium';\n        if (c.depthMm !== pantryDepthMm(c)) c.depthMm = pantryDepthMm(c);\n        continue;\n      }\n      const info = c.variantId && Catalogue.getVariantInfo ? Catalogue.getVariantInfo(c.variantId) : null;\n      if (info && info.heightMm > 0) c.heightMm = info.heightMm;\n      c.wallMountLevel = worktopDresserLevel(c.heightMm);\n    }\n  }\n  // Shared with the Stack popup's preview, which resolves its own copies.\n  function stackAnchorOpts() {\n    return {\n      worktopThicknessMm: worktopThicknessMm(),\n      worktopThicknessMmFor: (cab) => worktopThicknessForCab(cab),\n      planPlinthMm: (featureStyles && featureStyles.plinthHeightMm) || PLINTH_STD_MM,\n      plinthHeightMmFor: (cab) => {\n        // A free-standing appliance has no plinth to drop - the 150 fallback\n        // would sink a stacked dryer 150mm into the washer under it.\n        if (cab && cab.freestandingAppliance) return 0;\n        const ut = cab && cab.unitTypeId ? Catalogue.getUnitType(cab.unitTypeId) : null;\n        return (ut && ut.plinthHeightMm) || 150;\n      }\n    };\n  }\n\n  // Per-unit worktop extension - patch is partial ({ left } / { front }\n  // etc.). Clamped: left/right 0-1000mm, front/back 0-300mm. Rerender\n  // recomputes the run worktop polygon (2D outline + 3D slab).\n  function handleUpdateCabinetWorktop(cabinetId, patch) {\n    if (!patch || typeof patch !== 'object') return;\n    const idx = cabinets.findIndex(c => c.id === cabinetId);\n    if (idx === -1) return;\n    const cab = cabinets[idx];\n    const cur = cab.worktop || { left: 0, right: 0, front: 0, back: 0 };\n    const next = { ...cur };\n    for (const side of ['left', 'right', 'front', 'back']) {\n      if (!(side in patch)) continue;\n      const max = (side === 'left' || side === 'right') ? 1000 : 300;\n      next[side] = Math.max(0, Math.min(max, Math.round(Number(patch[side]) || 0)));\n    }\n    cabinets[idx] = { ...cab, worktop: next };\n    rerender();\n  }\n\nfunction handleUpdateCabinetHinge(cabinetId, newHingeSide) {\n    const idx = cabinets.findIndex(c => c.id === cabinetId);\n    if (idx === -1) return;\n    const c = cabinets[idx];\n    // True Handleless tall units carry the hand as an LH/RH product VARIANT (a\n    // production requirement - a different SKU per hand). Route the hand toggle\n    // through the variant-swap path so the correct SKU is basketed/priced; that\n    // handler's optionOverride logic sets hingeSide to match. Kept in sync with\n    // the reverse direction (picking the LH/RH pill flips the hinge).\n    const isTHTall = /^tall/i.test(c.category || '')\n      && !!(Catalogue.isStyleTrueRail && Catalogue.isStyleTrueRail(c.kitchenStyleId));\n    if (isTHTall && Catalogue.variantOptionInfo) {\n      const optInfo  = Catalogue.variantOptionInfo(c.variantId) || [];\n      const hingeOpt = optInfo.find(o => /hinge/i.test(o.labelKey || ''));\n      if (hingeOpt) {\n        // Resolve the variant's ACTUAL hinge value (authored casing/format \u2014\n        // \"LH\"/\"RH\", \"Left\"/\"Right\", \u2026) so the override matches a real variant.\n        const product = Catalogue.getProductForUnitInStyle\n          ? Catalogue.getProductForUnitInStyle(c.unitTypeId, c.kitchenStyleId) : null;\n        let wanted = null;\n        if (product) {\n          const hi = (product.optionNames || []).findIndex(n => /hinge/i.test(String(n || '')));\n          if (hi >= 0) {\n            const rx = (String(newHingeSide).toLowerCase() === 'right') ? /\\brh\\b|right/i : /\\blh\\b|left/i;\n            for (const v of product.variants || []) {\n              const val = (v.options || [])[hi];\n              if (val && rx.test(String(val))) { wanted = val; break; }\n            }\n          }\n        }\n        if (wanted != null) {\n          handleUpdateCabinetSize(cabinetId, { optionOverrides: { [hingeOpt.labelKey]: wanted } });\n          return;\n        }\n      }\n    }\n    cabinets[idx] = { ...c, hingeSide: newHingeSide };\n    rerender();\n  }\n\n  // ---- End-panel auto-detection ----\n  //\n  // Walks every cabinet's user-left / user-right side and decides\n  // whether the panel for that side should be active, following these\n  // rules:\n  //   * free end (no neighbour)         \u2192 activate\n  //   * neighbour, SAME category        \u2192 both deactivate\n  //   * neighbour, tall \u2194 base/wall     \u2192 tall wins (keeps panel)\n  //   * neighbour, base \u2194 wall (etc.)   \u2192 no rule (different heights \u2014\n  //                                       no interaction, both keep)\n  //\n  // Called after any structural change: add, move (drag-end), rotate,\n  // delete. When a side's panel goes from active \u2192 inactive against\n  // a same-category neighbour, the moved cabinet gets a re-snap pass\n  // to close the 20mm void where the panel was.\n  const END_PANEL_AUTO_TOL_MM = 6;\n  const END_PANEL_AUTO_THICK_MM   = 20;     // plain / T&G thickness (matches sub-modules)\n  const END_PANEL_AUTO_FORWARD_MM = 18;\n  // True Handleless vertical-rail plan gap: the profile sticks 30mm into the\n  // run on the grip (non-hinge) side, so a unit butting a grip side must sit\n  // 30mm off. Folded into that side's EFFECTIVE face (epAllSides) so the settle\n  // pass keeps the gap, exactly like an end panel holds its 20mm. Mirrors the\n  // TH_RAIL_GAP_MM in the 2D cabinets module.\n  const TH_RAIL_GAP_MM = 30;\n  // Breakfast-bar back panel: a full-width slab attached to the BACK\n  // of a base unit when that back is exposed (island / peninsula).\n  // Thickness here is a placeholder - real Unit Type products will\n  // supply the per-range value later. The side end panels on the\n  // host unit extend by this amount past their normal 650mm so the\n  // back panel's side is covered with an uncut edge.\n  const BB_BACK_PANEL_THICK_MM = 20;\n  // 'gap' used by isUnitBackExposed: cab back must be at least this\n  // far (mm) from a wall, another cab's front/back face, or a pillar\n  // to count as exposed.\n  const BB_BACK_GAP_MM = 100;\n  // The shortest OPEN stretch of a back that takes a panel. Shorter ones are\n  // slivers from units that do not quite line up. It used to be BB_BACK_GAP_MM\n  // (100), which dropped real gaps: a 300 unit with two end panels standing\n  // behind a 400 peninsula end unit leaves 82mm of its back open, and the\n  // whole unit lost its panel, so the peninsula back stopped short (Sales\n  // sheet line 112, PLN101152).\n  const BB_BACK_OPEN_MIN_MM = 40;\n  // Full as-supplied depth of a base end panel - the panel ships\n  // 650mm deep and installers scribe it down to fit the cab when\n  // it's against a wall (the cut edge hides against the wall). On\n  // an island the cut edge would be visible, so we show the full\n  // 650mm and step the breakfast-bar back panel out to line up\n  // with the panel's back face. Driven per-cab by\n  // cab.useFullSizeEndPanel, auto-set true when backPanel is\n  // active and false when 2 units are back-to-back.\n  const FULL_END_PANEL_DEPTH_MM = 650;\n  // How far a fitted end panel extends FORWARD of the carcase front to\n  // cover the door (which sits proud of the carcase). Matches the auto\n  // stubs' END_PANEL_FORWARD_MM in the 3D renderer, so a free-standing\n  // panel that adopts a neighbour's depth still covers that unit's door.\n  const END_PANEL_DOOR_PROUD_MM = 18;\n  // Per-style end-panel thickness in mm. Plain / T&G are the\n  // standard 20mm slab; Radius / Square are chunky 50mm panels.\n  // Keep in sync with the helper defined in the trim, worktop and\n  // 2D / 3D rendering modules.\n  function endPanelThickMm(sideOrStyle) {\n  // Accepts the end-panel SIDE OBJECT (cab.endPanels.left/right) or a bare\n  // style string. Radius / square are the chunky 50mm post-and-panel and TH is\n  // its 46mm assembly - both fixed. Plain / T&G thickness is PER RANGE\n  // (door_geometry.end_panel_thickness_mm), stamped onto each side as\n  // `thickMm` every render by the orchestrator; unset falls back to END_PANEL_AUTO_THICK_MM.\n  const o = (sideOrStyle && typeof sideOrStyle === 'object') ? sideOrStyle : null;\n  const style = o ? o.style : sideOrStyle;\n  if (o && o.pastryWidthMm > 0) return o.pastryWidthMm;   // Pastry Bench columns\n  if (style === 'radius' || style === 'square') return 50;\n  if (/^th-/.test(String(style || ''))) return 46;\n  const t = o && o.thickMm;\n  return (typeof t === 'number' && t > 0) ? t : END_PANEL_AUTO_THICK_MM;\n}\n  // Mount-line tops now live in the shared wall-mount module\n  // (WALL_MOUNT_TOPS) - see btk-kitchen-planner-engine-wall-mount.js.\n\n  // A unit that takes no end panels, cornice or pelmet and is nobody's\n  // neighbour for them (Arden, 2026-10-25): the Frame Shelf Unit, an open\n  // metal frame - a wall unit beside it keeps its own end panel. Its unit\n  // type's schema says \"noFinishing\": true.\n  function isNoFinishingUnit(cab) {\n    if (!cab) return false;\n    if (cab.cutoutSchema && cab.cutoutSchema.noFinishing) return true;\n    const ut = cab.unitTypeId && Catalogue.getUnitType ? Catalogue.getUnitType(cab.unitTypeId) : null;\n    return !!(ut && ut.cutoutSchema && ut.cutoutSchema.noFinishing);\n  }\n  function epCategoryGroup(cab) {\n    // Grouped as nothing, so the end-panel walk neither panels it nor counts\n    // it as a neighbour.\n    if (isNoFinishingUnit(cab)) return null;\n    // Corner units are base-height base units - group them with\n    // 'base' so the door-side end-panel rule (epDecideActive) treats\n    // a corner unit and an abutting base unit as the same category\n    // (equal depth \u2192 both panels drop). Without this, a corner unit\n    // whose category handle isn't 'base-*' falls through to null and\n    // its door-side panel never turns off against a neighbour.\n    const cat = cab.category || '';\n    // PSEUDO TALL UNIT: a carcase-on-carcase stack (Stack on Base /\n    // Midi Unit) has no worktop in the joint, so host + rider are one\n    // continuous run of carcase from floor to top - it finishes like a\n    // tall unit and wins the end-panel race against an abutting base\n    // unit, whose panel drops under the cross-category \"tall wins\"\n    // rule below. Units stacked on a WORKTOP are excluded on purpose:\n    // the slab running through is a break point, so both sides of it\n    // keep their own panel.\n    if (isInCarcaseColumn(cab)) return 'tall';\n    // MIDI: every midi unit is the same height, so any midi against any other\n    // midi is a flush joint and both panels drop. They can't be grouped by\n    // category - midi larders are 'tall-units' while midi appliance housings\n    // come through `appliance-housings`, which resolveBehaviourCategory turns\n    // into tall-units or base-units depending on a 1400mm carcase threshold.\n    // Two identical-height midis therefore landed in different groups and the\n    // cross-category \"tall wins\" rule kept a panel between them. Ahead of the\n    // corner branch too, so a diagonal corner midi groups with its own kind.\n    if (cab.isMidiUnit) return 'midi';\n    if (cab.cornerUnit || cab.lShapeUnit || cab.diagonalCornerUnit) {\n      // Corner / L-shape / diagonal units carry their own catalogue\n      // category - group follows the category prefix (wall-category\n      // corner units pair with wall cabs, tall larders with tall),\n      // defaulting to base for the common base corner units.\n      if (/^wall/i.test(cat))     return 'wall';\n      if (/^bridging/i.test(cat)) return 'bridging';\n      if (/^tall/i.test(cat))     return 'tall';\n      return 'base';\n    }\n    if (/^base/i.test(cat))     return 'base';\n    if (/^tall/i.test(cat))     return 'tall';\n    if (/^wall/i.test(cat))     return 'wall';\n    if (/^bridging/i.test(cat)) return 'bridging';\n    return null;\n  }\n\n  function epVerticalRange(cab) {\n    // Wall/bridging units honour their mount-line + anchor (top /\n    // bottom / panel); floor units honour their stack anchor. The\n    // shared helper covers both cases.\n    //\n    // This is what creates the WORKTOP BREAK POINT. Both neighbour\n    // finders gate on epRangesOverlap, so a unit stacked on a worktop\n    // shares no vertical band with the floor unit beside it - they\n    // never see each other as neighbours and each keeps its own end\n    // panel, split at the worktop line. It also stops a unit and the\n    // host directly beneath it (identical side lines, touching bands)\n    // reading as each other's side neighbour.\n    // A media wall column reaches as far as its end panels do: down past the\n    // unit it stands on, up to its top unit (towerRangeOf).\n    return towerRangeOf(cab) || unitVerticalRange(cab);\n  }\n  // MEDIA WALL COLUMNS (Arden, 2026-10-28): wall units standing on a floor\n  // unit's worktop, and any stacked on them. Their end panels run from the\n  // column's top down past the floor unit (towerPanelBottomMm), so for the\n  // end panel walk the column spans that whole height.\n  //   towerRangeOf(wallCab) -> { bottom, top } for a wall unit in such a\n  //     column, else null\n  //   towerRangeOn(floorCab) -> the same for the column standing on a floor\n  //     unit, else null\n  function wallColumnOf(cab) {\n    const own = planFootprintAABB(cab);\n    return (cabinets || []).filter(o => o && isWallMounted(o) && (o === cab || footprintsOverlap(own, planFootprintAABB(o))));\n  }\n  function towerRangeOf(cab) {\n    if (!cab || !isWallMounted(cab)) return null;\n    const col = wallColumnOf(cab);\n    let bottom = Infinity;\n    for (const u of col) for (const side of ['left', 'right']) {\n      const b = towerPanelBottomMm(u, side, cabinets);\n      if (b != null) bottom = Math.min(bottom, b);\n    }\n    if (!Number.isFinite(bottom)) return null;\n    return { bottom, top: Math.max(...col.map(u => unitVerticalRange(u).top)) };\n  }\n  function towerRangeOn(floorCab) {\n    if (!floorCab || isWallMounted(floorCab)) return null;\n    const w = (cabinets || []).find(o => o && isWallMounted(o) && o.onWorktopHostId === floorCab.id && towerRangeOf(o));\n    return w ? towerRangeOf(w) : null;\n  }\n\n  function epRangesOverlap(a, b) {\n    return (a.bottom < b.top - END_PANEL_AUTO_TOL_MM) && (a.top > b.bottom + END_PANEL_AUTO_TOL_MM);\n  }\n\n  // ---- Floor-height end panels (American fridge housing) --------------\n  // A deep bridging unit with a Tall End Panel has a panel standing on the\n  // FLOOR, so the assembly is no longer purely wall-hung: at floor level it\n  // meets, blocks and finishes the units beside it exactly like a tall unit's\n  // end panel does. The unit's own vertical band still says \"wall height\"\n  // (that's what keeps stacking / trims correct), so end-panel adjacency asks\n  // these two helpers instead of reading the band directly.\n\n  // Any ACTIVE floor-height panel on this cabinet?\n  function epHasFloorPanel(cab) {\n    const ep = cab && cab.endPanels;\n    return !!(ep && ((ep.left  && ep.left.active  && ep.left.toFloor) ||\n                     (ep.right && ep.right.active && ep.right.toFloor)));\n  }\n  // Band this cabinet occupies ON ONE SIDE. A floor-height panel drops that\n  // side's bottom to the floor; every other side keeps the plain unit band.\n  function epSideVerticalRange(cab, side, base) {\n    const r  = base || epVerticalRange(cab);\n    const ep = cab && cab.endPanels && cab.endPanels[side];\n    return (ep && ep.active && ep.toFloor) ? { bottom: 0, top: r.top } : r;\n  }\n  // Coarse \"does this unit reach the floor anywhere\" band - used by the\n  // proximity / staleness sweeps, which only decide WHO gets re-evaluated.\n  function epAdjacencyRange(cab) {\n    const r = epVerticalRange(cab);\n    return epHasFloorPanel(cab) ? { bottom: 0, top: r.top } : r;\n  }\n\n  // Cabinet sides in world plan coords, taking ACTIVE end panels into\n  // account: the side line for a panelled side sits at the panel's\n  // OUTER face, not the carcase edge. This is what makes adjacency\n  // detection work - when cabinet B is snapped to A's panel face, B's\n  // carcase edge coincides with A's panel-outer edge, and the auto-\n  // detect rule fires.\n  //\n  // user-LEFT  = cabinet-local +X (corners FR/BR, extended by panel)\n  // user-RIGHT = cabinet-local -X (FL/BL, extended by panel)\n  // EFFECTIVE side lines - the cabinet's footprint INCLUDING any\n  // active end panel / filler (panel = 20mm, filler = its width;\n  // mutually exclusive per side). Used by the post-auto-detect\n  // settle pass so adjacent units' effective faces touch exactly.\n  // How much a TH tall unit's GRIP side extends the effective face for spacing\n  // (the vertical-rail run width, or 0 if none). Normally TH_RAIL_GAP_MM.\n  // EXCEPTION - two TH talls butted GRIP-to-GRIP share ONE rail in ONE 30mm\n  // gap, so only the OWNER (lower id) contributes the 30mm; the partner\n  // contributes 0. Without this both extend 30mm and the effective pass settles\n  // them 60mm apart (rail face to rail face) with one rail floating in a double\n  // gap. Uses CARCASE sides only (never epAllSides \u2192 no recursion); a generous\n  // tolerance still pairs them at the settled 30mm gap.\n  const TH_RAIL_PAIR_TOL_MM = 45;\n  // Only two talls of the SAME HEIGHT share a rail. A Medium beside a High\n  // has two rails of different lengths, so each keeps its own Lateral, and the\n  // taller one's end panel (it stands above its neighbour) goes outside its\n  // rail (Arden, 2026-10-26, Planner Bugs 23).\n  const TH_RAIL_SHARE_HEIGHT_TOL_MM = 50;\n  function thRailHeightsMatch(a, b) {\n    const ra = epVerticalRange(a), rb = epVerticalRange(b);\n    return Math.abs(ra.top - rb.top) <= TH_RAIL_SHARE_HEIGHT_TOL_MM\n      && Math.abs(ra.bottom - rb.bottom) <= TH_RAIL_SHARE_HEIGHT_TOL_MM;\n  }\n  function thGripExtension(cab) {\n    const gs = thGripSide(cab);\n    if (!gs) return null;\n    const myGrip = epCarcaseSides(cab)[gs];\n    for (const other of cabinets) {\n      if (other.id === cab.id) continue;\n      const ogs = thGripSide(other);\n      if (!ogs) continue;   // only another TH tall unit can share a rail\n      if (!thRailHeightsMatch(cab, other)) continue;\n      if (epLinesCoincide(myGrip, epCarcaseSides(other)[ogs], TH_RAIL_PAIR_TOL_MM)) {\n        // grip\u2194grip: owner (lower id) keeps the 30mm, partner defers \u2192 one gap.\n        return (String(cab.id) < String(other.id)) ? gs : null;\n      }\n    }\n    return gs;   // lone grip / grip\u2194hinge \u2192 full 30mm\n  }\n\n  // A freestanding appliance is fitted with a gap each side so it can be\n  // pulled out, and its end panels stand that far off it. 0 for anything else.\n  function cabEndPanelGapMm(cab) {\n    const g = cab && cab.endPanelGapMm;\n    return (typeof g === 'number' && g > 0) ? g : 0;\n  }\n\n  function epAllSides(cab) {\n    const w = cab.widthMm, d = cab.depthMm;\n    const ep  = cab.endPanels || {};\n    const fil = cab.fillers   || {};\n    // L-shape units: the LEFT and RIGHT panel toggles sit on\n    // perpendicular ARM-END faces, NOT on the bbox sides. Extending\n    // the bbox by epL/epR/epF (as we do for rectangular cabs) places\n    // PHANTOM faces in cab-bbox space that don't correspond to any\n    // actual carcase or panel. Those phantom faces then confuse the\n    // post-detect settle pass (a neighbour 18mm/20mm away gets\n    // \"snapped\" toward a face that isn't really there) and corrupt\n    // adjacency checks. The L's true arm-end face geometry lives in\n    // epLShapeEndFaceWorld and is consulted directly by autoDetect\n    // via epLShapeFindEndNeighbour, so falling back to the bbox-\n    // only carcase sides here is the right move.\n    if (cab.lShapeUnit || cab.diagonalCornerUnit) return epCarcaseSides(cab);\n    let epL = ep.left?.active  ? endPanelThickMm(ep.left)  : (fil.left?.active  ? (fil.left.widthMm  || 0) : 0);\n    let epR = ep.right?.active ? endPanelThickMm(ep.right) : (fil.right?.active ? (fil.right.widthMm || 0) : 0);\n    // True Handleless tall units: the 30mm vertical rail on the GRIP side\n    // occupies real run width, so fold it into that side's EFFECTIVE face (on\n    // top of any end panel). The settle pass then leaves a 30mm carcase gap\n    // when a unit butts the grip side, and neighbour / end-panel detection\n    // still works across it - the same mechanism an end panel uses for 20mm.\n    const _gripExt = thGripExtension(cab);\n    if (_gripExt === 'left')       epL += TH_RAIL_GAP_MM;\n    else if (_gripExt === 'right') epR += TH_RAIL_GAP_MM;\n    // ...and the second rail of \"Add Rail to both sides\", on the hinge side.\n    if (cab.railSecondSide === 'left')       epL += TH_RAIL_GAP_MM;\n    else if (cab.railSecondSide === 'right') epR += TH_RAIL_GAP_MM;\n    // A freestanding appliance stands off its panels by the fitting gap, and\n    // that gap is real run width - the neighbour settles against the panel's\n    // outer face, not the appliance's side.\n    // The gap is there so the appliance can be PULLED OUT, so it is real run\n    // width whether or not a panel stands in it. It used to count only on a\n    // side carrying a panel, which was fine while the auto walk skipped\n    // appliances; now that Auto can take a panel off, a neighbour would\n    // otherwise settle hard against the machine and trap it.\n    const _epGap = cabEndPanelGapMm(cab);\n    if (_epGap) { epL += _epGap; epR += _epGap; }\n    const anyActive = ep.left?.active || ep.right?.active || fil.left?.active || fil.right?.active;\n    // Corner units carry no end panels / fillers, but the L-post\n    // still protrudes postYMm past the carcase front - treat that as\n    // the effective forward projection so the settle pass lands a\n    // neighbour against the post face, matching epCarcaseSides.\n    const epF = cab.cornerUnit\n      ? (cab.cornerUnit.postYMm || 0)\n      : (anyActive ? END_PANEL_AUTO_FORWARD_MM : 0);\n    const cx = cab.x + w / 2, cy = cab.y + d / 2;\n    const th = ((cab.rotationDeg || 0) * Math.PI) / 180;\n    const cs = Math.cos(th), sn = Math.sin(th);\n    const L2W = (lx, ly) => ({ x: cx + lx * cs - ly * sn, y: cy + lx * sn + ly * cs });\n    const FL = L2W(-w/2 - epR, -d/2 - epF);\n    const FR = L2W(+w/2 + epL, -d/2 - epF);\n    const BR = L2W(+w/2 + epL, +d/2);\n    const BL = L2W(-w/2 - epR, +d/2);\n    return {\n      front: { p1: FL, p2: FR }, back: { p1: BL, p2: BR },\n      left:  { p1: FR, p2: BR }, right: { p1: FL, p2: BL }\n    };\n  }\n\n  // Two line segments coincide when their lines are co-linear (within\n  // tol) AND they overlap in length by more than tol mm.\n  function epLinesCoincide(s1, s2, tol = END_PANEL_AUTO_TOL_MM) {\n    const dx = s1.p2.x - s1.p1.x, dy = s1.p2.y - s1.p1.y;\n    const len = Math.hypot(dx, dy);\n    if (len < 0.1) return false;\n    const ux = dx / len, uy = dy / len;\n    const nx = -uy,      ny = ux;\n    const d1 = (s2.p1.x - s1.p1.x) * nx + (s2.p1.y - s1.p1.y) * ny;\n    const d2 = (s2.p2.x - s1.p1.x) * nx + (s2.p2.y - s1.p1.y) * ny;\n    if (Math.abs(d1) > tol || Math.abs(d2) > tol) return false;\n    const tA = (s2.p1.x - s1.p1.x) * ux + (s2.p1.y - s1.p1.y) * uy;\n    const tB = (s2.p2.x - s1.p1.x) * ux + (s2.p2.y - s1.p1.y) * uy;\n    const lo = Math.max(0, Math.min(tA, tB));\n    const hi = Math.min(len, Math.max(tA, tB));\n    return (hi - lo) > tol;\n  }\n  // The stretch of s1 that s2 lies along: [lo, hi] in mm from s1.p1, or null\n  // when they aren't co-linear (within tol) or don't overlap. epLinesCoincide\n  // only answers yes/no, which reads a unit half on a wall as fully walled.\n  function epCoveredSpan(s1, s2, tol) {\n    const dx = s1.p2.x - s1.p1.x, dy = s1.p2.y - s1.p1.y;\n    const len = Math.hypot(dx, dy);\n    if (len < 0.1) return null;\n    const ux = dx / len, uy = dy / len;\n    const nx = -uy,      ny = ux;\n    const d1 = (s2.p1.x - s1.p1.x) * nx + (s2.p1.y - s1.p1.y) * ny;\n    const d2 = (s2.p2.x - s1.p1.x) * nx + (s2.p2.y - s1.p1.y) * ny;\n    if (Math.abs(d1) > tol || Math.abs(d2) > tol) return null;\n    const tA = (s2.p1.x - s1.p1.x) * ux + (s2.p1.y - s1.p1.y) * uy;\n    const tB = (s2.p2.x - s1.p1.x) * ux + (s2.p2.y - s1.p1.y) * uy;\n    const lo = Math.max(0, Math.min(tA, tB));\n    const hi = Math.min(len, Math.max(tA, tB));\n    return hi > lo ? [lo, hi] : null;\n  }\n\n  // Finds a cabinet adjacent to `cab` on side `sideKey` ('left' /\n  // 'right'). Two units are adjacent when their faces TOUCH - that's\n  // either carcase-to-carcase (no panel between) OR carcase-to-panel-\n  // face (one unit's surviving end panel fills the 20mm gap, so the\n  // carcases sit 20mm apart). A unit settled flush against a\n  // neighbour's panel is NOT carcase-flush, so a pure carcase-to-\n  // carcase test would miss it on a later auto-detect pass and wrongly\n  // re-add a free-end panel. Match `cab`'s carcase line against the\n  // other's carcase AND effective (panel-extended) line, and `cab`'s\n  // own effective line against the other's carcase, to catch all\n  // three cases. \u00B16mm tolerance.\n  // Does `other` present a FINISHED FACE on the face the caller just matched?\n  // Only a free-standing appliance is ever in doubt: it is a machine, not a\n  // carcase, so it is something to defer to on a side where it carries a panel\n  // and nothing at all on a side where it does not. Both callers used to ask\n  // \"has it ANY panel\", which let a machine with one side turned off still\n  // suppress the neighbour on the OFF side - so that joint came out bare from\n  // both directions (Julian, units 3 and 4). Front and back never carry one.\n  function epFaceIsFinished(other, key) {\n    if (!other || !other.freestandingAppliance) return true;\n    // A built-under double oven FILLS its opening: the units either side are\n    // closed by its fitting panels, never by end panels of their own.\n    if (other.freestandingAppliance.fillsOpening) return true;\n    if (key !== 'left' && key !== 'right') return false;\n    const ep = other.endPanels && other.endPanels[key];\n    return !!(ep && ep.active);\n  }\n\n  function epFindNeighbourOnSide(cab, sideKey, range, scope) {\n    const cabCarc = epCarcaseSides(cab)[sideKey];\n    // Side-aware band: a floor-height panel on THIS side reaches the floor, so\n    // this side can meet a base unit standing beside the housing even though\n    // the carcase itself hangs at wall height.\n    const myRange = epSideVerticalRange(cab, sideKey, range);\n    // A side carrying an active FILLER (not a panel) bridges a GAP to a\n    // wall / tall-end anchor - it is NOT flush against it. Matching the\n    // filler-extended effective face here would read that anchor as a\n    // flush neighbour, flip the side onto the end-panel rule and drop\n    // the filler - which then flip-flops back on the next nudge. So a\n    // filler side matches on the CARCASE line only; panel sides keep\n    // their panel-extended reach.\n    const epSides  = cab.endPanels || {};\n    const filSides = cab.fillers   || {};\n    const cabFillerSide = !!filSides[sideKey]?.active && !epSides[sideKey]?.active;\n    const cabEff  = cabFillerSide ? cabCarc : epAllSides(cab)[sideKey];\n    // Stepped cabs need a wider \"neighbour\" search: when a stepped\n    // run lost its panels in a previous layout, the carcases sit\n    // 50\u2013100mm apart (across the missing panels) and the tight 4-\n    // combo eff checks miss them, leaving constrainedCab to keep\n    // them sticky-off forever. Widen the search when EITHER cab is\n    // stepped so epDecideActive can re-activate the panels.\n    const cabSb = cab.wallSetbackMm || 0;\n    const MAX_PANEL_SUM_MM = 110;\n    for (const other of scope) {\n      if (other.id === cab.id) continue;\n      // A freestanding appliance counts as a neighbour on a side where it\n      // carries a panel - that panel finishes the joint, so the unit beside it\n      // does not add a second one. Tested PER FACE below (epFaceIsFinished),\n      // not once per unit.\n      const grp = epCategoryGroup(other);\n      // A corner unit is always a real neighbour even when its\n      // category doesn't classify as base/tall/wall - its blank\n      // panel + corner post finish the adjacent unit's end.\n      if (grp !== 'base' && grp !== 'tall' && grp !== 'midi' && grp !== 'wall' && grp !== 'bridging' && !other.cornerUnit) continue;\n      const oCarc = epCarcaseSides(other, { noEndPanelReach: true });\n      const oEff  = epAllSides(other);\n      const oSb   = other.wallSetbackMm || 0;\n      const stepped = cabSb > 0 || oSb > 0;\n      // The other unit's band is also side-aware: its LEFT / RIGHT faces reach\n      // the floor when that side carries a floor-height panel, its front / back\n      // never do. Tested per key rather than once per unit, so a housing only\n      // meets floor units on the side its panel actually stands on.\n      const oRangePlain = epVerticalRange(other);\n      const oRangeBySide = {\n        left:  epSideVerticalRange(other, 'left',  oRangePlain),\n        right: epSideVerticalRange(other, 'right', oRangePlain)\n      };\n      for (const key of ['front', 'back', 'left', 'right']) {\n        const oRange = (key === 'left' || key === 'right') ? oRangeBySide[key] : oRangePlain;\n        if (!epRangesOverlap(myRange, oRange)) continue;\n        if (!epFaceIsFinished(other, key)) continue;\n        if (epLinesCoincide(cabCarc, oCarc[key]) ||\n            epLinesCoincide(cabCarc, oEff[key])  ||\n            epLinesCoincide(cabEff,  oCarc[key])  ||\n            epLinesCoincide(cabEff,  oEff[key])   ||\n            (stepped && epLinesCoincide(cabCarc, oCarc[key], MAX_PANEL_SUM_MM))) {\n          return other;\n        }\n      }\n    }\n    return null;\n  }\n\n  // How much of a unit's SIDE (mm) no neighbour covers. epFindNeighbourOnSide\n  // answers \"is anything there\" - a single overlap past 6mm is enough - so a\n  // unit dropped against the back of a peninsula, where only the other unit's\n  // 62mm back-panel stand-off reaches its end, read as finished and lost its\n  // end panel (Arden, 2026-10-05). Same matching rules as that function, but\n  // every neighbour's overlap is added up along the side.\n  const EP_SIDE_OPEN_MM = 150;   // more than this uncovered \u2192 the end is on show\n  function epSideUncoveredMm(cab, sideKey, range, scope) {\n    const carc = epCarcaseSides(cab)[sideKey];\n    const eff  = epAllSides(cab)[sideKey];\n    const dx = carc.p2.x - carc.p1.x, dy = carc.p2.y - carc.p1.y;\n    const len = Math.hypot(dx, dy);\n    if (len < 0.1) return 0;\n    const ux = dx / len, uy = dy / len;\n    const along = (q) => (q.x - carc.p1.x) * ux + (q.y - carc.p1.y) * uy;\n    const myRange = epSideVerticalRange(cab, sideKey, range);\n    const cabSb = cab.wallSetbackMm || 0;\n    const cov = [];\n    for (const other of scope) {\n      if (other.id === cab.id) continue;\n      const grp = epCategoryGroup(other);\n      if (grp !== 'base' && grp !== 'tall' && grp !== 'midi' && grp !== 'wall' && grp !== 'bridging' && !other.cornerUnit) continue;\n      const oCarc = epCarcaseSides(other, { noEndPanelReach: true }), oEff = epAllSides(other);\n      const stepped = cabSb > 0 || (other.wallSetbackMm || 0) > 0;\n      const oRangePlain = epVerticalRange(other);\n      for (const key of ['front', 'back', 'left', 'right']) {\n        const oRange = (key === 'left' || key === 'right') ? epSideVerticalRange(other, key, oRangePlain) : oRangePlain;\n        if (!epRangesOverlap(myRange, oRange)) continue;\n        if (!epFaceIsFinished(other, key)) continue;\n        for (const o of [oCarc[key], oEff[key]]) {\n          if (!(epLinesCoincide(carc, o) || epLinesCoincide(eff, o) ||\n                (stepped && epLinesCoincide(carc, o, 110)))) continue;\n          const a = along(o.p1), b = along(o.p2);\n          const lo = Math.max(0, Math.min(a, b)), hi = Math.min(len, Math.max(a, b));\n          if (hi > lo) cov.push([lo, hi]);\n        }\n      }\n    }\n    cov.sort((p, q) => p[0] - q[0]);\n    let covered = 0, at = 0;\n    for (const [lo, hi] of cov) {\n      const s = Math.max(lo, at);\n      if (hi > s) { covered += hi - s; at = hi; }\n    }\n    return len - covered;\n  }\n\n  // Step-eligible categories - mirrors the selection panel's \"Step\n  // forward\" gating: base / tall units + corner + radius assemblies.\n  function isStepEligibleCab(cab) {\n    const cat = cab.category || '';\n    return /^base/i.test(cat) || /^tall/i.test(cat) || !!cab.cornerUnit || !!cab.radiusUnit;\n  }\n\n  // World wall-perpendicular coordinate of a cabinet's CARCASE FRONT\n  // face centre (cardinal rotations only). Used to tell whether a unit\n  // dropped beside a stepped neighbour is aligned to that neighbour's\n  // FRONT (\u2248 same coordinate) or sitting flush to the wall (\u2248 a setback\n  // behind it).\n  function carcaseFrontCoord(cab) {\n    const w = cab.widthMm || 0, d = cab.depthMm || 0;\n    const cx = cab.x + w / 2, cy = cab.y + d / 2;\n    const th = ((cab.rotationDeg || 0) * Math.PI) / 180;\n    const cs = Math.cos(th), sn = Math.sin(th);\n    const fx = cx + (d / 2) * sn;   // front-face centre (local 0,-d/2)\n    const fy = cy - (d / 2) * cs;\n    const rot = ((cab.rotationDeg || 0) % 360 + 360) % 360;\n    return (rot === 90 || rot === 270) ? fx : fy;\n  }\n\n  // \"Step Forward\" snap inheritance. When a moved unit has been dragged\n  // so its FRONT edge lines up with a side-adjacent STEPPED neighbour's\n  // front (the live neighbour-snap front-aligns it there), it joins the\n  // stepped run - adopt the neighbour's wallSetbackMm so both step\n  // forward by the same distance. Dragging the unit back to the wall\n  // instead leaves it flush (front coord sits a full setback behind the\n  // neighbour's), so it keeps the existing behaviour (wall snap + the\n  // stepped neighbour gets its auto end panel). Cardinal rotations only;\n  // called at drag-end BEFORE settle so the new setback feeds the\n  // settle + end-panel cascade.\n  // Bridging + top box units: wall-units by category, told apart by their\n  // unit-type group. (A literal, not a const: no TDZ if called early.)\n  function isBridgingDef(d) {\n    if (!d) return false;\n    if (/^bridging/i.test(d.category || '')) return true;\n    return Catalogue.getUnitType?.(d.unitTypeId)?.unitTypeGroupHandle === 'bridging-top-box-units';\n  }\n\n  // A bridging unit's FIRST landing against a wall unit lines its top up with\n  // that unit's: it takes the neighbour's mount line (top-anchored neighbours\n  // only, whose top IS the line). Once only, so a later move or a mount line\n  // the user picks is left alone.\n  function alignBridgingTops(ids) {\n    const wallUnits = cabinets.filter(o => /^wall/i.test(o.category || '')\n      && !isBridgingDef(o) && !o.dresserUnit && (o.mountAnchor || 'top') === 'top');\n    if (!wallUnits.length) return;\n    for (const id of ids) {\n      const cab = cabinets.find(c => c.id === id);\n      if (!cab || !cab.alignTopPending) continue;\n      const myRange = epVerticalRange(cab);\n      for (const side of ['left', 'right']) {\n        const n = epFindNeighbourOnSide(cab, side, myRange, wallUnits);\n        if (!n) continue;\n        cab.wallMountLevel = n.wallMountLevel || 'medium';\n        cab.mountAnchor = 'top';\n        delete cab.alignTopPending;\n        break;\n      }\n    }\n  }\n\n  function inheritStepForwardFromNeighbour(movedIds) {\n    for (const id of movedIds) {\n      const cab = cabinets.find(c => c.id === id);\n      if (!cab || !isStepEligibleCab(cab)) continue;\n      const rot = ((cab.rotationDeg || 0) % 360 + 360) % 360;\n      if (rot % 90 !== 0) continue;\n      const myRange = epVerticalRange(cab);\n      for (const side of ['left', 'right']) {\n        const n = epFindNeighbourOnSide(cab, side, myRange, cabinets);\n        if (!n) continue;\n        const nSb = n.wallSetbackMm || 0;\n        if (nSb <= 0) continue;                                   // neighbour not stepped\n        if (((n.rotationDeg || 0) % 360 + 360) % 360 !== rot) continue;\n        // Front-aligned (diff \u2248 0) \u2192 join the step. Flush-to-wall gives\n        // diff \u2248 nSb, so half the setback cleanly separates the two.\n        if (Math.abs(carcaseFrontCoord(cab) - carcaseFrontCoord(n)) < nSb * 0.5) {\n          if ((cab.wallSetbackMm || 0) !== nSb) cab.wallSetbackMm = nSb;\n          break;\n        }\n      }\n    }\n  }\n\n  // CARCASE side line segments (no panel / filler extension) - used\n  // for adjacency detection and gap measurement. front/back +\n  // user-left (cabinet-local +X) / user-right (-X).\n  function epCarcaseSides(cab, opts = {}) {\n    const w = cab.widthMm, d = cab.depthMm;\n    const cx = cab.x + w / 2, cy = cab.y + d / 2;\n    const th = ((cab.rotationDeg || 0) * Math.PI) / 180;\n    const cs = Math.cos(th), sn = Math.sin(th);\n    const L2W = (lx, ly) => ({ x: cx + lx * cs - ly * sn, y: cy + lx * sn + ly * cs });\n    // Corner units: the L-post protrudes postYMm forward of the\n    // carcase front, so a perpendicular run butts the POST, not the\n    // carcase. Push the front side line out by the protrusion so\n    // adjacency detection (and the settle pass) fire at the post\n    // face - base end panel then drops, tall keeps one.\n    const fEx = cab.cornerUnit ? (cab.cornerUnit.postYMm || 0) : 0;\n    // L-shape and diagonal-corner units carry end panels on the per-\n    // hand arm-end FACES (NOT on the cab's user-LEFT / user-RIGHT\n    // bbox sides). For settle / adjacency, push the bbox side(s) on\n    // which the active panel sits OUTWARD by the panel thickness, so\n    // neighbours flush against the PANEL face instead of overlapping\n    // it. Mapping per hand - which cab-local cardinal each panel\n    // covers:\n    //   NE: LEFT \u2192 +X (east);  RIGHT \u2192 -Y (north / front)\n    //   NW: LEFT \u2192 -Y (front); RIGHT \u2192 -X (west)\n    //   SE: LEFT \u2192 +Y (back);  RIGHT \u2192 +X (east)\n    //   SW: LEFT \u2192 -X (west);  RIGHT \u2192 +Y (back)\n    // { noEndPanelReach: true } leaves them off, giving the true carcase line\n    // a straight unit has: neighbour detection tests it alongside the panel\n    // face, and the run-join settle seats a unit carcase to carcase before\n    // the panels are decided. With only the panel face, a unit set against\n    // the L's carcase never met it and the panel stayed on (Sales bug sheet\n    // row 94).\n    let extE = 0, extW = 0, extN = 0, extS = 0;\n    if ((cab.lShapeUnit || cab.diagonalCornerUnit) && !opts.noEndPanelReach) {\n      const ls = cab.lShapeUnit || cab.diagonalCornerUnit;\n      const hand = (ls.hand || 'NE').toUpperCase();\n      const ep = cab.endPanels || {};\n      const epL = ep.left?.active  ? (endPanelThickMm ? endPanelThickMm(ep.left)  : 20) : 0;\n      const epR = ep.right?.active ? (endPanelThickMm ? endPanelThickMm(ep.right) : 20) : 0;\n      if (hand === 'NE')      { if (epL) extE = epL; if (epR) extN = epR; }\n      else if (hand === 'NW') { if (epL) extN = epL; if (epR) extW = epR; }\n      else if (hand === 'SE') { if (epL) extS = epL; if (epR) extE = epR; }\n      else                    { if (epL) extW = epL; if (epR) extS = epR; }\n    }\n    // Breakfast-bar back panel reach (cab-local +Y direction). The\n    // panel's back face sits at max(standOff, T) past the carcase\n    // back - same formula the 2D / 3D back-panel renderers and the\n    // snap engine's applyBackPanelReach use. Needed so a neighbour\n    // cab snapped against the BBBP outer face registers as \"flush\n    // with cab.back\" and autoDetectBackPanels drops the neighbour's\n    // own BBBP.\n    const bp = cab.backPanel;\n    let bpExt = 0;\n    // A partly walled back (bp.spans) has its carcase ON the wall, so it\n    // presents its carcase back, not the panel's reach.\n    if (bp && bp.active && !(Array.isArray(bp.spans) && bp.spans.length)) {\n      // A free-standing appliance's panel stands on the run's back-panel line\n      // (backPanel.standOffMm - see backPanelHost).\n      const standOff = (bp.standOffMm != null) ? bp.standOffMm\n        : cab.epManualBack ? cab.epManualBack.standOffMm\n        : cab.useFullSizeEndPanel\n        ? Math.max(0, 650 - 18 - (cab.depthMm || 0))\n        : 0;\n      const T = bp.thicknessMm || 20;\n      bpExt = Math.max(standOff, T);\n    }\n    // The breakfast-bar back-panel reach (bpExt) is normally folded into the\n    // back line so neighbour adjacency sees the panel's OUTER face. But a\n    // caller asking \"is the CARCASE back against a wall?\" must NOT include it \u2014\n    // otherwise a reduced-depth unit's own panel reach pushes the test line\n    // past the wall, the wall is never detected, and the panel never switches\n    // off (it stays stuck on, sticking through the wall). Such callers pass\n    // { noBackPanelReach: true } to get the true carcase back edge.\n    const bpReach = opts.noBackPanelReach ? 0 : bpExt;\n    const FL = L2W(-w/2 - extW, -d/2 - Math.max(fEx, extN));\n    const FR = L2W(+w/2 + extE, -d/2 - Math.max(fEx, extN));\n    const BR = L2W(+w/2 + extE, +d/2 + Math.max(extS, bpReach));\n    const BL = L2W(-w/2 - extW, +d/2 + Math.max(extS, bpReach));\n    return {\n      front: { p1: FL, p2: FR }, back: { p1: BL, p2: BR },\n      left:  { p1: FR, p2: BR }, right: { p1: FL, p2: BL }\n    };\n  }\n\n  // World-space faces of a DOOR LINE tall end panel. It is turned 90 deg out\n  // of the unit's side and stands on the DOOR LINE running to the wall, so it\n  // is an obstacle in its own right - a unit coming up the return butts its\n  // BACK face and takes a filler to it, exactly like butting a wall. It is not\n  // one of the unit's four bbox sides, so epAllSides / epCarcaseSides cannot\n  // describe it and it has to be offered separately.\n  function epDoorLinePanelFaces(cab) {\n    const ep = cab && cab.endPanels;\n    if (!ep) return [];\n    const w = cab.widthMm, d = cab.depthMm;\n    if (!(w > 0 && d > 0)) return [];\n    const cx = cab.x + w / 2, cy = cab.y + d / 2;\n    const th = ((cab.rotationDeg || 0) * Math.PI) / 180;\n    const cs = Math.cos(th), sn = Math.sin(th);\n    const L2W = (lx, ly) => ({ x: cx + lx * cs - ly * sn, y: cy + lx * sn + ly * cs });\n    const ks = (Catalogue && Catalogue.getKitchenStyle)\n      ? Catalogue.getKitchenStyle(cab.kitchenStyleId) : null;\n    const fwd = (ks && ks.doorThicknessMm) || 18;\n    const out = [];\n    for (const side of ['left', 'right']) {\n      const e = ep[side];\n      if (!(e && e.active && e.doorLine)) continue;\n      const L = Math.max(1, Math.min(650, e.doorLineMm || 650));\n      const T = endPanelThickMm(e);\n      const sign = side === 'left' ? 1 : -1;          // user-left = local +X\n      const x1 = sign * (w / 2), x2 = sign * (w / 2 + L);\n      const yFront = -d / 2 - fwd;                     // the door line\n      const yBack  = yFront + T;\n      out.push({ p1: L2W(x1, yFront), p2: L2W(x2, yFront), thickMm: T });\n      out.push({ p1: L2W(x1, yBack),  p2: L2W(x2, yBack),  thickMm: T });\n    }\n    return out;\n  }\n\n  // DOOR LINE tall end panels as SOLID obstacles, in the same shape the\n  // placement engine already understands for pillars / perimeter items\n  // ({ x, y, widthMm, depthMm, rotationDeg }, rotated about the rect centre).\n  // Settling on drop is too late to line a custom filler up against one - the\n  // drag itself has to stop at the panel, exactly like it does at a wall.\n  // exceptId skips the unit being dragged so a tall unit is never blocked by\n  // its own panel.\n  function epDoorLinePanelObstacles(exceptId) {\n    const out = [];\n    for (const cab of cabinets) {\n      if (!cab || cab.id === exceptId) continue;\n      const ep = cab.endPanels;\n      if (!ep) continue;\n      const w = cab.widthMm, d = cab.depthMm;\n      if (!(w > 0 && d > 0)) continue;\n      const cx = cab.x + w / 2, cy = cab.y + d / 2;\n      const th = ((cab.rotationDeg || 0) * Math.PI) / 180;\n      const cs = Math.cos(th), sn = Math.sin(th);\n      const ks = (Catalogue && Catalogue.getKitchenStyle)\n        ? Catalogue.getKitchenStyle(cab.kitchenStyleId) : null;\n      const fwd = (ks && ks.doorThicknessMm) || 18;\n      for (const side of ['left', 'right']) {\n        const e = ep[side];\n        if (!(e && e.active && e.doorLine)) continue;\n        const L = Math.max(1, Math.min(650, e.doorLineMm || 650));\n        const T = endPanelThickMm(e);\n        const sign = side === 'left' ? 1 : -1;         // user-left = local +X\n        const lx = sign * (w / 2 + L / 2);\n        const ly = -d / 2 - fwd + T / 2;               // centre through the thickness\n        const pcx = cx + lx * cs - ly * sn;\n        const pcy = cy + lx * sn + ly * cs;\n        out.push({ x: pcx - L / 2, y: pcy - T / 2, widthMm: L, depthMm: T,\n                   rotationDeg: cab.rotationDeg || 0, doorLinePanel: true });\n      }\n    }\n    return out;\n  }\n\n  // Distance (mm) from a carcase side line to the nearest filler\n  // ANCHOR that is PARALLEL to it and lies in the side's outward\n  // direction, within FILLER_MAX_GAP. An anchor is either a room wall\n  // segment OR a pillar (perimeter item) face - fillers fill against\n  // both the same way. Returns null when nothing parallel is close.\n  // Maximum filler panel width - matches the largest filler panel\n  // size sold (146mm). Wider gaps need a different solution (extra\n  // unit, end panel, or custom joinery) so we stop auto-filling\n  // beyond this and the inline width input also caps here.\n  const FILLER_MAX_GAP_MM = 146;\n  const FILLER_DEFAULT_MM = 20;\n  // FLUSH. epWallGapOnSide reports anything from -2mm upward, so a side already\n  // touching a wall comes back as 0 rather than as \"nothing there\". Below this\n  // there is nothing to fill and nothing to finish: no filler, no end panel.\n  // Without it, 0 fell into the near-a-wall branch and `Math.max(1, round(0))`\n  // wrote a 1mm filler, which then stuck - only a FULL re-detect ever revisits\n  // a side, and until 2026-10-01 moving a wall ran no re-detect at all.\n  const FILLER_FLUSH_MM = 2;\n  // When a base-unit filler anchors to a tall unit (or its end\n  // panel), it sits 20mm BACK from the door front for technical\n  // reasons. The plinth is unaffected.\n  const FILLER_TALL_SETBACK_MM = 20;\n\n  // The 4 world-space edges of a rectangular perimeter item (pillar /\n  // column), rotation-aware - same corner convention as\n  // projectItemOntoWall (CSS rotate is clockwise in screen coords).\n  function epItemEdges(item) {\n    const w = item?.widthMm, d = item?.depthMm;\n    if (!(w > 0) || !(d > 0)) return [];\n    // A cut-corner pillar is a PENTAGON, not its bounding box. The face\n    // that actually meets the room - the diagonal - is not a bbox edge\n    // at all, so a unit seated against an angled corner matched nothing\n    // here and read as exposed: its breakfast-bar back panel stayed on,\n    // and a filler had nothing to anchor to. Walk the real footprint\n    // instead, dropping any zero-length side (a full-span 'splay' cut\n    // collapses its two short legs, leaving just the diagonal).\n    if (item.cornerCut) {\n      const v = getPentagonVerticesWorld(item);\n      const out = [];\n      for (let i = 0; i < v.length; i++) {\n        const a = v[i], b = v[(i + 1) % v.length];\n        if (Math.hypot(b.x - a.x, b.y - a.y) > 0.5) out.push({ a, b });\n      }\n      return out;\n    }\n    const cx = item.x + w / 2, cy = item.y + d / 2;\n    const th = ((item.rotationDeg || 0) * Math.PI) / 180;\n    const cs = Math.cos(th), sn = Math.sin(th);\n    const c = [[-w / 2, -d / 2], [w / 2, -d / 2], [w / 2, d / 2], [-w / 2, d / 2]]\n      .map(([lx, ly]) => ({ x: cx + lx * cs - ly * sn, y: cy + lx * sn + ly * cs }));\n    return [\n      { a: c[0], b: c[1] }, { a: c[1], b: c[2] },\n      { a: c[2], b: c[3] }, { a: c[3], b: c[0] }\n    ];\n  }\n\n  // OPENINGS ARE HOLES. A door, walkway or window is a gap in its wall, so a\n  // unit end facing one - typically the last unit of a run on the wall beside\n  // it, standing in front of it - is on view through it, and needs an end\n  // panel, not the filler or bare edge a solid wall would take.\n  //\n  // Each hole as a world segment on the face it is cut into: the wall, or the\n  // front of a pillar standing against it (openingInsetMm). `range` keeps only\n  // holes that reach the unit's height - a door or walkway runs up from the\n  // floor, a window from its cill, so a base unit under a window still stands\n  // against solid wall. Same vertical defaults as the splashback engine.\n  const EP_HOLE_LINE_TOL_MM = 5;    // how close to a face a hole must lie to be cut into it\n  const EP_HOLE_SEEN_MM     = 20;   // this much of an end showing through counts as on view\n  function epOpeningHoles(range, ops = roomConfig.wallOpenings) {\n    const out = [];\n    if (!ops || !ops.length) return out;\n    const walls = getWalls(room);\n    for (const op of ops) {\n      if (!op || op.floating) continue;\n      const wall = walls[op.wallIndex];\n      if (!wall || !wall.lengthMm) continue;\n      const isWindow = op.type === 'window';\n      const bottom = isWindow ? (op.heightFromFloorMm != null ? op.heightFromFloorMm : 900) : 0;\n      const top    = bottom + (op.heightMm || (isWindow ? 1100 : 2040));\n      if (range && !epRangesOverlap(range, { bottom, top })) continue;\n      const ux = (wall.to.x - wall.from.x) / wall.lengthMm;\n      const uy = (wall.to.y - wall.from.y) / wall.lengthMm;\n      const inset = openingInsetMm(op);\n      const ix = -uy * inset, iy = ux * inset;       // into the room, onto the face\n      const o0 = op.offsetMm || 0, o1 = o0 + (op.widthMm || 0);\n      out.push({\n        a: { x: wall.from.x + ux * o0 + ix, y: wall.from.y + uy * o0 + iy },\n        b: { x: wall.from.x + ux * o1 + ix, y: wall.from.y + uy * o1 + iy }\n      });\n    }\n    return out;\n  }\n\n  // Does a hole cut into the anchor through `a` (direction wux,wuy) show any\n  // of the side that spans t1..t2 along it? Both hole ends must lie on the\n  // anchor's line - a hole in the wall BEHIND a pillar is not in the pillar.\n  function epSideFacesHole(holes, a, wux, wuy, t1, t2) {\n    const lo = Math.min(t1, t2), hi = Math.max(t1, t2);\n    const wnx = -wuy, wny = wux;\n    for (const h of holes) {\n      const off1 = (h.a.x - a.x) * wnx + (h.a.y - a.y) * wny;\n      const off2 = (h.b.x - a.x) * wnx + (h.b.y - a.y) * wny;\n      if (Math.abs(off1) > EP_HOLE_LINE_TOL_MM || Math.abs(off2) > EP_HOLE_LINE_TOL_MM) continue;\n      const h1 = (h.a.x - a.x) * wux + (h.a.y - a.y) * wuy;\n      const h2 = (h.b.x - a.x) * wux + (h.b.y - a.y) * wuy;\n      const seen = Math.min(hi, Math.max(h1, h2)) - Math.max(lo, Math.min(h1, h2));\n      if (seen > EP_HOLE_SEEN_MM) return true;\n    }\n    return false;\n  }\n\n  function epWallGapOnSide(carcSideLine, outward, scope, selfId, selfRange) {\n    const sdx = carcSideLine.p2.x - carcSideLine.p1.x;\n    const sdy = carcSideLine.p2.y - carcSideLine.p1.y;\n    const slen = Math.hypot(sdx, sdy);\n    if (slen < 1) return null;\n    const sux = sdx / slen, suy = sdy / slen;\n    const holes = epOpeningHoles(selfRange);\n\n    let best = null, bestTall = false, bestDoorLine = false, bestDoorLineThick = 0;\n    // Test one candidate anchor segment a\u2192b against the side line.\n    // isTall flags whether the anchor is a tall-unit face - the\n    // result tells the filler decision so a base-unit filler that\n    // anchors to a tall unit can be marked for the 20mm setback.\n    const consider = (a, b, isTall, isDoorLine, dlThickMm) => {\n      const wdx = b.x - a.x, wdy = b.y - a.y;\n      const wlen = Math.hypot(wdx, wdy);\n      if (wlen < 1) return;\n      const wux = wdx / wlen, wuy = wdy / wlen;\n      // Parallel to the side line? (cross product \u2248 0)\n      if (Math.abs(sux * wuy - suy * wux) > 0.06) return;\n      // Signed distance from side.p1 to the anchor line, and the gap\n      // in the side's outward direction:  gap = -d / (outward\u00B7n).\n      const wnx = -wuy, wny = wux;\n      const d = (carcSideLine.p1.x - a.x) * wnx + (carcSideLine.p1.y - a.y) * wny;\n      const outDotN = outward.x * wnx + outward.y * wny;\n      if (Math.abs(outDotN) < 0.5) return;\n      const gap = -d / outDotN;\n      if (gap < -2 || gap > FILLER_MAX_GAP_MM) return;\n      // The cabinet side must run ALONGSIDE this anchor section.\n      const t1 = (carcSideLine.p1.x - a.x) * wux + (carcSideLine.p1.y - a.y) * wuy;\n      const t2 = (carcSideLine.p2.x - a.x) * wux + (carcSideLine.p2.y - a.y) * wuy;\n      const overlap = Math.min(wlen, Math.max(t1, t2)) - Math.max(0, Math.min(t1, t2));\n      if (overlap < 20) return;\n      // Any of the side showing through an opening in this wall or pillar\n      // face, and the face is no finish for it - even where the rest of the\n      // side is against solid wall. Only walls and pillars have holes.\n      if (!isTall && holes.length && epSideFacesHole(holes, a, wux, wuy, t1, t2)) return;\n      const g = Math.max(0, gap);\n      if (best == null || g < best) {\n        best = g; bestTall = !!isTall; bestDoorLine = !!isDoorLine;\n        bestDoorLineThick = isDoorLine ? (dlThickMm || 0) : 0;\n      }\n    };\n\n    // Room wall segments.\n    const verts = room?.vertices || [];\n    for (let i = 0; i < verts.length; i++) {\n      consider(verts[i], verts[(i + 1) % verts.length], false);\n    }\n    // Pillar / perimeter-item faces - a filler anchors to these too.\n    for (const it of (roomConfig.perimeterItems || [])) {\n      for (const e of epItemEdges(it)) consider(e.a, e.b, false);\n    }\n    // Tall units (incl. their end panels) - a filler anchors to a\n    // tall unit's side the same way it anchors to a wall, so a wall\n    // unit beside a tall unit fills the gap to it. epAllSides gives\n    // the effective side (carcase + any active tall end panel).\n    // A unit standing INSIDE a walk-in larder (line 111) fills to the\n    // larder's inside faces - gables and door frame - like a wall; never\n    // through them to the larder's outside or its tall end panel.\n    const _self = (scope || []).find(c => c && c.id === selfId) || cabinets.find(c => c && c.id === selfId);\n    const _inLarder = _self ? (scope || []).find(o => o && o.id !== selfId && isWalkInLarder(o)\n      && unitInsideWalkInLarder(_self, _self.x || 0, _self.y || 0, o)) : null;\n    if (_inLarder) for (const f of walkInInteriorFaces(_inLarder)) consider(f.p1, f.p2, false);\n    for (const other of (scope || [])) {\n      if (!other || other.id === selfId) continue;\n      if (_inLarder && other.id === _inLarder.id) continue;\n      if (!/^tall/i.test(other.category || '')) continue;\n      if (other.freestandingAppliance) continue;   // a fridge is not a filler anchor\n      // Only a tall unit that actually shares this cab's vertical band\n      // can anchor its filler. Without this height gate a unit STACKED\n      // ABOVE (a midi rider is 'tall-units' by category) sat on exactly\n      // the same footprint, so its side lines coincided at gap 0 and the\n      // unit underneath read that as \"flush against a tall unit\" - which\n      // swaps an end panel for a filler and silently killed the lower\n      // unit's auto panel. A tall unit at a different height was never a\n      // real anchor anyway, so this is right independent of stacking.\n      if (selfRange && !epRangesOverlap(selfRange, epVerticalRange(other))) continue;\n      const sides = epAllSides(other);\n      for (const k of ['front', 'back', 'left', 'right']) {\n        consider(sides[k].p1, sides[k].p2, true);\n      }\n      // A DOOR LINE tall end panel anchors a filler exactly like a wall - it\n      // is the face a unit coming up the return butts into, so the unit takes\n      // a FILLER to it rather than keeping its own end panel.\n      for (const f of epDoorLinePanelFaces(other)) consider(f.p1, f.p2, true, true, f.thickMm);\n    }\n    return best == null ? null\n      : { gap: best, tall: bestTall, doorLine: bestDoorLine, doorLineThickMm: bestDoorLineThick };\n  }\n\n  // Tolerance for \"same depth\" (mm). Anything beyond and the depth\n  // comparison triggers the deeper-wins rule.\n  const EP_DEPTH_TOL_MM = 5;\n  // NO TRUE CARCASE (Non Urgent bug sheet rows 10 + 80, Arden 2026-11-11): an\n  // integrated appliance door (dishwasher, washer...) is a door on a machine,\n  // and the Built Under Double Oven Fitting Panels are two 100mm-deep strips -\n  // neither has a full side. Beside a real carcase that carcase's side does\n  // the job, but where two of them meet there is nothing between the\n  // machines to fix to or carry the worktop, so ONE end panel goes in.\n  function epNoTrueCarcase(c) {\n    if (!c || c.freestandingAppliance) return false;\n    if (c.cutoutSchema && c.cutoutSchema.fittingPanels) return true;\n    const ut = Catalogue.getUnitType ? Catalogue.getUnitType(c.unitTypeId) : null;\n    return !!(ut && (ut.unitTypeGroupHandle === 'ap-integrated-appliance-doors'\n      || (ut.cutoutSchema && ut.cutoutSchema.fittingPanels)));\n  }\n  function epDecideActive(cab, neighbour, side) {\n    if (!neighbour) return true;          // free end\n    // Radius unit on either side \u2192 the radius unit's curved face IS\n    // the end-of-run finish, so the abutting cabinet drops its end\n    // panel here. Without this, a 570mm base abutting a 300mm radius\n    // unit wins the \"deeper wins\" comparison below and keeps its\n    // panel even when it's flush against the curve.\n    if (cab.radiusUnit || neighbour.radiusUnit) return false;\n    // Kneehole Drawer Unit (see the walk): its floor-height panel finishes the\n    // end of a unit no taller than it; a taller unit keeps its own panel.\n    if (isHungBetweenUnit(neighbour) && !isHungBetweenUnit(cab)) {\n      return epVerticalRange(cab).top > epVerticalRange(neighbour).top + END_PANEL_AUTO_TOL_MM;\n    }\n    // Belfast sink units carry REQUIRED end panels that WIN over any\n    // abutting unit: a Belfast cab always keeps its own panel, and a\n    // neighbour Belfast forces a BASE cab's facing panel OFF. (Belfast\n    // cabs are also force-handled in the auto-detect walk, so this is\n    // mainly the rule the abutting base unit sees.)\n    if (cab.belfastSink) return true;\n    // ...except against a TALL unit (tall, midi, housing): it keeps its own\n    // tall end panel there, and the Belfast keeps its panel too - the user can\n    // untick the Belfast's (Arden, 2026-10-26, Planner Bugs 36). A base unit\n    // beside a Belfast still drops its panel.\n    if (neighbour.belfastSink) {\n      const g = epCategoryGroup(cab);\n      return g === 'tall' || g === 'midi';\n    }\n    // FLOOR-HEIGHT TALL END PANEL (American fridge housing): the panel runs\n    // from the bridging unit's top down to the floor, so it finishes the whole\n    // end - a unit butting it drops its own panel rather than doubling up,\n    // exactly like a tall unit's panel beating a base unit's. Two housings\n    // meeting each other fall through to the normal rules below.\n    const cabFloorPanel = epHasFloorPanel(cab);\n    const neiFloorPanel = epHasFloorPanel(neighbour);\n    if (neiFloorPanel && !cabFloorPanel) return false;\n    if (cabFloorPanel && !neiFloorPanel) return true;\n    // A FREE STANDING APPLIANCE is not a carcase. It is a machine standing in\n    // an opening with a fitting gap each side, so nothing beside it finishes\n    // its end and it keeps its panel: a corner post lands on the door line of\n    // the unit it belongs to and never reaches across the gap, and a deeper\n    // neighbour's side is still that neighbour's own. Julian: placed against a\n    // corner base unit the connected side was coming back off, because the\n    // appliance groups as 'base' and the corner rule below reads a same-group\n    // neighbour as finished by the post.\n    //\n    // Deliberately BELOW the floor-panel rules: an American fridge under a\n    // deep bridging housing is the one case where something really does\n    // finish its side, and the housing's floor-height panel runs the whole\n    // way down past the fridge. Only that and a Belfast beat it; otherwise\n    // just the user, in End Panels & Fillers.\n    //\n    // The unit beside it drops its own rather than doubling up - the same\n    // assumption epFindNeighbourOnSide already makes when it lets a panelled\n    // appliance count as the neighbour that finishes that side.\n    if (cab.freestandingAppliance) return true;\n    if (neighbour.freestandingAppliance) return false;\n    // Two units with no true carcase side by side: one panel between them, on\n    // the left-hand one's right side (facing the doors). Facing different ways,\n    // the lower id takes it, so there is never one on both.\n    if (epNoTrueCarcase(cab) && epNoTrueCarcase(neighbour)) {\n      const rot = u => ((Math.round(u.rotationDeg || 0) % 360) + 360) % 360;\n      if (side && rot(cab) === rot(neighbour)) return side === 'right';\n      return String(cab.id) < String(neighbour.id);\n    }\n    // Neighbour is a corner unit: its corner post finishes any\n    // SAME-category neighbour's end (a base corner post finishes a\n    // base unit; a wall corner post finishes a wall unit). Cross-\n    // category neighbours (e.g. a tall beside a base corner, or a\n    // base beside a wall corner) keep their panel.\n    if (neighbour.cornerUnit) {\n      return epCategoryGroup(cab) !== epCategoryGroup(neighbour);\n    }\n    // Corner Post + Void stub: the L-post finishes the run end the\n    // same way a cornerUnit's blank-panel + post does - its 60mm\n    // door-coloured leg sits where the adjacent SHB's end panel\n    // would otherwise go. Drop same-category neighbours' panels at\n    // the CPV interface so the door line continues clean across\n    // the corner.\n    if (neighbour.lShapeUnit && neighbour.lShapeUnit.cornerPostVoid) {\n      return epCategoryGroup(cab) !== epCategoryGroup(neighbour);\n    }\n    // Stepped cab always keeps its panel - the step exposes a front\n    // edge the panel covers, independent of category. Without this,\n    // a stepped base next to a tall would drop its panel under the\n    // \"tall wins\" cross-category rule below, leaving the step bare.\n    const cabSbEarly = cab.wallSetbackMm || 0;\n    const neiSbEarly = neighbour.wallSetbackMm || 0;\n    if (cabSbEarly > neiSbEarly + EP_DEPTH_TOL_MM) return true;\n\n    const cabGroup = epCategoryGroup(cab);\n    const neiGroup = epCategoryGroup(neighbour);\n\n    // L-shape units carry a bbox depth (= the full L outline) that's\n    // bigger than the actual side the neighbour butts against (= the\n    // L's arm, 330mm for a wall L-shape, 570mm for a base L-shape).\n    // Use the arm depth in every \"deeper wins\" comparison so an L vs\n    // a same-depth straight neighbour reads as equal.\n    const ruleDepth = (u) => {\n      const lShapeLike = u.lShapeUnit || u.diagonalCornerUnit;\n      return lShapeLike ? (lShapeLike.armDepthMm || 570) : (u.depthMm || 0);\n    };\n\n    // Wall-ish units (wall + bridging) all hang from a mount line and\n    // share the same ~330mm depth, so the \"deeper wins\" test below\n    // can't separate them - a 720 and a 575 wall unit are equal depth\n    // yet the taller one's end sticks out BELOW the shorter neighbour\n    // and is exposed. Decide by VERTICAL EXTENT instead: whichever\n    // unit protrudes past the other (reaches higher OR lower) keeps\n    // its panel; a unit whose end is fully covered by the neighbour\n    // drops it; identical extent \u2192 deeper wins, else both off. This is\n    // the \"tallest wall unit wins\" rule, applied across every wall +\n    // bridging height (mirrors tall-wins-over-base, just by extent).\n    const WALLISH = g => g === 'wall' || g === 'bridging';\n    if (WALLISH(cabGroup) && WALLISH(neiGroup)) {\n      const cr = epVerticalRange(cab);\n      const nr = epVerticalRange(neighbour);\n      const cabOut = (cr.top > nr.top + EP_DEPTH_TOL_MM) || (cr.bottom < nr.bottom - EP_DEPTH_TOL_MM);\n      const neiOut = (nr.top > cr.top + EP_DEPTH_TOL_MM) || (nr.bottom < cr.bottom - EP_DEPTH_TOL_MM);\n      if (cabOut !== neiOut) return cabOut;            // only one protrudes \u2192 it keeps the panel\n      if (cabOut && neiOut)  return true;              // each protrudes somewhere \u2192 both keep\n      // A SPLAY end unit's carcase runs ~10mm shallower than the standard units\n      // it butts (560 against a 570 run, 320 against a 330 one). That set-back\n      // is a construction detail, not an exposed step, so the tie-break below\n      // would hand the STRAIGHT neighbour a panel at a joint that needs none -\n      // and leave a panel sitting in the middle of the run. A splay's exposed\n      // end is its SHALLOW side; the deep side is always the run side.\n      if (cab.splayEnd || neighbour.splayEnd) return false;\n      const cd = ruleDepth(cab), nd = ruleDepth(neighbour);\n      if (cd > nd + EP_DEPTH_TOL_MM) return true;      // equal extent, deeper \u2192 keep\n      if (cd < nd - EP_DEPTH_TOL_MM) return false;     // equal extent, shallower \u2192 drop\n      return false;                                    // identical \u2192 both off\n    }\n\n    // Cross-category. Floor-standing runs finish by HEIGHT - tall > midi >\n    // base - so the taller unit keeps its facing panel (its end is the exposed\n    // step) and the shorter one drops it. Wall / bridging hang from the mount\n    // line and don't take part in that ordering.\n    if (cabGroup !== neiGroup) {\n      const FLOOR_RANK = { tall: 3, midi: 2, base: 1 };\n      const cRank = FLOOR_RANK[cabGroup], nRank = FLOOR_RANK[neiGroup];\n      if (cRank && nRank) return cRank > nRank;\n      if (cabGroup === 'tall' && (neiGroup === 'wall' || neiGroup === 'bridging')) return true;\n      if (neiGroup === 'tall' && (cabGroup === 'wall' || cabGroup === 'bridging')) return false;\n      // A wall unit hung BESIDE a floor unit at its level - lined up with the\n      // bottom of a floating Media unit, or standing on a worktop next to one\n      // (Arden, 2026-10-28): they butt like a run, so the taller keeps its\n      // facing panel (the step above the other is exposed) and the shorter\n      // drops it; the same height, neither has one.\n      const _wb = (g) => g === 'wall' || g === 'bridging';\n      if ((cabGroup === 'base' && _wb(neiGroup)) || (neiGroup === 'base' && _wb(cabGroup))) {\n        const ra = unitVerticalRange(cab), rb = unitVerticalRange(neighbour);\n        if (Math.min(ra.top, rb.top) - Math.max(ra.bottom, rb.bottom) > 50) {\n          // A column standing on the floor unit carries its side down past it:\n          // the wall unit beside keeps its panel only where it stands out of\n          // the column's, and the floor unit's own side is the column's.\n          const tower = towerRangeOn(cabGroup === 'base' ? cab : neighbour);\n          if (tower) {\n            if (cabGroup === 'base') return false;\n            return ra.top > tower.top + EP_DEPTH_TOL_MM || ra.bottom < tower.bottom - EP_DEPTH_TOL_MM;\n          }\n          return ra.top > rb.top + EP_DEPTH_TOL_MM;\n        }\n      }\n      return true;     // unrelated combination (e.g. base \u2194 wall - different heights, no real conflict)\n    }\n\n    // Same category but DIFFERENT HEIGHTS - e.g. a half-height base\n    // unit (~400mm) abutting a standard base (~720mm). The TALLER\n    // cab \"wins\" (keeps its facing panel - it's the exposed side\n    // protruding above the shorter neighbour), and the shorter cab\n    // drops its facing panel (= already covered by the taller's\n    // side panel). Mirrors the tall-vs-base cross-category rule\n    // applied to same-category cabs of different heights.\n    // Tolerance 100mm so a normal +/-20mm catalogue variation\n    // between two standard base units doesn't trip the test, while\n    // half-height vs standard (~300mm gap) always does.\n    // A carcase column races on its WHOLE extent (stackColumnTopMm =\n    // host + everything screwed on top), not on the single carcase it\n    // happens to be measured from - that's what makes a stacked pair\n    // read as one tall unit here.\n    const raceHeight = (u) => u.stackColumnTopMm || u.heightMm || 0;\n    const cabH = raceHeight(cab);\n    const neiH = raceHeight(neighbour);\n    if (cabH > neiH + 100) return true;     // this cab is taller \u2192 keep\n    if (cabH < neiH - 100) return false;    // this cab is shorter \u2192 drop\n    // Splay set-back is not an exposed step - see the wall-ish branch above.\n    if (cab.splayEnd || neighbour.splayEnd) return false;\n    // Same category: deeper wins (e.g. 570mm base keeps panel, 470mm\n    // reduced-depth base loses it). Equal depths \u2192 both off so the\n    // units sit unit-to-unit with no panel between. Uses the same\n    // ruleDepth helper defined above (arm depth for L-shape, bbox\n    // depth otherwise) so an L-shape vs an equal-arm-depth straight\n    // neighbour reads as \"equal\".\n    const cd = ruleDepth(cab);\n    const nd = ruleDepth(neighbour);\n    if (cd > nd + EP_DEPTH_TOL_MM) return true;     // this cabinet is deeper \u2192 keep\n    if (cd < nd - EP_DEPTH_TOL_MM) return false;    // this cabinet is shallower \u2192 off\n    // Same depth but DIFFERENT wall-setbacks: the MORE-STEPPED cab\n    // has a visible front edge sticking past the less-stepped one,\n    // so it keeps its panel; the less-stepped cab's side is already\n    // covered by the stepped cab's panel (and any back-end exposure\n    // sits in the void area, hidden by the stepped cab's body), so\n    // its panel drops to avoid two overlapping panels at the join.\n    const cabSb = cab.wallSetbackMm || 0;\n    const neiSb = neighbour.wallSetbackMm || 0;\n    if (Math.abs(cabSb - neiSb) > EP_DEPTH_TOL_MM) {\n      return cabSb > neiSb;                          // more setback \u2192 keep panel\n    }\n    return false;                                    // same depth + same setback \u2192 both off\n  }\n\n  // L-shape arm-end face line + outward normal in WORLD coords. Each\n  // (hand, side) picks the open END of one of the two arms; LEFT /\n  // RIGHT mapping mirrors lShapeEndPanelBboxMm in\n  // btk-kitchen-planner-2d-cabinets.js (user's left/right when facing\n  // the doors). Used by autoDetectEndPanels to decide whether each\n  // arm end is free, abuts a wall, or abuts a neighbour cabinet.\n  function epLShapeEndFaceWorld(cab, side) {\n    // Diagonal corner units share the L-shape arm geometry (same\n    // outer arm faces, same hand convention), so the same per-hand\n    // face math applies - just read from either struct.\n    const ls = cab.lShapeUnit || cab.diagonalCornerUnit;\n    const W = cab.widthMm, D = cab.depthMm;\n    const A = ls.armDepthMm || 570;\n    const cut = ls.cutoutMm || (W - A);\n    const hand = (ls.hand || 'NE').toUpperCase();\n    let p1, p2, ox, oy;     // cab-local TL-origin coords + outward\n    if (hand === 'NE') {\n      if (side === 'left') { p1 = { x: W,   y: cut }; p2 = { x: W, y: D }; ox = 1;  oy = 0; }\n      else                 { p1 = { x: 0,   y: 0   }; p2 = { x: A, y: 0 }; ox = 0;  oy = -1; }\n    } else if (hand === 'NW') {\n      if (side === 'left') { p1 = { x: cut, y: 0   }; p2 = { x: W, y: 0 }; ox = 0;  oy = -1; }\n      else                 { p1 = { x: 0,   y: cut }; p2 = { x: 0, y: D }; ox = -1; oy = 0; }\n    } else if (hand === 'SE') {\n      if (side === 'left') { p1 = { x: 0,   y: D   }; p2 = { x: A, y: D }; ox = 0;  oy = 1; }\n      else                 { p1 = { x: W,   y: 0   }; p2 = { x: W, y: A }; ox = 1;  oy = 0; }\n    } else { // SW\n      if (side === 'left') { p1 = { x: 0,   y: 0   }; p2 = { x: 0, y: A }; ox = -1; oy = 0; }\n      else                 { p1 = { x: cut, y: D   }; p2 = { x: W, y: D }; ox = 0;  oy = 1; }\n    }\n    const cx = cab.x + W / 2, cy = cab.y + D / 2;\n    const th = ((cab.rotationDeg || 0) * Math.PI) / 180;\n    const cs = Math.cos(th), sn = Math.sin(th);\n    const L2W = (lx, ly) => ({\n      x: cx + (lx - W/2) * cs - (ly - D/2) * sn,\n      y: cy + (lx - W/2) * sn + (ly - D/2) * cs\n    });\n    return {\n      p1: L2W(p1.x, p1.y),\n      p2: L2W(p2.x, p2.y),\n      outward: { x: ox * cs - oy * sn, y: ox * sn + oy * cs }\n    };\n  }\n\n  // Find a cabinet whose effective or carcase edge coincides with the\n  // L's arm-end face. Same logic as epFindNeighbourOnSide but takes\n  // the face line directly (the L's open-end line isn't one of the\n  // bbox sides, so the standard sideKey lookup doesn't apply).\n  function epLShapeFindEndNeighbour(cab, face, range, scope) {\n    for (const other of scope) {\n      if (other.id === cab.id) continue;\n      const grp = epCategoryGroup(other);\n      if (grp !== 'base' && grp !== 'tall' && grp !== 'midi' && grp !== 'wall' && grp !== 'bridging' && !other.cornerUnit) continue;\n      if (!epRangesOverlap(range, epVerticalRange(other))) continue;\n      const oCarc = epCarcaseSides(other, { noEndPanelReach: true });\n      const oEff  = epAllSides(other);\n      for (const key of ['front', 'back', 'left', 'right']) {\n        if (epLinesCoincide(face, oCarc[key]) ||\n            epLinesCoincide(face, oEff[key])) {\n          return other;\n        }\n      }\n    }\n    return null;\n  }\n\n  // Walks every cabinet and decides each side's finish - END PANEL,\n  // FILLER, or neither - then mutates cabinets[] in place.\n  //\n  // Per side:\n  //   * cabinet neighbour          \u2192 end-panel rule (epDecideActive)\n  //   * wall within 100mm, no nbr  \u2192 FILLER (no end panel):\n  //       - opposite side constrained (cabinet OR wall)\n  //                                 \u2192 filler = the measured gap\n  //       - opposite side free     \u2192 filler = 20mm default; the\n  //                                   cabinet is nudged away from\n  //                                   the wall so the gap = 20mm\n  //   * truly free end             \u2192 end panel\n  //\n  // ADJACENCY IS DECIDED FROM A SNAPSHOT - once panels start\n  // deactivating, each cabinet's effective side line (panel/filler-\n  // extended) shifts, which would corrupt later iterations. Snapshot,\n  // decide everything, then apply.\n  // `movedIdsArg` - Set/array of cabinet ids that were just dragged.\n  // A moved cab dropped into a CONSTRAINED gap (another cab 6-100mm\n  // away on a side) gets that side's auto end panel turned OFF, so\n  // the user resolves the gap manually via snap-left / snap-right /\n  // add-filler controls rather than the engine guessing. Non-moved\n  // cabs keep the standard rules (free-end panel for any side\n  // without a flush neighbour or wall anchor).\n  // A side as the planner starts with it: no panel, no filler, no finish of\n  // the user's on it. The detect pass builds from this, and handing a side\n  // back to Auto returns it to this - the same definition, so the two can\n  // never drift apart.\n  function epSideDefaults()     { return { active: false, style: 'flat', inline: false, pelmetExt: 'modern', toFloor: false }; }\n  function fillerSideDefaults() { return { active: false, widthMm: FILLER_DEFAULT_MM, setBackMm: 0 }; }\n\n  // A free-placed panel from the filler-panels group (715FILL, FILLPLIN) - the\n  // standalone counterpart of a unit's own filler. Read from the catalogue\n  // rather than stamped on the cab, so a plan saved before this existed picks\n  // it up on load. The end-panels group is deliberately NOT included: an end\n  // panel is a fixed-thickness board, not something that grows to a gap.\n  function isFillerPanelUnit(cab) {\n    if (!cab || !cab.endPanelUnit || !cab.unitTypeId) return false;\n    const ut = Catalogue.getUnitType?.(cab.unitTypeId);\n    return ut?.unitTypeGroupHandle === 'filler-panels';\n  }\n\n  // The open side of an open end unit: the end it is named for - \"Left End\" /\n  // \"Left Hand\" is open on the left, \"Right End\" / \"Right Hand\" on the right.\n  function openEndSideOf(cab) {\n    const id = String((cab && cab.unitTypeId) || '');\n    if (!/open-end/.test(id)) return null;\n    if (/-(left-end|left-hand)$/.test(id)) return 'left';\n    if (/-(right-end|right-hand)$/.test(id)) return 'right';\n    return null;\n  }\n\n  function autoDetectEndPanels(movedIdsArg) {\n    clampCornerReturns();\n    if (!autoEndPanels) return;   // manual mode: leave the user's end panels/fillers untouched\n    // Re-derive the stack anchors first. This walk is called from the\n    // mutation points (drop / add / delete / stack change), NOT from\n    // rerender, so without this it would read the vertical bands and\n    // column ids from the PREVIOUS render - and a unit that just moved\n    // off its host, or was just stacked, would be decided against a\n    // stale height. Idempotent and O(n), so it's safe to repeat.\n    syncStackAnchors();\n    const movedSet = movedIdsArg\n      ? (movedIdsArg instanceof Set ? movedIdsArg : new Set(movedIdsArg))\n      : null;\n    const defEp  = epSideDefaults;\n    const defFil = fillerSideDefaults;\n    // A freestanding appliance's panels and fillers are only ever the user's\n    // (Arden, 2026-11-05): none when placed, and the walk never decides anything\n    // about them - see the skip in the decision loop. It is in the snapshot\n    // because it is a real neighbour: a panel added to it finishes the side of\n    // the unit beside it, and with none that unit keeps its own.\n    const snapshot = cabinets.map(c => {\n      const ep = c.endPanels || {}, fil = c.fillers || {};\n      return {\n        ...c,\n        endPanels: { left: { ...defEp(),  ...ep.left  }, right: { ...defEp(),  ...ep.right  } },\n        fillers:   { left: { ...defFil(), ...fil.left }, right: { ...defFil(), ...fil.right } }\n      };\n    });\n\n    // FILLER CORNERS, across the whole plan and before anything is queued.\n    // The two halves of a corner meet across the void, not side to side, so\n    // nothing below would ever think of one as the other's neighbour.\n    const cornerHits = fillerCornerCandidates(snapshot);\n\n    // Which cabs need re-evaluation this pass:\n    //   * with movedIds: only the moved cab(s) + any cab within\n    //     100mm (in plan) of a moved cab. Unrelated static layout\n    //     state is PRESERVED - dropping cab D doesn't reset panel\n    //     decisions made when cabs A and B were placed earlier.\n    //   * without movedIds (load, redraw, etc.): everyone.\n    const toEvaluate = new Set();\n    if (movedSet && movedSet.size > 0) {\n      for (const id of movedSet) toEvaluate.add(id);\n      // Geometric neighbours of moved cabs (current positions).\n      for (const cab of snapshot) {\n        if (toEvaluate.has(cab.id)) continue;\n        const myCarc  = epCarcaseSides(cab);\n        // Coarse floor-reaching band here (and in the staleness sweep below):\n        // these only pick WHO gets re-evaluated, and a unit beside a fridge\n        // housing must be queued when the housing moves.\n        const myRange = epAdjacencyRange(cab);\n        for (const movedId of movedSet) {\n          const moved = snapshot.find(c => c.id === movedId);\n          if (!moved) continue;\n          if (!epRangesOverlap(myRange, epAdjacencyRange(moved))) continue;\n          const movedSides = epAllSides(moved);\n          let near = false;\n          for (const mk of ['front', 'back', 'left', 'right']) {\n            for (const ok of ['front', 'back', 'left', 'right']) {\n              if (epLinesCoincide(myCarc[mk], movedSides[ok], FILLER_MAX_GAP_MM)) {\n                near = true; break;\n              }\n            }\n            if (near) break;\n          }\n          if (near) { toEvaluate.add(cab.id); break; }\n        }\n      }\n      // Cabs whose current \"panel off\" state may be STALE - the cab\n      // that justified the deactivation has now moved away (or was\n      // deleted) and is no longer within 100mm. Without this, when\n      // user drags cab B away from a previously-flush cab A, cab A\n      // keeps its facing panel off even though it's now isolated.\n      for (const cab of snapshot) {\n        if (toEvaluate.has(cab.id)) continue;\n        const grp = epCategoryGroup(cab);\n        if (grp !== 'base' && grp !== 'tall' && grp !== 'midi' && grp !== 'wall' && grp !== 'bridging') continue;\n        const ep  = cab.endPanels || {};\n        const fil = cab.fillers   || {};\n        const myCarc  = epCarcaseSides(cab);\n        const myRange = epAdjacencyRange(cab);\n        const sideStale = (side) => {\n          // Only OFF panels can be stale; ON panels are either\n          // free-end or manually set - leave them alone.\n          if (ep[side]?.active || fil[side]?.active) return false;\n          for (const other of snapshot) {\n            if (other.id === cab.id) continue;\n            const oGrp = epCategoryGroup(other);\n            if (oGrp !== 'base' && oGrp !== 'tall' && oGrp !== 'midi' && oGrp !== 'wall' && oGrp !== 'bridging' && !other.cornerUnit) continue;\n            if (!epRangesOverlap(myRange, epAdjacencyRange(other))) continue;\n            const oSides = epAllSides(other);\n            for (const k of ['front', 'back', 'left', 'right']) {\n              if (epLinesCoincide(myCarc[side], oSides[k], FILLER_MAX_GAP_MM)) {\n                return false;   // a cab is still in range - keep off\n              }\n            }\n          }\n          return true;   // off with nothing in range - stale, re-evaluate\n        };\n        if (sideStale('left') || sideStale('right')) toEvaluate.add(cab.id);\n      }\n      // Corner partners - neither pass above can see them. Queue the other\n      // half of any corner a moved unit has just arrived in, and any unit\n      // still linked to a partner that has moved or been deleted: otherwise\n      // dragging one unit away leaves the other holding a mitred filler with\n      // nothing to meet.\n      for (const [key, hit] of cornerHits) {\n        if (movedSet.has(key.slice(0, key.lastIndexOf(':')))) toEvaluate.add(hit.partner.id);\n      }\n      const liveIds = new Set(snapshot.map(c => c.id));\n      for (const cab of snapshot) {\n        if (toEvaluate.has(cab.id)) continue;\n        for (const side of ['left', 'right']) {\n          const w = cab.fillers[side].cornerWith;\n          if (w && (movedSet.has(w.id) || !liveIds.has(w.id))) { toEvaluate.add(cab.id); break; }\n        }\n      }\n    } else {\n      for (const cab of snapshot) toEvaluate.add(cab.id);\n    }\n\n    // A carcase column is finished as ONE panel, so its members have to\n    // be decided together - pull in every sibling of anything already\n    // queued. Otherwise a member left un-evaluated keeps its old state,\n    // and since the column takes the UNION below, one stale ON would\n    // pin the whole column's panel on after it should have dropped.\n    {\n      const queuedCols = new Set(\n        snapshot.filter(c => c.stackColumnId && toEvaluate.has(c.id)).map(c => c.stackColumnId)\n      );\n      if (queuedCols.size) {\n        for (const c of snapshot) {\n          if (c.stackColumnId && queuedCols.has(c.stackColumnId)) toEvaluate.add(c.id);\n        }\n      }\n    }\n\n    const decisions = []; // { id, side, ep, filActive, filWidth }\n    // Unit sides behind a worktop's end waterfall (Sales row 149).\n    const wfCovered = waterfallCoveredEndSides(cabinets);\n    const shifts    = []; // { id, dx, dy }\n    for (const cab of snapshot) {\n      if (!toEvaluate.has(cab.id)) continue;\n      // KNEEHOLE DRAWER UNIT (Better Bedrooms, schema \"hungBetween\"; Arden,\n      // 2026-11-22): the drawer box hangs between end panels, so each side\n      // gets a panel from its top down to the FLOOR (toFloor) - on an open\n      // side, and beside a unit no taller than it too, where the panel also\n      // covers that unit's end (it drops its own: epDecideActive). Beside a\n      // taller unit that unit keeps its own panel and the kneehole hangs off\n      // it; against a wall, no panel.\n      if (isHungBetweenUnit(cab)) {\n        const kr = epVerticalRange(cab);\n        const full = { bottom: 0, top: kr.top };\n        for (const side of ['left', 'right']) {\n          const nbr = epFindNeighbourOnSide(cab, side, full, snapshot);\n          const taller = !!(nbr && epVerticalRange(nbr).top > kr.top + END_PANEL_AUTO_TOL_MM);\n          const wall = nbr ? null : epWallGapOnSide(epCarcaseSides(cab)[side], epUserSideOutward(cab, side), snapshot, cab.id, full);\n          const atWall = !!(wall && wall.gap != null && wall.gap <= FILLER_MAX_GAP_MM);\n          decisions.push({ id: cab.id, side, ep: !taller && !atWall, toFloor: true,\n                           filActive: false, filWidth: cab.fillers[side].widthMm });\n        }\n        continue;\n      }\n      // Corner units: the void / blank-panel side is finished by the\n      // blank panel + corner post, but the DOOR-side end is a normal\n      // exposed cabinet edge. Give just that side a free-end-aware\n      // auto end panel (no fillers - the door side runs into the run,\n      // not a wall); force the void side off so a hand-flip can never\n      // leave a stale panel behind.\n      if (cab.cornerUnit) {\n        const doorSide = cab.cornerUnit.hand === 'right' ? 'right' : 'left';\n        const voidSide = doorSide === 'left' ? 'right' : 'left';\n        const cuRange  = epVerticalRange(cab);\n        const nbr      = epFindNeighbourOnSide(cab, doorSide, cuRange, snapshot);\n        // ...and if there's no neighbour, is it against a WALL? This branch\n        // only ever asked about neighbours, so a side finishing on a wall\n        // counted as a \"free end\" and kept its panel - which then stood\n        // proud of the wall. Shows up in PENINSULA placement, where the\n        // unit butts a wall and turns into the room, so a side can meet a\n        // wall that never meets one when the unit is seated in a corner.\n        //\n        // Panel off, and no filler either - same reasoning as the L-shape\n        // arms below: a sliver between a corner unit and a wall is not\n        // something anyone wants.\n        const cuWall = nbr ? null : epWallGapOnSide(\n          epCarcaseSides(cab)[doorSide], epUserSideOutward(cab, doorSide),\n          snapshot, cab.id, cuRange);\n        const cuAgainstWall = !!(cuWall && cuWall.gap != null &&\n                                 cuWall.gap <= FILLER_MAX_GAP_MM);\n        // A FREE-STANDING APPLIANCE at the door end carrying its own panel on\n        // that side finishes the joint, so this unit drops its panel rather\n        // than standing a second one beside it (Arden, 2026-10-13: a\n        // Dishwasher off the end of a peninsula corner unit). The neighbour\n        // test above allows 6mm, and an appliance stands its panel AND its\n        // fitting gap off its carcase - snapped against this unit's own panel\n        // the faces miss by more than that, so the end read as free and both\n        // panels stayed. Here the carcases may be up to two panels and a gap\n        // apart (110mm).\n        const cuAppliance = cornerDoorEndAtAppliance(cab, snapshot);\n        decisions.push({\n          id: cab.id, side: doorSide,\n          ep: (cuAgainstWall || cuAppliance) ? false : epDecideActive(cab, nbr),\n          filActive: false, filWidth: cab.fillers[doorSide].widthMm\n        });\n        decisions.push({\n          id: cab.id, side: voidSide,\n          ep: false, filActive: false, filWidth: cab.fillers[voidSide].widthMm\n        });\n        continue;\n      }\n      // L-shape AND diagonal-corner units - each \"arm\" has one open\n      // END (the LEFT toggle on one arm, RIGHT on the other; see\n      // epLShapeEndFaceWorld for the per-hand mapping). Apply the\n      // same free-end / neighbour-wins / wall-touches rules as a\n      // normal cabinet, just against the arm-end face instead of the\n      // bbox L/R sides. Crucially: NO auto-fill on these unit types\n      // - they seat into a room corner so both arm faces typically\n      // run flush along walls; the user does not want a filler\n      // sliver between the cab and the wall.\n      // L-shape AND diagonal corner units share identical arm-END\n      // geometry (the diagonal only replaces the inner right-angle\n      // with a 45\u00B0 door; the two open arm ends are the same edges at\n      // x=W and y=0). Auto-detect each arm end with the standard\n      // free-end / neighbour-wins / wall-touches rules against the\n      // arm-end face (epLShapeEndFaceWorld handles both markers). No\n      // auto-fill - they seat into a room corner so both arm faces\n      // typically run flush along walls and the user doesn't want a\n      // filler sliver. Tall diagonal larders (walk-in 1154 + standard\n      // 1013) force BOTH arm panels ON - larder-height finished panels\n      // by design. Panels can still be toggled manually.\n      if (cab.lShapeUnit || cab.diagonalCornerUnit) {\n        // Diagonal corner LARDERS (standard 1013 + walk-in 1154) always carry a\n        // finished end panel on BOTH arm ends - by design, never auto-removed\n        // against a wall/neighbour. Detect the larder by height (\u22651500mm) as\n        // well as a 'tall' category string, so it fires for the real product\n        // regardless of how its category handle is spelled (base/wall diagonal\n        // corners are \u2264900mm and correctly fall through to normal auto-detect).\n        const forceOn = !!cab.diagonalCornerUnit\n          && (/^tall/i.test(cab.category || '') || cab.walkInLarder === true || (cab.heightMm || 0) >= 1500);\n        const myRange = epVerticalRange(cab);\n        for (const side of ['left', 'right']) {\n          let ep;\n          if (forceOn) {\n            ep = true;\n          } else {\n            const face = epLShapeEndFaceWorld(cab, side);\n            const nbr  = epLShapeFindEndNeighbour(cab, face, myRange, snapshot);\n            if (nbr) {\n              ep = epDecideActive(cab, nbr);\n            } else {\n              const wg = epWallGapOnSide(face, face.outward, snapshot, cab.id, myRange);\n              ep = !(wg && wg.gap < END_PANEL_AUTO_TOL_MM);\n            }\n          }\n          decisions.push({\n            id: cab.id, side, ep,\n            filActive: false,\n            filWidth: cab.fillers[side]?.widthMm || FILLER_DEFAULT_MM\n          });\n        }\n        continue;\n      }\n      // Radius units - the curved face IS the finished end of the\n      // run (no panel needed); the opposite side abuts the next\n      // cabinet in the run. Auto-spawned filler + backing pieces\n      // (cab.radiusGroup) are decorative add-ons that should not get\n      // end panels or fillers auto-detected either.\n      if (cab.radiusUnit || cab.radiusGroup) continue;\n      // Freestanding appliances are the user's to panel (see the note on the\n      // snapshot above). A built-under double oven also fills its opening\n      // between two units, so its neighbours drop theirs against it (Arden,\n      // 2026-10-12; epDecideActive: neighbour is an appliance).\n      if (cab.freestandingAppliance) continue;\n      // A Pastry Bench Set's sides are its legs, held by syncPastrySets.\n      if (isPastrySet(cab)) continue;\n      // Belfast sink units: REQUIRED end panels - both sides forced ON\n      // (they also win against base neighbours via epDecideActive), no\n      // fillers. A per-side `userOff` (set by the confirm-gated untick\n      // in the selection panel) is the only way a side stays off, and\n      // it survives auto-detect because we honour it here.\n      if (cab.belfastSink) {\n        for (const side of ['left', 'right']) {\n          const userOff = !!cab.endPanels?.[side]?.userOff;\n          decisions.push({\n            id: cab.id, side,\n            ep: !userOff, filActive: false,\n            filWidth: cab.fillers?.[side]?.widthMm || FILLER_DEFAULT_MM\n          });\n        }\n        continue;\n      }\n      // No end panels or fillers on a no-finishing unit (Frame Shelf Unit) -\n      // cleared, so one placed before this rule loses its panels too.\n      if (isNoFinishingUnit(cab)) {\n        for (const side of ['left', 'right']) {\n          decisions.push({ id: cab.id, side, ep: false, filActive: false,\n                           filWidth: cab.fillers?.[side]?.widthMm || FILLER_DEFAULT_MM });\n        }\n        continue;\n      }\n      const grp = epCategoryGroup(cab);\n      if (grp !== 'base' && grp !== 'tall' && grp !== 'midi' && grp !== 'wall' && grp !== 'bridging') continue;\n      const myRange = epVerticalRange(cab);\n      const carc    = epCarcaseSides(cab);\n\n      // Resolve both sides' neighbour + wall gap up front so each\n      // side can consult the opposite side's state.\n      // A neighbour only finishes a side it actually COVERS: one that just\n      // clips the end (the back-panel stand-off of a peninsula this unit was\n      // dropped against) leaves the rest on show, so the side keeps its panel.\n      const coveringNeighbour = (side) => {\n        const n = epFindNeighbourOnSide(cab, side, myRange, snapshot);\n        if (!n) return null;\n        return epSideUncoveredMm(cab, side, myRange, snapshot) > EP_SIDE_OPEN_MM ? null : n;\n      };\n      const neighbour = {\n        left:  coveringNeighbour('left'),\n        right: coveringNeighbour('right')\n      };\n      const wgL = neighbour.left  ? null : epWallGapOnSide(carc.left,  epUserSideOutward(cab, 'left'),  snapshot, cab.id, myRange);\n      const wgR = neighbour.right ? null : epWallGapOnSide(carc.right, epUserSideOutward(cab, 'right'), snapshot, cab.id, myRange);\n      const wallGap  = { left: wgL ? wgL.gap : null, right: wgR ? wgR.gap : null };\n      const wallTall = { left: !!(wgL && wgL.tall),  right: !!(wgR && wgR.tall) };\n      // Did the filler anchor to a DOOR LINE panel? The trim engine needs to\n      // know: the plinth / cornice has to run PAST the filler by the placement\n      // recess to meet the panel's own (recessed) run at the corner.\n      const wallDoorLine = { left: !!(wgL && wgL.doorLine), right: !!(wgR && wgR.doorLine) };\n      // The panel's own thickness: the trim run has to cross it as well as the\n      // filler before the recess, or it lands one panel-thickness short.\n      const wallDoorLineThick = { left: (wgL && wgL.doorLineThickMm) || 0,\n                                  right: (wgR && wgR.doorLineThickMm) || 0 };\n      // If a side faces another cabinet in the 6-100mm \"constrained\n      // gap\" zone, turn off the auto end panel on that side. The\n      // toEvaluate filter above already restricts who runs this\n      // logic (= moved cabs + their geometric neighbours), so a pair\n      // of unrelated static cabs elsewhere in the layout doesn't get\n      // their panel state churned by an unrelated drag.\n      const constrainedCab = (side) => {\n        const mySide = carc[side];\n        // A real constraint sits OUTWARD of this face (where an end panel\n        // would go), 6-146mm away. Project each candidate onto the face's\n        // outward normal and reject anything at/behind the face. Without\n        // this a NARROW unit (e.g. 150mm) matches its own run-partner's far\n        // side - which lies within 146mm but is reached back ACROSS the\n        // unit's body, not blocking this end - and wrongly drops the panel.\n        const outward = epUserSideOutward(cab, side);\n        const baseX = mySide.p1.x, baseY = mySide.p1.y;\n        // Only a unit facing MOST of this end constrains it - one that just\n        // clips it (a peninsula's back-panel stand-off) leaves the end on\n        // show, the same rule as coveringNeighbour.\n        const sLen = Math.hypot(mySide.p2.x - mySide.p1.x, mySide.p2.y - mySide.p1.y);\n        const sux = sLen ? (mySide.p2.x - mySide.p1.x) / sLen : 0;\n        const suy = sLen ? (mySide.p2.y - mySide.p1.y) / sLen : 0;\n        const overlapMm = (o) => {\n          const a = (o.p1.x - baseX) * sux + (o.p1.y - baseY) * suy;\n          const b = (o.p2.x - baseX) * sux + (o.p2.y - baseY) * suy;\n          return Math.max(0, Math.min(sLen, Math.max(a, b)) - Math.max(0, Math.min(a, b)));\n        };\n        for (const other of snapshot) {\n          if (other.id === cab.id) continue;\n          const grp = epCategoryGroup(other);\n          if (grp !== 'base' && grp !== 'tall' && grp !== 'midi' && grp !== 'wall' && grp !== 'bridging' && !other.cornerUnit) continue;\n          if (!epRangesOverlap(myRange, epVerticalRange(other))) continue;\n          const oSides = epAllSides(other);\n          for (const k of ['front', 'back', 'left', 'right']) {\n            const oSide = oSides[k];\n            // A machine with nothing on this side does not finish our end, so\n            // it must not kill our auto panel either - we are still on show.\n            if (!epFaceIsFinished(other, k)) continue;\n            if (!epLinesCoincide(mySide, oSide, FILLER_MAX_GAP_MM)) continue;\n            if (overlapMm(oSide) < sLen - EP_SIDE_OPEN_MM) continue;\n            const omx = (oSide.p1.x + oSide.p2.x) / 2, omy = (oSide.p1.y + oSide.p2.y) / 2;\n            const signed = (omx - baseX) * outward.x + (omy - baseY) * outward.y;\n            if (signed < EP_DEPTH_TOL_MM) continue;   // at/behind the face (e.g. run partner across the body) - not a constraint\n            return true;\n          }\n        }\n        return false;\n      };\n\n      for (const side of ['left', 'right']) {\n        const opp = side === 'left' ? 'right' : 'left';\n        // TALL END PANEL - the user picked the floor-height housing side on a\n        // deep bridging unit (American fridge). That's a structural decision,\n        // not an auto-finish, so PIN it on: nudging this unit or a neighbour\n        // must never silently drop one side of the housing. Cleared by picking\n        // a different feature in the popup (which also clears userOff/toFloor).\n        // DOOR LINE panel - same reasoning as toFloor below: the user chose a\n        // structural panel that runs to the wall, so dragging a unit alongside\n        // must never silently revert it to a standard panel or drop it.\n        // An Island Designer island's end beside its Pastry Bench: the bench's\n        // back stands against this panel, so the bench never takes it off.\n        if ((cab.endPanels?.[side]?.toFloor || cab.endPanels?.[side]?.doorLine || cab.endPanels?.[side]?.pastryEnd)\n            && !cab.endPanels[side].userOff) {\n          decisions.push({ id: cab.id, side, ep: true, filActive: false,\n                           filWidth: cab.fillers[side].widthMm });\n          continue;\n        }\n        // Behind a worktop's END waterfall (the back row of an island whose\n        // front row has Waterfall End): the waterfall finishes this side, so\n        // no panel of its own (Sales row 149).\n        if (wfCovered.has(cab.id + ':' + side)) {\n          decisions.push({ id: cab.id, side, ep: false, filActive: false,\n                           filWidth: cab.fillers[side].widthMm });\n          continue;\n        }\n        const cornerHit = cornerHits.get(cab.id + ':' + side);\n        // Short of the minimum face? The unit can only be moved out along its\n        // run when its other end has room to give: no unit against it, no\n        // wall closer than the move, and no second corner (a narrow U) that\n        // the move would break. Only ever in response to something the user\n        // just did - never on a load or a redraw.\n        const cornerNeed = cornerHit ? cornerDeficitMm(cornerHit) : 0;\n        const cornerCanNudge = cornerNeed > 0 && !!movedSet\n          && !neighbour[opp]\n          && !(wallGap[opp] != null && wallGap[opp] < cornerNeed)\n          && !cornerHits.has(cab.id + ':' + opp)\n          && !cab.fillers?.[side]?.userWidth;\n        const cornerFace = cornerHit ? cornerHit.frontMm + (cornerCanNudge ? cornerNeed : 0) : 0;\n        if (neighbour[side]) {\n          // Cabinet neighbour - end-panel rule, no filler.\n          decisions.push({\n            id: cab.id, side,\n            ep: epDecideActive(cab, neighbour[side], side),\n            filActive: false, filWidth: cab.fillers[side].widthMm\n          });\n        } else if (cornerHit && cornerFace > 0) {\n          // FILLER CORNER - this end meets another unit's across the void.\n          // Filler, cut to the mitre; the partner gets the same decision\n          // from its own side of the pair. A face that has closed to nothing\n          // is a door clash, not a corner, and falls through below.\n          const _userW = cab.fillers?.[side]?.userWidth ? cab.fillers[side].widthMm : null;\n          let width = fillerCornerBoardMm(cornerHit);\n          if (cornerCanNudge) {\n            const out = epUserSideOutward(cab, side);\n            shifts.push({ id: cab.id, dx: -out.x * cornerNeed, dy: -out.y * cornerNeed });\n            width += cornerNeed;\n          }\n          decisions.push({ id: cab.id, side, ep: false, filActive: true,\n                           filWidth: _userW != null ? _userW : Math.round(width),\n                           filSetBack: 0, filUserWidth: _userW != null,\n                           filAnchorDoorLine: false, filAnchorDoorLineThick: 0,\n                           filCornerWith: cornerHit.partner });\n        } else if (wallGap[side] != null && wallGap[side] < FILLER_FLUSH_MM) {\n          // FLUSH against the wall - nothing to fill, nothing to finish. This\n          // has to come BEFORE the near-a-wall branch, which treats 0 as a gap\n          // worth filling and clamps the width up to 1mm. It cannot be done by\n          // making epWallGapOnSide return null either: the side would then fall\n          // through to \"truly free end\" and take an end panel, jammed against\n          // the wall, which is worse than the 1mm filler it replaces.\n          //\n          // EXCEPT a unit the user has just put there with its other end free\n          // (seated into a corner, say): that is the first-instance 20mm\n          // filler, with the unit moved off the wall to make room - the same\n          // as the near-a-wall branch gives a unit dropped 10mm short. Flush\n          // had swallowed it, so a unit snapped into a corner got no filler.\n          // Only on a move, so opening a saved plan never shifts its units.\n          const oppFree = !neighbour[opp] &&\n            !(wallGap[opp] != null && wallGap[opp] <= FILLER_MAX_GAP_MM) &&\n            !cornerHits.has(cab.id + ':' + opp);\n          // A side set by hand is skipped when decisions apply - so must its move.\n          if (movedSet && movedSet.has(cab.id) && oppFree && !epSideUserSet(cab, side)) {\n            const _userW = cab.fillers?.[side]?.userWidth ? cab.fillers[side].widthMm : null;\n            const width = _userW != null ? _userW : FILLER_DEFAULT_MM;\n            const shiftMm = width - wallGap[side];\n            const out = epUserSideOutward(cab, side);\n            shifts.push({ id: cab.id, dx: -out.x * shiftMm, dy: -out.y * shiftMm, wallClear: true });\n            decisions.push({ id: cab.id, side, ep: false, filActive: true, filWidth: width,\n                             filSetBack: (grp === 'base' && wallTall[side]) ? FILLER_TALL_SETBACK_MM : 0,\n                             filUserWidth: _userW != null,\n                             filAnchorDoorLine: !!wallDoorLine[side],\n                             filAnchorDoorLineThick: wallDoorLineThick[side] || 0 });\n          } else {\n            decisions.push({ id: cab.id, side, ep: false, filActive: false,\n                             filWidth: cab.fillers[side].widthMm });\n          }\n        } else if (wallGap[side] != null && wallGap[side] <= FILLER_MAX_GAP_MM) {\n          // Near a wall - filler, no end panel.\n          // A corner at the other end holds the unit too: nudging it to suit\n          // this filler would drag the corner's mitre with it.\n          const oppConstrained = !!neighbour[opp] ||\n            (wallGap[opp] != null && wallGap[opp] <= FILLER_MAX_GAP_MM) ||\n            cornerHits.has(cab.id + ':' + opp);\n          let width;\n          const _userW = cab.fillers?.[side]?.userWidth\n            ? cab.fillers[side].widthMm : null;\n          if (_userW != null) {\n            // User-set width wins outright: keep it, and do NOT nudge the\n            // cabinet to chase the gap - that is what kept snapping it back.\n            width = _userW;\n          } else if (oppConstrained) {\n            // Filler simply fills the remaining gap.\n            width = Math.max(1, Math.min(FILLER_MAX_GAP_MM, Math.round(wallGap[side])));\n          } else {\n            // First-instance default: 20mm filler, nudge the cabinet\n            // so the gap matches (gap < 20 \u2192 moves away; gap > 20 \u2192\n            // the filler simply takes the larger value, no nudge).\n            width = Math.max(FILLER_DEFAULT_MM, Math.min(FILLER_MAX_GAP_MM, Math.round(wallGap[side])));\n            const shiftMm = width - wallGap[side];\n            if (Math.abs(shiftMm) > 0.5) {\n              const out = epUserSideOutward(cab, side);\n              shifts.push({ id: cab.id, dx: -out.x * shiftMm, dy: -out.y * shiftMm, wallClear: true });\n            }\n          }\n          // Base-unit filler against a tall unit / tall end panel\n          // sits 20mm back from the door front.\n          const setBack = (grp === 'base' && wallTall[side]) ? FILLER_TALL_SETBACK_MM : 0;\n          decisions.push({ id: cab.id, side, ep: false, filActive: true, filWidth: width,\n                           filSetBack: setBack, filUserWidth: _userW != null,\n                           filAnchorDoorLine: !!wallDoorLine[side],\n                           filAnchorDoorLineThick: wallDoorLineThick[side] || 0 });\n        } else if (constrainedCab(side)) {\n          // Moved cab dropped into a constrained gap (another cab\n          // 6-100mm away). Auto end panel / filler OFF on this side\n          // - the user manages it with the manual snap / add-filler\n          // controls. Avoids the seesaw of pass2 ping-ponging the\n          // cab between two valid \"close enough\" sides.\n          decisions.push({ id: cab.id, side, ep: false, filActive: false, filWidth: cab.fillers[side].widthMm });\n        } else {\n          // Truly free end - end panel, no filler.\n          decisions.push({ id: cab.id, side, ep: true, filActive: false, filWidth: cab.fillers[side].widthMm });\n        }\n      }\n    }\n\n    // PSEUDO TALL COLUMN: a carcase-on-carcase stack is finished with\n    // ONE full-height end panel covering every unit in it, so the\n    // members' side states have to agree. Each unit still decides its\n    // own side against its own neighbours (the host races at floor\n    // level, the rider up top), then the column takes the UNION: if any\n    // member needs that side finished, they all carry it, and the\n    // panel reads as one continuous board floor-to-top - matching the\n    // single tall board it's cut and charged as. Without this a rider\n    // with a free end would render a panel floating above nothing.\n    //\n    // Worktop stacks are deliberately NOT unioned: the slab through\n    // the joint is a break point, so the lower unit's panel stops at\n    // the worktop and the upper unit's is a separate piece above it.\n    {\n      const colUnion = new Map();   // `${columnId}:${side}` \u2192 true if any member needs it\n      const decided  = new Map();   // `${id}:${side}` \u2192 decision object\n      for (const dec of decisions) decided.set(`${dec.id}:${dec.side}`, dec);\n      const members = snapshot.filter(c => c.stackColumnId != null);\n      for (const m of members) {\n        for (const side of ['left', 'right']) {\n          const dec = decided.get(`${m.id}:${side}`);\n          // Members not re-evaluated this pass keep their current state.\n          const on = dec ? dec.ep : !!(m.endPanels && m.endPanels[side] && m.endPanels[side].active);\n          if (on) colUnion.set(`${m.stackColumnId}:${side}`, true);\n        }\n      }\n      for (const m of members) {\n        for (const side of ['left', 'right']) {\n          if (!colUnion.get(`${m.stackColumnId}:${side}`)) continue;\n          const dec = decided.get(`${m.id}:${side}`);\n          if (dec) { dec.ep = true; dec.filActive = false; }\n          else decisions.push({ id: m.id, side, ep: true, filActive: false,\n                                filWidth: m.fillers?.[side]?.widthMm || FILLER_DEFAULT_MM });\n        }\n      }\n    }\n\n    const changed = new Set();\n    for (const dec of decisions) {\n      const idx = cabinets.findIndex(c => c.id === dec.id);\n      if (idx === -1) continue;\n      const cab = cabinets[idx];\n      // A side the user set by hand is theirs: the auto pass never takes it\n      // back (Julian: \"the setting does not remain and defaults back\").\n      if (epSideUserSet(cab, dec.side)) continue;\n      // An open end unit's OPEN side is its finish - no auto end panel there\n      // (Arden, 2026-10-15). Set by hand on Manual it is still allowed.\n      if (dec.ep && openEndSideOf(cab) === dec.side) dec.ep = false;\n      // A side that is part of a breakfast bar panel (backedOnBbSide) neither.\n      if (dec.ep) { const bo = backedOnBbSide(cab, cabinets); if (bo && bo.side === dec.side) dec.ep = false; }\n      const ep  = cab.endPanels || { left: defEp(),  right: defEp()  };\n      const fil = cab.fillers   || { left: defFil(), right: defFil() };\n      const curEp  = !!ep[dec.side]?.active;\n      const curFil = !!fil[dec.side]?.active;\n      const curFilW = fil[dec.side]?.widthMm;\n      const curSetBack = fil[dec.side]?.setBackMm || 0;\n      const decSetBack = dec.filSetBack || 0;\n      const decAnchorDL = !!dec.filAnchorDoorLine;\n      const decAnchorDLT = dec.filAnchorDoorLineThick || 0;\n      const curAnchorDL = !!fil[dec.side]?.anchorDoorLine;\n      // Which corner partner this filler is cut to meet, if any. Kept on the\n      // filler so moving or deleting the partner re-decides this end too.\n      const decCorner = (dec.filActive && dec.filCornerWith) ? { ...dec.filCornerWith } : null;\n      const cornerKey = (w) => (w ? w.id + ':' + w.side : '');\n      const curCorner = fil[dec.side]?.cornerWith || null;\n      const curToFloor = !!ep[dec.side]?.toFloor;\n      if (curEp !== dec.ep || curFil !== dec.filActive ||\n          (dec.toFloor != null && curToFloor !== !!dec.toFloor) ||\n          cornerKey(curCorner) !== cornerKey(decCorner) ||\n          (dec.filActive && (curFilW !== dec.filWidth || curSetBack !== decSetBack ||\n                             curAnchorDL !== decAnchorDL))) {\n        cabinets[idx] = {\n          ...cab,\n          endPanels: { ...ep,  [dec.side]: { ...defEp(),  ...ep[dec.side],  active: dec.ep, ...(dec.toFloor != null ? { toFloor: !!dec.toFloor } : {}) } },\n          fillers:   { ...fil, [dec.side]: { ...defFil(), ...fil[dec.side], active: dec.filActive, widthMm: dec.filWidth, setBackMm: decSetBack, anchorDoorLine: decAnchorDL, anchorDoorLineThickMm: decAnchorDLT, cornerWith: decCorner } }\n        };\n        changed.add(dec.id);\n      }\n    }\n    // Apply wall-clearance nudges after decisions (positions don't\n    // perturb the snapshot-based adjacency).\n    const wallCleared = new Set();\n    for (const sh of shifts) {\n      const idx = cabinets.findIndex(c => c.id === sh.id);\n      if (idx === -1) continue;\n      if (cabinets[idx].positionLocked) continue;   // POSITION LOCK\n      cabinets[idx] = { ...cabinets[idx], x: cabinets[idx].x + sh.dx, y: cabinets[idx].y + sh.dy };\n      changed.add(sh.id);\n      if (sh.wallClear) wallCleared.add(sh.id);\n    }\n\n    // Panels change the unit's VISIBLE size, and it was placed before this\n    // pass ran - so the seating is now measured against the wrong shape.\n    // Turning one ON makes it wider than the carcase the drag was clamped\n    // against, so a flush unit overhangs the wall. Turning one OFF leaves\n    // its thickness behind as a gap: the corner snap had seated the PANEL\n    // FACE on the wall, then the panel went away and the carcase stayed\n    // 20mm off. Effectively the order was drop, snap, remove panel.\n    //\n    // So re-seat here, with the panels now settled - drop, remove panel,\n    // THEN snap. A unit the user just MOVED gets the full snap, which can\n    // close a gap as well as push out of a wall; anything else this pass\n    // merely touched gets containment only, so a panel decision elsewhere\n    // in the plan can never drag a settled unit around. One pass, not a\n    // loop: re-seating feeds adjacency, and chasing that would seesaw.\n    const others0 = () => cabinets;\n    for (const id of changed) {\n      const idx = cabinets.findIndex(c => c.id === id);\n      if (idx === -1) continue;\n      const cab = cabinets[idx];\n      if (cab.positionLocked) continue;   // POSITION LOCK\n      // A unit just moved OFF a wall to make room for its filler must not get\n      // the full snap: the wall snap measures the carcase (30mm reach) and\n      // would pull it straight back on, under its own filler.\n      const justMoved = !!(movedSet && movedSet.has(id)) && !wallCleared.has(id);\n      let fixed;\n      if (justMoved) {\n        const others = others0().filter(o => o.id !== id);\n        const obstacles = [...perimeterObstaclesFor(cab),\n                           ...epDoorLinePanelObstacles(id)];\n        fixed = snapAndClamp(cab, cab.x, cab.y, room, others, obstacles,\n                             roomConfig.wallOpenings || []);\n      } else {\n        fixed = clampToRoom(cab, cab.x, cab.y, room);\n      }\n      if (Math.abs(fixed.x - cab.x) > 0.01 || Math.abs(fixed.y - cab.y) > 0.01) {\n        cabinets[idx] = { ...cab, x: fixed.x, y: fixed.y };\n      }\n    }\n\n    // The worktop a floor-standing panel (base, island, breakfast bar - not a\n    // wall or tall one) stands under, as its resting height, or null. The\n    // worktops are built once, on first use, for the whole pass.\n    let _wtSlabs = null;\n    const worktopRestOverPanel = (panel, cx, cy) => {\n      const ut = Catalogue.getUnitType?.(panel.unitTypeId);\n      if (!ut || /wall/i.test(ut.name || '') || !((ut.carcaseHeightMm || panel.heightMm || 0) <= 1000)) return null;\n      if (!_wtSlabs) { try { _wtSlabs = buildWorktops() || []; } catch (e) { _wtSlabs = []; } }\n      const inside = (poly) => {\n        let hit = false;\n        for (let a = 0, b = poly.length - 1; a < poly.length; b = a++) {\n          const pa = poly[a], pb = poly[b];\n          if (((pa.y > cy) !== (pb.y > cy)) && (cx < (pb.x - pa.x) * (cy - pa.y) / ((pb.y - pa.y) || 1e-9) + pa.x)) hit = !hit;\n        }\n        return hit;\n      };\n      const s = _wtSlabs.find(w => w && !w.cushionTop && Array.isArray(w.polygon) && w.polygon.length > 2 && inside(w.polygon));\n      return (s && s.restMm > 0) ? s.restMm : null;\n    };\n    // Free-standing end-panel UNITS adopt the height + depth of the\n    // cabinet they're butted against - mirroring the auto side stubs, so a\n    // panel beside a reduced-depth or tall unit re-fits automatically.\n    // Detection reuses epFindNeighbourOnSide against the snapshot (its\n    // `other` filter already skips non-cabinet units, so panels never\n    // match each other). A panel in open space keeps its default dims.\n    // Idempotent: once matched it stops changing, so no settle churn.\n    for (let i = 0; i < cabinets.length; i++) {\n      const panel = cabinets[i];\n      if (!panel.endPanelUnit) continue;\n      const range = epVerticalRange(panel);\n      const host = epFindNeighbourOnSide(panel, 'left',  range, snapshot)\n                || epFindNeighbourOnSide(panel, 'right', range, snapshot);\n      // Running dims + centre. The host rule moves the panel along the\n      // FRONT-BACK axis and the filler fit along the SIDE axis, so the two\n      // compose on one centre instead of fighting over x / y.\n      let newW = panel.widthMm, newD = panel.depthMm, newH = panel.heightMm;\n      let ncx = panel.x + panel.widthMm / 2, ncy = panel.y + panel.depthMm / 2;\n      // A back panel runs the length of the units it backs: it takes their\n      // height, never one unit's depth. Nor does a panel given its length by\n      // hand.\n      if (host && (isBackPanelUnit(panel) || panel.lengthManual)) {\n        newH = host.heightMm || panel.heightMm;\n      } else if (host && !isFillerPanelUnit(panel)) {\n        // (Not a filler panel: it keeps the size it is given, not its\n        // neighbour's height and depth - row 22.)\n        // A TALL end panel takes only a tall unit's height: beside a base\n        // unit it stays a tall panel, at its product's height (Sales bug\n        // sheet row 95: tall panels either side of a nib shrank to 870).\n        const ownH = panelOwnHeightMm(panel);\n        newH = (isTallPanelHeight(ownH) && !isTallPanelHeight(host.heightMm || 0))\n          ? ownH : (host.heightMm || panel.heightMm);\n        const hostD = host.depthMm || panel.depthMm;\n        // Carcase depth + door proud, so the panel covers the door front.\n        newD = hostD + END_PANEL_DOOR_PROUD_MM;\n        // Align the panel's BACK to the host's back so the extra depth\n        // extends FORWARD (over the door), not behind. Shift only along the\n        // front\u2013back axis (host rotation); the against-the-side position is\n        // preserved. Panel centre = host centre pushed forward by proud/2.\n        const th  = (host.rotationDeg || 0) * Math.PI / 180;\n        const fdx = Math.sin(th), fdy = -Math.cos(th);          // front (room) direction\n        const hostF = (host.x + host.widthMm / 2) * fdx + (host.y + host.depthMm / 2) * fdy;\n        const panelF = ncx * fdx + ncy * fdy;\n        const delta = (hostF + END_PANEL_DOOR_PROUD_MM / 2) - panelF;   // move along frontDir only\n        ncx += delta * fdx; ncy += delta * fdy;\n      } else if (!isFillerPanelUnit(panel)) {\n        // No unit to take the height from, but under a worktop (a panel under\n        // a breakfast bar or a peninsula's end): cut to the units' height, the\n        // worktop's underside - 870 on a standard run (Arden, 2026-10-20).\n        const rest = worktopRestOverPanel(panel, ncx, ncy);\n        if (rest) newH = rest;\n      }\n      // A FILLER panel closes the gap it is dropped into, the same job a\n      // unit's own filler does - so it is measured the same way, to whichever\n      // is nearest on each side: a wall, a pillar or chimney breast, another\n      // panel, or a unit (its END PANEL face where it has one, which is why\n      // this measures effective faces rather than carcases). An END panel is a\n      // fixed-thickness board and is left alone.\n      //\n      // Only gaps within a filler's reach count: dropped in open space with a\n      // wall two metres off, the nearest face is still that wall, and without\n      // the reach test the panel would jump to full width and slide at it.\n      // A side already flush reads null and contributes nothing, so a fitted\n      // filler is stable - it fits once and then stops moving.\n      if (isFillerPanelUnit(panel) && !panel.widthManual) {\n        const reach = (g) => (g != null && Math.abs(g) <= FILLER_MAX_GAP_MM) ? g : 0;\n        const dL = reach(epClosestForwardGap(panel, 'left',  { includeRoomFeatures: true, includePanels: true }));\n        const dR = reach(epClosestForwardGap(panel, 'right', { includeRoomFeatures: true, includePanels: true }));\n        if (dL || dR) {\n          // Capped at the widest filler sold - past that it is not one board\n          // and the cut list could not make it.\n          newW = Math.max(1, Math.min(fillerStockOf(panel).widthMm || FILLER_MAX_GAP_MM, panel.widthMm + dL + dR));\n          // Normally each face simply moves onto what it measured, which also\n          // covers the case where the two cancel out (30mm one side, 30mm of\n          // overlap the other): same width, slid across into the gap.\n          let takeL = dL, takeR = dR;\n          const grow  = newW - panel.widthMm;   // what the cap let us apply\n          const asked = dL + dR;                // what the two sides wanted\n          if (Math.abs(grow - asked) > 1e-6) {\n            // Capped. Share what we can in the proportion the sides asked for,\n            // so it still sits where the gaps put it rather than jumping to\n            // one end of them.\n            if (Math.abs(asked) > 1e-6) { takeL = grow * (dL / asked); takeR = grow - takeL; }\n            else                        { takeL = grow / 2;            takeR = grow - takeL; }\n          }\n          const out   = epUserSideOutward(panel, 'right');\n          const shift = (takeR - takeL) / 2;\n          ncx += out.x * shift; ncy += out.y * shift;\n        }\n      }\n      // A back panel fills the gap it stands in, end to end: from whatever it\n      // butts at one end to whatever it butts at the other - a unit, another\n      // panel, a wall, or the inside of a waterfall (Arden, 2026-10-20: Karen\n      // Pratt's ran from an end panel through the waterfall). Not once its\n      // length has been typed in.\n      let board = null;\n      if (isBackPanelUnit(panel) && !panel.lengthManual) {\n        const fit = panelLengthGap({ ...panel, widthMm: newW, depthMm: newD, x: ncx - newW / 2, y: ncy - newD / 2 },\n                                   { extraFaces: waterfallInnerFaces(), maxMm: panelMaxLengthMm(panel) });\n        if (fit) {\n          newD = fit.lengthMm; ncx = fit.cx; ncy = fit.cy;\n          board = panelBoardFor(panel, newD);\n        }\n      }\n      if (panel.heightManual) newH = panel.heightMm;\n      const nx = ncx - newW / 2, ny = ncy - newD / 2;\n      if (Math.abs(panel.widthMm - newW) > 0.5 || Math.abs(panel.heightMm - newH) > 0.5 ||\n          Math.abs(panel.depthMm - newD) > 0.5 ||\n          Math.abs(panel.x - nx) > 0.5 || Math.abs(panel.y - ny) > 0.5 ||\n          (board && board.id !== panel.unitTypeId)) {\n        cabinets[i] = { ...panel, ...(board ? panelProductFields(panel, board) : {}),\n                        widthMm: newW, heightMm: newH, depthMm: newD, x: nx, y: ny };\n        changed.add(panel.id);\n      }\n    }\n    return changed;\n  }\n\n  const EP_GAP_LOOKUP_TOL_MM = 60;\n  // Effective pass needs more headroom - two 50mm radius / square\n  // panels meeting face-to-face leave a 100mm gap between the cabs'\n  // CARCASES, so the effective faces are up to (50+50) mm apart when\n  // the cab was dropped carcase-flush (panels then overlap into each\n  // other's body). 110mm covers the worst case with a small margin.\n  const EP_EFF_LOOKUP_TOL_MM = 110;\n\n  // Signed distance to move `cab` along `outward` so its side line\n  // (mySide) meets the neighbour's side line (otherSide). Positive =\n  // there's a GAP (move toward the neighbour). Negative = the sides\n  // OVERLAP (move away). Sides are assumed parallel.\n  function epSignedGap(mySide, otherSide, outward) {\n    const mx = (otherSide.p1.x + otherSide.p2.x) / 2;\n    const my = (otherSide.p1.y + otherSide.p2.y) / 2;\n    return (mx - mySide.p1.x) * outward.x + (my - mySide.p1.y) * outward.y;\n  }\n\n  // Shifts a cabinet so its side meets the nearest parallel neighbour\n  // side, resolving GAPS and OVERLAPS alike (signed shift).\n  //   useEffective=false \u2192 carcase-to-carcase (run-join, pre-detect):\n  //     pulls a near-but-not-snapped unit flush so auto-detect sees\n  //     the adjacency.\n  //   useEffective=true  \u2192 effective-to-effective (post-detect):\n  //     accounts for each cabinet's surviving panels/fillers so the\n  //     final faces touch (closing a void, or pushing out of a\n  //     surviving panel).\n  function settleCabinet(cabId, useEffective) {\n    if (cabPositionLocked(cabId)) return;   // POSITION LOCK - stays where it is\n    // The run-join (carcase) pass settles BOTH sides, so a unit dropped\n    // into a run sits flush against a neighbour on each side. Leaving a\n    // side un-flushed makes auto-detect miss that adjacency and give\n    // BOTH units a free-end panel there - a spurious double panel. The\n    // effective pass stays one-sided: a surviving end panel can't be\n    // made flush on both sides at once.\n    const maxSides = useEffective ? 1 : 2;\n    for (let pass = 0; pass < maxSides; pass++) {\n      const idx = cabinets.findIndex(c => c.id === cabId);\n      if (idx === -1) return;\n      const cab     = cabinets[idx];\n      const myRange = epVerticalRange(cab);\n      const mySides = useEffective ? epAllSides(cab) : epCarcaseSides(cab, { noEndPanelReach: true });\n\n      let settled = false;\n      for (const sideKey of ['left', 'right']) {\n        const mySide  = mySides[sideKey];\n        const outward = epUserSideOutward(cab, sideKey);\n        // Same side-aware band as neighbour detection - without it a base unit\n        // beside a fridge housing never settles against the floor-height panel\n        // and is left overlapping it.\n        const mySideRange = epSideVerticalRange(cab, sideKey, myRange);\n        let bestAbs = Infinity, bestSigned = 0;\n        for (const other of cabinets) {\n          if (other.id === cab.id) continue;\n          // The walk-in larder this unit stands in is no neighbour to settle\n          // against: its box faces are the larder's OUTSIDE, and the inside\n          // gables are placement's job (settleIntoWalkInLarder).\n          if (isWalkInLarder(other) && unitInsideWalkInLarder(cab, cab.x || 0, cab.y || 0, other)) continue;\n          // ...and the other way round: a larder settles against what is\n          // outside it, never the units fitted inside it (its set).\n          if (isWalkInLarder(cab) && ((other.walkInSet && other.walkInSet.hostId === cab.id)\n              || unitInsideWalkInLarder(other, other.x || 0, other.y || 0, cab))) continue;\n          const grp = epCategoryGroup(other);\n          if (grp !== 'base' && grp !== 'tall' && grp !== 'midi' && grp !== 'wall' && grp !== 'bridging' && !other.cornerUnit) continue;\n          const oSides = useEffective ? epAllSides(other) : epCarcaseSides(other, { noEndPanelReach: true });\n          const tol = useEffective ? EP_EFF_LOOKUP_TOL_MM : EP_GAP_LOOKUP_TOL_MM;\n          const oRangePlain = epVerticalRange(other);\n          const oRangeBySide = {\n            left:  epSideVerticalRange(other, 'left',  oRangePlain),\n            right: epSideVerticalRange(other, 'right', oRangePlain)\n          };\n          // A DOOR LINE tall end panel is solid: settle against its faces too,\n          // so a unit dragged up the return STOPS at the panel and sits flush\n          // against it instead of travelling straight through. Keyed in\n          // alongside the four bbox sides so it shares the same scoring; its\n          // band is the tall unit's full height (oRangePlain).\n          const _dlKeys = [];\n          const _dlFaces = epDoorLinePanelFaces(other);\n          for (let _i = 0; _i < _dlFaces.length; _i++) {\n            const _k = 'doorline' + _i;\n            oSides[_k] = _dlFaces[_i];\n            _dlKeys.push(_k);\n          }\n          for (const key of ['front', 'back', 'left', 'right', ..._dlKeys]) {\n            const oRange = (key === 'left' || key === 'right') ? oRangeBySide[key] : oRangePlain;\n            if (!epRangesOverlap(mySideRange, oRange)) continue;\n            if (!epLinesCoincide(mySide, oSides[key], tol)) continue;\n            const signed = epSignedGap(mySide, oSides[key], outward);\n            // A line as far in as this cab's OTHER side is that side's to meet,\n            // not this one's: an 18mm free end panel set against a unit's end\n            // had both its faces within reach of the unit's side, and its outer\n            // face was pulled onto it - into the unit - on release (Arden,\n            // 2026-10-22, Karen Pratt items 39-41). A unit is never this thin.\n            if (signed < 0 && -signed >= (cab.widthMm || 0) - 0.5) continue;\n            // Effective pass: only an OVERLAP is ever resolved (see below), so\n            // only overlaps compete - the biggest wins. Letting a nearer GAP\n            // win first hid the overlap: a TH oven housing (end panel + profile,\n            // 48mm) dropped flush to a 150 base unit stayed inside it, because\n            // a wall unit 42mm off the panel was \"nearer\" (Arden, 2026-10-21).\n            if (useEffective) {\n              if (signed < -0.5 && -signed > (bestAbs === Infinity ? 0 : bestAbs)) { bestAbs = -signed; bestSigned = signed; }\n              continue;\n            }\n            if (Math.abs(signed) < bestAbs) { bestAbs = Math.abs(signed); bestSigned = signed; }\n          }\n        }\n        const tolMax = useEffective ? EP_EFF_LOOKUP_TOL_MM : EP_GAP_LOOKUP_TOL_MM;\n        if (bestAbs === Infinity || bestAbs < 0.5 || bestAbs > tolMax) continue;\n        // Effective pass: ONLY resolve overlaps (signed < 0) so a\n        // cab with deactivated panels gets pushed clear of a surviving\n        // neighbour panel. Skip GAP cases (signed > 0) - the cab\n        // stays at its dropped position and the user resolves any\n        // resulting void with the manual snap / add-filler controls.\n        // Without this, settle would pick the \"closer side\" each pass\n        // and seesaw the cab between two valid neighbours.\n        if (useEffective && bestSigned > 0) continue;\n        // A corner unit seated against a room wall at its OTHER end stays\n        // there: closing this gap would pull it off the wall it was snapped\n        // to (corner units win in the corner - Arden, 2026-10-14). The gap is\n        // the corner post's to take up.\n        if (bestSigned > 0 && (cab.cornerUnit || cab.lShapeUnit || cab.diagonalCornerUnit)) {\n          const oppOut = epUserSideOutward(cab, sideKey === 'left' ? 'right' : 'left');\n          const wallGap = roomWallAheadGap(visualBbox(cab), oppOut);\n          if (wallGap != null && wallGap < 1) continue;\n        }\n        cabinets[idx] = {\n          ...cabinets[idx],\n          x: cabinets[idx].x + outward.x * bestSigned,\n          y: cabinets[idx].y + outward.y * bestSigned\n        };\n        settled = true;\n        break;   // recompute the cabinet's sides before settling the other\n      }\n      if (!settled) return;   // nothing left to settle\n    }\n  }\n\n  // Re-measures every active filler's wall gap from the cabinet's\n  // CURRENT (settled) position and sets the width to fill it. Run\n  // as the LAST step after all panel/position changes so the filler\n  // always matches the real gap - this is what makes an end-of-run\n  // unit fill its gap to the wall (rather than defaulting to 20mm).\n  // ---- Filler corners ------------------------------------------------\n  // Two units meeting in a corner with no corner unit between them. Each\n  // stops short of the corner, their door lines cross, and the space behind\n  // is a void. On site that corner is finished with the two units' own\n  // fillers, cut to meet and mitred into an L-shaped post - the Corner Post\n  // + Void unit, without the unit - and the worktop runs over the void to\n  // the room corner. The geometry lives in engine-filler-corners; these\n  // adapt planner cabinets to it.\n  //\n  // Every run that takes fillers. A corner only ever pairs like with like\n  // (see fillerCornerPairGroup), because a filler is the height of its own\n  // doors.\n  const FILLER_CORNER_GROUPS = new Set(['base', 'wall', 'bridging', 'tall', 'midi']);\n  // A bridging unit hangs on the same line as a wall unit and meets one in\n  // a corner exactly as another wall unit would.\n  const fillerCornerPairGroup = (g) => (g === 'bridging' ? 'wall' : g);\n\n  function fillerCornerEligible(cab) {\n    if (!cab || !(cab.widthMm > 0) || !(cab.depthMm > 0)) return false;\n    // These finish their own corners - post, void and all.\n    if (cab.cornerUnit || cab.lShapeUnit || cab.diagonalCornerUnit) return false;\n    if (cab.radiusUnit || cab.radiusGroup || cab.endPanelUnit) return false;\n    if (cab.freestandingAppliance) return false;\n    return FILLER_CORNER_GROUPS.has(epCategoryGroup(cab));\n  }\n\n  // One end of a unit, in the engine's terms. epCarcaseSides lists each side\n  // line from its FRONT point, so p1 is the carcase-front corner the filler\n  // grows out of.\n  function fillerCornerEnd(cab, side) {\n    const carc = epCarcaseSides(cab, { noBackPanelReach: true });\n    return {\n      id: cab.id, side,\n      group:  fillerCornerPairGroup(epCategoryGroup(cab)),\n      band:   epVerticalRange(cab),\n      corner: carc[side].p1,\n      out:    epUserSideOutward(cab, side),\n      front:  epUserSideOutward(cab, 'front')\n    };\n  }\n\n  // Every corner the plan has room for, whether or not its fillers are on\n  // yet - what Auto switches to, and what the popup measures when a corner\n  // end is changed to a filler by hand. An end that already butts a unit, or\n  // carries a pinned structural panel, is spoken for and never joins one.\n  function fillerCornerCandidates(scope) {\n    const ends = [];\n    for (const c of scope) {\n      if (!fillerCornerEligible(c)) continue;\n      const range = epVerticalRange(c);\n      for (const side of ['left', 'right']) {\n        const e = c.endPanels?.[side];\n        if (e && (e.toFloor || e.doorLine) && !e.userOff) continue;\n        if (epFindNeighbourOnSide(c, side, range, scope)) continue;\n        ends.push(fillerCornerEnd(c, side));\n      }\n    }\n    return findFillerCorners(ends, { maxMm: FILLER_MAX_GAP_MM, depthMm: CORNER_FILLER_DEPTH_MM });\n  }\n\n  // Corners between ends whose fillers are ON. With `reaching`, both fillers\n  // must also actually get to the mitre - what the renderers need, because a\n  // filler the user has sized short of the corner is just a filler.\n  function activeFillerCorners({ reaching = false, scope = cabinets } = {}) {\n    const byId = new Map();\n    const ends = [];\n    for (const c of scope) {\n      if (!fillerCornerEligible(c)) continue;\n      byId.set(c.id, c);\n      for (const side of ['left', 'right']) {\n        if (c.fillers?.[side]?.active) ends.push(fillerCornerEnd(c, side));\n      }\n    }\n    if (ends.length < 2) return new Map();\n    const width = (e) => byId.get(e.id)?.fillers?.[e.side]?.widthMm || 0;\n    return findFillerCorners(ends, {\n      maxMm: FILLER_MAX_GAP_MM,\n      depthMm: CORNER_FILLER_DEPTH_MM,\n      // A face closed to nothing is a door clash, not a corner - mitring it\n      // would turn the strip inside out.\n      accept: reaching\n        ? (a, b, g) => g.a.frontMm > 0 && g.b.frontMm > 0\n                    && width(a) >= fillerCornerBoardMm(g.a) - CORNER_FILLER_TOUCH_MM\n                    && width(b) >= fillerCornerBoardMm(g.b) - CORNER_FILLER_TOUCH_MM\n        : null\n    });\n  }\n\n  function resizeFillers() {\n    // Fillers that meet in a corner are cut to the mitre - in Manual mode as\n    // well as Auto, so switching both ends to fillers by hand joins them.\n    const corners = activeFillerCorners();\n    for (let i = 0; i < cabinets.length; i++) {\n      const cab = cabinets[i];\n      if (!cab.fillers || cab.cornerUnit) continue;\n      if (cab.radiusUnit || cab.radiusGroup) continue;\n      if (cab.lShapeUnit) continue;\n      if (cab.diagonalCornerUnit) continue;\n      const carc = epCarcaseSides(cab);\n      let mutated = false;\n      const next = {\n        left:  { ...cab.fillers.left },\n        right: { ...cab.fillers.right }\n      };\n      for (const side of ['left', 'right']) {\n        if (!next[side]?.active) continue;\n        // A width the user typed in the popup is theirs - the auto re-fit\n        // must not keep pulling it back to the measured gap.\n        if (next[side].userWidth) continue;\n        const hit = corners.get(cab.id + ':' + side);\n        if (hit) {\n          const w = Math.round(fillerCornerBoardMm(hit));\n          if (w !== next[side].widthMm) { next[side].widthMm = w; mutated = true; }\n          continue;\n        }\n        const res = epWallGapOnSide(carc[side], epUserSideOutward(cab, side), cabinets, cab.id, epVerticalRange(cab));\n        if (res == null) continue;   // no wall - leave width untouched\n        // The gap has closed to nothing: the filler has nothing left to fill,\n        // so it comes OFF rather than being clamped up to a 1mm slither. This\n        // is the other half of FILLER_FLUSH_MM - the detect pass decides a\n        // flush side gets no filler, and this stops an already-active one\n        // being re-measured into a 1mm one behind its back.\n        if (res.gap < FILLER_FLUSH_MM) {\n          next[side].active = false;\n          mutated = true;\n          continue;\n        }\n        const w = Math.max(1, Math.min(FILLER_MAX_GAP_MM, Math.round(res.gap)));\n        if (w !== next[side].widthMm) { next[side].widthMm = w; mutated = true; }\n      }\n      if (mutated) cabinets[i] = { ...cab, fillers: next };\n    }\n  }\n\n  // Units with an END running along this opening's face within reach of it -\n  // the ends whose finish can change when the opening arrives, moves, changes\n  // size or goes. Only ends: a unit on the opening's own wall has its back\n  // there, and re-deciding it would only reset panels the user set by hand.\n  // For L-shape and diagonal units the ends are the arm-end faces.\n  function epUnitsBesideOpening(op) {\n    const h = epOpeningHoles(null, [op])[0];\n    if (!h) return [];\n    const hl = Math.hypot(h.b.x - h.a.x, h.b.y - h.a.y);\n    if (hl < 1) return [];\n    const ux = (h.b.x - h.a.x) / hl, uy = (h.b.y - h.a.y) / hl;\n    const reach = FILLER_MAX_GAP_MM + END_PANEL_AUTO_THICK_MM + 10;\n    const facesAlong = (f) => {\n      const fl = Math.hypot(f.p2.x - f.p1.x, f.p2.y - f.p1.y);\n      if (fl < 1) return false;\n      if (Math.abs(((f.p2.x - f.p1.x) / fl) * uy - ((f.p2.y - f.p1.y) / fl) * ux) > 0.06) return false;\n      if (Math.abs((f.p1.x - h.a.x) * -uy + (f.p1.y - h.a.y) * ux) > reach) return false;\n      const s1 = (f.p1.x - h.a.x) * ux + (f.p1.y - h.a.y) * uy;\n      const s2 = (f.p2.x - h.a.x) * ux + (f.p2.y - h.a.y) * uy;\n      return Math.min(hl, Math.max(s1, s2)) - Math.max(0, Math.min(s1, s2)) > 0;\n    };\n    const ids = [];\n    for (const cab of cabinets) {\n      if (!cab || !(cab.widthMm > 0) || !(cab.depthMm > 0)) continue;\n      const ends = (cab.lShapeUnit || cab.diagonalCornerUnit)\n        ? [epLShapeEndFaceWorld(cab, 'left'), epLShapeEndFaceWorld(cab, 'right')]\n        : [epCarcaseSides(cab).left, epCarcaseSides(cab).right];\n      if (ends.some(f => f && facesAlong(f))) ids.push(cab.id);\n    }\n    return ids;\n  }\n\n  // Re-decide the unit ends beside these openings - pass the opening as it\n  // WAS as well as as it IS, so an end it has just moved away from gets its\n  // wall finish back. Returns true when anything changed, for a caller that\n  // does not already redraw.\n  function epReDecideBesideOpenings(ops) {\n    const ids = new Set();\n    for (const op of ops) for (const id of epUnitsBesideOpening(op)) ids.add(id);\n    if (!ids.size) return false;\n    const sig = () => JSON.stringify(cabinets.map(c => [c.id, c.x, c.y, c.endPanels, c.fillers]));\n    const before = sig();\n    autoDetectEndPanels([...ids]);\n    resizeFillers();\n    return sig() !== before;\n  }\n\n  // World direction pointing OUTWARD from the cabinet on its user-LEFT\n  // (+cabinet-local-X) or user-RIGHT (-cabinet-local-X) side.\n  function epUserSideOutward(cab, side) {\n    const th = ((cab.rotationDeg || 0) * Math.PI) / 180;\n    const cs = Math.cos(th), sn = Math.sin(th);\n    if (side === 'left')  return { x: +cs, y: +sn };\n    if (side === 'right') return { x: -cs, y: -sn };\n    // front = the unit's forward (into-room) face; back = toward the wall.\n    if (side === 'front' || side === 'forward')  return { x: +sn, y: -cs };\n    if (side === 'back'  || side === 'backward') return { x: -sn, y: +cs };\n    return { x: 0, y: 0 };\n  }\n\n  // Change which \"wall mount line\" a wall unit hangs from (low /\n  // medium / high \u2192 1975 / 2120 / 2300mm tops).\n  function handleUpdateCabinetMountLevel(cabinetId, level) {\n    const idx = cabinets.findIndex(c => c.id === cabinetId);\n    if (idx === -1) return;\n    // The user's choice wins: a bridging unit stops following its neighbour.\n    const { alignTopPending, ...rest } = cabinets[idx];\n    cabinets[idx] = { ...rest, wallMountLevel: level };\n    rerender();\n  }\n\n  // Change which EDGE of a wall/bridging unit sits on the mount line:\n  // 'top' (default, hangs below), 'bottom' (sits above - stacks on a\n  // top-anchored unit) or 'panel' (sits above with an 18mm divider).\n  // 'under' (Planner Bugs rows 53 + 351) hangs it from the bottom of the wall\n  // unit above; underSince orders a column of them, top down.\n  function handleUpdateCabinetMountAnchor(cabinetId, anchor) {\n    const idx = cabinets.findIndex(c => c.id === cabinetId);\n    if (idx === -1) return;\n    const { underSince, onSince, ...rest } = cabinets[idx];\n    cabinets[idx] = { ...rest, mountAnchor: anchor,\n      ...(anchor === 'under' ? { underSince: underSince || Date.now() } : {}),\n      // 'on' (stands on the wall unit under it): a column builds in the order\n      // its units were set, as 'under' does.\n      ...((anchor === 'on' || anchor === 'worktop') ? { onSince: onSince || Date.now() } : {}) };\n    // Its height changes, so do its end panels and its neighbours'.\n    syncStackAnchors();\n    autoDetectEndPanels([cabinetId]);\n    rerender();\n  }\n  // A headboard's height off the floor (Position popup).\n  function handleUpdateCabinetMountBottom(cabinetId, mm) {\n    const idx = cabinets.findIndex(c => c.id === cabinetId);\n    if (idx === -1) return;\n    cabinets[idx] = { ...cabinets[idx], mountAnchor: 'set', mountBottomMm: Math.max(0, Math.round(mm) || 0) };\n    syncStackAnchors();\n    rerender();\n  }\n  // Line Up (Position popup): a wall unit's top or bottom edge level with\n  // another unit's, followed live (engine-stack resolveWallAnchors). With no\n  // unit chosen yet it hangs from its line meanwhile.\n  function handleSetCabinetAlign(cabinetId, align) {\n    const idx = cabinets.findIndex(c => c.id === cabinetId);\n    if (idx === -1) return;\n    const edge = (align && align.edge === 'bottom') ? 'bottom' : 'top';\n    cabinets[idx] = { ...cabinets[idx], mountAnchor: 'align', alignTo: { cabId: (align && align.cabId) || null, edge } };\n    syncStackAnchors();\n    autoDetectEndPanels([cabinetId]);\n    rerender();\n  }\n  // How high a wall or bridging unit hangs (Non Urgent sheet row 12, Julian):\n  // its bottom from the floor, and above the worktop under it when there is\n  // one - that worktop's own rest height plus its real thickness. Worked out\n  // each time, so nothing is saved and older plans show it too.\n  // -> { fromFloorMm, aboveWorktopMm | null } or null for other units.\n  // `slabs` lets one render reuse its worktops for every unit.\n  function wallUnitHeights(cabOrId, slabs) {\n    const c = (cabOrId && typeof cabOrId === 'object') ? cabOrId : (cabinets || []).find(x => x && x.id === cabOrId);\n    if (!c || !isWallMounted(c)) return null;\n    const bottom = unitVerticalRange(c).bottom;\n    if (!Number.isFinite(bottom)) return null;\n    const box = planFootprintAABB(c);\n    const px = (box.minX + box.maxX) / 2, py = (box.minY + box.maxY) / 2;\n    const inside = (poly) => {\n      let inn = false;\n      for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {\n        const a = poly[i], b = poly[j];\n        if ((a.y > py) !== (b.y > py) && px < (b.x - a.x) * (py - a.y) / (b.y - a.y) + a.x) inn = !inn;\n      }\n      return inn;\n    };\n    let top = null;\n    for (const s of (slabs || buildWorktops() || [])) {\n      if (!s || !Array.isArray(s.polygon) || s.polygon.length < 3 || !inside(s.polygon)) continue;\n      const t = (s.restMm || 720) + (s.thicknessMm || 38);\n      if (t <= bottom + 1 && (top == null || t > top)) top = t;\n    }\n    return { fromFloorMm: Math.round(bottom), aboveWorktopMm: top == null ? null : Math.round(bottom - top) };\n  }\n\n  // The units a wall unit can line up with: every other unit on the plan,\n  // nearest first, named as the plan numbers them.\n  function getAlignCandidates(cabinetId) {\n    const me = cabinets.find(c => c && c.id === cabinetId);\n    if (!me) return [];\n    const mx = (me.x || 0) + (me.widthMm || 0) / 2, my = (me.y || 0) + (me.depthMm || 0) / 2;\n    return cabinets\n      .filter(c => c && c.id !== cabinetId && !c.endPanelUnit && !c.freestandingAppliance)\n      .map(c => ({ c, d: Math.hypot((c.x || 0) + (c.widthMm || 0) / 2 - mx, (c.y || 0) + (c.depthMm || 0) / 2 - my) }))\n      .sort((a, b) => a.d - b.d)\n      .slice(0, 12)\n      .map(({ c }) => {\n        const ut = c.unitTypeId && Catalogue.getUnitType ? Catalogue.getUnitType(c.unitTypeId) : null;\n        const name = (ut && ut.name) || c.code || 'Unit';\n        const num = c.displayNumber != null ? '#' + c.displayNumber + ' ' : '';\n        return { id: c.id, label: (num + name + ' ' + (c.widthMm || '')).trim(), floor: !isWallMounted(c) };\n      });\n  }\n\n  // Stack mode (base + midi units) - 'base' / 'midi' / null. The two\n  // modes are mutually exclusive: picking one replaces the other, and\n  // re-picking the active one turns stacking back off. Switching a\n  // stack ON also drops the plinth (a plinth in mid-air is nonsense -\n  // the carcase sits straight on the host's top); switching it OFF puts\n  // the plinth back, so a unit dragged out of a stack is a normal\n  // floor unit again. Both stay overridable from the same popup.\n  function handleSetCabinetStackMode(cabinetId, mode) {\n    const idx = cabinets.findIndex(c => c.id === cabinetId);\n    if (idx === -1) return;\n    const cab  = cabinets[idx];\n    const next = (mode === cab.stackOn) ? null : (mode || null);\n    const trim = { ...stackTrimOf(cab), plinth: next ? false : true };\n    const prevHostId = cab.stackHostId || null;\n    cabinets[idx] = { ...cab, stackOn: next, stackTrim: trim };\n    // Stacking changes the unit's vertical band, which changes who its\n    // end-panel neighbours are - and whether it fuses into a pseudo\n    // tall column. Re-run the walk for the unit, the host it just\n    // landed on, and the host it just left.\n    syncStackAnchors();   // resolve the NEW host before naming it below\n    const affected = [cabinetId, prevHostId, cabinets[idx].stackHostId].filter(Boolean);\n    autoDetectEndPanels(affected);\n    rerender();\n  }\n\n  // Plinth / worktop / cornice toggles from the Stack popup. Patch is\n  // partial ({ worktop: false }); the rest of the unit's finish is\n  // preserved. These drive the trim + worktop engines directly, so\n  // turning one off removes both the render AND the charge.\n  function handleSetCabinetStackTrim(cabinetId, patch) {\n    if (!patch || typeof patch !== 'object') return;\n    const idx = cabinets.findIndex(c => c.id === cabinetId);\n    if (idx === -1) return;\n    const cab = cabinets[idx];\n    cabinets[idx] = { ...cab, stackTrim: { ...stackTrimOf(cab), ...patch } };\n    // The plinth toggle changes the unit's height, and the worktop\n    // toggle changes what a rider above sits on - both move vertical\n    // bands, so the end-panel decisions for this unit and its host may\n    // change with them.\n    syncStackAnchors();\n    autoDetectEndPanels([cabinetId, cabinets[idx].stackHostId].filter(Boolean));\n    rerender();\n  }\n\n  // The Stack popup's Confirm: stack mode, top and bottom finish land as ONE\n  // edit (one undo step, one end-panel pass). The popup has already applied\n  // the plinth-follows-mode rule to what it sends, so it is written as is.\n  function handleApplyCabinetStack(cabinetId, { mode = null, trim = {} } = {}) {\n    const idx = cabinets.findIndex(c => c.id === cabinetId);\n    if (idx === -1) return;\n    const cab = cabinets[idx];\n    const prevHostId = cab.stackHostId || null;\n    cabinets[idx] = { ...cab, stackOn: mode || null, stackTrim: { ...stackTrimOf(cab), ...trim } };\n    syncStackAnchors();   // resolve the NEW host before naming it below\n    autoDetectEndPanels([cabinetId, prevHostId, cabinets[idx].stackHostId].filter(Boolean));\n    rerender();\n  }\n\n  // ---- Stack popup preview -------------------------------------------------\n  // The popup previews its STAGED choice on a 3D renderer of its own: the unit\n  // being changed and the floor units stacked with it (sharing its footprint,\n  // never the ones beside it), in its room against its wall, drawn by the\n  // same render() as the plan, so the worktop, cornice and plinth are the real\n  // ones. It is given COPIES of those units with the staged stack applied, so\n  // nothing on the plan moves until Confirm. Built on first use and kept; the\n  // popup moves its canvas in and out and it only draws while shown.\n  let _stackPreview = null;      // Promise<{ handle, el } | null>\n  let _stackPreviewSeq = 0;      // newest paint wins; hide cancels the rest\n  function stackPreviewRenderer() {\n    if (!_stackPreview) {\n      _stackPreview = load3DRenderer().then(({ init3DRenderer }) => {\n        const el = document.createElement('div');\n        el.className = 'btk-kp-stack-preview-canvas';\n        return { handle: init3DRenderer(el, { catalogue: Catalogue }), el };\n      }).catch((err) => {\n        console.warn('[BTK stack] preview renderer failed', err);\n        _stackPreview = null;   // allow a retry next time the popup opens\n        return null;\n      });\n    }\n    return _stackPreview;\n  }\n  async function renderStackPreview(slot, cabId, staged = {}) {\n    const seq = ++_stackPreviewSeq;\n    const r = await stackPreviewRenderer();\n    if (!r) return false;\n    if (seq !== _stackPreviewSeq || !slot || !slot.isConnected) return true;\n    const cab = cabinets.find(c => c.id === cabId);\n    if (!cab) return false;\n    if (r.el.parentNode !== slot) slot.appendChild(r.el);\n    const own = stackPreviewFootprint(cab);\n    const mini = cabinets\n      .filter(o => o && (o.id === cabId || (!isWallMounted(o) && footprintsOverlap(own, stackPreviewFootprint(o)))))\n      .map(o => (o.id === cabId\n        ? { ...o, stackOn: staged.mode || null, stackTrim: { ...stackTrimOf(o), ...(staged.trim || {}) } }\n        : { ...o }));\n    resolveStackAnchors(mini, stackAnchorOpts());\n    const h = r.handle;\n    h.setWallColour(getWallColour(wallColourHandle).hex);\n    applyFeatureWallsTo3D(h);\n    applyFloorTo3D(h);\n    h.setActive(true);\n    h.render({ room, roomConfig, cabinets: mini, baseRoom, featureStyles, railFinishHandle, segmentColours,\n               worktops: buildWorktops(mini), worktopColourHex, worktopColours, worktopCornerRadii,\n               worktopItems: [], furnitureItems: [], handleGroups, lights: [], lightsOn: false });\n    h.resize();\n    frameStackPreview(h, mini, cabId);\n    return true;\n  }\n  // Customise Handle's preview (Arden, 2026-10-13): the unit's own picture -\n  // the same stand-alone render as the selected unit's panel and Add Units -\n  // with the handle picks still staged in the popup laid over its saved ones,\n  // so a change shows before Confirm. A still image, not the live room view:\n  // that showed the room around the unit, could be zoomed, and jumped back to\n  // its framing on every pick. The popup body is redrawn on each pick, so the\n  // last picture of this unit goes straight into the new slot and is swapped\n  // when the new one is ready - no blank \"Loading\" between picks. Seen a little\n  // round from straight on, where the handle is.\n  let _handlePreviewSeq = 0;\n  let _handlePreviewLast = null;   // { cabId, url }\n  async function renderHandlePreview(slot, cabId, stagedHandle) {\n    const seq = ++_handlePreviewSeq;\n    hideStackPreview();\n    const cab = cabinets.find(c => c.id === cabId);\n    if (!cab || !slot) return false;\n    const show = (url) => {\n      let img = slot.querySelector('img.btk-kp-stack-preview-img');\n      if (!img) {\n        img = document.createElement('img');\n        img.className = 'btk-kp-stack-preview-img';\n        img.alt = '';\n        slot.appendChild(img);\n      }\n      if (img.getAttribute('src') !== url) img.src = url;\n      const msg = slot.querySelector('[data-ch-preview-msg]');\n      if (msg) msg.hidden = true;\n    };\n    if (_handlePreviewLast && _handlePreviewLast.cabId === cabId) show(_handlePreviewLast.url);\n    const url = await renderCabinetThumbHeadless(\n      { ...cab, handle: { ...(cab.handle || {}), ...(stagedHandle || {}) } },\n      { width: 600, height: 760, camDirX: 0.35, handleGroups });\n    if (seq !== _handlePreviewSeq) return true;\n    if (!url) return false;\n    _handlePreviewLast = { cabId, url };\n    if (slot.isConnected) show(url);\n    return true;\n  }\n  // A unit's footprint as the plan places it: turned about its CENTRE\n  // (getEffectiveAABB), in the min/max shape footprintsOverlap takes.\n  function stackPreviewFootprint(c) {\n    const a = getEffectiveAABB(c, c.x || 0, c.y || 0);\n    return { minX: a.x, maxX: a.x + a.widthMm, minY: a.y, maxY: a.y + a.depthMm };\n  }\n  function hideStackPreview() {\n    _stackPreviewSeq++;\n    if (!_stackPreview) return;\n    _stackPreview.then((r) => {\n      if (!r) return;\n      r.handle.setActive(false);\n      r.el.remove();\n    });\n  }\n\n  // ---- Island Designer's 3D view ---------------------------------------------\n  // The island on its own, as Add Island to Plan would build it: addIsland run\n  // on an empty plan (_islandDry: no drawing, saving, undo, basket or\n  // selection), its units kept and the plan put back as it was. Drawn on a 3D\n  // renderer of its own in the customer's room, like the Stack popup's preview.\n  // var: rerender reads it before this line has run.\n  var _islandDry = false;\n  let _islandPreview = null;     // Promise<{ handle, el } | null>\n  let _islandPreviewSeq = 0;\n  function dryIsland(spec) {\n    const keep = { cabinets, selected: selectedCabinetIds };\n    let out = null;\n    _islandDry = true;\n    try {\n      cabinets = [];\n      selectedCabinetIds = new Set();\n      const s = { ...spec, units: (spec.units || []).map(u => ({ ...u })) };\n      delete s.replaceGroupId;\n      if (addIsland(s)) out = cabinets;\n    } catch (err) {\n      console.warn('[BTK island] 3D view build failed', err);\n    } finally {\n      cabinets = keep.cabinets;\n      selectedCabinetIds = keep.selected;\n      _islandDry = false;\n    }\n    return out;\n  }\n  function islandPreviewRenderer() {\n    if (!_islandPreview) {\n      _islandPreview = load3DRenderer().then(({ init3DRenderer }) => {\n        const el = document.createElement('div');\n        el.className = 'btk-kp-isl-3d-canvas';\n        return { handle: init3DRenderer(el, { catalogue: Catalogue }), el };\n      }).catch((err) => {\n        console.warn('[BTK island] 3D view renderer failed', err);\n        _islandPreview = null;\n        return null;\n      });\n    }\n    return _islandPreview;\n  }\n  // reframe: point the camera at the island again (first showing, or a new\n  // shape); otherwise it stays where the customer turned it.\n  async function renderIslandPreview(slot, spec, { reframe = true } = {}) {\n    const seq = ++_islandPreviewSeq;\n    const mini = spec ? dryIsland(spec) : null;\n    if (!mini || !mini.length) return false;\n    const r = await islandPreviewRenderer();\n    if (!r) return false;\n    if (seq !== _islandPreviewSeq || !slot || !slot.isConnected) return true;\n    const fresh = r.el.parentNode !== slot;\n    if (fresh) slot.appendChild(r.el);\n    const h = r.handle;\n    h.setWallColour(getWallColour(wallColourHandle).hex);\n    applyFeatureWallsTo3D(h);\n    applyFloorTo3D(h);\n    h.setActive(true);\n    h.render({ room, roomConfig, cabinets: mini, baseRoom, featureStyles, railFinishHandle, segmentColours,\n               worktops: buildWorktops(mini), worktopColourHex, worktopColours, worktopCornerRadii,\n               worktopItems: [], furnitureItems: [], handleGroups, lights: [], lightsOn: false });\n    h.resize();\n    if (reframe) frameIslandPreview(h, mini);\n    return true;\n  }\n  // From the front units' side, a little round and above, the island filling\n  // the view.\n  function frameIslandPreview(h, mini) {\n    let minX = Infinity, maxX = -Infinity, minZ = Infinity, maxZ = -Infinity, top = 0;\n    for (const o of mini) {\n      const b = stackPreviewFootprint(o);\n      minX = Math.min(minX, b.minX); maxX = Math.max(maxX, b.maxX);\n      minZ = Math.min(minZ, b.minY); maxZ = Math.max(maxZ, b.maxY);\n      top = Math.max(top, unitVerticalRange(o).top);\n    }\n    const front = mini.find(c => c.islandRun === 'front') || mini[0];\n    const th = ((front.rotationDeg || 0) * Math.PI) / 180;\n    const fx = Math.sin(th), fz = -Math.cos(th), swing = 0.5;\n    const dx = fx * Math.cos(swing) - fz * Math.sin(swing);\n    const dz = fx * Math.sin(swing) + fz * Math.cos(swing);\n    const cx = (minX + maxX) / 2, cz = (minZ + maxZ) / 2, cy = top * 0.4;\n    const size = Math.max(top, Math.hypot(maxX - minX, maxZ - minZ));\n    const dist = size * 1.2;\n    h.setCameraState({ pos: [cx + dx * dist, cy + size * 0.5, cz + dz * dist], target: [cx, cy, cz] });\n  }\n  // The Island Designer's Waterfall End / waterfall breakfast bar back: the\n  // same switches as Add Waterfall Side, on every side of the island's own\n  // worktops that can take one (an end with an end panel, a breakfast bar's\n  // back). The seating's cushion tops take none, nor a round edge laminate.\n  // The back row's end panels behind an end waterfall come off with it\n  // (waterfallCoveredEndSides, Sales row 149).\n  function islandWaterfalls(ids, spec) {\n    const idSet = new Set(ids);\n    const cabById = new Map(cabinets.map(c => [c.id, c]));\n    const ends = [], bar = new Set();\n    for (const s of (buildWorktops() || [])) {\n      if (!s || s.cushionTop || !(s.cabinetIds || []).some(id => idSet.has(id)) || waterfallBarredForSlab(s)) continue;\n      for (const x of worktopWaterfallSides(s, cabById)) {\n        if (x.on) continue;\n        if (x.side === 'back') {\n          if (spec.barWaterfall) for (const c of worktopBarUnits(s, cabById)) if (idSet.has(c.id)) bar.add(c.id);\n          continue;\n        }\n        if (!spec.waterfall) continue;\n        const u = worktopEndUnit(s, cabById, x.side === 'left');\n        if (u && idSet.has(u.c.id)) ends.push(u);\n      }\n    }\n    if (!ends.length && !bar.size) return;\n    cabinets = cabinets.map(c => {\n      let out = c;\n      for (const u of ends) {\n        if (u.c.id !== c.id) continue;\n        const ep = out.endPanels || {};\n        out = { ...out, endPanels: { ...ep, [u.key]: { ...(ep[u.key] || {}), active: false, userOff: true, userSet: true, waterfall: true, toFloor: false, doorLine: false } } };\n      }\n      if (bar.has(c.id)) out = { ...out, breakfastBarBack: { ...(out.breakfastBarBack || {}), waterfall: true } };\n      return out;\n    });\n    autoDetectEndPanels(ids);\n    rerender();\n  }\n  // Whether the island's worktop (the kitchen's) can take a waterfall.\n  function islandWaterfallInfo() {\n    return { barred: waterfallBarredMaterial(worktopMaterialForSlab(null)) };\n  }\n  function hideIslandPreview() {\n    _islandPreviewSeq++;\n    if (!_islandPreview) return;\n    _islandPreview.then((r) => {\n      if (!r) return;\n      r.handle.setActive(false);\n      r.el.remove();\n    });\n  }\n  // A three-quarter view of the column from in front of the unit. Plan x/y are\n  // world x/z (height is world y), and a unit's front faces (sin, -cos) of its\n  // rotation on the plan - the same front the 2D labels and end panels use.\n  function frameStackPreview(h, mini, cabId, swingRad) {\n    let minX = Infinity, maxX = -Infinity, minZ = Infinity, maxZ = -Infinity, top = 0;\n    for (const o of mini) {\n      const b = stackPreviewFootprint(o);\n      minX = Math.min(minX, b.minX); maxX = Math.max(maxX, b.maxX);\n      minZ = Math.min(minZ, b.minY); maxZ = Math.max(maxZ, b.maxY);\n      top = Math.max(top, unitVerticalRange(o).top);\n    }\n    top += 150;   // headroom for a worktop or cornice on the top unit\n    const cab = mini.find(o => o.id === cabId);\n    const th = (((cab && cab.rotationDeg) || 0) * Math.PI) / 180;\n    const fx = Math.sin(th), fz = -Math.cos(th);\n    const swing = (typeof swingRad === 'number') ? swingRad : 0.6;   // ~35 degrees round from straight on\n    const dx = fx * Math.cos(swing) - fz * Math.sin(swing);\n    const dz = fx * Math.sin(swing) + fz * Math.cos(swing);\n    const cx = (minX + maxX) / 2, cz = (minZ + maxZ) / 2, cy = top / 2;\n    const size = Math.max(top, maxX - minX, maxZ - minZ);\n    const dist = size * 1.7;\n    h.setCameraState({ pos: [cx + dx * dist, cy + size * 0.35, cz + dz * dist], target: [cx, cy, cz] });\n  }\n\n  // Standalone draggable lights. `lights` is an array of { id, x, y,\n  // settings } in plan-mm world coords. The 3D renderer decides\n  // per-light whether it's an under-cab (inside a wall cab's plan\n  // footprint) or a ceiling-mounted light (elsewhere).\n  function handleAddLight(planX, planY) {\n    const light = {\n      id: nextLightId++,\n      x:  planX,\n      y:  planY,\n      settings: { brightness: 'medium', colour: 'warm', spread: 'medium' }\n    };\n    lights.push(light);\n    rerender();\n    return light;\n  }\n  function handleRemoveLight(id) {\n    const idx = lights.findIndex(l => l.id === id);\n    if (idx === -1) return;\n    lights.splice(idx, 1);\n    rerender();\n  }\n  function handleUpdateLightSetting(id, patch) {\n    if (!patch || typeof patch !== 'object') return;\n    const idx = lights.findIndex(l => l.id === id);\n    if (idx === -1) return;\n    lights[idx] = {\n      ...lights[idx],\n      settings: { ...lights[idx].settings, ...patch }\n    };\n    rerender();\n  }\n\n  // Patch one of the cabinet's end panels (side = 'left' | 'right').\n  // The patch is a partial object - { active }, { style }, { inline },\n  // { pelmetExt }, or any combination - and is merged into the current\n  // end-panel state for that side. The trim engine reads\n  // cabinet.endPanels[side].active to decide whether to emit a side\n  // return + widen the front trim; the 3D renderer reads inline /\n  // pelmetExt to size the panel slab; the basket reads style to\n  // pick the right product.\n  // Re-sync an EXISTING planner basket after an edit that changes what a line\n  // IS rather than just how it looks - an end panel switching Plain \u2192 T&G is a\n  // DIFFERENT product (BEPP \u2192 BEPTG), so the basket would otherwise sit on the\n  // old variant and the quote would be wrong.\n  //\n  // Guarded: if the plan has no basket yet this does NOTHING. transferPlanToBasket\n  // would happily CREATE one, and adding to the basket behind the user's back\n  // because they toggled a panel finish is not on. Debounced because Apply\n  // commits BOTH sides and each side fires its own update.\n  let _basketResyncTimer = null;\n  function scheduleBasketResync() {\n    if (_islandDry) return;\n    if (_basketResyncTimer) clearTimeout(_basketResyncTimer);\n    _basketResyncTimer = setTimeout(async () => {\n      _basketResyncTimer = null;\n      // A plan is opening: try again once it is drawn.\n      if (planOpening) { scheduleBasketResync(); return; }\n      // Its prices have not loaded: ensureStyleProducts resyncs when they land.\n      if (planPricesPending()) return;\n      try {\n        const api = window.BTKBasketAPI;\n        if (!api || !planStore || typeof planStore.getActiveBasketId !== 'function') return;\n        const id = await planStore.getActiveBasketId();\n        if (!id) return;\n        const project = await api.getProject();\n        if (!project || !(project.baskets || []).some(b => b && b.id === id)) return;\n        await transferPlanToBasket(false, { quiet: true });\n      } catch (e) { /* never let a basket re-sync break the planner */ }\n    }, 300);\n  }\n\n  // A side the user set from the unit's own panel - end panel OR filler, they\n  // are the same decision. The auto pass leaves these alone; nothing else in\n  // the planner stamps it (the two handlers below are only wired to the\n  // selection panel, so every call is the user's own doing).\n  function epSideUserSet(cab, side) {\n    if (!cab) return false;\n    const ep  = (cab.endPanels || {})[side];\n    const fil = (cab.fillers   || {})[side];\n    return !!((ep && ep.userSet) || (fil && fil.userSet));\n  }\n\n  // Hand ONE side of ONE unit to the user, or give it back to the planner.\n  // Turning Auto OFF stamps the side as theirs WITHOUT changing what is on it,\n  // so \"keep what auto chose, but stop re-deciding it\" is sayable. Turning it\n  // back ON drops the flag and re-runs the detect pass, which is the only way\n  // back - the plan-wide switch cannot release a side (turning it on runs the\n  // very pass that skips userSet, turning it off strips every panel in the\n  // kitchen).\n  function handleSetCabinetSideAuto(cabinetId, side, auto) {\n    if (side !== 'left' && side !== 'right') return;\n    const idx = cabinets.findIndex(c => c.id === cabinetId);\n    if (idx === -1) return;\n    const cab = cabinets[idx];\n    // Going to Auto RESETS the side rather than just unflagging it. The pass's\n    // write-back overwrites `active` and nothing else, so a Radius end, a T&G\n    // finish, a cut-down depth or a door-line panel would ride back over the\n    // defaults and sit there fixed; and `userOff` (picking None) suppresses\n    // the auto panel outright, so a side turned off by hand could never be\n    // turned back on. Going to Manual keeps everything and just marks the side.\n    const stamp = (all, defaults) => {\n      const prevAll = all || {};\n      if (auto) return { ...prevAll, [side]: defaults() };\n      return { ...prevAll, [side]: { ...(prevAll[side] || defaults()), userSet: true } };\n    };\n    let next = {\n      ...cab,\n      endPanels: stamp(cab.endPanels, epSideDefaults),\n      fillers:   stamp(cab.fillers,   fillerSideDefaults)\n    };\n    // Radius / Square on an L-shape or diagonal corner unit also turns on the\n    // full 650 uncut side panel. That is a WHOLE-UNIT flag, so it only comes\n    // off once neither side is asking for it.\n    if (auto && next.useFullSizeEndPanel && !next.fullSizeEndPanelUserSet\n        && (next.lShapeUnit || next.diagonalCornerUnit)) {\n      const otherStyle = (next.endPanels[side === 'left' ? 'right' : 'left'] || {}).style;\n      if (otherStyle !== 'radius' && otherStyle !== 'square') next = { ...next, useFullSizeEndPanel: false };\n    }\n    cabinets[idx] = next;\n    // Giving it back: let the planner decide this side again right away, so\n    // the user sees what Auto makes of it rather than a frozen leftover.\n    if (auto) { autoDetectEndPanels(); resizeFillers(); }\n    rerender();\n    scheduleBasketResync();\n  }\n\n  function doorEndVoidMm(cab, doorWidthMm) {\n    const face = /^open/.test(String(cab.unitTypeId || '')) ? 0 : Math.round(Number(cab.doorFaceMm) || 0);\n    return Math.max(0, Math.round(Number(doorWidthMm) || 0) - Math.round(Number(cab.depthMm) || 0) - face);\n  }\n  // The door product behind a door end: the range's 715mm high door (unit type\n  // door-715), the chosen width's variant. -> { variantId, title, variantTitle,\n  // priceCents, compareAtCents, handle } or null.\n  function doorEndProduct(cab, de) {\n    if (!de || !de.variantId) return null;\n    const pr = Catalogue.getProductForUnitInStyle ? Catalogue.getProductForUnitInStyle('door-715', cab.kitchenStyleId) : null;\n    const v = pr && (pr.variants || []).find(x => String(x.id) === String(de.variantId));\n    if (!pr || !v) return null;\n    const info = Catalogue.getVariantInfo ? (Catalogue.getVariantInfo(v.id) || {}) : {};\n    const cents = (n) => (typeof n === 'number' ? n : (n != null && n !== '' ? Math.round(Number(n) * 100) : null));\n    return {\n      variantId: v.id, title: pr.title || 'Door', variantTitle: v.title || (de.widthMm + ''),\n      priceCents: info.priceCents != null ? info.priceCents : cents(v.price),\n      compareAtCents: info.compareAtCents != null ? info.compareAtCents : cents(v.compareAtPrice),\n      handle: pr.handle || null\n    };\n  }\n\n  function handleUpdateCabinetEndPanel(cabinetId, side, patch) {\n    if (side !== 'left' && side !== 'right') return;\n    if (!patch || typeof patch !== 'object') return;\n    const idx = cabinets.findIndex(c => c.id === cabinetId);\n    if (idx === -1) return;\n    const cab = cabinets[idx];\n    const prevAll = cab.endPanels || {\n      left:  { active: false, style: 'flat', inline: false, pelmetExt: 'modern' },\n      right: { active: false, style: 'flat', inline: false, pelmetExt: 'modern' }\n    };\n    const prevSide = prevAll[side] || { active: false, style: 'flat', inline: false, pelmetExt: 'modern' };\n    let updated = {\n      ...cab,\n      // userSet: this side is the user's from now on - see epSideUserSet.\n      endPanels: { ...prevAll, [side]: { ...prevSide, ...patch, userSet: true } }\n    };\n    // Mutual exclusion with filler on the same side - activating\n    // the end panel turns off any filler there.\n    if (patch.active === true) {\n      const filAll  = updated.fillers || { left: { active: false, widthMm: 20, setBackMm: 0 }, right: { active: false, widthMm: 20, setBackMm: 0 } };\n      const filSide = filAll[side]    || { active: false, widthMm: 20, setBackMm: 0 };\n      if (filSide.active) {\n        updated = { ...updated, fillers: { ...filAll, [side]: { ...filSide, active: false } } };\n      }\n    }\n    // DOOR END PANEL (Sales sheet line 110): a 715mm high door on this end. A\n    // door wider than the side it covers (the carcase plus the door on the\n    // front) leaves a void BEHIND the unit, and the unit moves out by it -\n    // Arden's call, so the door is never cut down. One void for the unit: the\n    // wider of its two door ends. Only the change is moved, so picking the\n    // same door again, or a narrower one, never walks the unit off.\n    if (Object.prototype.hasOwnProperty.call(patch, 'doorEnd')) {\n      const sideNow = updated.endPanels[side];\n      if (sideNow.doorEnd && sideNow.doorEnd.widthMm) {\n        updated.endPanels[side] = { ...sideNow, doorEnd: { ...sideNow.doorEnd, voidMm: doorEndVoidMm(updated, sideNow.doorEnd.widthMm) } };\n      } else if (sideNow.doorEnd) {\n        updated.endPanels[side] = { ...sideNow, doorEnd: null };\n      }\n      const wantVoid = Math.max(0, ...['left', 'right'].map(s => {\n        const de = (updated.endPanels[s] || {}).doorEnd;\n        return de && de.widthMm ? (de.voidMm || 0) : 0;\n      }));\n      const delta = wantVoid - (Number(cab.doorVoidMm) || 0);\n      if (Math.abs(delta) > 0.5) {\n        const th = ((updated.rotationDeg || 0) * Math.PI) / 180;\n        updated = { ...updated, x: (updated.x || 0) + Math.sin(th) * delta, y: (updated.y || 0) - Math.cos(th) * delta };\n      }\n      updated.doorVoidMm = wantVoid || null;\n      // The unit has moved: a run's panel carried along its side follows it.\n      cabinets[idx] = updated;\n      try { autoDetectBackPanels(); } catch (e) { console.warn('[BTK door end] back panels', e); }\n      updated = cabinets[idx];\n    }\n    // Radius/square end feature on an L/diagonal uses the full 650mm\n    // uncut side panel (post + flat + rebate). Default Use Full Size End\n    // Panel ON so the real construction (posts + flat + voids) renders.\n    if ((updated.lShapeUnit || updated.diagonalCornerUnit) &&\n        (patch.style === 'radius' || patch.style === 'square') &&\n        !updated.useFullSizeEndPanel) {\n      updated = { ...updated, useFullSizeEndPanel: true };\n    }\n    cabinets[idx] = updated;\n    rerender();\n    scheduleBasketResync();\n  }\n\n  // Patch one of the cabinet's fillers (side = 'left' | 'right').\n  // patch is partial - { active }, { widthMm }, or both. Activating\n  // a filler turns off any end panel on the same side (mutually\n  // exclusive). Width is clamped to 1mm - FILLER_MAX_GAP_MM.\n  function handleUpdateCabinetFiller(cabinetId, side, patch) {\n    if (side !== 'left' && side !== 'right') return;\n    if (!patch || typeof patch !== 'object') return;\n    const idx = cabinets.findIndex(c => c.id === cabinetId);\n    if (idx === -1) return;\n    const cab = cabinets[idx];\n    const prevAll = cab.fillers || {\n      left:  { active: false, widthMm: 20, setBackMm: 0 },\n      right: { active: false, widthMm: 20, setBackMm: 0 }\n    };\n    const prevSide = prevAll[side] || { active: false, widthMm: 20, setBackMm: 0 };\n    // userSet: this side is the user's from now on - see epSideUserSet.\n    const nextSide = { ...prevSide, ...patch, userSet: true };\n    if (typeof nextSide.widthMm === 'number') {\n      // Same ceiling as the auto fit - the widest filler sold. Capped at\n      // 100 here, a filler the auto pass had sized to 120 was cut back to\n      // 100 the first time anyone touched it.\n      nextSide.widthMm = Math.max(1, Math.min(FILLER_MAX_GAP_MM, Math.round(nextSide.widthMm)));\n    }\n    let updated = { ...cab, fillers: { ...prevAll, [side]: nextSide } };\n    // Mutual exclusion with end panel.\n    if (nextSide.active === true) {\n      const epAll  = updated.endPanels || {\n        left:  { active: false, style: 'flat', inline: false, pelmetExt: 'modern' },\n        right: { active: false, style: 'flat', inline: false, pelmetExt: 'modern' }\n      };\n      const epSide = epAll[side];\n      if (epSide?.active) {\n        updated = { ...updated, endPanels: { ...epAll, [side]: { ...epSide, active: false } } };\n      }\n    }\n    cabinets[idx] = updated;\n    // Switching a corner end to a filler by hand should join it to the filler\n    // it meets, exactly as Auto would. resizeFillers leaves a width the user\n    // typed alone, so this never overrides one.\n    resizeFillers();\n    rerender();\n    scheduleBasketResync();\n  }\n\n  // Patch a corner unit's descriptor - { postXMm }, { postYMm },\n  // { hand }. Post sizes are clamped; postXMm sits along the run, so\n  // changing it re-derives the plan footprint width (which keeps\n  // dimensions / snapping / collision correct).\n  function handleUpdateCornerUnit(cabinetId, patch) {\n    if (!patch || typeof patch !== 'object') return;\n    const idx = cabinets.findIndex(c => c.id === cabinetId);\n    if (idx === -1) return;\n    const cab = cabinets[idx];\n    if (!cab.cornerUnit) return;\n    const merged = { ...cab.cornerUnit, ...patch };\n    // SIZE change: patch.cabinetMm (Width) or patch.depthMm (Depth [split])\n    // selects a different variant. Resolve it (preserving the blank-panel SIDE,\n    // i.e. the current non-dimension option values), pull the variant's cabinet\n    // + door + depth, and swap the variant so the basket line + price + void\n    // (reach) follow. Post / hand / placement patches skip this.\n    let _newVariantId = null, _newPriceCents = null, _newDepthMm = null, _newCompareAt;\n    // HEIGHT: a tall corner (the Tall Larder Corner Unit) is sold Medium and\n    // High. The variant used to be swapped here with the cab's height and door\n    // layout left as they were, so Medium -> High changed the basket line and\n    // nothing on the plan (Arden, 2026-11-17). Height is carcase + the unit\n    // type's plinth, as in handleUpdateCabinetSize.\n    const _cornerUt     = Catalogue.getUnitType ? Catalogue.getUnitType(cab.unitTypeId) : null;\n    const _cornerPlinth = (_cornerUt && _cornerUt.plinthHeightMm) || 0;\n    const _curCarcaseH  = Math.max(0, (cab.heightMm || 0) - _cornerPlinth);\n    let _newCarcaseH = null, _newInfoVariantId = null;\n    const _wantW = (typeof patch.cabinetMm === 'number') ? patch.cabinetMm : cab.cornerUnit.cabinetMm;\n    const _wantD = (typeof patch.depthMm   === 'number') ? patch.depthMm   : cab.depthMm;\n    // A DOOR change counts as a size change on its own: the same 1000 cabinet\n    // is sold with a 500, 550 or 600 door, so gating on cabinetMm alone meant\n    // picking \"1000 Cab / 600 Door\" over \"1000 Cab / 500 Door\" resolved no new\n    // variant and left the door (and the basket line) where it was.\n    // `patch.variantId` = apply THIS variant (the Edit popup resolves one from\n    // the product's own options). It carries every axis at once - cabinet,\n    // door, depth, height AND the blank-panel side - so it must not be gated\n    // on a dimension differing: a side-only change keeps all the dimensions.\n    const _explicit = patch.variantId\n      ? (Catalogue.getVariantInfo ? Catalogue.getVariantInfo(patch.variantId) : null)\n      : null;\n    const _sizeChange = !!_explicit\n                     || (typeof patch.cabinetMm === 'number' && patch.cabinetMm !== cab.cornerUnit.cabinetMm)\n                     || (typeof patch.doorMm    === 'number' && patch.doorMm    !== cab.cornerUnit.doorMm)\n                     || (typeof patch.depthMm   === 'number' && patch.depthMm   !== cab.depthMm);\n    if (_sizeChange) {\n      const optInfo = Catalogue.variantOptionInfo ? Catalogue.variantOptionInfo(cab.variantId) : [];\n      const optionValues = optInfo.filter(o => !o.isDimension && o.value != null).map(o => o.value);\n      // patch.widthOption is the authored Width value (\"1000 Cab / 600 Door\") -\n      // the only thing that separates two variants sharing a cabinet width. On\n      // a DEPTH-only change there's no new label, so pin the CURRENT one:\n      // matching a 1000 cabinet alone would take the first 1000 variant and\n      // silently swap a 600 door for a 500.\n      const _curWidthOpt = (optInfo.find(o => /^width\\b/.test(o.labelKey)) || {}).value || null;\n      const _wantOpt = (typeof patch.widthOption === 'string' && patch.widthOption)\n        ? patch.widthOption\n        : ((typeof patch.cabinetMm === 'number' || typeof patch.doorMm === 'number') ? null : _curWidthOpt);\n      const _find = (withOpt, h) => Catalogue.findVariant({\n        unitTypeId: cab.unitTypeId, kitchenStyleId: cab.kitchenStyleId,\n        widthMm: _wantW, depthMm: _wantD, heightMm: (h != null ? h : null),\n        optionValues: withOpt ? optionValues.concat([withOpt]) : optionValues\n      });\n      // Fall back to the dimensions alone if the authored label doesn't match\n      // this product (e.g. a stale pill after a style change). A width / door\n      // / depth change keeps the CURRENT height where the product sells it -\n      // a tall corner sold Medium and High must not drop to the first one.\n      const info = _explicit\n        || (_wantOpt ? (_find(_wantOpt, _curCarcaseH) || _find(_wantOpt)) : null)\n        || _find(null, _curCarcaseH) || _find(null);\n      if (info) {\n        if (info.heightMm != null && info.heightMm > 0 && info.heightMm !== _curCarcaseH) {\n          _newCarcaseH = info.heightMm;\n        }\n        _newInfoVariantId = info.variant.id;\n        merged.cabinetMm = (info.widthMm != null) ? info.widthMm : _wantW;\n        if (info.doorMm != null) merged.doorMm = info.doorMm;\n        // Depth = the corner's reach (perpendicular run depth), which sizes the void.\n        if (info.depthMm != null) { merged.reachMm = info.depthMm; _newDepthMm = info.depthMm; }\n        _newVariantId  = info.variant.id;\n        _newPriceCents = info.priceCents;\n        _newCompareAt  = (typeof info.compareAtCents === 'number') ? info.compareAtCents : null;\n        // The blank-panel SIDE is one of this product's options, so if the\n        // resolved variant is the other side the DRAWING has to follow (hand\n        // names the door side). Skipped when the caller set the hand itself -\n        // the Corner Side pane passes { hand } and syncCornerHandVariant swaps\n        // the variant afterwards, so deriving here would undo their pick.\n        if (patch.hand == null && Catalogue.cornerHandForVariant) {\n          const _h = Catalogue.cornerHandForVariant(info.variant.id);\n          if (_h) merged.hand = _h;\n        }\n      } else {\n        console.warn('[BTK Kitchen Planner] No corner variant for', _wantW, 'x', _wantD);\n        return;\n      }\n    }\n    delete merged.depthMm;      // depthMm belongs on the cab, not the cornerUnit marker\n    delete merged.widthOption;  // a pill's authored label, not marker state\n    delete merged.variantId;    // lives on the cab, not the marker\n    // The post and the blank panel share the fixed cabinet width, so\n    // the post is capped to leave at least CORNER_MIN_BLANK_MM of\n    // blank panel. postY (forward protrusion) is independent.\n    const cabinetMm = merged.cabinetMm || CORNER_BLANK_DEFAULTS.cabinetMm;\n    const maxPostX  = Math.max(CORNER_POST_MIN_MM, cabinetMm - merged.doorMm - CORNER_MIN_BLANK_MM);\n    // Along the run the same: past a post only when its XL Post is ticked\n    // (xlRun) - then a wall end panel, as the return's XL is.\n    const _xMax = merged.xlRun ? CORNER_POST_XL_MAX_MM : CORNER_POST_MAX_MM;\n    merged.postXMm = Math.max(CORNER_POST_MIN_MM,\n      Math.min(_xMax, maxPostX, Math.round(merged.postXMm)));\n    // A bigger run post first grows TOWARDS the corner while the front of the\n    // unit round the corner is still further on - the blank panel gives the\n    // room, the door and the footprint stay where they are - and only then\n    // pushes the door end out as before. A smaller one gives that back first.\n    if (!_sizeChange && typeof patch.postXMm === 'number') {\n      const _was = Math.round(cab.cornerUnit.postXMm || 0);\n      const _in  = Math.max(0, Math.round(cab.cornerUnit.postInMm || 0));\n      const _d   = merged.postXMm - _was;\n      if (_d > 0) merged.postInMm = _in + Math.min(_d, cornerPostFrontGap(cab));\n      else if (_d < 0) merged.postInMm = Math.max(0, _in + _d);\n    }\n    // The return runs past the normal post range only when XL Post is ticked;\n    // unticking it clamps back and drops the panel from the order.\n    const _yMax = merged.xlReturn ? CORNER_POST_XL_MAX_MM : CORNER_POST_MAX_MM;\n    merged.postYMm = Math.max(CORNER_POST_MIN_MM,\n      Math.min(_yMax, Math.round(merged.postYMm)));\n    const cu = normaliseCornerUnit(merged);\n    // The cabinet stays cabinetMm wide (the blank panel absorbed the\n    // post change), but the void grew with the post so the footprint\n    // changes. Pin the CORNER end in world space so the corner - and\n    // the post's wall-side edge - never move; the door end extends\n    // outward instead. Shift accounts for the cabinet's rotation.\n    const widthMm = cu.cabinetMm + cu.voidMm;\n    const dW = widthMm - (cab.widthMm || widthMm);\n    const th = ((cab.rotationDeg || 0) * Math.PI) / 180;\n    const k  = (cu.hand === 'left') ? 1 : -1;\n    let x  = cab.x - dW / 2 + k * (dW / 2) * Math.cos(th);\n    let y  = cab.y + k * (dW / 2) * Math.sin(th);\n    let rotationDeg = cab.rotationDeg || 0;\n    // Peninsula mode: re-orient against the nearest wall so toggling the\n    // mode (or flipping the hand) re-snaps the void / back immediately,\n    // not just on the next drag. No-op when the unit isn't near a wall.\n    if (cu.placement && cu.placement !== 'auto') {\n      const probe = { ...cab, cornerUnit: cu, widthMm };\n      const pen = cornerUnitPeninsulaPlacement(probe, x, y, cu.placement);\n      if (pen) {\n        rotationDeg = pen.rotationDeg;\n        ({ x, y } = flushCabToWall({ ...probe, rotationDeg }, x, y, pen.wall));\n      }\n    }\n    cabinets[idx] = {\n      ...cab, cornerUnit: cu, widthMm, x, y, rotationDeg,\n      ...(_newVariantId  != null ? { variantId:  _newVariantId }  : {}),\n      ...(_newPriceCents != null ? { priceCents: _newPriceCents } : {}),\n      ...(_newCompareAt  !== undefined ? { compareAtCents: _newCompareAt } : {}),\n      ...(_newDepthMm    != null ? { depthMm:    _newDepthMm }    : {})\n    };\n    // A new HEIGHT brings its own door layout (the corner larder's lower door\n    // is 715 at Medium, 895 at High) - re-resolve the schema snapshot for it.\n    if (_newCarcaseH != null) {\n      const _schema = (_cornerUt && Catalogue.resolveCutoutSchema)\n        ? Catalogue.resolveCutoutSchema(_cornerUt.cutoutSchema, {\n            heightMm:       _newCarcaseH,\n            widthMm:        cabinets[idx].widthMm,\n            categoryHandle: _cornerUt.categoryHandle,\n            groupHandle:    _cornerUt.unitTypeGroupHandle,\n            optionValues:   Catalogue.nonDimensionOptionValues ? Catalogue.nonDimensionOptionValues(_newInfoVariantId) : []\n          })\n        : null;\n      cabinets[idx] = {\n        ...cabinets[idx],\n        heightMm: _newCarcaseH + _cornerPlinth,\n        ...(_schema ? { cutoutSchema: _schema } : {})\n      };\n    }\n    // A hand change swaps the panel-side variant. (A size change resolved its\n    // variant on the OLD side above; this is a no-op for it.)\n    syncCornerHandVariant(cabinets[idx]);\n    // Placement, hand and size changes all MOVE the unit - switching to\n    // Peninsula flushes the VOID END onto a wall that it was nowhere near\n    // a moment ago. The panels have to be re-decided against the new\n    // position, and this handler never did it: the unit kept whatever it\n    // was given in corner placement, so a void-side panel stayed on and\n    // stood proud of the wall it had just been flushed to.\n    //\n    // Called with NO ids on purpose. Passing this cab would mark it as\n    // \"just moved\", which triggers the full re-seat in that pass - and\n    // that would re-snap the unit straight back out of the peninsula\n    // placement set immediately above. No ids = re-decide everyone,\n    // containment only, placement left alone.\n    autoDetectEndPanels();\n    autoDetectBackPanels();\n    // A return asked for past the unit it meets is shortened to meet it (see\n    // clampCornerReturns) - say so on the Corner Posts tab.\n    cornerPostNote = null;\n    if (typeof patch.postYMm === 'number') {\n      const now = cabinets.find(c => c.id === cabinetId);\n      const got = now && now.cornerUnit ? Math.round(now.cornerUnit.postYMm || 0) : null;\n      if (got != null && got < merged.postYMm) {\n        const out = {};\n        returnReachToNeighbour(now, { anySide: true, out });\n        const o = out.id ? cabinets.find(c => c.id === out.id) : null;\n        const n = o && o.displayNumber;\n        cornerPostNote = { cabId: cabinetId,\n          text: `Shortened to ${got}mm to meet ${n ? 'unit ' + n : 'the next unit'}.` };\n      }\n    }\n    rerender();\n  }\n\n  // Auto Post - cast a ray from the cab's \"open\" face in the\n  // axis-appropriate direction, find the first wall / cab / pillar\n  // it hits, and grow that axis's post by the hit distance (clamped\n  // to 20..70). Each axis measures a different gap:\n  //\n  //   axis='x'  ray from the cab body's DOOR-END edge in the run\n  //             direction (away from the void). The post grows the\n  //             void \u2192 cab body extends outward toward the obstacle\n  //             until the door end butts against it.\n  //\n  //   axis='y'  ray from the POST FORWARD FACE in the cab-front\n  //             direction. The post grows forward until it butts\n  //             against the perpendicular run's TOP-end face.\n  //\n  // The \"distance to nearest vertex\" approach the old version used\n  // returned 0 whenever the cab was snapped to a room corner - which\n  // is exactly when the user wants Auto Post most. Raycasting from\n  // the OPEN side gives the gap to close regardless of how the cab\n  // is snapped.\n  // Toggle \"bench seat cushion top\" on a half-height unit. The\n  // worktop engine reads cab.cushionTop when grouping the cab's run\n  // - a slab containing any cushion-top cab swaps its 38mm stone\n  // thickness for a 75mm soft cushion (rendered with a fabric\n  // material instead of swatch stone) and suppresses upstands so\n  // the bench seat reads as a separate furniture object, not a\n  // worktop run extension.\n  function handleToggleCushionTop(cabinetId) {\n    const idx = cabinets.findIndex(c => c.id === cabinetId);\n    if (idx === -1) return;\n    const cab = cabinets[idx];\n    cabinets[idx] = { ...cab, cushionTop: !cab.cushionTop };\n    rerender();\n    // Re-render the side panel so the toggle label flips from\n    // \"Add\" \u2192 \"Remove\" (and the colour-picker block becomes\n    // visible / hides) without waiting for a re-selection.\n    if (selectionPanelHandle && typeof selectionPanelHandle.refresh === 'function') {\n      selectionPanelHandle.refresh();\n    }\n  }\n\n  function handleSetCushionColour(cabinetId, hex) {\n    const idx = cabinets.findIndex(c => c.id === cabinetId);\n    if (idx === -1) return;\n    cabinets[idx] = { ...cabinets[idx], cushionColourHex: hex };\n    rerender();\n    if (selectionPanelHandle && typeof selectionPanelHandle.refresh === 'function') {\n      selectionPanelHandle.refresh();\n    }\n  }\n\n  // Ray-cast out from a corner unit's post face and return the distance to the\n  // first thing in the way, or null when the ray hits nothing.\n  //\n  //   axis 'x' - out of the door-end face, along the run\n  //   axis 'y' - forward off the post face, on the return\n  //\n  // `hit` selects what counts as an obstruction. Auto Post stops at anything;\n  // the Extra Large Return Post auto-fill passes { cabs: true } only, because\n  // it is filling the gap to the next UNIT rather than to the room.\n  function cornerRayHit(cab, axis, hit) {\n    const cu = cab && cab.cornerUnit;\n    if (!cu) return null;\n    const want = { walls: true, cabs: true, pillars: true, ...(hit || {}) };\n\n    const W = cab.widthMm, D = cab.depthMm;\n    const cx = cab.x + W / 2, cy = cab.y + D / 2;\n    const th = ((cab.rotationDeg || 0) * Math.PI) / 180;\n    const cs = Math.cos(th), sn = Math.sin(th);\n\n    let edgeMidLocal, dirLocal;\n    if (axis === 'x') {\n      const k = cu.hand === 'left' ? 1 : -1;\n      edgeMidLocal = { x: k * W / 2, y: 0 };\n      dirLocal     = { x: k,         y: 0 };\n    } else {\n      // Forward off the post's front face. The X must be the POST's own centre,\n      // not the cabinet's: the post sits at one end of the cab body, so a ray\n      // from the cab centre measures to whatever happens to be opposite the\n      // MIDDLE of the unit, which is a different (often nearer) neighbour.\n      // Post start mirrors cornerLayout: door-first for hand 'right', and\n      // void + blank first for hand 'left'.\n      const py        = cu.postYMm || 0;\n      const postStart = (cu.hand === 'right')\n        ? (cu.doorMm || 0)\n        : ((cu.voidMm || 0) + (cu.blankMm || 0));\n      const postCx    = postStart + (cu.postXMm || 0) / 2 - W / 2;\n      edgeMidLocal = { x: postCx, y: -D / 2 - py };\n      dirLocal     = { x: 0,      y: -1 };\n    }\n    const origin = {\n      x: cx + edgeMidLocal.x * cs - edgeMidLocal.y * sn,\n      y: cy + edgeMidLocal.x * sn + edgeMidLocal.y * cs\n    };\n    const dir = {\n      x: dirLocal.x * cs - dirLocal.y * sn,\n      y: dirLocal.x * sn + dirLocal.y * cs\n    };\n\n    // ray = origin + t*dir (t>0); segment = p1 + s*(p2-p1), s in [0,1].\n    const hitDist = (p1, p2) => {\n      const dx = p2.x - p1.x, dy = p2.y - p1.y;\n      const denom = dir.x * dy - dir.y * dx;\n      if (Math.abs(denom) < 1e-9) return null;\n      const ox = p1.x - origin.x, oy = p1.y - origin.y;\n      const t = (ox * dy - oy * dx) / denom;\n      const sPar = (ox * dir.y - oy * dir.x) / denom;\n      if (sPar < -0.05 || sPar > 1.05) return null;  // outside the segment\n      // A face touching the start point is a unit (or wall) already butted\n      // to this end: no gap. Skipping it measured through that unit to its\n      // far side, and Auto Post grew the post to its maximum (Planner Phase 2\n      // row 36). The unit's own faces are never scanned.\n      if (t <= 0.5) return t > -0.5 ? 0 : null;\n      return t;\n    };\n    const scanPoly = (pts, cabId) => {\n      for (let i = 0; i < pts.length; i++) {\n        const t = hitDist(pts[i], pts[(i + 1) % pts.length]);\n        if (t !== null && t < minT) { minT = t; hitCabId = cabId || null; }\n      }\n    };\n\n    let minT = Infinity;\n    let hitCabId = null;\n    if (want.walls) scanPoly((room && room.vertices) || [], null);\n    if (want.cabs) {\n      for (const other of cabinets) {\n        if (other.id === cab.id) continue;\n        scanPoly(getCornersForPush(other, other.x, other.y), other.id);\n      }\n    }\n    if (want.pillars) {\n      for (const ob of (roomConfig.perimeterItems || [])) {\n        if (!ob || !ob.widthMm || !ob.depthMm) continue;\n        scanPoly(getCornersForPush(ob, ob.x, ob.y), null);\n      }\n    }\n    // Distance plus what was struck - the return needs to know which cabinet\n    // it met so that unit's now-covered end panel can be dropped.\n    return isFinite(minT) ? { t: minT, cabId: hitCabId } : null;\n  }\n\n  // Nearest unit the RETURN should grow to meet: the one whose end panel faces\n  // this corner unit's front (blank panel + door), anywhere along its width.\n  //\n  // A single ray from the post samples ONE lateral position, so a unit sitting\n  // further along the blank panel is missed entirely and the ray sails on to\n  // the far wall - which is what produced a full 375 panel through the unit it\n  // should have stopped at. This instead projects every candidate end onto the\n  // unit's front normal and takes the nearest one that lies within its width.\n  // opts.anySide: any unit's end in the same height band counts, panel or\n  // not - for clampCornerReturns, which only needs to know where the return\n  // has to STOP.\n  function returnReachToNeighbour(cab, opts = {}) {\n    const cu = cab && cab.cornerUnit;\n    if (!cu) return null;\n    const myBand = opts.anySide ? epVerticalRange(cab) : null;\n    const W = cab.widthMm || 0, D = cab.depthMm || 0;\n    const cx = cab.x + W / 2, cy = cab.y + D / 2;\n    const th = ((cab.rotationDeg || 0) * Math.PI) / 180;\n    const cs = Math.cos(th), sn = Math.sin(th);\n    // Front normal (cab-local -Y) and the along-run axis (cab-local +X).\n    const nx = sn,  ny = -cs;\n    const ax = cs,  ay = sn;\n    // Centre of the front face.\n    const fx = cx + 0 * cs - (-D / 2) * sn;\n    const fy = cy + 0 * sn + (-D / 2) * cs;\n\n    let best = null;\n    for (const other of cabinets) {\n      if (!other || other.id === cab.id) continue;\n      if (opts.anySide ? !epRangesOverlap(myBand, epVerticalRange(other)) : !other.endPanels) continue;\n      const W2 = other.widthMm || 0, D2 = other.depthMm || 0;\n      const c2x = other.x + W2 / 2, c2y = other.y + D2 / 2;\n      const t2 = ((other.rotationDeg || 0) * Math.PI) / 180;\n      const cs2 = Math.cos(t2), sn2 = Math.sin(t2);\n      const mid = (lx, ly) => ({ x: c2x + lx * cs2 - ly * sn2,\n                                 y: c2y + lx * sn2 + ly * cs2 });\n      // The customer's LEFT is cabinet-local +X (epUserSideOutward); this\n      // had them swapped, so it measured to the FAR end of the unit and an\n      // Auto return ran 375 across its doors (Arden, 2026-10-21). A unit of\n      // the corner unit's own kind drops that panel once the post meets it\n      // (epDecideActive: the post finishes its end), so the return runs to\n      // its carcase; any other kind (a tall beside a wall corner) keeps its\n      // panel, and the return stops at the panel's outer face.\n      // Even a panel set by hand: the return replaces it (clampCornerReturns\n      // takes it off - Arden, 2026-10-22).\n      const keepsSide = () => epCategoryGroup(other) !== epCategoryGroup(cab);\n      for (const [side, pt] of [['left', mid(W2 / 2, 0)], ['right', mid(-W2 / 2, 0)]]) {\n        const _ep = other.endPanels && other.endPanels[side];\n        const _panel = !!(_ep && _ep.active);\n        if (!_panel && !opts.anySide) continue;\n        const dx = pt.x - fx, dy = pt.y - fy;\n        const fwd = dx * nx + dy * ny - (keepsSide(side) && _panel ? endPanelThickMm(_ep) : 0);   // how far in front of the face\n        const lat = Math.abs(dx * ax + dy * ay); // offset along the run\n        if (fwd <= 0) continue;                  // behind the front face\n        if (lat > W / 2 + EP_GAP_LOOKUP_TOL_MM) continue;   // not across this unit\n        if (!best || fwd < best) { best = fwd; if (opts.out) { opts.out.id = other.id; opts.out.side = side; } }\n      }\n    }\n    return best;\n  }\n\n  // A corner unit's RETURN never runs past the unit it meets: one left\n  // longer (an XL return sized before a neighbour moved in, or by the old\n  // Auto that measured to the far end of the unit) stood across that unit's\n  // doors, pushed its cornice / ceiling filler out and was cut as a panel no\n  // one needs (Arden, 2026-10-21). Shortened to meet the unit - never grown;\n  // that's Auto Post's job. Runs at the head of every end-panel walk (plan\n  // load, drops, adds), so the panel decisions see the corrected post.\n  // Returns the ids it touched (each corner unit + the unit its return now\n  // meets), for a caller that has to re-decide their end panels.\n  function clampCornerReturns() {\n    const touched = [];\n    for (let i = 0; i < cabinets.length; i++) {\n      const cab = cabinets[i];\n      const cu = cab && cab.cornerUnit;\n      if (!cu || !(cu.postYMm > 0)) continue;\n      const out = {};\n      const reach = returnReachToNeighbour(cab, { anySide: true, out });\n      if (reach == null) continue;\n      let post = cu.postYMm;\n      if (post > reach + 1) {\n        post = Math.max(CORNER_POST_MIN_MM, Math.round(reach));\n        cabinets[i] = { ...cab, cornerUnit: { ...cu, postYMm: post, xlReturn: post > CORNER_POST_MAX_MM } };\n        touched.push(cab.id);\n        if (out.id) touched.push(out.id);\n      }\n      // A return that meets a unit of its own kind FINISHES that unit's end:\n      // its end panel there is replaced by the post, even one set by hand\n      // (Arden, 2026-10-22). Handed back to Auto, which keeps it off.\n      const oi = out.id ? cabinets.findIndex(c => c && c.id === out.id) : -1;\n      const o = oi >= 0 ? cabinets[oi] : null;\n      const oep = o && o.endPanels && out.side ? o.endPanels[out.side] : null;\n      if (oep && oep.active && epCategoryGroup(o) === epCategoryGroup(cab) && post >= reach - 25) {\n        cabinets[oi] = { ...o, endPanels: { ...o.endPanels,\n          [out.side]: { ...oep, active: false, userSet: false, userOff: false } } };\n        if (!touched.includes(cab.id)) touched.push(cab.id);\n        touched.push(o.id);\n      }\n    }\n    return touched;\n  }\n\n  // How far the FRONT of the unit round the corner (the one the return meets)\n  // stands past the run post's wall-side edge, along the run towards the\n  // corner. 0 when it doesn't (the usual corner: the run's front lands on the\n  // post edge). Planner Phase 2 row 36: wall units lined up with the tall\n  // housings stood 66mm past it, and the post could never be grown to them.\n  // A reduced depth corner BASE unit's void follows the run round its corner\n  // (bug sheet row 69, Arden, 2026-11-02): the reach is how far forward the\n  // units at its void end stand, not its own depth - a 300 unit reaching only\n  // 300 had no void at all (its 360 blank is already past that), so its door\n  // met a 570 run. 570 with nothing there. Standard depth corners keep their\n  // saved reach, so no placed standard unit shifts.\n  function reducedCornerReachMm(cab) {\n    const cu = cab.cornerUnit, W = cab.widthMm || 0, D = cab.depthMm || 0;\n    const s = cu.hand === 'left' ? -1 : 1;   // the void end, cab-local x\n    const edge = s * W / 2;\n    const cx = cab.x + W / 2, cy = cab.y + D / 2;\n    const th = ((cab.rotationDeg || 0) * Math.PI) / 180, cs = Math.cos(th), sn = Math.sin(th);\n    let reach = -1;\n    for (const o of cabinets) {\n      if (!o || o.id === cab.id || !/^(base|corner-base|tall)/i.test(o.category || '')) continue;\n      // Round the corner: at right angles to this unit.\n      if (Math.abs(Math.cos((((o.rotationDeg || 0) - (cab.rotationDeg || 0)) * Math.PI) / 180)) > 0.1) continue;\n      const ow = o.widthMm || 0, od = o.depthMm || 0;\n      if (!ow || !od) continue;\n      const ocx = o.x + ow / 2, ocy = o.y + od / 2;\n      const oth = ((o.rotationDeg || 0) * Math.PI) / 180, ocs = Math.cos(oth), osn = Math.sin(oth);\n      let x0 = Infinity, x1 = -Infinity, y0 = Infinity, y1 = -Infinity;\n      for (const [lx, ly] of [[-ow / 2, -od / 2], [ow / 2, -od / 2], [ow / 2, od / 2], [-ow / 2, od / 2]]) {\n        const dx = ocx + lx * ocs - ly * osn - cx, dy = ocy + lx * osn + ly * ocs - cy;\n        const px = dx * cs + dy * sn, py = -dx * sn + dy * cs;\n        x0 = Math.min(x0, px); x1 = Math.max(x1, px); y0 = Math.min(y0, py); y1 = Math.max(y1, py);\n      }\n      // Its back in line with this unit's void end, and standing in front of\n      // this unit (local -y is the front).\n      const far = s > 0 ? x1 : x0, near = s > 0 ? x0 : x1;\n      if (Math.abs(far - edge) > 60 || y1 < -D / 2 - 150 || y0 > D / 2) continue;\n      reach = Math.max(reach, s * (edge - near));\n    }\n    return reach < 0 ? CORNER_POST_REACH_MM : Math.max(0, Math.min(CORNER_POST_REACH_MM, Math.round(reach)));\n  }\n  function syncReducedCornerReach() {\n    for (let i = 0; i < cabinets.length; i++) {\n      const cab = cabinets[i];\n      if (!cab || !cab.cornerUnit || !(cab.depthMm > 0) || cab.depthMm >= CORNER_POST_REACH_MM) continue;\n      if (!/^(base|corner-base)/i.test(cab.category || '')) continue;\n      const reachMm = reducedCornerReachMm(cab);\n      if (reachMm === cab.cornerUnit.reachMm) continue;\n      const cu = normaliseCornerUnit({ ...cab.cornerUnit, reachMm });\n      // Pinned at the corner end, as a post change is: the door end moves.\n      const widthMm = cu.cabinetMm + cu.voidMm;\n      const dW = widthMm - (cab.widthMm || widthMm);\n      const th = ((cab.rotationDeg || 0) * Math.PI) / 180;\n      const k = (cu.hand === 'left') ? 1 : -1;\n      cabinets[i] = { ...cab, cornerUnit: cu, widthMm,\n        x: cab.x - dW / 2 + k * (dW / 2) * Math.cos(th),\n        y: cab.y + k * (dW / 2) * Math.sin(th) };\n    }\n  }\n\n  function cornerPostFrontGap(cab) {\n    const cu = cab && cab.cornerUnit && normaliseCornerUnit(cab.cornerUnit);\n    if (!cu) return 0;\n    const out = {};\n    if (returnReachToNeighbour(cab, { anySide: true, out }) == null || !out.id) return 0;\n    const o = cabinets.find(c => c && c.id === out.id);\n    if (!o) return 0;\n    const W = cab.widthMm || 0, D = cab.depthMm || 0;\n    const th = ((cab.rotationDeg || 0) * Math.PI) / 180;\n    const ax = Math.cos(th), ay = Math.sin(th);\n    const toCorner = cu.hand === 'right' ? 1 : -1;\n    const edgeLocal = cu.hand === 'right'\n      ? -W / 2 + cu.doorMm + cu.postXMm\n      : -W / 2 + cu.voidMm + cu.blankMm;\n    const ex = cab.x + W / 2 + edgeLocal * ax, ey = cab.y + D / 2 + edgeLocal * ay;\n    // The neighbour's front must face back along the run, at the post.\n    const W2 = o.widthMm || 0, D2 = o.depthMm || 0;\n    const t2 = ((o.rotationDeg || 0) * Math.PI) / 180;\n    const nx2 = Math.sin(t2), ny2 = -Math.cos(t2);\n    if ((nx2 * ax + ny2 * ay) * toCorner > -0.9) return 0;\n    const fx = o.x + W2 / 2 + (D2 / 2) * Math.sin(t2), fy = o.y + D2 / 2 - (D2 / 2) * Math.cos(t2);\n    const g = ((fx - ex) * ax + (fy - ey) * ay) * toCorner;\n    return g > 0.5 ? Math.round(g) : 0;\n  }\n\n  // The note the Corner Posts tab shows when a typed return was shortened to\n  // meet a unit, so the box changing back doesn't look like nothing happened.\n  let cornerPostNote = null;\n  function getCornerPostNote(cabId) {\n    return cornerPostNote && cornerPostNote.cabId === cabId ? cornerPostNote.text : '';\n  }\n\n  function handleAutoCornerPost(cabinetId, axis) {\n    const cab = cabinets.find(c => c.id === cabinetId);\n    if (!cab || !cab.cornerUnit) return;\n    const cu = cab.cornerUnit;\n    // Run post: first line its face up with the front of the unit round the\n    // corner (grows into the blank panel), then close any gap at the door end.\n    if (axis === 'x') {\n      const front = cornerPostFrontGap(cab);\n      if (front > 0) {\n        const np = Math.min(CORNER_POST_XL_MAX_MM, Math.round(cu.postXMm || 0) + front);\n        handleUpdateCornerUnit(cabinetId, { postXMm: np, xlRun: np > CORNER_POST_MAX_MM });\n        const after = cabinets.find(c => c.id === cabinetId);\n        const hit = after && cornerRayHit(after, 'x');\n        if (hit && Math.round(hit.t) > 0) {\n          const np2 = Math.min(CORNER_POST_XL_MAX_MM, after.cornerUnit.postXMm + Math.round(hit.t));\n          handleUpdateCornerUnit(cabinetId, { postXMm: np2, xlRun: np2 > CORNER_POST_MAX_MM });\n        }\n        return;\n      }\n    }\n    let gap;\n    if (axis === 'y') {\n      // Return: grow to the neighbour whose end panel faces this unit's front.\n      const reach = returnReachToNeighbour(cab);\n      if (reach == null) return;\n      gap = Math.round(reach) - Math.round(cu.postYMm || 0);\n      // The return is set to what fits, SHORTER as well as longer: one left\n      // over-long (375 across the next unit's doors) comes back to the panel\n      // (Arden, 2026-10-21).\n      if (gap === 0) return;\n    } else {\n      const hitInfo = cornerRayHit(cab, axis);\n      if (!hitInfo) return;\n      gap = Math.round(hitInfo.t);\n      if (gap <= 0) return;\n    }\n    const currentPost = axis === 'x' ? cu.postXMm : cu.postYMm;\n    // Either post may need to reach further than a post can, so Auto Post\n    // ticks that post's XL itself and the wall end panel joins the order -\n    // the user shouldn't have to know the threshold.\n    //\n    // Nothing else is needed here: postYMm IS the return, so the bigger number\n    // flows through the existing connection logic on its own. snapFootprintAABB\n    // already extends the corner unit's footprint by postYMm so neighbours snap\n    // to the post face, and autoDetectEndPanels already allows for the post\n    // when it decides which ends are covered. An XL return is just a longer\n    // post to both of them.\n    // Along the run too (Arden, 2026-10-14): a gap bigger than a post is lost\n    // in an XL post rather than left open or given a filler mid-run, so both\n    // axes may run to the XL ceiling. handleUpdateCornerUnit still keeps the\n    // along-run post short of eating the whole blank panel.\n    const cap = CORNER_POST_XL_MAX_MM;\n    const newPost = Math.max(CORNER_POST_MIN_MM, Math.min(cap, currentPost + gap));\n    if (newPost === currentPost) return;\n    if (axis === 'x') {\n      handleUpdateCornerUnit(cabinetId, { postXMm: newPost, xlRun: newPost > CORNER_POST_MAX_MM });\n    } else {\n      handleUpdateCornerUnit(cabinetId, {\n        postYMm: newPost,\n        xlReturn: newPost > CORNER_POST_MAX_MM\n      });\n    }\n  }\n\n  // Per-end-panel colour override. handle = null resets to the\n  // cabinet's door colour (inherit).\n  function handleSetEndPanelColour(cabinetId, side, handle) {\n    if (side !== 'left' && side !== 'right') return;\n    const idx = cabinets.findIndex(c => c.id === cabinetId);\n    if (idx === -1) return;\n    const prev = cabinets[idx].endPanelColours || { left: null, right: null };\n    cabinets[idx] = { ...cabinets[idx], endPanelColours: { ...prev, [side]: handle || null } };\n    rerender();\n  }\n\n  // Per-trim-segment colour override. handle = null deletes the\n  // override and the segment falls back to the global door colour.\n  function handleSetSegmentColour(segmentId, handle) {\n    if (!segmentId) return;\n    if (handle) {\n      segmentColours = { ...segmentColours, [segmentId]: handle };\n    } else {\n      const next = { ...segmentColours };\n      delete next[segmentId];\n      segmentColours = next;\n    }\n    rerender();\n  }\n\n  // Colour for PARTS picked in the Door & Carcase popup (Arden, 2026-10-06):\n  //   { cabId, kind: 'end', side }  - that end: its panel or filler, and the\n  //                                   radius / square posts that follow it\n  //   { cabId, kind: 'back' }       - the unit's breakfast-bar back panel\n  // A part set to its unit's own door colour goes back to FOLLOWING the door,\n  // so a later door change still carries it. The colour decides the board a\n  // panel is cut from and its basket line, so an open basket is re-synced.\n  function handleSetPartColours(parts, handle) {\n    if (!Array.isArray(parts) || !parts.length || !handle) return;\n    const byId = new Map();\n    for (const p of parts) {\n      if (!p || p.cabId == null) continue;\n      const k = String(p.cabId);\n      if (!byId.has(k)) byId.set(k, []);\n      byId.get(k).push(p);\n    }\n    cabinets = cabinets.map(c => {\n      const mine = byId.get(String(c.id));\n      if (!mine) return c;\n      const own = handle !== c.doorColourHandle ? handle : null;\n      let next = c;\n      for (const p of mine) {\n        if (p.kind === 'end' && (p.side === 'left' || p.side === 'right')) {\n          next = { ...next, endPanelColours: { ...(next.endPanelColours || { left: null, right: null }), [p.side]: own } };\n        } else if (p.kind === 'back') {\n          next = { ...next, backPanelColour: own };\n        }\n      }\n      return next;\n    });\n    rerender();\n    scheduleBasketResync();\n  }\n\n  // ---- Global colour state handlers ----\n\n  // Push a buying-style ctx into btk_comparison_styles (the \"alts\"\n  // list the drawer reads). Idempotent - won't add a duplicate.\n  // Also filters out any alt that matches `excludeCtx` so we never\n  // keep the same style as both the active AND an alt.\n  function pushBuyingStyleAlt(ctxToPush, excludeCtx) {\n    if (!ctxToPush || !ctxToPush.style || !ctxToPush.colour) return;\n    try {\n      let alts = [];\n      try { alts = JSON.parse(sessionStorage.getItem('btk_comparison_styles') || '[]'); } catch (_) {}\n      const already = alts.some(a => a && a.style === ctxToPush.style && a.colour === ctxToPush.colour);\n      if (!already) alts.push(ctxToPush);\n      if (excludeCtx && excludeCtx.style && excludeCtx.colour) {\n        alts = alts.filter(a => !(a && a.style === excludeCtx.style && a.colour === excludeCtx.colour));\n      }\n      sessionStorage.setItem('btk_comparison_styles', JSON.stringify(alts));\n    } catch (_) {}\n  }\n\n  // Mirror the planner's current (style, door, carcase) into the\n  // shared sessionStorage key the kitchen units listing + style\n  // detail pages read from. Lets the user pick a style here and\n  // see it reflected in the Active Buying Style bar everywhere,\n  // and pre-fills /pages/kitchens when they switch tabs. Idempotent\n  // - when the drawer triggers the change it has already written\n  // the same data, so this is a no-op in that direction.\n  function syncBuyingStyleToSession() {\n    if (!kitchenStyleId) return;\n    let prev = null;\n    try { prev = JSON.parse(sessionStorage.getItem('btk_kitchen_context') || 'null'); } catch (_) {}\n    const ks = Catalogue.getKitchenStyle?.(kitchenStyleId);\n    const doorColour = lookupColourInList(\n      Catalogue.getDoorColoursForStyle?.(kitchenStyleId), globalDoorColourHandle\n    );\n    const next = {\n      style:      kitchenStyleId,\n      styleName:  ks?.name || prev?.styleName || kitchenStyleId,\n      colour:     globalDoorColourHandle || prev?.colour || '',\n      colourName: doorColour?.name || prev?.colourName || '',\n      carcase:    globalCarcaseColourHandle || prev?.carcase || 'white'\n    };\n    if (prev && prev.style === next.style && prev.colour === next.colour && prev.carcase === next.carcase) {\n      return;   // nothing changed, skip the storage + event spam\n    }\n    try { sessionStorage.setItem('btk_kitchen_context', JSON.stringify(next)); } catch (_) {}\n    reconcileBuyingStyleSlots();\n    // Mirror into cart attributes. Without this, the kitchen-units\n    // pages' top-bar (btk-units-top-bar.liquid) reads cart on load\n    // and unconditionally overwrites btk_kitchen_context - so any\n    // style picked here would be silently reset to the cart's stale\n    // value the moment the user navigates away. Same call shape the\n    // listing-page drawer's switchToStyle uses, just fire-and-forget.\n    try {\n      fetch('/cart/update.js', {\n        method: 'POST',\n        headers: { 'Content-Type': 'application/json' },\n        body: JSON.stringify({ attributes: {\n          kitchen_style:          next.style,\n          kitchen_style_name:     next.styleName || '',\n          kitchen_colour:         next.colour,\n          kitchen_carcase_colour: next.carcase\n        }})\n      });\n    } catch (_) {}\n    try { document.dispatchEvent(new CustomEvent('btk:style-changed', { detail: next })); } catch (_) {}\n  }\n\n  // Reconcile btk_style_slots against the current ctx + alts.\n  //\n  // A single modal commit can fire syncBuyingStyleToSession twice \u2014\n  // once when handleKitchenStyleChange resets the door colour to\n  // the new style's first-available, then again when the user's\n  // actual door pick arrives via handleSetGlobalDoorColour. Without\n  // this pass the first sync's slot key (which used the first-door\n  // colour) goes stale, so the drawer can't match it to any\n  // allStyles entry and renders a placeholder, AND\n  // btkCheckSlotsAndProceed on the listing page counts the stale\n  // entry as filled - falsely showing \"no slots left\".\n  //\n  // Strategy: keep slot positions stable, clear keys that no longer\n  // match the active or any alt, then drop the active + each alt\n  // into any empty position so the drawer has something to render\n  // for every saved style. Also runs on planner init so corruption\n  // from previous sessions self-heals on the next page load.\n  function reconcileBuyingStyleSlots() {\n    try {\n      let slots = [];\n      try { slots = JSON.parse(sessionStorage.getItem('btk_style_slots') || '[]'); } catch (_) {}\n      let ctxNow = null;\n      try { ctxNow = JSON.parse(sessionStorage.getItem('btk_kitchen_context') || 'null'); } catch (_) {}\n      let altsNow = [];\n      try { altsNow = JSON.parse(sessionStorage.getItem('btk_comparison_styles') || '[]'); } catch (_) {}\n      const validKeys = new Set();\n      if (ctxNow && ctxNow.style && ctxNow.colour) validKeys.add(ctxNow.style + ':' + ctxNow.colour);\n      altsNow.forEach(a => {\n        if (a && a.style && a.colour) validKeys.add(a.style + ':' + a.colour);\n      });\n      for (let i = 0; i < slots.length; i++) {\n        if (slots[i] && !validKeys.has(slots[i])) slots[i] = '';\n      }\n      validKeys.forEach(k => {\n        if (slots.indexOf(k) !== -1) return;\n        const emptyIdx = slots.indexOf('');\n        if (emptyIdx > -1) slots[emptyIdx] = k;\n        else if (slots.length < 3) slots.push(k);\n      });\n      while (slots.length < 3) slots.push('');\n      sessionStorage.setItem('btk_style_slots', JSON.stringify(slots));\n    } catch (_) {}\n  }\n  reconcileBuyingStyleSlots();\n  function lookupColourInList(list, handle) {\n    if (!list || !handle) return null;\n    return list.find(c => c.handle === handle) || null;\n  }\n\n  function handleSetGlobalDoorColour(handle) {\n    globalDoorColourHandle = handle;\n    // No rerender - global change alone doesn't affect any rendered\n    // cabinet. The cabinets UI module re-renders its own picker.\n    syncBuyingStyleToSession();\n  }\n\n  function handleSetGlobalCarcaseColour(handle) {\n    globalCarcaseColourHandle = handle;\n    syncBuyingStyleToSession();\n  }\n\n  function handleSetWallColour(handle) {\n  const colour = getWallColour(handle);\n  if (!colour) return;\n  wallColourHandle = colour.handle;\n  if (handle3D && handle3D.setWallColour) handle3D.setWallColour(colour.hex);\n  roomShapeHandle?.refresh();\n}\n\nfunction handleSetFloorColour(handle) {\n  const colour = resolveFloorColour(handle);\n  if (!colour) return;\n  floorColourHandle = colour.handle;\n  applyFloorTo3D();\n  roomShapeHandle?.refresh();\n}\n\n  // The carcase colour a cabinet may actually take when something wants to set\n  // one on it. A unit sold in only SOME carcase colours (the Larder Pantry is\n  // made in Davenport Oak only) must not take a kitchen-wide colour it isn't\n  // made in; it keeps its own if that is allowed, else falls to the first one\n  // that is. A STRICT no-op for every unit with no restriction, which is all\n  // of them bar the few the unit_type names - so nothing else changes.\n  function carcaseHandleFor(cab, wanted) {\n    const ut   = Catalogue.getUnitType?.(cab.unitTypeId);\n    // A no_carcase_colour unit (Integrated Extractor door, end panels,\n    // fillers) never takes one - a group restyle in Door & Carcase used to\n    // hand it the group's carcase colour.\n    if (ut && ut.noCarcaseColour) return null;\n    const only = (ut && Array.isArray(ut.carcaseColourHandles)) ? ut.carcaseColourHandles : [];\n    if (!only.length || wanted == null) return wanted;\n    const allowed = Catalogue.getCarcaseColoursForUnit(cab.unitTypeId, cab.kitchenStyleId) || [];\n    if (!allowed.length || allowed.some(c => c.handle === wanted)) return wanted;\n    return allowed.some(c => c.handle === cab.carcaseColourHandle)\n      ? cab.carcaseColourHandle\n      : allowed[0].handle;\n  }\n\n  function handleApplyColoursToAll() {\n    cabinets = cabinets.map(c => ({\n      ...c,\n      doorColourHandle:    globalDoorColourHandle    ?? c.doorColourHandle,\n      carcaseColourHandle: carcaseHandleFor(c, globalCarcaseColourHandle) ?? c.carcaseColourHandle\n    }));\n    rerender();\n  }\n\n  function handleApplyColoursToSelected(cabinetId) {\n    const idx = cabinets.findIndex(c => c.id === cabinetId);\n    if (idx === -1) return;\n    cabinets[idx] = {\n      ...cabinets[idx],\n      doorColourHandle:    globalDoorColourHandle    ?? cabinets[idx].doorColourHandle,\n      carcaseColourHandle: carcaseHandleFor(cabinets[idx], globalCarcaseColourHandle)\n                           ?? cabinets[idx].carcaseColourHandle\n    };\n    rerender();\n  }\n\n  // Re-point any cabinet whose variant does not belong to its own style.\n  // A kitchen style IS a separate Shopify product, and handleApplyStyleToIds\n  // used to move kitchenStyleId while leaving variantId on the original\n  // style's product: the plan rendered in the new style while the basket line\n  // carried the old one. That is fixed at the source now, but plans SAVED in\n  // the broken state stay broken until something repairs them, and a customer\n  // will never think to re-apply a style they already set.\n  // Needs every plan style's products loaded first (see the load path).\n  // Returns how many were repaired.\n  function repairStyleVariants() {\n    let fixed = 0;\n    cabinets = cabinets.map(c => {\n      if (!c || c.variantId == null || !c.unitTypeId || !c.kitchenStyleId) return c;\n      const vi = Catalogue.getVariantInfo?.(c.variantId);\n      const vStyle = vi && vi.product && vi.product.kitchenStyleId;\n      // Unknown product - that style's catalogue is not loaded, or the variant\n      // was withdrawn. Leave it rather than guess: a wrong repair is worse.\n      if (!vStyle || vStyle === c.kitchenStyleId) return c;\n      const info = Catalogue.findVariantInStyle?.(c.variantId, c.kitchenStyleId, c.unitTypeId) || Catalogue.findVariant({\n        unitTypeId:     c.unitTypeId,\n        kitchenStyleId: c.kitchenStyleId,\n        widthMm:        c.widthMm,\n        depthMm:        c.depthMm,\n        heightMm:       c.heightMm,\n        optionValues:   Catalogue.nonDimensionOptionValues\n                          ? Catalogue.nonDimensionOptionValues(c.variantId) : null\n      });\n      const newVariantId = info && info.variant && info.variant.id;\n      if (!newVariantId) return c;   // not sold here in this size - leave as-is\n      fixed++;\n      const _cmp = info.variant.compareAtPrice;\n      return {\n        ...c,\n        variantId:      newVariantId,\n        priceCents:     (info.priceCents != null) ? info.priceCents : c.priceCents,\n        compareAtCents: (typeof _cmp === 'number') ? _cmp : null\n      };\n    });\n    return fixed;\n  }\n\n  // A unit saved WITHOUT its plinth in its height. A unit's height is the\n  // carcase plus the unit type's plinth, worked out when it is added and then\n  // SAVED - so when a unit type's plinth is corrected, plans already holding\n  // it keep the old sum. The Tall Larder Corner Unit had plinth 0 until\n  // 2026-11-17 (sales bug sheet row 135): its saved 1970 / 2150 now read as\n  // 1820 / 2000 of carcase on a 150 plinth, and it stood 150mm lower than the\n  // larder beside it (Arden, 'Pastry Bench Test'). Only a unit whose height is\n  // EXACTLY its bare carcase is touched, and never one with a plinth of its\n  // own (floating / as-base units carry c.plinthHeightMm). Needs the unit's\n  // style products loaded, like repairStyleVariants. Returns how many.\n  function repairMissingPlinthHeights() {\n    let fixed = 0;\n    cabinets = cabinets.map(c => {\n      if (!c || !c.unitTypeId || c.variantId == null || c.plinthHeightMm != null || c.asBase) return c;\n      const def = Catalogue.buildCabinetDefinition?.({ unitTypeId: c.unitTypeId, variantId: c.variantId, kitchenStyleId: c.kitchenStyleId });\n      if (!def || !(def.carcaseHeightMm > 0) || !(def.plinthHeightMm > 0)) return c;\n      if (c.heightMm !== def.carcaseHeightMm) return c;\n      fixed++;\n      return { ...c, heightMm: def.carcaseHeightMm + def.plinthHeightMm };\n    });\n    return fixed;\n  }\n\n  // After a style / colour change: when the whole plan now stands in ONE\n  // style + door + carcase, that becomes the active planning style (Arden,\n  // 2026-09-30) - buyingStyles[0], the planner's kitchenStyleId + global\n  // colours, and the buying-style bar everywhere - so what gets added next\n  // matches what is already there. A plan still mixing styles or colours\n  // keeps its active style as it is. Only called from the change handlers,\n  // never on a plain render: a customer who picks another active style to\n  // add, say, an island in it must not be flipped back by the next redraw.\n  // Units that cannot follow the plan are left out of the count: free-standing\n  // appliances (no door or carcase of their own) and units made in only some\n  // carcase colours (the Pantry, Davenport Oak only) for the carcase.\n  function adoptSinglePlanStyle() {\n    let combo = null;\n    for (const c of cabinets) {\n      if (!c || c.freestandingAppliance || !c.kitchenStyleId) continue;\n      const ut = Catalogue.getUnitType?.(c.unitTypeId);\n      const carcaseFixed = !!(ut && Array.isArray(ut.carcaseColourHandles) && ut.carcaseColourHandles.length);\n      if (!combo) combo = { styleId: c.kitchenStyleId, doorHandle: c.doorColourHandle || null, carcaseHandle: null };\n      if (c.kitchenStyleId !== combo.styleId || (c.doorColourHandle || null) !== combo.doorHandle) return;\n      if (carcaseFixed) continue;\n      if (combo.carcaseHandle == null) combo.carcaseHandle = c.carcaseColourHandle || null;\n      else if ((c.carcaseColourHandle || null) !== combo.carcaseHandle) return;\n    }\n    if (!combo || !combo.doorHandle) return;\n    if (combo.carcaseHandle == null) combo.carcaseHandle = globalCarcaseColourHandle;\n    const cur = buyingStyles[0];\n    if (cur && cur.styleId === combo.styleId && cur.doorHandle === combo.doorHandle\n        && cur.carcaseHandle === combo.carcaseHandle && kitchenStyleId === combo.styleId\n        && globalDoorColourHandle === combo.doorHandle && globalCarcaseColourHandle === combo.carcaseHandle) return;\n    // To the front of the buying styles: moved there if already one of them,\n    // otherwise added - the old active style stays on as an alternate.\n    const same = s => s && s.styleId === combo.styleId && s.doorHandle === combo.doorHandle && s.carcaseHandle === combo.carcaseHandle;\n    buyingStyles = [combo, ...buyingStyles.filter(s => !same(s))].slice(0, J_STYLE_MAX);\n    const styleMoved = kitchenStyleId !== combo.styleId;\n    kitchenStyleId            = combo.styleId;\n    globalDoorColourHandle    = combo.doorHandle;\n    globalCarcaseColourHandle = combo.carcaseHandle;\n    syncJourneyFromOptions();\n    syncBuyingStylesToSession();\n    // Synchronous up to here (the size card fires the restyle without waiting\n    // on it). A restyle has already loaded the style's products; Add Units\n    // repaints once they are in either way.\n    const refresh = () => cabinetsHandle?.refresh();\n    if (styleMoved) ensureStyleProducts(kitchenStyleId).then(refresh, refresh);\n    else refresh();\n  }\n\n  // Step 3 (Change Style & Colours) - apply a style + colour patch to\n  // a specific set of cabinets (a row's group, or the currently\n  // selected subset). Each cabinet stores its own kitchenStyleId +\n  // door/carcase handles so the change is per-unit.\n  async function handleApplyStyleToIds(ids, patch) {\n    if (!Array.isArray(ids) || ids.length === 0 || !patch) return;\n    // Restyling to another style needs THAT style's products loaded so the\n    // re-render can resolve each cabinet's variant (see ensureStyleProducts).\n    const targetIds = new Set(ids);\n    // The ranges the units are moving out of - parts added from the basket\n    // follow a range the plan no longer has any unit in (see moveExtrasToStyle).\n    const restyledFrom = new Set(cabinets.filter(c => c && targetIds.has(c.id)).map(c => c.kitchenStyleId).filter(Boolean));\n    // ...and the styles the units are coming FROM: the like-for-like match\n    // reads each unit's current variant (findVariantInStyle), and a mixed\n    // plan's non-leading styles only load in the background on plan load, so\n    // they can still be missing here - or have failed (the catalogue endpoint\n    // 500s after a push). Without them every corner fell back to the\n    // footprint match and was reported \"not available\" (Arden, 2026-09-30).\n    if (patch.styleId) {\n      const fromStyles = [...new Set(cabinets.filter(c => targetIds.has(c.id)).map(c => c.kitchenStyleId).filter(Boolean))];\n      await Promise.all([patch.styleId, ...fromStyles].map(s => ensureStyleProducts(s).catch(() => {})));\n    }\n    // \u26A0 THE VARIANT HAS TO FOLLOW THE STYLE. Each kitchen style is a SEPARATE\n    // Shopify product, so a style change is a product change. Moving\n    // kitchenStyleId on its own left the cab pointing at the old style's\n    // variant: the plan re-rendered in the new style (the render resolves per\n    // style on every draw) while the basket line, which sends c.variantId\n    // verbatim, stayed on the old one - so a two-style plan reached the cart\n    // as a single style. End panels never showed the bug because their board\n    // lines resolve their product live at basket-build time\n    // (endPanelBoardProduct), which is why \"the panels survive\" was the clue.\n    // Confirmed on the saved plan \"2 style test\": two SHB cabs, two different\n    // kitchenStyleIds, one shared variantId 58272785662296.\n    const skipped = [];\n    cabinets = cabinets.map(c => {\n      if (!targetIds.has(c.id)) return c;\n      const styleId = patch.styleId ?? c.kitchenStyleId;\n      const next = {\n        ...c,\n        kitchenStyleId:      styleId,\n        doorColourHandle:    patch.doorHandle    ?? c.doorColourHandle,\n        // Restricted units keep a colour they are actually made in - this is\n        // the funnel for the Style Colours panel AND the size card's Confirm.\n        carcaseColourHandle: carcaseHandleFor({ ...c, kitchenStyleId: styleId }, patch.carcaseHandle)\n                             ?? c.carcaseColourHandle\n      };\n      // Its own plinth colour (an island's) follows the doors again, as the\n      // kitchen's trim colours do below.\n      if ((patch.styleId || patch.doorHandle) && next.plinthColour) delete next.plinthColour;\n      // Colour-only patch, or the style is not actually moving: nothing to\n      // re-point. Same for cabs that carry no product of their own (free\n      // -standing appliances, board-only cabs) - they have no variant to move.\n      if (!patch.styleId || styleId === c.kitchenStyleId\n          || c.variantId == null || !c.unitTypeId) return next;\n      // Like for like or not at all, the same rule swapCabinetUnitType uses.\n      // The same variant in the new style, matched on its own options (a\n      // corner's footprint is not its product size - see findVariantInStyle),\n      // then the footprint as before, holding the non-dimension config (door\n      // layout etc.) so a restyle can never silently resize or reconfigure a unit.\n      const info = Catalogue.findVariantInStyle?.(c.variantId, styleId, c.unitTypeId) || Catalogue.findVariant({\n        unitTypeId:     c.unitTypeId,\n        kitchenStyleId: styleId,\n        widthMm:        c.widthMm,\n        depthMm:        c.depthMm,\n        heightMm:       c.heightMm,\n        optionValues:   Catalogue.nonDimensionOptionValues\n                          ? Catalogue.nonDimensionOptionValues(c.variantId) : null\n      });\n      const newVariantId = info && info.variant && info.variant.id;\n      if (!newVariantId) {\n        // This style does not sell this unit in this size / config. Leave the\n        // cabinet completely alone, style included: a half-applied restyle is\n        // exactly the state that put the wrong product in the basket. The\n        // colours are style-scoped too, so they must not move on their own.\n        skipped.push(c);\n        return c;\n      }\n      next.variantId  = newVariantId;\n      next.priceCents = (info.priceCents != null) ? info.priceCents : c.priceCents;\n      const _cmp = info.variant && info.variant.compareAtPrice;\n      next.compareAtCents = (typeof _cmp === 'number') ? _cmp : null;\n      return next;\n    });\n    // THE TRIMS FOLLOW THE UNITS (Arden, 2026-10-09). A cornice, pelmet or\n    // plinth given its own colour in Customise > Cornice, Pelmet & Plinth kept\n    // it through a restyle, so the doors changed and the trims stayed in the\n    // old colour. A change to the WHOLE plan's style or door colour hands every\n    // trim back to matching its units; a change to only some units clears just\n    // a trim colour the plan's ranges no longer sell.\n    if (patch.styleId || patch.doorHandle) {\n      const doorCabs = cabinets.filter(c => c && c.doorColourHandle);\n      const wholePlan = doorCabs.length > 0 && doorCabs.every(c => targetIds.has(c.id));\n      const planStyles = [...new Set(cabinets.map(c => c && c.kitchenStyleId).filter(Boolean))];\n      const sold = (h) => planStyles.some(s => (Catalogue.getDoorColoursForStyle(s) || []).some(d => d.handle === h));\n      let nextFs = featureStyles;\n      for (const f of ['plinth', 'cornice', 'pelmet']) {\n        const h = nextFs[f + 'Colour'];\n        if (h && (wholePlan || !sold(h))) nextFs = { ...nextFs, [f + 'Colour']: null };\n      }\n      featureStyles = nextFs;\n    }\n    // A PLINTH, CORNICE or PELMET the new range does not sell goes back to that\n    // trim's default (Arden, 2026-10-10): a skirting plinth chosen on the old\n    // range stayed set on one that has none, and the stored choice still drove\n    // where the trim sits (a Classic cornice stands 50mm proud) and what the\n    // Trims popup shows. One the range does sell is kept; 'none' stays none.\n    // The plan's trims are drawn from its first unit's range (the 3D's\n    // repTrimStyleId), so that is the range checked.\n    if (patch.styleId) {\n      const repStyle = (cabinets.find(c => c && c.kitchenStyleId) || {}).kitchenStyleId || null;\n      const trims = repStyle ? (Catalogue.getTrimForStyle?.(repStyle) || {}) : {};\n      for (const f of ['plinth', 'cornice', 'pelmet']) {\n        const sel = featureStyles[f];\n        if (!repStyle || !sel || sel === 'none' || sel === CEILING_FILLER || sel === DEFAULT_FEATURE_STYLES[f]) continue;\n        const list = trims[f] || [];\n        const sold = list.filter(p => p && p.available !== false);\n        const has = (sold.length ? sold : list).some(p => String(p.name || '').toLowerCase() === String(sel).toLowerCase());\n        if (list.length && !has) featureStyles = { ...featureStyles, [f]: DEFAULT_FEATURE_STYLES[f] };\n      }\n    }\n    // Before the render, so the autosave it triggers carries the new active style.\n    adoptSinglePlanStyle();\n    rerender();\n    styleColoursHandle?.refresh();\n    // DOORS ONLY AND OTHER PARTS FROM THE BASKET (Sales line 104): a 715 x 496\n    // door added with Add other items stayed the old range's product when the\n    // units changed range. Once no unit is left in a range, its parts move to\n    // the units' new range, like for like - before the resync, so the rebuilt\n    // basket carries them.\n    let extrasMissed = [];\n    if (patch.styleId) {\n      const emptied = [...restyledFrom].filter(s => s !== patch.styleId && !cabinets.some(c => c && c.kitchenStyleId === s));\n      if (emptied.length) extrasMissed = await moveExtrasToStyle(new Set(emptied), patch.styleId);\n    }\n    // A colour or style change is what the basket lines carry, so an open\n    // basket is brought up to date now, not on its next rebuild.\n    scheduleBasketResync();\n    if (extrasMissed.length && window.BTKKPDialog) {\n      const styleName = Catalogue.getKitchenStyle?.(patch.styleId)?.name || 'that style';\n      const one = extrasMissed.length === 1;\n      window.BTKKPDialog.alert(\n        (one ? 'This item in your basket is' : 'These items in your basket are') + ' not made in ' +\n        styleName + ' in the same size, so ' + (one ? 'it has' : 'they have') + ' been left as ' +\n        (one ? 'it was' : 'they were') + ':\\n\\n' + extrasMissed.map(n => '\u2022 ' + n).join('\\n') + '\\n\\n' +\n        'You can remove ' + (one ? 'it' : 'them') + ' from your basket and choose again with Add other items.',\n        { title: 'Some basket items could not change' }\n      );\n    }\n    if (skipped.length && window.BTKKPDialog) {\n      const styleName = Catalogue.getKitchenStyle?.(patch.styleId)?.name || 'that style';\n      const names = skipped.map(c => {\n        const size = c.widthMm ? ` ${c.widthMm}mm` : '';\n        return `\u2022 ${c.code || c.name || 'Unit'}${size}`;\n      });\n      // A unit whose CURRENT range's details did not load cannot be matched\n      // like for like - that is a loading failure, not \"not available\", and\n      // saying so is what tells a refresh apart from a missing product.\n      const unloaded = skipped.filter(c => !Catalogue.getVariantInfo?.(c.variantId));\n      if (unloaded.length) {\n        window.BTKKPDialog.alert(\n          `The details for ${unloaded.length === 1 ? 'this unit' : 'these units'} did not load, so ` +\n          `${unloaded.length === 1 ? 'it has' : 'they have'} been left as ${unloaded.length === 1 ? 'it was' : 'they were'}:\\n\\n` +\n          `${names.join('\\n')}\\n\\nPlease refresh the page and try the change again.`,\n          { title: 'Some units could not change' }\n        );\n        return;\n      }\n      window.BTKKPDialog.alert(\n        `${skipped.length === 1 ? 'This unit is' : 'These units are'} not available in ` +\n        `${styleName} in the same size, so ${skipped.length === 1 ? 'it has' : 'they have'} ` +\n        `been left as ${skipped.length === 1 ? 'it was' : 'they were'}:\\n\\n${names.join('\\n')}\\n\\n` +\n        `Everything else in your selection has changed.`,\n        { title: 'Some units could not change' }\n      );\n    }\n  }\n\n  // \u2500\u2500 Per-style scoped product loading \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n  // The inline catalogue carries ONLY the buying style's products (scoped +\n  // paginated - see sections/btk-kitchen-planner.liquid). Switching to another\n  // style fetches that style's scoped catalogue - the same\n  // /collections/<handle>?view=catalogue endpoint the storefront thumbnails use\n  // - and injects JUST its products into the engine, so big unit-group\n  // collections are no longer 50-capped in the planner. Cached per style in\n  // sessionStorage so repeat switches this session skip the fetch.\n  const _styleProductsInflight = new Map(); // styleId -> Promise<products[]>\n\n  // /collections/<style>?view=catalogue renders close to Shopify's Liquid\n  // render-time limit (see templates/collection.catalogue.liquid) and 500s\n  // intermittently - most often right after a theme push, when its\n  // server-side render cache is cold. A single failure used to leave the\n  // planner with NO products for the whole session, which shows up as an\n  // Add Units popup whose every group reads \"No matching cabinets\". Retry a\n  // couple of times, spaced out, before giving up on the attempt.\n  const STYLE_PRODUCTS_RETRIES  = 2;\n  const STYLE_PRODUCTS_RETRY_MS = 900;\n\n  async function fetchStyleProductsOnce(styleId) {\n    const handle = (window.BTKStyleData && window.BTKStyleData[styleId] && window.BTKStyleData[styleId].collectionHandle)\n      || ('bedroom-units-' + styleId);\n    const res = await fetch('/collections/' + encodeURIComponent(handle) + '?view=catalogue', { credentials: 'same-origin' });\n    if (!res.ok) throw new Error('planner catalogue fetch ' + res.status + ' for ' + styleId);\n    const text = await res.text();\n    // Sandbox-eval so we DON'T clobber the planner's FULL inline\n    // window.BTKKitchenCatalogue - we only want this style's products array.\n    const sandbox = {};\n    // A body that won't eval, or one carrying no products ARRAY at all, is a\n    // FAILED load - a truncated response or a Shopify error page - not a\n    // style that happens to sell nothing. This used to `return []`, which\n    // made the two indistinguishable, so the failure got cached as fact.\n    try { (new Function('window', text))(sandbox); }\n    catch (_) { throw new Error('planner catalogue unparseable for ' + styleId); }\n    const cat = sandbox.BTKKitchenCatalogue || {};\n    if (!Array.isArray(cat.products)) throw new Error('planner catalogue malformed for ' + styleId);\n    return cat.products;\n  }\n\n  async function fetchStyleProducts(styleId) {\n    let lastErr = null;\n    for (let attempt = 0; attempt <= STYLE_PRODUCTS_RETRIES; attempt++) {\n      if (attempt) await new Promise(r => setTimeout(r, STYLE_PRODUCTS_RETRY_MS * attempt));\n      try { return await fetchStyleProductsOnce(styleId); }\n      catch (e) { lastErr = e; }\n    }\n    throw lastErr || new Error('planner catalogue fetch failed for ' + styleId);\n  }\n\n  // \u2500\u2500\u2500 Style/colour preview images (deferred off the page render) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n  // doorPreviews + heroPreviews used to be inlined into the planner document.\n  // Measured 2026-08-16 from a HAR of the live page: 264KB of a 2,682KB\n  // document, and ~2.9s of its 3.63s server render, for images that are only\n  // read by getDoorPreviewUrl / getHeroPreviewUrl to decorate the style and\n  // colour pickers. Nothing needs them to paint, so they now come from\n  // /cart?view=previews after boot and are cached for the session.\n  //\n  // Every call site already tolerates a null return (`|| ''`), so a picker\n  // opened before the fetch lands simply shows no photo. `btk:previews-ready`\n  // lets open UI repaint once they arrive.\n  let _previewsPromise = null;\n\n  async function fetchPreviews() {\n    const res = await fetch('/cart?view=previews', { credentials: 'same-origin' });\n    if (!res.ok) throw new Error('planner previews fetch ' + res.status);\n    const text = await res.text();\n    // Sandbox-eval, same as fetchStyleProducts: this endpoint sets its own\n    // global and must not touch window.BTKKitchenCatalogue.\n    const sandbox = {};\n    try { (new Function('window', text))(sandbox); } catch (_) { return null; }\n    return sandbox.BTKKitchenPreviews || null;\n  }\n\n  function ensurePreviews() {\n    if (Catalogue.hasPreviews && Catalogue.hasPreviews()) return Promise.resolve();\n    if (_previewsPromise) return _previewsPromise;\n    // v2: the feed now carries frontDoorPreviews too.\n    const CK = 'btk_planner_previews_v2';\n    _previewsPromise = (async () => {\n      let raw = null;\n      try { const c = sessionStorage.getItem(CK); if (c) raw = JSON.parse(c); } catch (_) {}\n      if (!raw) {\n        raw = await fetchPreviews();\n        if (raw) { try { sessionStorage.setItem(CK, JSON.stringify(raw)); } catch (_) {} }\n      }\n      if (raw && Catalogue.setPreviews) {\n        Catalogue.setPreviews(raw);\n        // Repaint anything already on screen that drew without a photo.\n        try { document.dispatchEvent(new CustomEvent('btk:previews-ready')); } catch (_) {}\n      }\n    })().catch((e) => {\n      console.warn('[BTK Kitchen Planner] preview images unavailable:', e);\n      _previewsPromise = null;   // allow a later retry (e.g. next picker open)\n    });\n    return _previewsPromise;\n  }\n\n  // Loads a style's products, or THROWS. Throwing is the point: the caller\n  // (the Add Units popup) turns a rejection into a Retry, where before a\n  // failed load was indistinguishable from a style with nothing in it.\n  async function ensureStyleProducts(styleId) {\n    if (!styleId || Catalogue.hasProductsForStyle(styleId)) return;\n    const ck = 'btk_planner_products_v1:' + styleId;\n    let list = null;\n    try { const c = sessionStorage.getItem(ck); if (c) list = JSON.parse(c); } catch (_) {}\n    // An EMPTY cached list is never trusted. Earlier builds wrote the result\n    // of a failed fetch straight to sessionStorage, and because that cache\n    // outlives a reload the popup stayed empty for the whole tab - the one\n    // failure mode a refresh could not clear. Bin it and fetch again.\n    if (!Array.isArray(list) || !list.length) {\n      if (list !== null) { try { sessionStorage.removeItem(ck); } catch (_) {} }\n      list = null;\n    }\n    if (!list) {\n      if (!_styleProductsInflight.has(styleId)) {\n        _styleProductsInflight.set(styleId, fetchStyleProducts(styleId)\n          // Only a NON-EMPTY result is cached - caching a failure is what let\n          // this survive a refresh.\n          .then(l => {\n            if (l && l.length) { try { sessionStorage.setItem(ck, JSON.stringify(l)); } catch (_) {} }\n            return l;\n          })\n          .finally(() => _styleProductsInflight.delete(styleId)));\n      }\n      list = await _styleProductsInflight.get(styleId);\n    }\n    // Nothing loaded: leave the style UNMARKED so the next call retries,\n    // rather than the planner taking an empty catalogue as the truth for the\n    // rest of the session.\n    if (!list || !list.length) throw new Error('planner catalogue: no products for style ' + styleId);\n    if (!Catalogue.hasProductsForStyle(styleId)) {\n      Catalogue.setProductsForStyle(styleId, list);\n      // A basket built before these products arrived (a plan opened while this\n      // load was failing or still in flight) named its lines by unit code and\n      // had no Was prices - and nothing rebuilt it. Rebuild it now they are here.\n      refreshQuoteLocally();\n    }\n  }\n\n  // \u2500\u2500\u2500 A PLAN'S PRICES ARE TODAY'S, OR THEY ARE NOT SHOWN \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n  // A unit's range products may not have loaded yet, or the load may have\n  // failed (the feed 500s while its cache is cold, right after a theme push).\n  // The totals then fell back to the price stored when each unit was placed and\n  // lost the lines priced from the range, and that low figure was shown and\n  // saved: customers saw it jump when the prices did load, a \"price rise\" on a\n  // plan nobody had touched (bug sheet, Arden, 2026-11-04).\n  // A range the planner no longer sells can never load, so it does not count.\n  function planPricesPendingStyles() {\n    const styles = new Set();\n    (cabinets || []).forEach(c => {\n      if (!c || !c.variantId) return;\n      const s = c.kitchenStyleId || kitchenStyleId;\n      if (s && window.BTKStyleData && window.BTKStyleData[s] && !Catalogue.hasProductsForStyle(s)) styles.add(s);\n    });\n    return [...styles];\n  }\n  // A carcase-only unit's hidden product counts too (see carcaseOnlyVariant).\n  function planPricesPending() { return planPricesPendingStyles().length > 0 || carcaseOnlyPending(); }\n\n  const PLAN_PRICES_RETRY_MS = 20000;\n  let _planPricesLoad = null;\n  let _planPricesFailed = false;\n  let _planPricesTimer = null;\n\n  function repaintPlanPrices() {\n    document.documentElement.classList.toggle('btk-kp-prices-pending', planPricesPending());\n    try { if (window.BTKCartAdvanced?.getBasket?.()) window.BTKCartAdvanced.renderOnly?.(); } catch (_) {}\n  }\n  function loadPlanPrices() {\n    if (_planPricesLoad) return _planPricesLoad;\n    if (_planPricesTimer) { clearTimeout(_planPricesTimer); _planPricesTimer = null; }\n    _planPricesFailed = false;\n    const _coTypes = [...new Set((cabinets || []).filter(c => c && c.carcaseOnly).map(c => c.unitTypeId))];\n    _planPricesLoad = Promise.all(planPricesPendingStyles().map(s => ensureStyleProducts(s).catch(() => {}))\n      .concat(_coTypes.map(ut => ensureCarcaseOnlyProduct(ut).catch(() => {}))))\n      .then(() => {\n        _planPricesLoad = null;\n        _planPricesFailed = planPricesPending();\n        if (_planPricesFailed) {\n          _planPricesTimer = setTimeout(() => { _planPricesTimer = null; if (planPricesPending()) loadPlanPrices(); }, PLAN_PRICES_RETRY_MS);\n        } else {\n          repairStyleVariants();\n          repairMissingPlinthHeights();\n          try { cabinetsHandle?.refresh?.(); } catch (_) {}\n          try { rerender(); } catch (_) {}\n        }\n        repaintPlanPrices();\n      });\n    repaintPlanPrices();\n    return _planPricesLoad;\n  }\n  // Every redraw: a plan that needs prices starts getting them.\n  function syncPlanPrices() {\n    const pending = planPricesPending();\n    document.documentElement.classList.toggle('btk-kp-prices-pending', pending);\n    if (pending && !_planPricesLoad && !_planPricesTimer) loadPlanPrices();\n  }\n  // The basket asks: null, 'loading' or 'failed'.\n  window.__btkPlanPricesState = () => (!planPricesPending() ? null : (_planPricesFailed ? 'failed' : 'loading'));\n  document.addEventListener('click', (e) => {\n    if (e.target?.closest?.('[data-btk-kp-retry-prices]')) loadPlanPrices();\n  });\n\n  async function handleKitchenStyleChange(newStyleId) {\n    if (!newStyleId || newStyleId === kitchenStyleId) return;\n    kitchenStyleId = newStyleId;\n\n    // Reset global colour handles to the new style's first-available.\n    // (Colours are style metadata carried inline for every style, so they\n    // resolve immediately - no product fetch needed.)\n    const doors    = Catalogue.getDoorColoursForStyle(kitchenStyleId)    || [];\n    const carcases = Catalogue.getCarcaseColoursForStyle(kitchenStyleId) || [];\n    globalDoorColourHandle    = doors[0]?.handle    || null;\n    globalCarcaseColourHandle = carcases[0]?.handle || null;\n\n    // Mirror into the buying-style sessionStorage so the Active Buying Style\n    // bar (here + on the listing page) repaints straight away.\n    syncBuyingStyleToSession();\n\n    // Load this style's products (fetch on first switch, cached after) BEFORE\n    // redrawing Step 3's cabinet list - otherwise Add Units would flash\n    // \"No matching cabinets\" until the fetch lands.\n    try { await ensureStyleProducts(kitchenStyleId); } catch (e) { console.warn('[planner] style products load failed', e); }\n    cabinetsHandle.refresh();\n  }\n\n\n  // A unit's own note (Non Urgent sheet row 56, Matt): typed in the unit's Add\n  // Note, it is the note on the unit's line in the basket, and a note typed on\n  // that line in the basket comes back to the unit (buildQuote). Marked on the\n  // unit's number on the 2D plan and printed on the plan report's Unit notes\n  // page. notePending: typed here and not yet on the basket line.\n  const UNIT_NOTE_MAX = 500;\n  // A unit with a note: a small amber dot on its number on the 2D plan, and\n  // the note when the number is hovered. On the unit's own number only - not\n  // its sink, appliance, panel or rail badges.\n  function markNotedUnits(root) {\n    if (!root) return;\n    root.querySelectorAll('.btk-kp-unit-note-dot').forEach(el => el.remove());\n    root.querySelectorAll('.btk-kp-cabinet-number[data-unit-note]').forEach(el => {\n      el.removeAttribute('data-unit-note');\n      if (el.dataset.unitNoteTitle != null) { el.title = el.dataset.unitNoteTitle; delete el.dataset.unitNoteTitle; }\n    });\n    for (const c of (cabinets || [])) {\n      if (!c || !c.note) continue;\n      const badge = [...root.querySelectorAll(`.btk-kp-cabinet-number[data-cabinet-id=\"${c.id}\"]`)]\n        .find(el => !/--(over-sink|appliance|endpanel|rail)\\b/.test(el.className));\n      if (!badge) continue;\n      badge.setAttribute('data-unit-note', '');\n      badge.dataset.unitNoteTitle = badge.title || '';\n      badge.title = 'Note: ' + c.note;\n      const dot = document.createElement('span');\n      dot.className = 'btk-kp-unit-note-dot';\n      dot.setAttribute('aria-hidden', 'true');\n      // Sized with the badge under the 2D zoom (--btk-kp-chrome).\n      dot.style.cssText = 'position:absolute;top:calc(-2px * var(--btk-kp-chrome, 1));right:calc(-2px * var(--btk-kp-chrome, 1));'\n        + 'width:calc(8px * var(--btk-kp-chrome, 1));height:calc(8px * var(--btk-kp-chrome, 1));border-radius:50%;'\n        + 'background:#f0a400;box-shadow:0 0 0 calc(1.5px * var(--btk-kp-chrome, 1)) #fff;pointer-events:none;';\n      // On the number itself, which is kept upright, so the dot is top right\n      // however the unit (and its badge) is turned.\n      const host = badge.querySelector('.btk-kp-cabinet-number-inner') || badge;\n      if (getComputedStyle(host).position === 'static') host.style.position = 'relative';\n      dot.style.top = 'calc(-6px * var(--btk-kp-chrome, 1))';\n      dot.style.right = 'calc(-8px * var(--btk-kp-chrome, 1))';\n      host.appendChild(dot);\n    }\n  }\n  function handleSetUnitNote(cabinetId, text) {\n    const idx = cabinets.findIndex(c => c.id === cabinetId);\n    if (idx === -1) return;\n    const c = cabinets[idx];\n    const note = String(text || '').trim().slice(0, UNIT_NOTE_MAX) || null;\n    if ((c.note || null) === note) return;\n    cabinets[idx] = { ...c, note, notePending: true };\n    rerender();\n    scheduleBasketResync();\n  }\n\n// A unit's own Cornice & Pelmet (unit panel, sales row 132): `off` is\n// { cornice: true, pelmet: true } (each None) or null for the Kitchen Default.\n// Applied to this unit and every other unit selected with it, so a run of\n// glass wall units is done in one go. The trim engine leaves a unit out of a\n// run it is set to None for (engine-trim participatesIn).\nfunction handleSetTrimOff(cabinetId, off) {\n    const next = (off && (off.cornice || off.pelmet))\n      ? { cornice: !!off.cornice, pelmet: !!off.pelmet } : null;\n    const ids = new Set([cabinetId, ...selectedCabinetIds]);\n    let changed = false;\n    for (const c of cabinets) {\n      if (!c || !ids.has(c.id)) continue;\n      if (JSON.stringify(c.trimOff || null) === JSON.stringify(next)) continue;\n      changed = true;\n      if (next) c.trimOff = { ...next }; else delete c.trimOff;\n    }\n    if (changed) rerender();\n}\n\nfunction handleUpdateCabinetSize(cabinetId, updates) {\n    const idx = cabinets.findIndex(c => c.id === cabinetId);\n    if (idx === -1) return;\n    const c = cabinets[idx];\n\n    // Free-standing appliance - no variant to look up. Each dimension is\n    // clamped to the range its catalogue entry allows (one with no range is\n    // fixed and ignores the request), and the BACK edge stays put, so an\n    // appliance standing against a wall is still against it after a depth\n    // change. Width grows about the centre. Only for a SIZE change - its\n    // Breakfast Bar Back Panel finish rides the pass-through below.\n    if (c.freestandingAppliance && ['widthMm', 'depthMm', 'heightMm'].some(k => updates[k] != null)) {\n      const lim = (planApplianceEntry(c) || {}).limits || {};\n      const pick = (key, cur) => {\n        const v = Number(updates[key]);\n        const r = lim[key];\n        if (updates[key] == null || !Number.isFinite(v) || !r) return cur;\n        return Math.max(r.min, Math.min(r.max, Math.round(v)));\n      };\n      const nw = pick('widthMm', c.widthMm);\n      const nd = pick('depthMm', c.depthMm);\n      const nh = pick('heightMm', c.heightMm);\n      if (nw === c.widthMm && nd === c.depthMm && nh === c.heightMm) return;\n      // Cab-local +Y (the back) points (-sin \u03B8, cos \u03B8) in world.\n      const th = ((c.rotationDeg || 0) * Math.PI) / 180;\n      const back = (c.depthMm - nd) / 2;\n      const ncx = c.x + c.widthMm / 2 - Math.sin(th) * back;\n      const ncy = c.y + c.depthMm / 2 + Math.cos(th) * back;\n      cabinets[idx] = { ...c, widthMm: nw, depthMm: nd, heightMm: nh,\n                        x: ncx - nw / 2, y: ncy - nd / 2 };\n      rerender();\n      return;\n    }\n\n    // Pass-through fields that aren't part of the size triple\n    // (widthMm / depthMm / heightMm) but ride on this handler for\n    // UI convenience. Apply directly and skip the variant lookup\n    // when none of the size fields are present.\n    const sizeKeys   = ['widthMm', 'depthMm', 'heightMm'];\n    const hasSize    = sizeKeys.some(k => updates[k] != null);\n    const hasOptionOverride = updates.optionOverrides && Object.keys(updates.optionOverrides).length > 0;\n    // Custom Changes is tested by the key being PRESENT, not by its value:\n    // clearing it sends customFit: null, and `null != null` is false. That\n    // used to skip this branch entirely - the unticked Confirm fell through\n    // to the variant re-resolve below, the unit kept its customFit, and the\n    // popup re-seeded the tick straight back on.\n    const hasCustomFit = Object.prototype.hasOwnProperty.call(updates, 'customFit');\n    if (!hasSize && !hasOptionOverride && (updates.useFullSizeEndPanel != null || updates.backEndPost != null || updates.backPanel != null || updates.breakfastBarBack != null || hasCustomFit)) {\n      const next = { ...c };\n      // Custom Changes - \"Ignore walls, units, doors & windows\" + on-site fitting notes.\n      // Whole-object replace (not a merge) so unticking really clears it.\n      if (hasCustomFit) {\n        next.customFit = updates.customFit || null;\n      }\n      if (updates.useFullSizeEndPanel != null) {\n        next.useFullSizeEndPanel = !!updates.useFullSizeEndPanel;\n        next.fullSizeEndPanelUserSet = true;\n      }\n      // Breakfast-bar back panel Plain / T&G. The popup has always sent this,\n      // but the key was never accepted here, so the toggle silently did\n      // nothing and the panel was stuck on Plain - and the board it is cut\n      // from was always charged as plain too.\n      if (updates.breakfastBarBack != null) {\n        next.breakfastBarBack = {\n          ...(c.breakfastBarBack || {}),\n          ...updates.breakfastBarBack\n        };\n      }\n      if (updates.backEndPost != null) {\n        next.backEndPost = {\n          ...(c.backEndPost || {}),\n          ...updates.backEndPost\n        };\n      }\n      if (updates.backPanel != null) {\n        next.backPanel = {\n          ...(c.backPanel || {}),\n          ...updates.backPanel\n        };\n      }\n      cabinets[idx] = next;\n      // None on the Back Panel tile (or a finish again): the back panels, and\n      // the end panels that run back to them, are decided again at once.\n      if (updates.backPanel != null && !!updates.backPanel.userOff !== !!(c.backPanel && c.backPanel.userOff)) {\n        autoDetectEndPanels();\n        autoDetectBackPanels();\n      }\n      rerender();\n      return;\n    }\n\n    // Free-place end panels & fillers have no Shopify variant - they're\n    // arbitrary geometry. Skip the variant lookup and accept whatever\n    // the user types for width / depth / height / heightOffGround /\n    // distanceFromWall. Anchor by centre so resizing doesn't slide the\n    // panel sideways.\n    if (c.endPanelFiller) {\n      const cx = c.x + (c.widthMm  || 0) / 2;\n      const cy = c.y + (c.depthMm  || 0) / 2;\n      const next = {\n        ...c,\n        widthMm:            updates.widthMm  != null ? Math.max(1, updates.widthMm)  : c.widthMm,\n        depthMm:            updates.depthMm  != null ? Math.max(1, updates.depthMm)  : c.depthMm,\n        heightMm:           updates.heightMm != null ? Math.max(1, updates.heightMm) : c.heightMm,\n        heightOffGroundMm:  updates.heightOffGroundMm  != null ? Math.max(0, updates.heightOffGroundMm)  : (c.heightOffGroundMm  || 0),\n        distanceFromWallMm: updates.distanceFromWallMm != null ? Math.max(0, updates.distanceFromWallMm) : (c.distanceFromWallMm || 0),\n        snapFace:           updates.snapFace != null ? updates.snapFace : (c.snapFace || 'none')\n      };\n      next.x = cx - next.widthMm / 2;\n      next.y = cy - next.depthMm / 2;\n      cabinets[idx] = next;\n      rerender();\n      return;\n    }\n\n    let newWidth  = updates.widthMm  != null ? updates.widthMm  : c.widthMm;\n    let newDepth  = updates.depthMm  != null ? updates.depthMm  : c.depthMm;\n    // Variant Height is CARCASE-only (plinth is added separately).\n    // cab.heightMm = variant.heightMm + plinthMm, so peel the\n    // plinth off the cab's stored height when the caller didn't\n    // supply a new height.\n    const ut         = Catalogue.getUnitType(c.unitTypeId);\n    const plinthMm   = (ut && ut.plinthHeightMm) || 0;\n    let newHeight  = updates.heightMm != null\n      ? updates.heightMm\n      : Math.max(0, (c.heightMm || 0) - plinthMm);\n\n    // Preserve the cab's non-dimension options (e.g. a \"Door\" config) across\n    // a resize, and apply an explicit door-config override when the caller\n    // sends one. optionOverrides is keyed by option label (lowercased).\n    const optInfo   = Catalogue.variantOptionInfo ? Catalogue.variantOptionInfo(c.variantId) : [];\n    const overrides = updates.optionOverrides || null;\n    const wantOptionValues = optInfo\n      .filter(o => !o.isDimension && o.value != null)\n      .map(o => (overrides && overrides[o.labelKey] != null) ? overrides[o.labelKey] : o.value);\n\n    // Corner-family units (L-shape / diagonal / blank-corner / radius) store the\n    // FOOTPRINT as widthMm/depthMm (e.g. 630\u00D7630), NOT the variant's own dims \u2014\n    // so constraining findVariant by them rejects the real variant and a height\n    // change silently fails. These units have a fixed footprint with only HEIGHT\n    // variants, so match on height (+ options) alone.\n    const isCornerFamily = !!(c.lShapeUnit || c.diagonalCornerUnit || c.cornerUnit || c.radiusUnit);\n    // `updates.variantId` = the caller already knows WHICH variant (the Edit\n    // popup resolves one from the product's own option values - see\n    // btk-kitchen-planner-ui-variant-options.js). Dimensions then come FROM\n    // that variant instead of being matched by millimetre, which is what made\n    // variants sharing a cabinet width indistinguishable.\n    const explicit = updates.variantId\n      ? (Catalogue.getVariantInfo ? Catalogue.getVariantInfo(updates.variantId) : null)\n      : null;\n    const info = explicit || Catalogue.findVariant({\n      unitTypeId:     c.unitTypeId,\n      kitchenStyleId: c.kitchenStyleId,\n      widthMm:        isCornerFamily ? null : newWidth,\n      depthMm:        isCornerFamily ? null : newDepth,\n      heightMm:       newHeight,\n      optionValues:   wantOptionValues\n    });\n    if (!info) {\n      console.warn(`[BTK Kitchen Planner] No variant for ${c.unitTypeId} at ${newWidth}x${newDepth}x${newHeight}`, wantOptionValues);\n      return;\n    }\n    if (explicit) {\n      // Adopt the variant's own dimensions. A corner-family unit keeps its\n      // marker-derived footprint (its widthMm/depthMm are the footprint, not\n      // the variant's own) - a blank corner is applied through\n      // handleUpdateCornerUnit instead.\n      if (!isCornerFamily) {\n        if (info.widthMm != null) newWidth = info.widthMm;\n        if (info.depthMm != null) newDepth = info.depthMm;\n      }\n      if (info.heightMm != null) newHeight = info.heightMm;\n    }\n\n    // Anchor by back-edge midpoint. The back edge is the side opposite\n    // the door indicator (door is at local-top \u2192 back is at local-bottom).\n    // In local coords, the back-edge midpoint sits at offset (0, depth/2)\n    // from the cabinet's centre. We rotate that offset into world coords\n    // using the cabinet's rotation, lock the back-edge world point in\n    // place, then derive new x,y such that the same offset (with the new\n    // depth) lands back on that fixed world point.\n    const R    = (c.rotationDeg || 0) * Math.PI / 180;\n    const sinR = Math.sin(R);\n    const cosR = Math.cos(R);\n\n    const oldCx = c.x + c.widthMm / 2;\n    const oldCy = c.y + c.depthMm / 2;\n    const backX = oldCx + (-sinR * (c.depthMm / 2));\n    const backY = oldCy + ( cosR * (c.depthMm / 2));\n\n    const newCx = backX - (-sinR * (newDepth / 2));\n    const newCy = backY - ( cosR * (newDepth / 2));\n    const newX  = newCx - newWidth / 2;\n    const newY  = newCy - newDepth / 2;\n\n    // Re-resolve the cutout schema for the new height - unit types\n    // authored with a `variants` block ship different door layouts\n    // per height (e.g. a tall larder's Low version is 2 doors, High\n    // is 3 doors).\n    const resolvedSchema = (ut && Catalogue.resolveCutoutSchema)\n      ? Catalogue.resolveCutoutSchema(ut.cutoutSchema, {\n          heightMm:       newHeight,\n          widthMm:        c.widthMm,   // pairDoorsFromWidthMm (wide larders: door pairs)\n          categoryHandle: ut.categoryHandle,\n          groupHandle:    ut.unitTypeGroupHandle,\n          optionValues:   Catalogue.nonDimensionOptionValues ? Catalogue.nonDimensionOptionValues(info?.variant?.id) : []\n        })\n      : c.cutoutSchema;\n\n    // The height variant can also flip the door between a top-hung FLAP and\n    // a side-hinged door - arbitrarily, with no pattern (a Medium may be a\n    // flap on one housing and hinged on another). So re-derive the hinge\n    // state for the new height rather than carrying the old one over.\n    const _newSchema     = resolvedSchema || c.cutoutSchema;\n    const _newFirstDoor  = (_newSchema?.openings || []).find(o => o.type === 'door');\n    const _newIsTopHung  = _newFirstDoor?.hingeSide === 'top';\n    const _newProduct    = Catalogue.getProductForUnitInStyle\n      ? Catalogue.getProductForUnitInStyle(c.unitTypeId, c.kitchenStyleId)\n      : null;\n    const _newSelectable = Catalogue.isHingeSelectable\n      ? Catalogue.isHingeSelectable(_newSchema, _newProduct, c.unitTypeId)\n      : c.hingeSelectable;\n    // True Handleless tall units carry the hand as an LH/RH \"Hinge\" VARIANT (a\n    // production requirement). When the user picks the LH/RH pill it arrives as\n    // an optionOverride on that option - sync the cab's hingeSide to the chosen\n    // variant so the 3D door hand + vertical rail follow (LH \u2192 left, RH \u2192 right).\n    // This is the reverse of handleUpdateCabinetHinge, which routes the hinge\n    // toggle back through here as a hinge override - both stay in sync.\n    let _thHandOverride = null;\n    if (overrides) {\n      for (const k of Object.keys(overrides)) {\n        if (!/hinge/i.test(k)) continue;\n        const v = String(overrides[k] || '');\n        if (/\\brh\\b|right/i.test(v))      _thHandOverride = 'right';\n        else if (/\\blh\\b|left/i.test(v))  _thHandOverride = 'left';\n      }\n    }\n    // Applied by variant id (the Edit popup's option selection) there are no\n    // overrides to read, so take the hand from the RESOLVED variant's own\n    // Hinge option - same rule, whichever route the change arrived by.\n    if (!_thHandOverride && explicit && Catalogue.variantOptionInfo) {\n      for (const o of (Catalogue.variantOptionInfo(info.variant.id) || [])) {\n        if (!/hinge/i.test(o.labelKey) || o.value == null) continue;\n        const v = String(o.value);\n        if (/\\brh\\b|right/i.test(v))      _thHandOverride = 'right';\n        else if (/\\blh\\b|left/i.test(v))  _thHandOverride = 'left';\n      }\n    }\n    // flap \u2192 'top'. Coming FROM a flap into a hinged height, adopt the new\n    // schema's default side. Hinge \u2192 hinge keeps whatever hand the user\n    // picked, so switching height doesn't silently discard their choice.\n    const _newHingeSide = _thHandOverride\n      ? _thHandOverride\n      : (_newIsTopHung\n          ? 'top'\n          : (String(c.hingeSide || '').toLowerCase() === 'top'\n              ? (_newFirstDoor?.hingeSide || 'left')\n              : c.hingeSide));\n\n    // Preserve a chosen appliance across a height change. Selections are keyed\n    // by opening index, but the appliance opening can sit at a DIFFERENT index\n    // per height variant (a fridge door is index 0 in Medium but index 1 in\n    // High once the top filler appears). Re-map each choice from its OLD slot\n    // index to the NEW slot index by ORDINAL - deduping ganged doors, exactly\n    // as the Choose Appliance picker does - so the selection (and its diorama /\n    // badge / basket line) follows the appliance. Applies to every appliance\n    // housing: `oven` apertures AND `appliance`-flagged integrated doors.\n    const _applSlotReps = (openings) =>\n      Catalogue.applianceSlotsOf({ openings: openings || [] }).map(s => s.i);\n    let _remappedAppliances = c.appliances;\n    if (c.appliances && Object.keys(c.appliances).length) {\n      const _oldReps = _applSlotReps(c.cutoutSchema?.openings || []);\n      const _newReps = _applSlotReps(_newSchema?.openings || []);\n      const _next = {};\n      _oldReps.forEach((oldIdx, ord) => {\n        const h = c.appliances[oldIdx];\n        const newIdx = _newReps[ord];\n        if (h && newIdx != null) _next[newIdx] = h;\n        // The warming drawer under a compact travels with it (index + 0.5).\n        const hd = c.appliances[oldIdx + 0.5];\n        if (hd && newIdx != null) _next[newIdx + 0.5] = hd;\n      });\n      _remappedAppliances = _next;\n    }\n\n    let updated = {\n      ...c,\n      variantId:    info.variant.id,\n      widthMm:      newWidth,\n      depthMm:      newDepth,\n      heightMm:     newHeight + plinthMm,\n      priceCents:   info.priceCents,\n      compareAtCents: (typeof info.compareAtCents === 'number') ? info.compareAtCents : null,\n      cutoutSchema: resolvedSchema || c.cutoutSchema,\n      hingeSide:       _newHingeSide,\n      hingeSelectable: _newSelectable,\n      appliances:      _remappedAppliances,\n      x: newX,\n      y: newY\n    };\n\n    // Only re-snap/clamp when the PLAN footprint actually changed\n    // (width or depth). A height-only change leaves x/y/width/depth\n    // identical, so re-snapping would needlessly pull the cab to a\n    // nearby wall - breaking, e.g., a filler that's holding the\n    // carcase 20mm off the wall (20mm < the 30mm snap distance).\n    const footprintChanged = newWidth !== c.widthMm || newDepth !== c.depthMm;\n    if (footprintChanged) {\n      const others       = cabinets.filter(o => o.id !== cabinetId);\n      const obstacles    = [...perimeterObstaclesFor(updated),\n                            ...epDoorLinePanelObstacles(cabinetId)];\n      const wallOpenings = roomConfig.wallOpenings || [];\n      const { x, y }     = snapAndClamp(updated, updated.x, updated.y, room, others, obstacles, wallOpenings);\n      updated.x = x;\n      updated.y = y;\n    }\n\n    cabinets[idx] = updated;\n    // A new height changes which end panels the unit and its neighbours need\n    // (the taller unit keeps its panel), so decide them again - without the\n    // unit in a moved set, so nothing is slid along to make room. Where a new\n    // panel has no room, the Advisory says so (Arden, 2026-10-26, Bugs 23).\n    if (autoEndPanels && updated.heightMm !== c.heightMm) {\n      // The walk can still nudge a unit to suit a filler; on a height change\n      // every unit stays exactly where it stood.\n      const _pos = new Map(cabinets.map(o => [o.id, { x: o.x, y: o.y }]));\n      try { autoDetectEndPanels(); } catch (e) { /* keep the size change */ }\n      cabinets = cabinets.map(o => {\n        const p = _pos.get(o.id);\n        return (p && (o.x !== p.x || o.y !== p.y)) ? { ...o, x: p.x, y: p.y } : o;\n      });\n      try { resizeFillers(); } catch (e) { /* cosmetic */ }\n    }\n    rerender();\n  }\n\n\n\n\n  // -------- 3D viewport (Phase 1: placeholder boxes) --------\n  let viewport3D = null;\n  let handle3D   = null;\n\n  // The viewport DIV must exist SYNCHRONOUSLY: on3DStepActive sets its\n  // display the moment the user toggles to 3D and cannot wait for a module\n  // download. Creating it is cheap and independent of the renderer.\n  function ensure3DViewport() {\n    if (viewport3D) return viewport3D;\n    const mainEl = document.getElementById('btk-kp-main');\n    if (!mainEl) return null;\n    viewport3D = document.createElement('div');\n    viewport3D.className = 'btk-kp-3d-viewport';\n    viewport3D.dataset.btkKp3dViewport = '';\n    // Default-hide the 3D viewport. The 2D plan sits in the same\n    // #btk-kp-main container and would otherwise be covered when\n    // ensure3DReady is called outside the 3D view-switch flow (e.g.\n    // by the selection-panel thumbnail callback). on3DStepActive\n    // explicitly sets display:'block' when the user toggles to 3D.\n    viewport3D.style.display = 'none';\n    mainEl.appendChild(viewport3D);\n    return viewport3D;\n  }\n\n  // NOW ASYNC - the renderer module is fetched on demand. Returns a promise\n  // resolving to handle3D (or null if the container isn't in the DOM).\n  //\n  // \u26A0 Callers that use handle3D straight afterwards MUST await this. The\n  // in-flight guard matters: two rapid calls would otherwise both get past\n  // the handle3D check and mount two renderers.\n  let _ensure3DPromise = null;\n  function ensure3DReady() {\n    if (handle3D) return Promise.resolve(handle3D);\n    if (_ensure3DPromise) return _ensure3DPromise;\n    if (!ensure3DViewport()) return Promise.resolve(null);\n    try { window.BTKKPTiming && window.BTKKPTiming.mark('3D boot started'); } catch (e) {}\n    _ensure3DPromise = load3DRenderer().then(({ init3DRenderer }) => {\n      try { window.BTKKPTiming && window.BTKKPTiming.mark('3D module ready'); } catch (e) {}\n      _init3DRenderer(init3DRenderer);\n      try { window.BTKKPTiming && window.BTKKPTiming.mark('3D viewport built'); } catch (e) {}\n      return handle3D;\n    }).catch((err) => {\n      console.error('[BTK planner] 3D renderer failed to load', err);\n      _ensure3DPromise = null;   // allow a retry on the next toggle\n      return null;\n    });\n    return _ensure3DPromise;\n  }\n\n  function _init3DRenderer(init3DRenderer) {\n    handle3D = init3DRenderer(viewport3D, {\n      catalogue: Catalogue,\n      // Right-click \"Exclude from Quote\" toggle on a 3D cabinet.\n      onToggleExcludeFromQuote: (id) => setCabinetExcludeFromQuote(id),\n      isExcludedFromQuote: (id) => {\n        const c = cabinets.find(cc => cc.id === id);\n        return !!(c && c.excludeFromQuote);\n      },\n      // A free-standing appliance is never in the quote, so no toggle.\n      canToggleQuote: (id) => {\n        const c = cabinets.find(cc => cc.id === id);\n        return !!c && !c.freestandingAppliance;\n      },\n      // Right-click \"Step Forward \u25B8\" submenu - set/clear the wall setback.\n      onSetStepForward: (id, mm) => handleUpdateCabinetSetback(id, mm),\n      isStepEligible: (id) => {\n        const c = cabinets.find(cc => cc.id === id);\n        return !!(c && isStepEligibleCab(c));\n      },\n      // The 3D loader reports each furniture model's footprint (width \u00D7\n      // depth from its bounding box) so we can size the 2D footprint.\n      onFurnitureSize: (id, w, d, h) => {\n        const fi = furnitureItems.find(f => f.id === id);\n        if (!fi) return;\n        if (fi.furnitureId) furnitureSizeCache[fi.furnitureId] = { w, d, h };\n        const heightChanged = h && Math.round(fi.heightMm || 0) !== Math.round(h);\n        if (h) fi.heightMm = h;\n        if (heightChanged && Math.round(fi.widthMm || 0) === Math.round(w) &&\n            Math.round(fi.depthMm || 0) === Math.round(d) && furnitureStandsOnItems()) { rerender(); return; }\n        if (Math.round(fi.widthMm || 0) === Math.round(w) &&\n            Math.round(fi.depthMm || 0) === Math.round(d)) return;   // unchanged \u2192 no loop\n        const firstSize = !fi.widthMm;\n        fi.widthMm = w;\n        fi.depthMm = d;\n        // Placed at the 500 x 500 stand-in until its model reports in: a big\n        // piece grows out of its clear spot and into a unit, so move it back out.\n        if (firstSize) nudgeFurnitureClear(fi);\n        rerender();\n      },\n      // 3D click \u2192 typed target. Cabinet hits go through the\n      // existing multi-select flow; trim-segment and end-panel\n      // hits become single-item selections that open their own\n      // panels via selectItem(...).\n      onCanvasClick: (target) => {\n        if (!target) { selectItem(null); return; }\n        // Add Items and Customise share the 3D view, but each owns its own\n        // things: a worktop, splashback or trim is worked on in Customise, a\n        // unit, end panel or filler in Add Items. A click on the other stage's\n        // kind moves there first - staying in 3D - so its menu has somewhere\n        // to open instead of the click doing nothing.\n        const home = PICK_STAGE[target.type];\n        if (home && home !== currentStep &&\n            (currentStep === 'add-units' || currentStep === 'style-colours')) {\n          goToStage(home, '3d');\n        }\n        if (target.type === 'cabinet') {\n          // Mirror the 2D click logic 1:1 so 2D and 3D selection\n          // and grouping behave identically. Ctrl/shift-click on a\n          // grouped unit ungroups THIS unit only (the rest of the\n          // group stays grouped); on an ungrouped unit it toggles\n          // into/out of the multi-selection.\n          const cab = cabinets.find(c => c.id === target.id);\n          if (target.additive) {\n            const next = new Set(selectedCabinetIds);\n            let changedGroup = false;\n            if (cab?.groupId) {\n              delete cab.groupId;\n              changedGroup = true;\n              next.delete(target.id);\n            } else if (next.has(target.id)) {\n              next.delete(target.id);\n            } else {\n              next.add(target.id);\n            }\n            setCabinetSelection([...next]);\n            if (changedGroup) rerender();\n          } else {\n            setCabinetSelection(clickSelectIds(cab));\n            // Reverse of clicking a basket line: slide the basket to this\n            // unit + open its details (when the embedded basket is open).\n            focusBasketLineForCab(target.id);\n          }\n          return;\n        }\n        if (target.type === 'trim-segment') { selectItem({ kind: 'trim-segment', segmentId: target.segmentId, runId: target.runId, feature: target.feature, cabinetIds: target.cabinetIds }); return; }\n        if (target.type === 'end-panel')    { selectEndPanelFace(target.cabinetId, target.side); return; }\n        if (target.type === 'worktop')      { selectItem({ kind: 'worktop',      worktopId: target.worktopId }); return; }\n        if (target.type === 'worktop-item') { selectItem({ kind: 'worktop-item', id: target.id }); return; }\n        if (target.type === 'furniture')    { selectItem({ kind: 'furniture', id: target.id }); return; }\n        if (target.type === 'sink-set')     { selectItem({ kind: 'planner-sink', cabinetId: target.cabinetId }); return; }\n        if (target.type === 'splashback-section') { selectItem({ kind: 'splashback-section', slabId: target.slabId, slabIds: target.slabIds || null, wallIndex: target.wallIndex, stripKind: target.kind }); return; }\n      }\n    });\n    handle3D.setWallColour(getWallColour(wallColourHandle).hex);\n    applyFeatureWallsTo3D();\n    applyFloorTo3D();\n    // Console diagnostic for door / window geometry - measures what is really\n    // in the scene rather than what the sizing maths predicts. Run\n    // btkOpeningReport() in the browser console with an opening on the plan.\n    if (typeof window !== 'undefined' && handle3D.openingReport) {\n      window.btkOpeningReport = handle3D.openingReport;\n    }\n    // Subscribe to flythrough state changes so the play button can\n    // flip between \u25B6 (play) and \u25A0 (stop) and aria-pressed updates.\n    // Also drives the record button: when the flythrough finishes\n    // (naturally or via Stop), the recorder is finalised, which\n    // assembles the WebM Blob and triggers the download.\n    if (typeof handle3D.onFlythroughChange === 'function') {\n      handle3D.onFlythroughChange(isPlaying => {\n        if (typeof updateFlyPlayState === 'function') updateFlyPlayState(isPlaying);\n        if (!isPlaying && typeof stopRecordingFlythrough === 'function') {\n          stopRecordingFlythrough();\n        }\n      });\n    }\n    // Refresh the cog overlay so the 3D preset buttons can wire up\n    // against the freshly-created renderer.\n    renderViewportOverlay();\n  }\n\n  // Tracks what the user last asked for, so a renderer that finishes loading\n  // AFTER they've switched back to 2D doesn't wake itself up over the plan.\n  let _want3D = false;\n\n  // \u2500\u2500\u2500 ONE 3D rebuild per burst \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n  // A full 3D rebuild tears the scene down and builds every cabinet, trim,\n  // plinth and worktop again, and it costs the better part of a second on a\n  // real kitchen. A stage change does not ask for one rebuild: it fans out\n  // into several rerender() calls (each refresh handle triggers its own) plus\n  // _activate3D on the view switch, and with 144 rerender() call sites there\n  // is no single caller to fix. Customise was measured building the IDENTICAL\n  // scene five times back to back - 4.2s inside one unbreakable task, which is\n  // also where the lag on every button click came from (?btktime=1, Arden\n  // 2026-09-30).\n  //\n  // Coalesced onto a task of its own. A microtask checkpoint was too early a\n  // boundary: _activate3D asks for its rebuild from inside an awaited\n  // continuation (ensure3DReady), so on Customise its request arrived after the\n  // first microtask had already fired and the scene was still built twice.\n  // Deferring to a task catches both, and has a second benefit - the click\n  // handler now returns, so the menu and plan paint while the scene is built\n  // after them instead of behind them.\n  //\n  // Last state wins, and that ordering matters: rerender's state carries\n  // openingFaceInsets and flythroughWaypoints that _activate3D's does not, and\n  // rerender always asks second. Suppressing the later request instead would\n  // quietly drop the wall opening insets from 3D.\n  //\n  // The two snapshot paths (plan report, saved-plan thumbnail) still call\n  // handle3D.render() directly: they capture the scene moments later and must\n  // not race a queued rebuild.\n  let _pending3D = null;\n  function request3DRebuild(state) {\n    const alreadyQueued = !!_pending3D;\n    _pending3D = state;\n    if (alreadyQueued) return;\n    setTimeout(() => {\n      const s = _pending3D;\n      _pending3D = null;\n      if (!s) return;\n      try { handle3D?.render(s); } catch (e) { console.error('[BTK KP] 3D rebuild', e); }\n    }, 0);\n  }\n\n  // Pushes the current scene into the renderer. Runs either immediately (the\n  // renderer is already loaded) or as soon as it arrives.\n  function _activate3D() {\n    if (!_want3D || !handle3D) return;\n    handle3D.setActive?.(true);   // resume the render loop's work\n    // Through the coalescer: arriving on a 3D stage fires this AND a rerender,\n    // which used to be two full rebuilds of the same scene.\n    // The FULL state, as rerender sends it: without openingFaceInsets a door\n    // or window on a pillar face is cut nowhere in 3D whenever no rerender\n    // happens to follow (Arden, 2026-10-16 - an 820 door missing from 3D).\n    request3DRebuild({ room, roomConfig, openingFaceInsets: openingFaceInsetMap(), cabinets, baseRoom, featureStyles, railFinishHandle, segmentColours, worktops: buildWorktops(), worktopColourHex, worktopColours, worktopCornerRadii, worktopItems: worktopItems3D(), furnitureItems, handleGroups, flythroughWaypoints, lights, lightsOn });\n    handle3D.resize();\n  }\n\n  // Stays SYNCHRONOUS - its callers don't await it, and it has to hide/show\n  // DOM immediately. Only the renderer work is deferred.\n  function on3DStepActive(active) {\n    const mainEl = document.getElementById('btk-kp-main');\n    if (!mainEl) return;\n    _want3D = !!active;\n    if (active) {\n      ensure3DViewport();          // sync: the div must exist for the line below\n      ensure3DReady().then(_activate3D);\n      // Hide every 2D child; show only the 3D viewport. The viewport\n      // overlay (toggle + gear + lighting panel) stays visible.\n      Array.from(mainEl.children).forEach(child => {\n        if (child === viewport3D) return;\n        if (child.classList?.contains('btk-kp-viewport-overlay')) return;\n        if (child.hasAttribute?.('data-btk-kp-home')) return;   // home layer is controlled by its [hidden] attr\n        child.style.display = 'none';\n      });\n      if (viewport3D) viewport3D.style.display = 'block';\n      _activate3D();               // no-op unless the renderer is already loaded\n    } else {\n      // Restore 2D children; hide the 3D viewport.\n      Array.from(mainEl.children).forEach(child => {\n        if (child === viewport3D) return;\n        if (child.classList?.contains('btk-kp-viewport-overlay')) return;\n        if (child.hasAttribute?.('data-btk-kp-home')) return;   // home layer is controlled by its [hidden] attr\n        child.style.display = '';\n      });\n      if (viewport3D) viewport3D.style.display = 'none';\n      handle3D?.setActive?.(false);   // pause the render loop's work while 2D shows\n    }\n  }\n\n  // ---- Design warnings ----\n  // Recomputed on every rerender. Outlines the offending items on the plan,\n  // and the list itself lives in the sidebar's Warnings panel, reached from\n  // the red button by the 2D/3D toggle (Arden, 2026-09-25 - it was a popup\n  // floating over the plan). Rules live in engine-warnings.js - add a rule\n  // there and it flows through here automatically.\n  let designWarnings = [];\n\n  // Short titles for the list, what the designer scans down; the rule's own\n  // message stays as the row's detail (Arden, 2026-09-25).\n  const WARN_TITLES = {\n    'unit-covers-door':  'Door Blocked',\n    'unit-overlap':      'Units Overlap',\n    'unit-into-pillar':  'Unit Runs Into a Pillar',\n    'door-clash':        'Doors Clash',\n    'front-blocked':     'Front Blocked',\n    'bed-clash':         'Bed Too Close',\n    'walkway-too-small': 'Walkway Too Narrow',\n    'door-colour-not-made': 'Not Available in This Colour',\n    'waterfall-round-edge': 'No Waterfall on Round Edge Laminate',\n    'unit-gap':          'Gap Between Units',\n    'above-ceiling':     'Taller Than the Room',\n    'under-beam':        'Runs Into a Beam',\n    'under-block':       'Runs Into a Block',\n    'under-chimney':     'Runs Into the Chimney Breast',\n    'under-slope':       'Runs Into the Sloped Ceiling',\n    'bullnose-curve':    'Round Edge Worktop on a Curve',\n    'belfast-worktop-edge': 'Worktop Too Thin by the Belfast Sink',\n    'th-rail-room':      'No Room for the Rail or End Panel',\n    'door-colour-range': 'Door Colour Not Made in This Range'\n  };\n  // Help behind a row's Details button. PLACEHOLDER IMAGE for now - this\n  // becomes a metaobject lookup (one entry per ruleId) once the content exists.\n  const WARN_HELP = {\n    'unit-covers-door':  'A unit stands in the clearance in front of a door or window. The planner allows it, because a run is sometimes carried across an architrave and trimmed on site, but check that the door still opens and the way through is usable.',\n    'unit-overlap':      'Two units occupy the same space. One of them needs to move, or one needs to be a narrower unit.',\n    'unit-into-pillar':  'This unit is too wide for the space beside the pillar or internal wall. Choose a narrower unit, or move the units next to it to make room.',\n    'door-clash':        'Two cabinet doors open into each other. Consider changing a hinge side, or leaving a filler between them.',\n    'bed-clash':         'A bed stands right in front of this unit, so its doors or drawers will not open past it.',\n    'front-blocked':     'Something stands directly in front of this unit, so its door or drawers cannot open fully.',\n    'th-rail-room':      'True Handleless tall units have an aluminium rail on the side opposite the hinge, and a tall unit that stands higher than the one beside it has an end panel on that side. Rails and panels take up room in the run. These two units stand too close together for them. Move one of the units along, or make them the same height.',\n    'door-colour-range': 'Each bedroom range is made in its own set of door colours, and a unit is ordered as its range\\'s product. This unit\\'s door colour belongs to another range, so it would be made in its own range\\'s finish, not the colour shown. Select the unit, open Door & Carcase and choose the range that sells this colour (or a colour this range sells).',\n    'unit-gap':          'Two units stand a small gap apart with nothing filling it. Add a filler (Auto size fills it exactly) or move the units together.',\n    'walkway-too-small': 'The gap between these runs is below the comfortable minimum. Aim for 1000mm where you can, and treat 900mm as the floor.',\n    'above-ceiling':     'A unit, or the cornice along its top, is taller than the room. Choose a shorter unit, take the cornice off, or check the room height you entered in Room Setup.',\n    'under-beam':        'A unit, or the cornice along its top, reaches higher than the underside of a beam above it. Choose a shorter unit, take the cornice off, or move the unit so it is clear of the beam.',\n    'bullnose-curve':    'A round edge (bullnose) laminate worktop can be cut to follow a curved unit or a radius end post, but its rounded front edge cannot follow the curve cleanly, so that end will not look as neat as a straight one. Square edge laminate, or a solid worktop such as quartz, gives a much better curved finish. If you are happy with how it will look, you can keep it.',\n    'under-block':       'A unit, or the cornice along its top, reaches higher than the underside of a Custom Block above it. Choose a shorter unit, take the cornice off, or move the unit so it is clear of the block.',\n    'under-chimney':     'A unit, or the cornice along its top, reaches higher than the underside of a chimney breast above it: the bulkhead across the middle, or the side columns of a Worktop to Ceiling chimney breast. Choose a shorter unit, take the cornice off, or move the unit so it is clear of the chimney breast.',\n    'under-slope':       'A sloped ceiling comes down lower than the top of a unit, or its cornice, standing under it. Choose a shorter unit, take the cornice off, or move the unit towards the high side of the slope.'\n  };\n  const WARN_HELP_IMAGE = 'https://placehold.co/640x360/eeeeee/999999?text=Warning+help+image';\n\n  // A warning's stable identity, so an Accept survives save and reload. Item\n  // ids (cabinet-3, opening-1) last for the life of the plan, and the rule\n  // plus the items it names is what makes one warning THAT warning.\n  const warnKey = (wn) => {\n    const items = [...(wn.itemIds || [])].sort().join(',');\n    // A walkway warning names NO items (itemIds: []), so the rule alone is not\n    // an identity - every walkway in the plan shared one key, and clicking or\n    // accepting one hit them all (Arden, 2026-09-25). Its region is what makes\n    // it that walkway, and the geometry is stable across a reload.\n    const r = wn.region;\n    const reg = r\n      ? '@' + Math.round(r.cx) + ',' + Math.round(r.cy) +\n        ',' + Math.round(r.widthMm || 0) + 'x' + Math.round(r.depthMm || 0)\n      : '';\n    return wn.ruleId + '|' + items + reg;\n  };\n  let acceptedWarnings = new Set();\n  let expandedWarnKey = null;\n  // Checklist approvals, saved with the plan: { checkKey: what was approved }.\n  // An approval holds only while the plan still matches what was approved -\n  // see renderChecklist (Arden, 2026-10-07).\n  let checklistApprovals = {};\n  // Inventory's core items the customer is buying elsewhere (worktops, handles...).\n  let checklistElsewhere = new Set();\n  // What each approved check said, as approved (Arden, 2026-10-28): the card's\n  // title, its approve line, what it approved (signature) and, for Not In Your\n  // Order, the items. Saved with the plan; the planner server stamps who\n  // approved each and when, and posts the list in the Odoo sale order's\n  // chatter when the order lands (planner-api src/checklist-log.js).\n  let checklistRecord = [];\n  // Basket lines that are not units, taken out of the quote in the basket's\n  // Exclude Items from Quote popup (Arden, 2026-10-12): an appliance, sink,\n  // worktop, trim, handle or extra bought elsewhere. Keyed by the line's\n  // stable derived id ('q:...'), with its name and basket group so the popup\n  // can still list it - an excluded line has no basket line. Saved with the\n  // plan. Units keep their own flag (cabinet.excludeFromQuote).\n  let quoteExcludedLines = {};\n  // Basket lines staff made FREE (Arden, 2026-10-13: a free sink for one\n  // customer). Keyed like quoteExcludedLines, by the line's derived id; each\n  // holds the one-use Shopify code planner-api minted for it (src/free-item.js)\n  // with the variant and quantity it was minted for. buildQuote marks the line\n  // free only while both still match - a changed sink is a different item and\n  // pays again until staff make it free again. Saved with the plan.\n  let quoteFreeLines = {};\n  // A Worktop Quote copy (Sales line 108): { ordered, orderRef, sourceName },\n  // saved with the plan; null on every other plan. See isWorktopQuote.\n  let worktopQuote = null;\n  let worktopQuoteLink = null;   // its order link (Order Extras), fetched on open\n  let worktopQuoteLinkFor = null, worktopQuoteStyleAdded = false, worktopQuoteLocked = false;\n\n  function warnTitle(wn) {\n    if (wn.ruleId === 'unit-covers-door' && /window/i.test(wn.message || '')) return 'Window Blocked';\n    // Any advisory without a title of its own still reads as one, not \"Check This\".\n    return WARN_TITLES[wn.ruleId] || 'Plan Advisory';\n  }\n  // What a warning is ABOUT, which is what gets highlighted and is why the row\n  // no longer names a unit (Arden, 2026-09-25). A blocked door is about the\n  // DOOR, not the unit standing in it; a walkway is about the gap. A clash or\n  // an overlap has nothing but its units, so those still point at them.\n  function warnFocusIds(wn) {\n    if (wn.ruleId === 'unit-covers-door') {\n      return (wn.itemIds || []).filter(id => !cabinets.some(c => c.id === id));\n    }\n    return wn.itemIds || [];\n  }\n  // The unit a warning belongs to, so the list groups and numbers by it. A\n  // warning naming no unit (a walkway between two runs) sorts last.\n  function warnCabinet(wn) {\n    for (const id of (wn.itemIds || [])) {\n      const c = cabinets.find(x => x.id === id);\n      if (c) return c;\n    }\n    return null;\n  }\n  // Warnings in the Advisory list's order: by the unit that causes them, in\n  // item-number order, ones naming no unit last.\n  function warnsInListOrder(list) {\n    const num = (wn) => { const c = warnCabinet(wn); return c ? (c.displayNumber == null ? 9e6 : c.displayNumber) : 9e9; };\n    return list.map(wn => ({ wn, n: num(wn) })).sort((a, b) => a.n - b.n).map(r => r.wn);\n  }\n  // The Checklist's Advisory Points picture (Sales bug sheet row 91): the\n  // plan from above - walls, base and tall units, wall units dashed - with\n  // each open point's units in red and a numbered ring round it, the numbers\n  // matching the card's list. A point with nothing on the plan to ring (a\n  // door or window only) keeps its number in the list alone.\n  function advisoryPlanSVG(points) {\n    const verts = (room && room.vertices) || [];\n    const corners = (c) => {\n      const w = c.widthMm || 0, d = c.depthMm || 0;\n      const cx = c.x + w / 2, cy = c.y + d / 2;\n      const th = ((c.rotationDeg || 0) * Math.PI) / 180, cs = Math.cos(th), sn = Math.sin(th);\n      return [[-w / 2, -d / 2], [w / 2, -d / 2], [w / 2, d / 2], [-w / 2, d / 2]]\n        .map(([lx, ly]) => [cx + lx * cs - ly * sn, cy + lx * sn + ly * cs]);\n    };\n    const regionCorners = (r) => corners({ x: r.cx - (r.widthMm || 0) / 2, y: r.cy - (r.depthMm || 0) / 2,\n      widthMm: r.widthMm, depthMm: r.depthMm, rotationDeg: r.angleDeg || 0 });\n    const poly = (pts) => pts.map(([x, y]) => `${Math.round(x)},${Math.round(y)}`).join(' ');\n    let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;\n    const grow = ([x, y]) => { minX = Math.min(minX, x); maxX = Math.max(maxX, x); minY = Math.min(minY, y); maxY = Math.max(maxY, y); };\n    verts.forEach(v => grow([v.x, v.y]));\n    cabinets.forEach(c => corners(c).forEach(grow));\n    if (!isFinite(minX)) return '';\n    const span = Math.max(maxX - minX, maxY - minY) || 1000;\n    const fs = Math.round(Math.max(120, span * 0.065));\n    const pad = fs * 1.6;\n    const vb = [minX - pad, minY - pad, maxX - minX + pad * 2, maxY - minY + pad * 2].map(Math.round).join(' ');\n    const R = (n) => Math.round(n);\n    const hit = new Set();\n    // Each badge on its ring at the first angle clear of the badges before it.\n    const badges = [];\n    const marks = points.map((wn, i) => {\n      const pts = [];\n      for (const id of warnFocusIds(wn)) {\n        const c = cabinets.find(x => x.id === id);\n        if (c) { hit.add(c.id); pts.push(...corners(c)); }\n      }\n      let region = '';\n      if (wn.region) {\n        const rc = regionCorners(wn.region);\n        pts.push(...rc);\n        region = `<polygon points=\"${poly(rc)}\" fill=\"rgba(211,47,47,0.22)\" stroke=\"#d32f2f\" stroke-width=\"${R(fs / 8)}\"/>`;\n      }\n      if (!pts.length) return '';\n      const xs = pts.map(q => q[0]), ys = pts.map(q => q[1]);\n      const x0 = Math.min(...xs), x1 = Math.max(...xs), y0 = Math.min(...ys), y1 = Math.max(...ys);\n      const cx = (x0 + x1) / 2, cy = (y0 + y1) / 2;\n      const r = Math.max(fs * 1.2, Math.hypot(x1 - x0, y1 - y0) / 2 + fs * 0.5);\n      let bx = cx + r * 0.7071, by = cy - r * 0.7071;\n      for (const deg of [-45, -135, 45, 135, -90, 0, 180, 90]) {\n        const tx = cx + r * Math.cos(deg * Math.PI / 180), ty = cy + r * Math.sin(deg * Math.PI / 180);\n        if (badges.every(([qx, qy]) => Math.hypot(qx - tx, qy - ty) > fs * 1.6)) { bx = tx; by = ty; break; }\n      }\n      badges.push([bx, by]);\n      return region\n        + `<circle cx=\"${R(cx)}\" cy=\"${R(cy)}\" r=\"${R(r)}\" fill=\"none\" stroke=\"#d32f2f\" stroke-width=\"${R(fs / 5)}\"/>`\n        + `<circle cx=\"${R(bx)}\" cy=\"${R(by)}\" r=\"${R(fs * 0.75)}\" fill=\"#d32f2f\"/>`\n        + `<text x=\"${R(bx)}\" y=\"${R(by)}\" font-size=\"${fs}\" font-weight=\"700\" fill=\"#fff\" text-anchor=\"middle\" dominant-baseline=\"central\">${i + 1}</text>`;\n    }).join('');\n    const unit = (c) => {\n      const wall = isWallMounted(c), on = hit.has(c.id);\n      return `<polygon points=\"${poly(corners(c))}\" fill=\"${on ? 'rgba(211,47,47,0.18)' : wall ? 'none' : '#e6e6e6'}\"`\n        + ` stroke=\"${on ? '#d32f2f' : wall ? '#b5b5b5' : '#a8a8a8'}\" stroke-width=\"${R(fs / 10)}\"`\n        + (wall && !on ? ` stroke-dasharray=\"${R(fs / 3)} ${R(fs / 4)}\"` : '') + '/>';\n    };\n    // Floor units, then wall units over them, then the units in a point on top.\n    const order = [...cabinets.filter(c => !hit.has(c.id) && !isWallMounted(c)),\n                   ...cabinets.filter(c => !hit.has(c.id) && isWallMounted(c)),\n                   ...cabinets.filter(c => hit.has(c.id))];\n    const walls = verts.length > 2\n      ? `<polygon points=\"${poly(verts.map(v => [v.x, v.y]))}\" fill=\"#fafafa\" stroke=\"#555\" stroke-width=\"${R(fs / 4)}\" stroke-linejoin=\"round\"/>` : '';\n    return `<svg viewBox=\"${vb}\" width=\"100%\" height=\"100%\" preserveAspectRatio=\"xMidYMid meet\" role=\"img\"`\n      + ` aria-label=\"Your plan, with each advisory point still to decide ringed and numbered\" font-family=\"inherit\">`\n      + walls + order.map(unit).join('') + marks + '</svg>';\n  }\n\n  // Where the cornice on each unit tops out, in mm from the floor, for the\n  // above-the-ceiling advisory (Arden, 2026-10-12). The cornice sits on its\n  // band (the top of the units under it) and rises by the profile's height:\n  // the real moulding's, measured from its model once the 3D view has\n  // loaded it (window.__btkGlbSizes, recorded by the 3D renderer), and until\n  // then the trim engine's nominal 40mm.\n  const CORNICE_NOMINAL_MM = 40;\n  function corniceProfileHeightMm(styleId) {\n    try {\n      const sel = featureStyles && featureStyles.cornice;\n      const forStyle = (styleId && Catalogue.getTrimForStyle?.(styleId)) || {};\n      const all = forStyle.cornice || [];\n      const sold = all.filter(p => p.available !== false);\n      const list = sold.length ? sold : all;\n      const p = list.find(x => (x.name || '').toLowerCase() === String(sel || '').toLowerCase()) || list[0];\n      const sz = p && p.straightGlbUrl && window.__btkGlbSizes && window.__btkGlbSizes[p.straightGlbUrl];\n      return (sz && sz.y > 0) ? Math.max(CORNICE_NOMINAL_MM, sz.y) : CORNICE_NOMINAL_MM;\n    } catch (_) { return CORNICE_NOMINAL_MM; }\n  }\n  function corniceTopsByUnit() {\n    const tops = new Map();\n    try {\n      const fs = featureStyles || {};\n      if (!fs.cornice || fs.cornice === 'none' || fs.cornice === CEILING_FILLER) return tops;\n      const trim = computeTrimRuns({\n        cabinets, featureStyles: fs,\n        roomVertices: room?.vertices || [],\n        perimeterItems: roomConfig?.perimeterItems || [],\n        doorThicknessMm: 18\n      });\n      const byId = new Map(cabinets.map(c => [c.id, c]));\n      for (const run of ((trim.cornice && trim.cornice.runs) || [])) {\n        for (const seg of (run.segments || [])) {\n          for (const id of (seg.cabinetIds || [])) {\n            const c = byId.get(id);\n            if (!c) continue;\n            const top = run.bandY + corniceProfileHeightMm(c.kitchenStyleId);\n            if (!(tops.get(id) >= top)) tops.set(id, top);\n          }\n        }\n      }\n    } catch (e) { console.warn('[BTK Kitchen Planner] cornice heights not worked out', e); }\n    return tops;\n  }\n\n  // A placed size that isn't made in its door colour (Odoo's Colour Exclusion\n  // tab, variant custom.excluded_door_colours). A colour change leaves the unit\n  // where it is and says so; the basket holds checkout until it is put right.\n  function doorColourExclusionWarnings() {\n    const out = [];\n    for (const c of cabinets) {\n      if (!c || !c.variantId || !c.doorColourHandle || c.excludeFromQuote) continue;\n      const list = Catalogue.getVariantInfo?.(c.variantId)?.variant?.excludedColours;\n      const colour = list && list.length ? Catalogue.getMasterDoorColour?.(c.doorColourHandle)?.name : null;\n      if (!colour) continue;\n      const want = String(colour).trim().toLowerCase();\n      if (!list.some(n => String(n).trim().toLowerCase() === want)) continue;\n      out.push({\n        ruleId: 'door-colour-not-made', severity: 'warning', itemIds: [c.id],\n        message: `Unit #${c.displayNumber ?? '?'} is not available in ${colour}. Choose another door colour or another unit before checking out.`,\n        _signature: 'door-colour-not-made|' + c.id + '|' + c.variantId + '|' + c.doorColourHandle\n      });\n    }\n    return out;\n  }\n\n  // A unit whose door colour its own range is not made in: a Lacquered Oak\n  // unit with Porcelain doors orders as the oak product. Plans reopened with\n  // their active style split from its colours placed these (see ONE ACTIVE\n  // STYLE in applyState); units already saved that way stay as they are -\n  // the planner never restyles a placed unit on its own - and staff put them\n  // right in Door & Carcase. One point per unit.\n  function doorColourRangeWarnings() {\n    const out = [];\n    for (const c of cabinets) {\n      if (!c || !c.kitchenStyleId || !c.doorColourHandle || c.freestandingAppliance) continue;\n      const doors = Catalogue.getDoorColoursForStyle?.(c.kitchenStyleId) || [];\n      if (!doors.length || doors.some(d => d.handle === c.doorColourHandle)) continue;\n      const style  = Catalogue.getKitchenStyle?.(c.kitchenStyleId)?.name || c.kitchenStyleId;\n      const colour = Catalogue.getMasterDoorColour?.(c.doorColourHandle)?.name || c.doorColourHandle;\n      out.push({\n        ruleId: 'door-colour-range', severity: 'warning', itemIds: [c.id],\n        message: `${c.code || 'This unit'} is ${style} with ${colour} doors, which ${style} is not made in. Set its style and door colour in Door & Carcase before it is ordered.`,\n        _signature: 'door-colour-range|' + c.id + '|' + c.kitchenStyleId + '|' + c.doorColourHandle\n      });\n    }\n    return out;\n  }\n\n  // PLINTH HEIGHT (Non-urgent sheet row 95): an integrated dishwasher, washer\n  // or fridge door unit needs about 820mm from the floor to the underside of\n  // the worktop for the machine behind it. A plinth under 100mm leaves less.\n  const INTEGRATED_APPLIANCE_MIN_SPACE_MM = 820;\n  function lowPlinthApplianceWarnings() {\n    const out = [];\n    for (const c of cabinets || []) {\n      if (!c || c.excludeFromQuote || !hasPlinthBand(c) || !(Number(c.plinthShiftMm) > 0)) continue;\n      const ut = Catalogue.getUnitType ? Catalogue.getUnitType(c.unitTypeId) : null;\n      if (!ut || ut.unitTypeGroupHandle !== 'ap-integrated-appliance-doors') continue;\n      const space = Math.round(unitTopY(c));\n      if (space >= INTEGRATED_APPLIANCE_MIN_SPACE_MM) continue;\n      out.push({\n        ruleId: 'appliance-under-low-worktop', severity: 'warning', itemIds: [c.id],\n        message: `Unit #${c.displayNumber ?? '?'} is an integrated appliance with ${space}mm under the worktop on a ${Math.round(plinthHeightOf(c))}mm plinth. Most integrated appliances need about ${INTEGRATED_APPLIANCE_MIN_SPACE_MM}mm, so check your appliance's fitting height or use a taller plinth.`\n      });\n    }\n    return out;\n  }\n\n  function applyWarnings(grid) {\n    designWarnings = computeWarnings({\n      cabinets,\n      beds: furnitureItems.filter(f => f.tableKind === 'bed'),\n      room,\n      wallOpenings: roomConfig.wallOpenings || [],\n      perimeterItems: roomConfig.perimeterItems || [],\n      walkwayMinMm: 900,\n      ceilingHeightMm: (roomConfig && roomConfig.ceilingHeightMm) || 2400,\n      // Assumed only when nothing says otherwise: a plan saved before the\n      // \"set\" flag existed may still carry a height the customer gave.\n      ceilingAssumed:  !(roomConfig && roomConfig.ceilingHeightSet)\n        && !(roomConfig && roomConfig.ceilingHeightMm && roomConfig.ceilingHeightMm !== 2400),\n      corniceTops:     corniceTopsByUnit()\n    });\n    // Round edge worktop over a curve (bullnoseCurveWarning).\n    try { const bw = bullnoseCurveWarning(); if (bw) designWarnings.push(bw); } catch (e) {}\n    // Belfast sink with too thin a worktop strip on one side (Planner Bugs 37).\n    try { designWarnings.push(...belfastWorktopWarnings()); } catch (e) {}\n    // A sink bowl over the unit beside it, or over an appliance (sinkStraddleWarnings).\n    try { designWarnings.push(...sinkStraddleWarnings()); } catch (e) {}\n    // A placed size its door colour isn't made in (doorColourExclusionWarnings).\n    try { designWarnings.push(...doorColourExclusionWarnings()); } catch (e) {}\n    try { designWarnings.push(...waterfallMaterialWarnings()); } catch (e) {}\n    try { designWarnings.push(...pantryTopStepWarnings()); } catch (e) {}\n    // True Handleless rails / end panels with no room between units (Planner Bugs 23).\n    try { designWarnings.push(...thRailRoomWarnings()); } catch (e) {}\n    // An integrated appliance under a worktop lowered by the plinth height (row 95).\n    try { designWarnings.push(...lowPlinthApplianceWarnings()); } catch (e) {}\n    // Units in a door colour their own range is not made in - STAFF ONLY\n    // (Arden, 2026-10-28: customers do not need to know).\n    try {\n      const api = window.BTKBasketAPI;\n      if (api && typeof api.isStaffMode === 'function' && api.isStaffMode()) designWarnings.push(...doorColourRangeWarnings());\n    } catch (e) {}\n    // Ceiling filler under a sloped / vaulted ceiling: it is cut to the flat\n    // ceiling height, so say to measure on site (Arden, 2026-10-21).\n    try {\n      if (ceilingFillerOn()) {\n        const slopes = (roomConfig.perimeterItems || []).filter(it => it && (it.type === 'sloped-ceiling' || it.type === 'vaulted-ceiling'));\n        const hit = new Set();\n        for (const c of cabinets) for (const pc of (c.ceilingFillerPieces || [])) {\n          const mx = (pc.x1 + pc.x2) / 2, my = (pc.y1 + pc.y2) / 2;\n          for (const s of slopes) {\n            const w = s.widthMm || 0, d = s.depthMm || 0, th = (s.rotationDeg || 0) * Math.PI / 180;\n            const cx = (s.x || 0) + w / 2, cy = (s.y || 0) + d / 2;\n            const lx = (mx - cx) * Math.cos(-th) - (my - cy) * Math.sin(-th);\n            const ly = (mx - cx) * Math.sin(-th) + (my - cy) * Math.cos(-th);\n            if (Math.abs(lx) <= w / 2 && Math.abs(ly) <= d / 2) hit.add(c.id);\n          }\n        }\n        if (hit.size) designWarnings.push({ ruleId: 'ceiling-filler-slope', severity: 'warning', itemIds: [...hit],\n          message: 'Ceiling filler under a sloped ceiling: the planner cuts it to the flat ceiling height - measure the height on site.',\n          _signature: 'ceiling-filler-slope|' + [...hit].sort().join(',') });\n      }\n    } catch (e) {}\n    // Outline every flagged item in the freshly-rendered 2D plan. Accepting a\n    // warning does NOT clear the plan colour (Arden, 2026-09-25): the tick is\n    // a record that it was reviewed, not that it went away.\n    const flagged = new Set();\n    for (const wn of designWarnings) {\n      // A unit standing across a door or window marks the OPENING, not the\n      // unit. Standing there is a legitimate choice to be trimmed on site, so\n      // reddening the carcase reads as an error when it is not; what needs to\n      // be obvious is which way through is blocked. The warning still NAMES\n      // the unit in itemIds, which the Magic auto-fix relies on to know what\n      // to remove, so only the HIGHLIGHT is narrowed.\n      const openingOnly = wn.ruleId === 'unit-covers-door';\n      for (const id of (wn.itemIds || [])) {\n        if (openingOnly && cabinets.some(c => c.id === id)) continue;\n        flagged.add(id);\n      }\n    }\n    for (const id of flagged) {\n      const el = root.querySelector('[data-cabinet-id=\"' + id + '\"]')\n              || root.querySelector('[data-opening-id=\"' + id + '\"]');\n      if (el) el.classList.add('btk-kp-warn');\n    }\n    // Region warnings (e.g. walkway gaps) - draw a cross-hatched red\n    // rectangle in the gap with its size, on the plan coordinate layer.\n    if (grid && grid.el) {\n      for (const wn of designWarnings) {\n        const r = wn.region;\n        if (!r) continue;\n        const div = document.createElement('div');\n        div.className = 'btk-kp-warn-region';\n        div.dataset.warnKey = warnKey(wn);   // so a row can highlight ITS gap\n        div.style.left   = (r.cx * grid.pxPerMm) + 'px';\n        div.style.top    = (r.cy * grid.pxPerMm) + 'px';\n        div.style.width  = ((r.widthMm || 0) * grid.pxPerMm) + 'px';\n        div.style.height = ((r.depthMm || 0) * grid.pxPerMm) + 'px';\n        div.style.transform = 'translate(-50%, -50%) rotate(' + (r.angleDeg || 0) + 'deg)';\n        if (r.label) {\n          const lbl = document.createElement('span');\n          if (r.angleDeg) lbl.style.transform = 'rotate(' + (-r.angleDeg) + 'deg)';\n          lbl.textContent = r.label;\n          div.appendChild(lbl);\n        }\n        grid.el.appendChild(div);\n      }\n    }\n    // Drop accepts whose warning has gone, so the saved list cannot grow\n    // without bound as a plan is edited.\n    const live = new Set(designWarnings.map(warnKey));\n    for (const k of [...acceptedWarnings]) if (!live.has(k)) acceptedWarnings.delete(k);\n    renderWarningsButton();\n    renderWarningsPanel();\n  }\n\n  function renderWarningsButton() {\n    const btn = root.querySelector('[data-btk-kp-warnings-open]');\n    if (!btn) return;\n    const total = designWarnings.length;\n    const open  = designWarnings.filter(w => !acceptedWarnings.has(warnKey(w))).length;\n    btn.hidden = total === 0;\n    // All signed off: keep the button, in the accepted green with a tick, so\n    // the list stays reachable and red keeps meaning \"needs attention\".\n    btn.classList.toggle('is-clear', total > 0 && open === 0);\n    const countEl = btn.querySelector('[data-btk-kp-warnings-count]');\n    if (countEl) countEl.textContent = String(open || total);\n    btn.setAttribute('aria-label', open\n      ? open + ' advisory point' + (open === 1 ? '' : 's') + ' to review'\n      : total + ' advisory point' + (total === 1 ? '' : 's') + ', all accepted');\n  }\n\n  function renderWarningsPanel() {\n    const host = root.querySelector('[data-btk-kp-warnings-list]');\n    if (!host) return;\n    if (!designWarnings.length) {\n      host.innerHTML = '<p class=\"btk-kp-warnlist-empty\">No advisory points on this plan.</p>';\n      return;\n    }\n    const esc = s => String(s == null ? '' : s).replace(/[&<>\"]/g, ch => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '\"': '&quot;' }[ch]));\n    // Grouped by the unit that causes them, in item-number order. A warning\n    // naming no unit (a walkway between two runs) goes last.\n    const rows = designWarnings.map(wn => ({ wn, cab: warnCabinet(wn) }));\n    rows.sort((a, b) => {\n      const na = a.cab ? (a.cab.displayNumber == null ? 9e6 : a.cab.displayNumber) : 9e9;\n      const nb = b.cab ? (b.cab.displayNumber == null ? 9e6 : b.cab.displayNumber) : 9e9;\n      return na - nb;\n    });\n    host.innerHTML = rows.map(function (r) {\n      const wn = r.wn;\n      const key = warnKey(wn);\n      const accepted = acceptedWarnings.has(key);\n      const isOpen = expandedWarnKey === key && !accepted;\n\n      return '' +\n        '<div class=\"btk-kp-warnrow' + (accepted ? ' is-accepted' : '') + (isOpen ? ' is-open' : '') + '\" data-warn-key=\"' + esc(key) + '\">' +\n          '<button type=\"button\" class=\"btk-kp-warnrow-head\" data-warn-toggle aria-expanded=\"' + (isOpen ? 'true' : 'false') + '\">' +\n            '<span class=\"btk-kp-warnrow-title\">' + esc(warnTitle(wn)) + '</span>' +\n            '<span class=\"btk-kp-warnrow-tick\" aria-hidden=\"true\">' +\n              '<svg viewBox=\"0 0 24 24\" width=\"14\" height=\"14\"><path fill=\"none\" stroke=\"currentColor\" stroke-width=\"3\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M4 12.5 9.5 18 20 6.5\"/></svg>' +\n            '</span>' +\n          '</button>' +\n          '<div class=\"btk-kp-warnrow-body\"' + (isOpen ? '' : ' hidden') + '>' +\n            '<p class=\"btk-kp-warnrow-msg\">' + esc(wn.message) + '</p>' +\n            '<div class=\"btk-kp-warnrow-actions\">' +\n              '<button type=\"button\" class=\"btk-kp-action-btn btk-kp-action-btn--light btk-kp-action-btn--sm\" data-warn-details>' +\n                '<span class=\"btk-kp-action-btn-label\">Details</span></button>' +\n              '<button type=\"button\" class=\"btk-kp-action-btn btk-kp-action-btn--green btk-kp-action-btn--sm\" data-warn-accept>' +\n                '<span class=\"btk-kp-action-btn-label\">Accept</span></button>' +\n            '</div>' +\n          '</div>' +\n        '</div>';\n    }).join('');\n  }\n\n  // Point at what a warning is about, without selecting it. Selection swaps the\n  // sidebar to the unit's properties, which would throw away the list the user\n  // is reading. Applied straight to the rendered elements; the next rerender\n  // clears it, which is right for a transient highlight.\n  function focusWarningOnPlan(wn) {\n    root.querySelectorAll('.btk-kp-warn-focus').forEach(el => el.classList.remove('btk-kp-warn-focus'));\n    if (!wn) return;\n    for (const id of warnFocusIds(wn)) {\n      const el = root.querySelector('[data-cabinet-id=\"' + id + '\"]')\n              || root.querySelector('[data-opening-id=\"' + id + '\"]');\n      if (el) el.classList.add('btk-kp-warn-focus');\n    }\n    // A walkway warning has no items at all - its gap is the thing.\n    if (wn.region) {\n      const key = warnKey(wn);\n      root.querySelectorAll('.btk-kp-warn-region').forEach(el => {\n        if (el.dataset.warnKey === key) el.classList.add('btk-kp-warn-focus');\n      });\n    }\n  }\n\n  // Opening the list behaves like clicking a unit: the menu slides on to it,\n  // and the Back pill slides back and deselects (Arden, 2026-09-25).\n  function openWarningsPanel() {\n    if (selectedItem) selectItem(null);\n    renderWarningsPanel();\n    setActivePanel('warnings');\n    setWarningsHeader(true);\n  }\n  // The sidebar header normally says what STAGE you are on (\"Add Items\", and\n  // its one-line intro). While the warnings list is open it says what this\n  // panel is instead (Arden, 2026-09-25); Close puts the stage's own back.\n  function setWarningsHeader(on) {\n    const titleEl = root.querySelector('[data-btk-kp-sidebar-title]');\n    const introEl = root.querySelector('[data-btk-kp-sidebar-intro]');\n    if (!on) { updateSidebarTitle(currentStep); return; }\n    const n = designWarnings.filter(w => !acceptedWarnings.has(warnKey(w))).length;\n    if (titleEl) titleEl.textContent = 'Advisory';\n    if (introEl) {\n      introEl.textContent = n\n        ? n + ' item' + (n === 1 ? '' : 's') + ' to review. Open one to see it on the plan.'\n        : 'Everything here has been accepted.';\n    }\n    root.querySelectorAll('[data-btk-kp-header-action]').forEach(b => { b.hidden = true; });\n  }\n\n  function rerender(opts = {}) {\n    liveDragCabs = null;   // any committed change supersedes an in-progress drag overlay\n    syncReducedCornerReach();   // a reduced depth corner's void follows the run round its corner\n    syncExtractorsToHobs();   // hoods follow their hob (and go with it) before anything reads them\n    syncCanopiesToHosts();    // canopy extractors sit in (and move with) their wall unit\n    syncTapsToHosts();        // a tap on a unit moves and turns with it\n    syncBeamsToCeiling();     // a ceiling beam hangs flush under the ceiling\n    syncApplianceBackMaterials();   // appliance island back panels follow the unit they copy\n    syncWallEndPanels();      // wall end panels placed by hand hang from the wall unit beside them\n    syncSinkMounts();         // each sink unit's fitting (inset / undermount) for the 3D\n    if (_islandDry) { syncStackAnchors(); return; }\n    // rerender IS the commit point for every change the plan can undergo, so\n    // it is where both autosave and the undo history take their cue.\n    //\n    // \u26A0 NOT a plan-changed signal. rerender also runs for VIEW changes -\n    // mountLiveViewIntoEmbed calls it when the basket opens - so counting\n    // renders made the plan look changed every time and checkout re-saved\n    // regardless (Arden, 2026-09-27). Whether the plan changed is answered by\n    // undoSnapshot(), off the design's own content.\n    if (typeof scheduleAutosave === 'function') scheduleAutosave();\n    if (typeof pushUndoSnapshot === 'function') pushUndoSnapshot();\n    // The Worktops popup shows prices and slabs, so refresh it after this\n    // render completes - only while it is open, so it costs nothing otherwise.\n    if (worktopsPopupHandle) requestAnimationFrame(() => worktopsPopupHandle.refreshIfOpen());\n    syncStackAnchors();    // stacked units resolve their height off the unit below\n    window.__BTK_room      = roomConfig;\n    window.__BTK_cabinets  = cabinets;\n    window.__BTK_roomObj   = room;\n    window.__BTK_Catalogue = Catalogue;\n    // To Do's section in the sidebar reads the current cabinets list\n    // to decide which Choose Sink button (if any) to show. Light-\n    // weight refresh so it's safe to fire on every render.\n    refreshSpareSinks();\n    cabinetsHandle?.refreshTodos?.();\n    refreshBasketTasks();   // keep the basket's \"Still to do\" tiles in step\n    destroyRender();\n    room     = buildRoomPolygon(roomConfig);\n    baseRoom = buildBaseRoom(roomConfig);\n\n    // Unified numbering + end-panel yield. Numbers sweep clockwise from\n    // the bottom-left: per wall, every unit on it (any category) by\n    // position, with each unit's end-panel BOARD numbered right after the\n    // unit (first-seen), then islands. So the wall-grouped basket reads\n    // sequentially and a panel's number sits with its unit. Sets\n    // cab.displayNumber + board.itemNumber and stores the layout.\n    endPanelLayout = computeNumberingAndLayout();\n    window.__BTK_endPanelLayout = endPanelLayout;\n\n    // DIAGNOSTIC: run __btkDrag() to get the whole plan as JSON (paste it\n    // back and the drag pipeline can be re-run offline against the real\n    // engine), or __btkDrag(2) to walk unit 2 along both axes through the\n    // REAL snapAndClamp and see exactly where it stops - and, at the point\n    // it stops, which stage of the pipeline is holding it: turn each one\n    // off in turn and whichever release lets it through is the culprit.\n    window.__btkDrag = (num, spanMm = 1600, stepMm = 50) => {\n      const round = (v) => Math.round(v);\n      // The polygon as the ENGINE sees it. Three things here have bitten\n      // before and are worth reading off directly: a wall shorter than a\n      // millimetre (a doubled vertex - its normal is meaningless, so it\n      // becomes a phantom barrier), a bbox that does not start at 0,0 (the\n      // room and the units then disagree about where the origin is), and\n      // the turn direction at each vertex (a mis-signed one makes the wall\n      // clamp push where it should let go).\n      const V = room.vertices || [];\n      const wallRows = V.map((a, i) => {\n        const b = V[(i + 1) % V.length];\n        const prev = V[(i - 1 + V.length) % V.length];\n        const cross = (a.x - prev.x) * (b.y - a.y) - (a.y - prev.y) * (b.x - a.x);\n        return { i, fromX: round(a.x), fromY: round(a.y), toX: round(b.x), toY: round(b.y),\n                 len: round(Math.hypot(b.x - a.x, b.y - a.y)),\n                 turn: cross < -1e-6 ? 'concave' : (cross > 1e-6 ? 'convex' : 'STRAIGHT/DEGENERATE') };\n      });\n      const xs = V.map(v => v.x), ys = V.map(v => v.y);\n      const bbox = { minX: round(Math.min(...xs)), minY: round(Math.min(...ys)),\n                     maxX: round(Math.max(...xs)), maxY: round(Math.max(...ys)) };\n      const dump = {\n        build:    window.__BTK_BUILD,\n        shapeId:  roomConfig.shapeId,\n        bbox,\n        shortWalls: wallRows.filter(w => w.len < 5),\n        walls:    wallRows,\n        vertices: V.map(v => ({ x: round(v.x), y: round(v.y) })),\n        cabinets: cabinets.map(c => ({\n          n: c.displayNumber, id: c.id,\n          x: round(c.x), y: round(c.y), w: c.widthMm, d: c.depthMm,\n          rot: c.rotationDeg || 0, cat: c.category, type: c.unitTypeId,\n          h: c.heightMm, off: c.heightOffGroundMm || 0,\n          setback: c.wallSetbackMm || 0, endPanels: c.endPanels || null,\n          cornerUnit: c.cornerUnit || null, lShapeUnit: c.lShapeUnit || null,\n          diagonalCornerUnit: c.diagonalCornerUnit || null,\n          customFit: c.customFit || null\n        })),\n        perimeterItems: (roomConfig.perimeterItems || []),\n        wallOpenings:   (roomConfig.wallOpenings || [])\n      };\n      if (num == null) {\n        console.log('%c=== __btkDrag: plan ===', 'font-weight:bold');\n        console.log('bbox', bbox, bbox.minX || bbox.minY ? '  <-- NOT 0,0' : '');\n        console.table(wallRows);\n        console.log(JSON.stringify(dump));\n        return dump;\n      }\n      const cab = cabinets.find(c => String(c.displayNumber) === String(num));\n      if (!cab) { console.log('[__btkDrag] no unit numbered ' + num); return; }\n      const others       = cabinets.filter(o => o.id !== cab.id);\n      const obstacles    = [...perimeterObstaclesFor(cab),\n                            ...epDoorLinePanelObstacles(cab.id)];\n      const wallOpenings = roomConfig.wallOpenings || [];\n      // Exactly the call the drag handler makes for a standard unit.\n      const run = (rx, ry, o = {}) => snapAndClamp(\n        o.item || cab, rx, ry, room,\n        o.others    !== undefined ? o.others    : others,\n        o.obstacles !== undefined ? o.obstacles : obstacles,\n        o.openings  !== undefined ? o.openings  : wallOpenings,\n        o.opts || {});\n\n      // 1. Where does it actually go, asked to move along each axis?\n      const sweep = (axis) => {\n        const rows = [];\n        for (let d = -spanMm; d <= spanMm; d += stepMm) {\n          const rx = cab.x + (axis === 'x' ? d : 0);\n          const ry = cab.y + (axis === 'y' ? d : 0);\n          const r  = run(rx, ry);\n          rows.push({ asked: d,\n                      got: round((axis === 'x' ? r.x - cab.x : r.y - cab.y)),\n                      offAxis: round((axis === 'x' ? r.y - cab.y : r.x - cab.x)) });\n        }\n        return rows;\n      };\n      console.log('%c=== __btkDrag: unit ' + num + ' ===', 'font-weight:bold');\n      console.log('at', { x: round(cab.x), y: round(cab.y), w: cab.widthMm, d: cab.depthMm,\n                          rot: cab.rotationDeg || 0, cat: cab.category, type: cab.unitTypeId });\n      console.log('%csweep along X (asked vs got, mm)', 'font-weight:bold');\n      console.table(sweep('x'));\n      console.log('%csweep along Y (asked vs got, mm)', 'font-weight:bold');\n      console.table(sweep('y'));\n\n      // 2. At the far end of each sweep, who is holding it? Each row drops\n      //    one stage; the row whose \"got\" jumps to the asked figure names it.\n      const stages = [\n        ['everything on',     {}],\n        ['no other units',    { others: [] }],\n        ['no obstacles',      { obstacles: [] }],\n        ['no openings',       { openings: [] }],\n        ['no corner snap',    { opts: { skipCornerSnap: true } }],\n        ['ignore clash',      { item: { ...cab, customFit: { ignoreClash: true } } }],\n        ['room clamp only',   { others: [], obstacles: [], openings: [],\n                                item: { ...cab, customFit: { ignoreClash: true } } }]\n      ];\n      const blame = [];\n      for (const [label, o] of stages) {\n        const row = { stage: label };\n        for (const [dir, dx, dy] of [['-X', -spanMm, 0], ['+X', spanMm, 0],\n                                     ['-Y', 0, -spanMm], ['+Y', 0, spanMm]]) {\n          const r = run(cab.x + dx, cab.y + dy, o);\n          row[dir] = round(dx ? r.x - cab.x : r.y - cab.y);\n        }\n        blame.push(row);\n      }\n      console.log('%cwho is holding it (asked for +/-' + spanMm + 'mm)', 'font-weight:bold');\n      console.table(blame);\n      return { dump, blame };\n    };\n\n    // DIAGNOSTIC: run __btkDumpNumbering() in the console to see every\n    // cabinet's plan number + every end-panel board's number, so basket vs\n    // 2D mismatches (duplicates / out-of-order) can be pinned down exactly.\n    window.__btkDumpNumbering = () => {\n      const cabRows = cabinets.map(c => ({\n        num: c.displayNumber, id: c.id,\n        type: (Catalogue.getUnitType?.(c.unitTypeId)?.name) || c.unitTypeId || '',\n        excl: !!c.excludeFromQuote, hasVariant: !!c.variantId,\n        endPanelUnit: !!c.endPanelUnit, filler: !!c.endPanelFiller\n      })).sort((a, b) => (a.num || 0) - (b.num || 0));\n      const boardRows = (endPanelLayout?.boards || []).map(b => ({\n        num: b.itemNumber, code: b.code, type: b.type, ownerCabId: b.ownerCabId,\n        faces: (b.pieces || []).map(p => p.face.id).join('  |  ')\n      })).sort((a, b) => (a.num || 0) - (b.num || 0));\n      console.log('%c=== CABINETS (num = plan number) ===', 'font-weight:bold');\n      console.table(cabRows);\n      console.log('%c=== END-PANEL / FILLER BOARDS ===', 'font-weight:bold');\n      console.table(boardRows);\n      return { cabinets: cabRows, boards: boardRows };\n    };\n\n    const grid = renderGrid(main, room, {\n      wallOpenings: roomConfig.wallOpenings || [],\n      perimeterItems: roomConfig.perimeterItems || [],\n      baseRoom,\n      // An opening on a pillar / internal wall face cuts that face's band.\n      insetFor: (op) => openingInsetMm(op),\n      // In the basket mini view the wall dimensions are hidden (see the\n      // .btk-kp-embed-viewing .btk-kp-dim-layer rule), so don't reserve the\n      // full ~120px dim-stack margin - let the room fill the small viewport.\n      // (Read the DOM class, not the `embedViewing` var - it's declared far\n      // below this fn, so this stays safe if rerender runs during init.)\n      ...(root.classList.contains('btk-kp-embed-viewing') ? { dimStackPx: 14 } : {})\n    });\n    renderHandles.push(grid);\n    // Re-apply the persisted scroll-zoom to the freshly built grid.\n    currentGridEl = grid.el;\n    lastGrid = grid;\n    applyView2dTransform();\n    clearanceCtx = { gridEl: grid.el, pxPerMm: grid.pxPerMm };\n    renderHandles.push({ destroy() {\n      if (clearanceHandle) { clearanceHandle.destroy(); clearanceHandle = null; }\n      clearanceCtx = null;\n    } });\n\n    // Dimension labels use the corner-to-corner base polygon so the\n    // A/D/C/B labels keep their meaning even when items have carved\n    // notches out of the walls.\n    const dims = renderWallDimensions(grid.el, baseRoom, grid.pxPerMm, {\n      wallOpenings:   roomConfig.wallOpenings   || [],\n      perimeterItems: roomConfig.perimeterItems || [],\n      cabinets,\n      // Carry \"Hide units\" through the FULL render too. refreshDims passed\n      // it, but every rerender re-created the dim layer without it, so the\n      // per-unit tiers came straight back while the tick was still on.\n      hideUnits: hideUnits && currentStep === 'room-setup',\n      wallSpans: (wi) => wallDimSpans(wi)\n    });\n    dimsHandle = dims;\n    renderHandles.push(dims);\n\n    // Worktops once for this render, for the wall units' heights on hover.\n    let _gapSlabs = null;\n    const cabs = renderCabinets(grid.el, cabinets, grid.pxPerMm, Catalogue, {\n      // Item numbers spaced at the badge size on screen at this zoom.\n      badgeScale:             badgeScaleFor(grid.pxPerMm),\n      // How high a wall or bridging unit hangs, for its hover text (row 12).\n      wallUnitHeights:        (c) => wallUnitHeights(c, _gapSlabs || (_gapSlabs = buildWorktops() || [])),\n      // Lines excluded from the quote show no number on the plan.\n      hiddenNumbers:          () => excludedPlanNumbers(),\n      onPlannerSinkSelect:    (cabinetId) => selectItem({ kind: 'planner-sink', cabinetId }),\n      // Neither picker opens on a purchased plan: choosing is changing.\n      // The sink + and tap + open the unit's sink and tap in 3D (Arden, 2026-10-24).\n      // A yellow + (a sink in the basket can go here) opens Add Sinks & Taps with it on top.\n      onOpenChooseSinkPopup:  (cabinetId) => {\n        if (_bootOrdered) return;\n        if (spareSinkByCab.has(cabinetId)) cabinetsHandle?.openChooseSinkPopup?.(cabinetId);\n        else showSinkSet(cabinetId);\n      },\n      hasSpareSink:           (cabinetId) => spareSinkByCab.has(cabinetId),\n      // An empty Walk-In Corner Larder Frame: + opens Customise Walk-in Larder.\n      walkInSetPlusAt:        (cab) => walkInSetPlusAt(cab),\n      onOpenWalkInSets:       (cabinetId) => openWalkInSetsPopup(cabinetId),\n      // Green tap \"+\" beside a fitted sink with no tap yet -> Taps, fitting to it.\n      onOpenChooseTapPopup:   (cabinetId) => { if (!_bootOrdered) showSinkSet(cabinetId); },\n      hasTapOnCabinet:        (cabinetId) => cabinetHasTap(cabinetId),\n      // Green \"+\" in front of an EMPTY appliance aperture \u2192 Choose Appliance.\n      onOpenChooseAppliancePopup: (cabinetId, openingIndex) => {\n        if (!_bootOrdered) cabinetsHandle?.openChooseAppliancePopup?.(cabinetId, openingIndex);\n      },\n      // Green appliance/sink badge click \u2192 product detail popup (live\n      // listing data fetched from /products/{handle}.js). ctx carries\n      // { cabId, kind, openingIndex } so the popup's Change Item button\n      // can reopen the matching Choose Appliance / Choose Sink picker.\n      onOpenProductDetail:    (handle, ctx) => cabinetsHandle?.openProductDetailPopup?.(handle, ctx),\n      // Twin badge on a stacked wall unit \u2192 select that single unit.\n      onSelectCabinet:        (cabinetId) => setCabinetSelection([cabinetId]),\n      // Shared end-panel board numbers (one per physical board) + the\n      // click \u2192 select-the-face handler (opens its cut plan in the left\n      // panel and highlights the piece).\n      endPanelNumbers:        endPanelLayout?.cabSideToNumber || {},\n      endFeatureNumbers:      endPanelLayout?.cabSideToFeatureNumber || {},\n      endPanelFaces:          endPanelLayout?.cabSideToFace || {},\n      onSelectEndPanelFace:   (cabId, side) => selectEndPanelFace(cabId, side),\n      // A vertical PROFILE number: select the profile itself and open its\n      // own quote line.\n      onSelectRail:           (cabId, side) => selectRail(cabId, side),\n      onSelectCornerPost:     (cabId, side, pos) => selectCornerPost(cabId, side, pos)\n    });\n    renderHandles.push(cabs);\n    mainCabsHandle = cabs;\n    _badgeLayoutZoom = view2d.zoom || 1;\n    cabs?.elements?.forEach(({ cabinet, el }) => wireCabinet(cabinet, el, grid.pxPerMm));\n\n    // Worktops - thin black perimeter outline per run, drawn over the\n    // cabinets (non-interactive in 2D; selection happens in 3D).\n    // Handle + ctx hoisted so the drag handlers can re-render the\n    // outlines mid-drag (otherwise they snap to the new position only\n    // on drop, which lags behind the cabinet visually).\n    const worktopSlabs = buildWorktops();\n    settleFurnitureHeights(worktopSlabs);\n    window.__BTK_worktops = worktopSlabs;\n    worktops2dHandle = renderWorktops(grid.el, worktopSlabs, grid.pxPerMm, worktopRenderOpts(cabinets));\n    worktops2dCtx    = { gridEl: grid.el, pxPerMm: grid.pxPerMm };\n    renderHandles.push({ destroy() {\n      if (worktops2dHandle) { worktops2dHandle.destroy(); worktops2dHandle = null; }\n      worktops2dCtx = null;\n    } });\n\n    // Sinks & hobs - drawn on top of the worktops as draggable markers\n    // with their cutout outline. Phase 1: visual only; the actual\n    // worktop hole is a later phase.\n    const wi2d = renderWorktopItems(grid.el, worktopItems, grid.pxPerMm);\n    renderHandles.push(wi2d);\n    wi2d?.elements?.forEach(({ item, el }) => (item.kind === 'extractor'\n      ? wireExtractor2D(item, el, grid.pxPerMm)\n      : item.kind === 'canopy'\n      ? wireCanopy2D(item, el, grid.pxPerMm)\n      : wireWorktopItem(item, el, grid.pxPerMm)));\n\n    // Furniture footprints (free-standing, draggable). Footprint size\n    // comes from the GLB bbox (set by onFurnitureSize); default until\n    // the model has loaded. x/y are the footprint CENTRE.\n    if (furnitureItems.length) {\n      const furnLayer = document.createElement('div');\n      furnLayer.className = 'btk-kp-furniture-layer';\n      // Stools, chairs and tables stand on the floor, so they go below the\n      // worktop and units: a stool under an overhang shows through it. One\n      // already in a unit (a saved plan, or a unit moved onto it) stays on top\n      // in furnLayer, or it couldn't be seen or dragged out.\n      const furnUnderLayer = document.createElement('div');\n      furnUnderLayer.className = 'btk-kp-furniture-layer btk-kp-furniture-layer--under';\n      const furnBlockers = furnitureUnitBlockers();\n      // Chairs, benches and stools first, then tables, so a chair tucks under its\n      // table; then what stands on a surface, so a mug or lamp stays on the table.\n      const furnitureDrawOrder = (f) => (furniturePlacement(f) !== 'floor' ? 2 : furnitureEntry(f)?.category === 'tables' ? 1 : 0);\n      // Among those, the higher piece on top: stacked shelves read from the top down.\n      [...furnitureItems].sort((a, b) => furnitureDrawOrder(a) - furnitureDrawOrder(b) || (a.elevationMm || 0) - (b.elevationMm || 0)).forEach(item => {\n        const w = item.widthMm || 500;\n        const d = item.depthMm || 500;\n        const el = document.createElement('div');\n        el.className = 'btk-kp-furniture-2d';\n        el.dataset.furnitureId = item.id;\n        el.style.width  = `${w * grid.pxPerMm}px`;\n        el.style.height = `${d * grid.pxPerMm}px`;\n        el.style.left   = `${(item.x - w / 2) * grid.pxPerMm}px`;\n        el.style.top    = `${(item.y - d / 2) * grid.pxPerMm}px`;\n        if (item.rotationDeg) el.style.transform = `rotate(${item.rotationDeg}deg)`;\n        // Stools, chairs and tables are drawn as they look from above; the rest\n        // (freestanding appliances) stay a labelled box.\n        const furnCat = (Catalogue.getFurniture?.() || []).find(f => f.id === item.furnitureId)?.category;\n        const drawn = appendFurnitureDrawing(el, item, furnCat, w, d);\n        if (drawn) {\n          el.style.background = 'none';\n          el.style.border = 'none';\n          el.title = item.name || '';\n        } else {\n          const lab = document.createElement('div');\n          lab.className = 'btk-kp-furniture-2d-label';\n          lab.textContent = item.name || '';\n          el.appendChild(lab);\n        }\n        (drawn && furniturePlacement(item) === 'floor' && !furnitureHitsUnit(item, item.x, item.y, furnBlockers) ? furnUnderLayer : furnLayer).appendChild(el);\n        wireFurnitureItem(item, el, grid.pxPerMm, w, d);\n      });\n      grid.el.appendChild(furnUnderLayer);\n      grid.el.appendChild(furnLayer);\n      renderHandles.push({ destroy() { furnUnderLayer.remove(); furnLayer.remove(); } });\n    }\n\n    // Upstands + splashbacks + per-hob splashbacks - strip records\n    // come from the engine helper (mirrors the worktop engine\n    // pattern). Strips skip cabinets that don't touch a wall, pick up\n    // both arms of corner units, and carry per-strip window cutouts.\n    const splashbackStrips = computeSplashbackStrips({\n      cabinets,\n      worktopItems,\n      worktopSlabs,\n      room,\n      perimeterItems: roomConfig.perimeterItems,\n      wallOpenings: roomConfig.wallOpenings,\n      settings:     roomConfig.splashbacks\n    }).strips;\n    const splash2d = renderSplashbacks(grid.el, splashbackStrips, grid.pxPerMm);\n    if (splash2d) renderHandles.push(splash2d);\n\n    normaliseStructureRotations();\n    syncRoomFeatureButtons();\n    // A ceiling wedge and a vaulted ceiling are big shapes lying over the\n    // floor, and once the room is settled they only sit between the user and\n    // the units they are working on. They belong to Room Setup, so that is\n    // where they are drawn. A beam stays - it is a thin line, and it is worth\n    // knowing where it runs while a tall unit is going in under it.\n    const planFeatures = (roomConfig.perimeterItems || []).filter(it =>\n      !(HIDE_CEILING_SHAPES_IN.has(currentStep)\n        && (it.type === 'sloped-ceiling' || it.type === 'vaulted-ceiling')));\n    const feats = renderFeatures(grid.el, planFeatures, grid.pxPerMm, room);\n    renderHandles.push(feats);\n    feats?.elements?.forEach(({ feature, el }) => wirePerimeterItem(feature, el, grid.pxPerMm, grid));\n\n    const ops = renderOpenings(grid.el, roomConfig, room, grid.pxPerMm, {\n      insetFor: (op) => openingInsetMm(op)\n    });\n    renderHandles.push(ops);\n    ops?.elements?.forEach(({ opening, el }) => wireOpening(opening, el, grid, ops));\n\n    syncPlanPrices();\n    pricingHandle.update(headPriceState());\n    roomShapeHandle.refresh();\n    doorsWindowsHandle.refresh();\n    basketDrawerHandle.refresh();\n    applySelectionVisual();\n    applyWarnings(grid);\n    if (typeof renderWaypoints === 'function') renderWaypoints();\n    if (typeof renderLights === 'function') renderLights();\n    if (paintMode && typeof renderPaint === 'function') renderPaint();  // re-append paint layer (grid was rebuilt)\n    // The full 3D rebuild is by far the most expensive part of a rerender. The\n    // live-session viewer skips it for a pure-drag update and nudges the meshes\n    // instead (see applyMirrorSnapshot), then reconciles once the drag settles.\n    // ?btktime=1: the 2D plan and the 3D scene are the two halves of a redraw\n    // and they cost wildly different amounts. Split them, or \"plan redrawn:\n    // 4200ms\" says nothing about which (Arden, 2026-09-30).\n    try { window.BTKKPTiming && window.BTKKPTiming.mark('2D plan drawn'); } catch (e) {}\n    if (!opts.skip3D) request3DRebuild({ room, roomConfig, openingFaceInsets: openingFaceInsetMap(), cabinets, baseRoom, featureStyles, railFinishHandle, segmentColours, worktops: buildWorktops(), worktopColourHex, worktopColours, worktopCornerRadii, worktopItems: worktopItems3D(), furnitureItems, handleGroups, flythroughWaypoints, lights, lightsOn });\n    try { window.BTKKPTiming && window.BTKKPTiming.mark(opts.skip3D ? '3D skipped' : '3D rebuild queued'); } catch (e) {}\n    // handle3D.render() is not async and returns nothing, but it queues a\n    // .then() per cabinet. With the GLBs cached those callbacks all resolve\n    // without yielding, so they drain in one uninterruptible block at the end\n    // of THIS task - invisible to any mark placed inline. A setTimeout(0)\n    // lands after that drain, so the gap between the two is its real cost.\n    if (!opts.skip3D) {\n      const _d0 = performance.now();\n      setTimeout(() => {\n        try {\n          window.BTKKPTiming && window.BTKKPTiming.mark(\n            '3D async builders drained (+' + Math.round(performance.now() - _d0) + 'ms after the call)');\n        } catch (e) {}\n      }, 0);\n    }\n\n    // While on the 3D step, hide the freshly-rebuilt 2D children of\n    // `main` so they don't overlay the 3D viewport. on3DStepActive\n    // only runs on step change; rerender re-appends 2D children\n    // (grid, cabinets, dims, openings, features) with default\n    // display, which would otherwise sit on top of the 3D canvas.\n    if (viewMode === '3d' && viewport3D) {\n      Array.from(main.children).forEach(child => {\n        if (child !== viewport3D\n            && !child.classList?.contains('btk-kp-viewport-overlay')\n            && !child.hasAttribute?.('data-btk-kp-home')) {   // never hide the Home overlay (its own [hidden] controls it)\n          child.style.display = 'none';\n        }\n      });\n    }\n  }\n\n  function applySelectionVisual() {\n    root.querySelectorAll('.btk-kp-selected').forEach(el => el.classList.remove('btk-kp-selected'));\n    // Cabinets: every id in the multi-selection set.\n    selectedCabinetIds.forEach(id => {\n      const el = root.querySelector(`[data-cabinet-id=\"${id}\"]`);\n      if (el) el.classList.add('btk-kp-selected');\n    });\n    // Item-number badge highlight - every badge carrying a selected\n    // cabinet id gets a blue ring (in-cabinet, stacked-twin and\n    // over-sink badges all carry data-cabinet-id), so the active unit's\n    // number matches the blue selection outline. Applies to all units.\n    root.querySelectorAll('.btk-kp-cabinet-number--active')\n      .forEach(el => el.classList.remove('btk-kp-cabinet-number--active'));\n    selectedCabinetIds.forEach(id => {\n      root.querySelectorAll(`.btk-kp-cabinet-number[data-cabinet-id=\"${id}\"]`)\n        .forEach(el => el.classList.add('btk-kp-cabinet-number--active'));\n    });\n    try { markNotedUnits(root); } catch (e) { console.error('[BTK unit notes]', e); }\n    // Group-selection ring lives on the worktop SVG - refresh that\n    // layer so the blue stroke follows the worktop perimeter as the\n    // selection changes. Cheap (a handful of SVG polygons).\n    refreshWorktops();\n    // Features / openings / worktop-items: single selection only.\n    if (selectedItem && selectedItem.kind !== 'cabinet') {\n      const attr = selectedItem.kind === 'feature'       ? 'data-feature-id'\n                :  selectedItem.kind === 'opening'       ? 'data-opening-id'\n                :  selectedItem.kind === 'worktop-item'  ? 'data-worktop-item-id'\n                :  selectedItem.kind === 'furniture'     ? 'data-furniture-id'\n                :  null;\n      if (attr) {\n        const el = root.querySelector(`[${attr}=\"${selectedItem.id}\"]`);\n        if (el) el.classList.add('btk-kp-selected');\n      }\n    }\n    // Clickable wall runs for a selected door / window.\n    // Reported, not swallowed: a throw in here takes out every wall section at\n    // once with nothing on screen to show for it, which has now hidden two\n    // separate bugs.\n    try { renderWallHits(); } catch (e) { console.error('[BTK wallHits]', e); }\n    try { renderPlanCorners(); } catch (e) { console.error('[BTK planCorners]', e); }\n    try { renderRunAddButtons(); } catch (e) { console.error('[BTK runAdd]', e); }\n    // End-panel 2D selection highlight (only visible in plan view \u2014\n    // trim segments are a 3D-only concept). Also flags the matching\n    // end-panel NUMBER badge so the clicked circle highlights too.\n    root.querySelectorAll('.btk-kp-cabinet-end-panel.is-selected, .btk-kp-cabinet-back-panel.is-selected, .btk-kp-cabinet-filler.is-selected, [data-end-panel-cabinet-id].is-selected, [data-rail-cabinet-id].is-selected, [data-cpost-face].is-selected')\n      .forEach(el => el.classList.remove('is-selected'));\n    root.querySelectorAll('.btk-kp-cabinet-number--endpanel.btk-kp-cabinet-number--active')\n      .forEach(b => b.classList.remove('btk-kp-cabinet-number--active'));\n    if (selectedItem?.kind === 'end-panel') {\n      if (String(selectedItem.side || '').startsWith('back')\n          && selectedItem.side !== 'back-sy' && selectedItem.side !== 'back-sx') {\n        // Breakfast-bar back panel - highlight the back-panel slab(s). A split\n        // run draws one slab per segment, each tagged with its own side, so\n        // match on that when present and fall back to the whole back otherwise.\n        // The panel is drawn ONCE by the unit it starts on, which may not be\n        // the unit the basket line names, so look across every unit the face\n        // covers rather than only the selected one.\n        const _sideSel = `[data-back-panel-side=\"${selectedItem.side}\"]`;\n        const _hit = (typeof findBoardForFace === 'function')\n          ? findBoardForFace(endPanelLayout, selectedItem.cabinetId, selectedItem.side) : null;\n        const _ids = (_hit && _hit.piece && _hit.piece.face\n                      && _hit.piece.face.cabIds && _hit.piece.face.cabIds.length)\n          ? _hit.piece.face.cabIds : [selectedItem.cabinetId];\n        let _found = 0;\n        for (const _cid of _ids)\n          root.querySelectorAll(\n            `.btk-kp-cabinet-back-panel[data-back-panel-cabinet-id=\"${_cid}\"]${_sideSel}`)\n            .forEach(el => { el.classList.add('is-selected'); _found++; });\n        if (!_found)\n          root.querySelectorAll(\n            `.btk-kp-cabinet-back-panel[data-back-panel-cabinet-id=\"${selectedItem.cabinetId}\"]`)\n            .forEach(el => el.classList.add('is-selected'));\n      } else {\n        // Resolve the whole FACE - a merged / stacked panel spans several\n        // units, so highlight EVERY unit's strip + filler on that side (not\n        // just the clicked one). Fillers share the same cabId:side slot when\n        // there's no end panel there, so a filler line highlights its own\n        // strip too, independently of the host unit.\n        // A radius/square end is TWO lines - the flat panel and the feature\n        // post - so 'left:feature' picks the post alone and 'left' picks\n        // everything that isn't a post.\n        const _p = epFacePart(selectedItem.side);\n        const hit = (typeof findBoardForFace === 'function')\n          ? findBoardForFace(endPanelLayout, selectedItem.cabinetId, _p.side) : null;\n        const cabIds = (hit && hit.piece && hit.piece.face && hit.piece.face.cabIds && hit.piece.face.cabIds.length)\n          ? hit.piece.face.cabIds\n          : [selectedItem.cabinetId];\n        const partSel = _p.part ? `[data-end-feature=\"${_p.part}\"]` : ':not([data-end-feature])';\n        let hits = 0;\n        for (const cid of cabIds) {\n          // A filler only ever belongs to the panel row, never the feature.\n          const sel = [\n            `[data-end-panel-cabinet-id=\"${cid}\"][data-end-panel-side=\"${_p.side}\"]${partSel}`,\n            _p.part ? null\n              : `.btk-kp-cabinet-filler[data-filler-cabinet-id=\"${cid}\"][data-filler-side=\"${_p.side}\"]`\n          ].filter(Boolean).join(',');\n          root.querySelectorAll(sel)\n            .forEach(el => { el.classList.add('is-selected'); hits++; });\n        }\n        // Wall / tall radius ends draw as ONE element, so a feature row has\n        // no post of its own - light the whole side rather than nothing.\n        if (!hits && _p.part) {\n          for (const cid of cabIds) {\n            root.querySelectorAll(\n              `[data-end-panel-cabinet-id=\"${cid}\"][data-end-panel-side=\"${_p.side}\"]`\n            ).forEach(el => el.classList.add('is-selected'));\n          }\n        }\n      }\n      const badge = root.querySelector(\n        `.btk-kp-cabinet-number--endpanel[data-ep-face=\"${selectedItem.cabinetId}:${selectedItem.side}\"]`\n      );\n      if (badge) badge.classList.add('btk-kp-cabinet-number--active');\n    } else if (selectedItem?.kind === 'cpost') {\n      const _cf = `${selectedItem.cabinetId}:${selectedItem.side}:${selectedItem.pos}`;\n      root.querySelectorAll(`.btk-kp-cabinet-th-corner-post[data-cpost-face=\"${_cf}\"]`).forEach(el => el.classList.add('is-selected'));\n      root.querySelectorAll(`.btk-kp-cabinet-number[data-cpost-face=\"${_cf}\"]`).forEach(el => el.classList.add('btk-kp-cabinet-number--active'));\n    } else if (selectedItem?.kind === 'rail') {\n      const _rs = `[data-rail-cabinet-id=\"${selectedItem.cabinetId}\"][data-rail-side=\"${selectedItem.side}\"]`;\n      root.querySelectorAll(`.btk-kp-cabinet-th-rail${_rs}`).forEach(el => el.classList.add('is-selected'));\n      const _rb = root.querySelector(`.btk-kp-cabinet-number--rail[data-rail-face=\"${selectedItem.cabinetId}:${selectedItem.side}\"]`);\n      if (_rb) _rb.classList.add('btk-kp-cabinet-number--active');\n    }\n    // Clearance dims follow the active selection (committed positions;\n    // drag handlers refresh it live with the dragged positions).\n    refreshClearance();\n    // 3D outline mirrors the same selection set.\n    handle3D?.setSelectedCabinetIds?.([...selectedCabinetIds]);\n    handle3D?.setSelectedTrimSegmentId?.(\n      selectedItem?.kind === 'trim-segment' ? selectedItem.segmentId : null\n    );\n    handle3D?.setSelectedEndPanel?.(\n      selectedItem?.kind === 'rail'\n        ? { cabIds: [selectedItem.cabinetId], side: 'rail-' + selectedItem.side }\n      : selectedItem?.kind === 'cpost'\n        ? { cabIds: [selectedItem.cabinetId], side: `${selectedItem.side}:cpost${selectedItem.pos === 'back' ? '-back' : ''}` }\n      : selectedItem?.kind === 'end-panel'\n        ? (() => {\n            // Resolve to the whole FACE so a stacked column (one face,\n            // several per-unit meshes) highlights as a single item.\n            const _p = epFacePart(selectedItem.side);\n            const hit = findBoardForFace(endPanelLayout, selectedItem.cabinetId, _p.side);\n            const cabIds = hit?.piece?.face?.cabIds || [selectedItem.cabinetId];\n            return { cabIds, side: selectedItem.side };\n          })()\n        : null\n    );\n    handle3D?.setSelectedWorktopId?.(\n      selectedItem?.kind === 'worktop' ? selectedItem.worktopId : null\n    );\n    handle3D?.setSelectedWorktopItemId?.(\n      selectedItem?.kind === 'worktop-item' ? selectedItem.id : null\n    );\n    // A sink unit's sink + tap, selected as one: both outlined in 3D, the\n    // tap lit in 2D too.\n    {\n      const _ss = selectedItem?.kind === 'planner-sink' ? selectedItem.cabinetId : null;\n      const _tapIds = _ss ? tapsOnCabinet(_ss).map(t => t.id) : [];\n      handle3D?.setSelectedSinkSet?.(_ss ? { cabinetId: _ss, tapIds: _tapIds } : null);\n      _tapIds.forEach(id => root.querySelector(`[data-worktop-item-id=\"${id}\"]`)?.classList.add('btk-kp-selected'));\n    }\n    handle3D?.setSelectedSplashbackSection?.(\n      selectedItem?.kind === 'splashback-section' ? selectedItem : null\n    );\n    // 3D: float the selected item's plan number (white circle) at the centre\n    // of its highlight - units AND end panels / fillers, i.e. any item that\n    // carries a number badge in the 2D plan. The 3D side works out the centre\n    // from its live selection; we just pass the number (null clears it).\n    // Wrapped defensively - a badge glitch must never break the whole render.\n    try {\n      let num = null, skip = false;\n      if (selectedItem?.kind === 'rail') {\n        num = railNumberOf(cabinets.find(c => c.id === selectedItem.cabinetId), selectedItem.side);\n      } else if (selectedItem?.kind === 'cpost') {\n        num = cornerPostNumberOf(cabinets.find(c => c.id === selectedItem.cabinetId), selectedItem.side, selectedItem.pos);\n      } else if (selectedItem?.kind === 'end-panel') {\n        const map = (endPanelLayout && endPanelLayout.cabSideToNumber) || {};\n        const _p = epFacePart(selectedItem.side);\n        if (_p.part) {\n          // Feature rows are numbered in their own map, keyed by the piece\n          // ('back' being the post at the far end of the same side).\n          const fmap = (endPanelLayout && endPanelLayout.cabSideToFeatureNumber) || {};\n          num = fmap[`${selectedItem.cabinetId}:${_p.side}`\n                     + (_p.part === 'feature-back' ? ':back' : '')];\n        } else {\n          num = map[`${selectedItem.cabinetId}:${selectedItem.side}`];\n          if (num == null) {\n            // Merged / stacked face - any of its units shares the board number.\n            const hit = findBoardForFace(endPanelLayout, selectedItem.cabinetId, selectedItem.side);\n            for (const cid of (hit?.piece?.face?.cabIds || [])) {\n              if (map[`${cid}:${selectedItem.side}`] != null) { num = map[`${cid}:${selectedItem.side}`]; break; }\n            }\n          }\n        }\n      } else if (selectedCabinetIds.size === 1) {\n        const c = cabinets.find(cc => cc.id === [...selectedCabinetIds][0]);\n        num = c ? c.displayNumber : null;\n      } else if (embedSelectedKey && String(embedSelectedKey).indexOf('ep:') === 0) {\n        // A panel/filler line is focused in the basket mini-3D (that path\n        // drives the badge itself, without selectItem) - leave it be.\n        skip = true;\n      }\n      if (!skip) handle3D?.setSelectionBadge?.(num == null ? null : num);\n    } catch (e) {}\n\n    // Re-assert the Properties panel while anything is selected so\n    // downstream refreshes (e.g. after rerender from a panel control\n    // like Mount line / Hinge / Rotate) can't flip the sidebar back\n    // to the active step's panel. Style-colours step keeps its own\n    // panel by design.\n    if (selectedItem && (currentStep !== 'style-colours' || CUSTOMISE_PICKS.has(selectedItem.kind))) {\n      setActivePanel(positionMenuOpen ? 'unit-position' : 'selection');\n    }\n  }\n\n  // ---- Cabinet groups ----\n\n  function genGroupId() {\n    return 'g-' + Math.random().toString(36).slice(2, 9);\n  }\n\n  // Which cabs a plain (non-additive) click selects. Radius end-of-run members\n  // are INDIVIDUALLY selectable - so the user can inspect the curve, backing\n  // and filler separately, exactly like their separate basket lines - while the\n  // assembly still drags together via the curve anchor. Other groups select as\n  // a whole; ungrouped units select themselves. Shared by the 2D + 3D click.\n  function clickSelectIds(cab) {\n    if (!cab) return [];\n    const isRadiusMember = cab.radiusUnit || cab.radiusGroup;\n    if (cab.groupId && !isRadiusMember) {\n      return cabinets.filter(c => c.groupId === cab.groupId).map(c => c.id);\n    }\n    return [cab.id];\n  }\n\n  // The units screwed into one column, top first: the unit given, whatever it\n  // sits on (stackHostId, stamped by the stack engine's derive pass), and\n  // whatever sits on it. One unit on its own comes back as a column of one.\n  function stackColumnFor(cab) {\n    if (!cab) return [];\n    const byId = new Map(cabinets.filter(Boolean).map(c => [c.id, c]));\n    let rootCab = cab, guard = 0;\n    while (rootCab.stackHostId != null && byId.has(rootCab.stackHostId) && guard++ < 8) {\n      rootCab = byId.get(rootCab.stackHostId);\n    }\n    const out = [rootCab];\n    for (let i = 0; i < out.length && out.length < 8; i++) {\n      for (const c of cabinets) {\n        if (c && c.stackHostId === out[i].id && !out.includes(c)) out.push(c);\n      }\n    }\n    return out.sort((a, b) => unitVerticalRange(b).top - unitVerticalRange(a).top);\n  }\n\n  // A stacked column draws as ONE shape on the plan, so clicking it again goes\n  // DOWN the stack rather than re-picking what is already selected: top unit,\n  // then the one under it, then round again. The number badges still select\n  // their own unit outright, so either way in works.\n  function nextInStackColumn(cab) {\n    const column = stackColumnFor(cab);\n    if (column.length < 2) return cab;\n    const sel = (selectedCabinetIds.size === 1) ? [...selectedCabinetIds][0] : null;\n    const at  = column.findIndex(c => c.id === sel);\n    return column[(at + 1) % column.length];   // nothing of the column selected -> its top\n  }\n\n  // Expand a list of cabinet ids so that picking any grouped unit\n  // pulls in all its group-mates.\n  function expandToGroups(ids) {\n    const set = new Set();\n    for (const id of ids) {\n      const c = cabinets.find(x => x.id === id);\n      if (!c) continue;\n      // Radius end-of-run members are individually selectable (see\n      // clickSelectIds) so the user can inspect the curve, backing and filler\n      // separately - don't re-inflate the whole group here (that hid the detail\n      // panel). Other groups expand so picking one picks all.\n      const isRadiusMember = c.radiusUnit || c.radiusGroup;\n      if (c.groupId && !isRadiusMember) {\n        cabinets.forEach(x => { if (x.groupId === c.groupId) set.add(x.id); });\n      } else {\n        set.add(c.id);\n      }\n    }\n    return set;\n  }\n\n  // Set the cabinet multi-selection. One unit \u2192 behaves like the old\n  // single select (properties panel shows). More than one \u2192 highlight\n  // only, no per-unit panel.\n  function setCabinetSelection(ids) {\n    selectedCabinetIds = expandToGroups(ids);\n    let changed = false;\n\n    // A multi-selection IS a persistent group - formed on selection,\n    // no drag needed. If the selected units don't already share one\n    // group, bind them into a new one.\n    if (selectedCabinetIds.size >= 2) {\n      const sel = [...selectedCabinetIds]\n        .map(id => cabinets.find(c => c.id === id)).filter(Boolean);\n      const g0 = sel[0].groupId;\n      const same = g0 && sel.every(c => c.groupId === g0);\n      if (!same) {\n        const gid = genGroupId();\n        sel.forEach(c => { c.groupId = gid; });\n        changed = true;\n      }\n    }\n\n    // Dissolve any group left with fewer than 2 members.\n    const counts = {};\n    cabinets.forEach(c => { if (c.groupId) counts[c.groupId] = (counts[c.groupId] || 0) + 1; });\n    cabinets.forEach(c => {\n      if (c.groupId && counts[c.groupId] < 2) { delete c.groupId; changed = true; }\n    });\n\n    if (selectedCabinetIds.size === 1) {\n      selectItem({ kind: 'cabinet', id: [...selectedCabinetIds][0] });\n    } else if (selectedCabinetIds.size >= 2 && currentStep !== 'style-colours') {\n      // A group: its own panel, with Position for the whole group (Arden,\n      // 2026-10-12). selectedItem stays null - the group is the cabinet\n      // multi-selection, and everything that acts on a group reads that.\n      selectedItem = null;\n      setActivePanel('selection');\n      selectionPanelHandle.show({ kind: 'cabinet-group', ids: [...selectedCabinetIds] });\n      applySelectionVisual();\n    } else {\n      selectedItem = null;\n      // Swap before hiding - see the note in selectItem.\n      if (currentStep === 'style-colours') { selectionPanelHandle.hide(); styleColoursHandle.refresh(); }\n      else                                 { setActivePanel(currentStep); selectionPanelHandle.hide(); }\n      applySelectionVisual();\n    }\n    if (changed) rerender();\n  }\n\n  // How long the sidebar takes to slide between a stage menu and an item's\n  // properties. Must match --btk-kp-panel-slide in btk-kitchen-planner-base.css.\n  const PANEL_SLIDE_MS = 420;\n  let panelSwapTimer = null;\n\n  // Swapping the stage menu for an item's properties used to be instantaneous,\n  // and test users reported losing their bearings: the menu they were reading\n  // was simply replaced, and although clicking off the item brings it back,\n  // they never spotted that. The two panels now travel together - the one being\n  // left slides out as the new one slides in, same duration and easing - so the\n  // change reads as a move sideways, with an obvious way back.\n  //\n  // The outgoing panel is animated as a CLONE rather than in place. The live\n  // panel can then be hidden and rewritten the moment the swap starts, so\n  // nothing downstream has to wait on an animation, and a half-cleared panel\n  // can never be caught travelling across the sidebar.\n  // Take down whatever is still moving. A quick double-click would otherwise\n  // strand a clone lying over the sidebar.\n  function endPanelSwap() {\n    if (panelSwapTimer) { clearTimeout(panelSwapTimer); panelSwapTimer = null; }\n    root.querySelectorAll('.btk-kp-panel-ghost').forEach(g => g.remove());\n    root.querySelectorAll('.btk-kp-panel-entering').forEach(p => {\n      p.classList.remove('btk-kp-panel-entering', 'is-forward', 'is-backward');\n    });\n    root.querySelector('.btk-kp-sidebar-scroll')?.classList.remove('btk-kp-swapping');\n  }\n\n  const PANEL_DEPTH = { 'edit-walls': 1, warnings: 1, selection: 2, 'unit-position': 3 };\n  const panelDepth = (name) => PANEL_DEPTH[name] || 0;\n\n  // The sidebar panel showing now (ignoring a clone still sliding out).\n  function visiblePanelName() {\n    const p = [...root.querySelectorAll('[data-btk-kp-panel]')]\n      .find(x => !x.hidden && !x.classList.contains('btk-kp-panel-ghost'));\n    return p ? p.dataset.btkKpPanel : null;\n  }\n\n  // Room Setup's Edit Room Size menu. A wall picked from its list - or\n  // clicked on the plan while it is open - slides on to that wall's panel. Its\n  // green Back pill steps back to this menu (one level); clicking off the\n  // wall anywhere else leaves it altogether, back to the Room Setup menu.\n  let wallMenuReturn = false;\n  let deselectViaBack = false;   // set by the properties panel's Back pill\n  function openEditWallsMenu() {\n    const list = root.querySelector('[data-btk-kp-edit-walls-list]');\n    if (list) selectionPanelHandle?.renderWallPicker?.(list, (wi) => selectWallFromList(wi));\n    syncOuterSizeCard(false);\n    setActivePanel('edit-walls');\n  }\n\n  // Edit Outer Room Size (Edit Room/Wall Sizes menu): the room's overall\n  // width and length - shapeParams widthMm / heightMm, which every starter\n  // shape is built from - set together through handleParamsApply, the same\n  // route a wall's own size and the Room Shape popup take, so corners,\n  // pillars, openings and units are re-fitted the same way. A drawn room has\n  // no overall size, so the button isn't offered there.\n  function outerSizeEditable() {\n    const p = roomConfig && roomConfig.shapeParams;\n    return !!(roomConfig && roomConfig.shapeId !== 'freeshape' && p && p.widthMm > 0 && p.heightMm > 0);\n  }\n  function syncOuterSizeCard(open) {\n    const btn  = root.querySelector('[data-btk-kp-outer-size-toggle]');\n    const card = root.querySelector('[data-btk-kp-outer-size-card]');\n    if (!btn || !card) return;\n    const can = outerSizeEditable();\n    btn.hidden = !can;\n    const show = can && !!open;\n    card.hidden = !show;\n    btn.setAttribute('aria-expanded', show ? 'true' : 'false');\n    if (show) {\n      const p = roomConfig.shapeParams;\n      const w = card.querySelector('[data-btk-kp-outer-width]');\n      const l = card.querySelector('[data-btk-kp-outer-length]');\n      if (w) w.value = String(Math.round(p.widthMm));\n      if (l) l.value = String(Math.round(p.heightMm));\n    }\n  }\n\n  // A selected unit's Position sub-menu. Same shape as the wall menu above:\n  // the selection-panel module renders the controls it already owns into this\n  // panel, and the Back pill steps back to the unit's properties.\n  let positionMenuOpen = false;\n  function openUnitPositionMenu() {\n    const host = root.querySelector('[data-btk-kp-position-body]');\n    if (!host) return;\n    selectionPanelHandle?.renderPositionMenu?.(host);\n    positionMenuOpen = true;\n    setActivePanel('unit-position');\n  }\n  function closeUnitPositionMenu() {\n    if (!positionMenuOpen) return;\n    positionMenuOpen = false;\n    clearPositionSpan();\n    setActivePanel('selection');\n  }\n\n  function setActivePanel(name) {\n    const scroll = root.querySelector('.btk-kp-sidebar-scroll');\n    // A clone still sliding out keeps its data-btk-kp-panel so it stays styled\n    // like the panel it is a picture of - so it has to be kept out of here, or\n    // it would be picked as the thing to swap FROM and cloned all over again.\n    const panels = [...root.querySelectorAll('[data-btk-kp-panel]')]\n      .filter(p => !p.classList.contains('btk-kp-panel-ghost'));\n    const next = panels.find(p => p.dataset.btkKpPanel === name);\n    const prev = panels.find(p => !p.hidden && p !== next);\n    const apply = () => panels.forEach(p => { p.hidden = p.dataset.btkKpPanel !== name; });\n\n    // Nothing to swap FROM: this is a re-assert of the panel already showing,\n    // which applySelectionVisual does on every refresh. Leave any animation in\n    // flight alone - tearing it down here killed the slide on the very next\n    // line after selectItem started it.\n    if (!prev) { apply(); return; }\n\n    endPanelSwap();\n\n    const reduced = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;\n    if (!scroll || !next || reduced) { apply(); return; }\n\n    // Deeper = forward (the menu leaves left), shallower = backward (it comes\n    // back from the left). A stage menu is the top; Room Setup's Edit Wall\n    // Size menu sits one level in, and an item's properties below that.\n    const dir = panelDepth(name) > panelDepth(prev.dataset.btkKpPanel) ? 'is-forward' : 'is-backward';\n\n    const cs = getComputedStyle(scroll);\n    // Where the user actually WAS in the menu. The incoming panel starts at its\n    // top, so the scroller is reset below - but the outgoing ghost has to stay\n    // put, or the menu visibly jumps to its top before the slide even begins.\n    // On a long menu that jump is a step from wherever you were reading (the\n    // Reset Room button at the foot of Room Setup) back up to the start.\n    const prevScrollTop = scroll.scrollTop || 0;\n    const ghost = prev.cloneNode(true);\n    ghost.hidden = false;\n    ghost.setAttribute('aria-hidden', 'true');\n    ghost.classList.add('btk-kp-panel-ghost', dir);\n    // Absolute children sit against the scroller's padding box, so offset by\n    // its padding to land exactly where the panel was.\n    ghost.style.top    = (parseFloat(cs.paddingTop) || 0) - prevScrollTop + 'px';\n    ghost.style.left   = cs.paddingLeft;\n    ghost.style.right  = cs.paddingRight;\n    ghost.style.height = prev.offsetHeight + 'px';\n\n    scroll.scrollTop = 0;\n    scroll.classList.add('btk-kp-swapping');\n    scroll.appendChild(ghost);\n\n    apply();\n    next.classList.add('btk-kp-panel-entering', dir);\n\n    panelSwapTimer = setTimeout(() => {\n      panelSwapTimer = null;\n      ghost.remove();\n      scroll.classList.remove('btk-kp-swapping');\n      next.classList.remove('btk-kp-panel-entering', 'is-forward', 'is-backward');\n    }, PANEL_SLIDE_MS + 40);\n  }\n\n  function selectItem(itemRef) {\n    // A tap on a sink unit is selected WITH its sink (Arden, 2026-10-24).\n    if (itemRef && itemRef.kind === 'worktop-item') {\n      const _host = sinkUnitForTap(itemRef.id);\n      if (_host) itemRef = { kind: 'planner-sink', cabinetId: _host.id };\n    }\n    const hadSelection = !!selectedItem;\n    positionMenuOpen = false;   // a new selection leaves the Position sub-menu\n    // Picked from (or clicked on the plan while showing) the Edit Wall Size\n    // menu: leaving this item goes back to that menu.\n    if (itemRef && visiblePanelName() === 'edit-walls') wallMenuReturn = true;\n    selectedItem = itemRef;\n    // Keep the cabinet multi-selection in sync: clear it for\n    // non-cabinet / no selection; for a lone cabinet make it the set.\n    if (!itemRef || itemRef.kind !== 'cabinet') {\n      selectedCabinetIds = new Set();\n    } else if (!selectedCabinetIds.has(itemRef.id)) {\n      selectedCabinetIds = new Set([itemRef.id]);\n    }\n    if (itemRef) {\n      if (currentStep === 'style-colours' && !CUSTOMISE_PICKS.has(itemRef.kind)) {\n        // Anything else stays on the Customise menu.\n        styleColoursHandle.refresh();\n      } else {\n        setActivePanel('selection');\n        selectionPanelHandle.show(itemRef);\n      }\n      // Tablet drawer: tapping a cabinet on the canvas needs to\n      // surface the selection panel - otherwise the user has no\n      // visual confirmation the tap landed. Opens the sidebar drawer\n      // when in drawer mode (900px and below - landscape tablets keep\n      // the permanent sidebar). Desktop layouts have a permanent sidebar so this\n      // is a no-op there.\n      if (isDrawerMode()) {\n        root.classList.add('btk-kp-sidebar-open');\n        const hamburger = root.querySelector('.btk-kp-topbar-hamburger');\n        if (hamburger) hamburger.setAttribute('aria-expanded', 'true');\n      }\n    } else {\n      if (currentStep === 'style-colours') {\n        // Back out of a worktop / splashback / trim to the Customise menu.\n        // Swap before hiding - see below.\n        setActivePanel('style-colours');\n        selectionPanelHandle.hide();\n        styleColoursHandle.refresh();\n      } else {\n        // Swap BEFORE hiding: setActivePanel photographs the outgoing panel to\n        // animate it, and hide() empties that panel. Clearing first sent an\n        // empty card sliding across the sidebar.\n        const viaBack = deselectViaBack;\n        deselectViaBack = false;\n        if (!hadSelection && visiblePanelName() === 'edit-walls') {\n          // Nothing was selected - a click on empty plan while the wall menu\n          // is open. Stay in it.\n        } else if (viaBack && wallMenuReturn && currentStep === 'room-setup') {\n          // The Back pill: one step back, to the menu the wall was picked from.\n          wallMenuReturn = false;\n          openEditWallsMenu();   // redrawn: a wall may have just been resized\n        } else {\n          // Clicking off the item: out to the stage's own menu.\n          wallMenuReturn = false;\n          setActivePanel(currentStep);\n        }\n        selectionPanelHandle.hide();\n        // The wall's highlight goes with the selection. It used to clear only\n        // when the wall's size box lost focus - which a wall clicked on the plan\n        // has, but one picked from a list does not, so it stayed lit.\n        clearOpeningSpan();\n      }\n    }\n    applySelectionVisual();\n    // Keep the quote drawer's active-line highlight + its exclude \u2715 in\n    // sync with whatever is selected (canvas click or quote-line click).\n    basketDrawerHandle?.refresh?.();\n  }\n\n  // Matches the CSS media query that turns the sidebar into a drawer.\n  // Keep these two in sync if breakpoints change in btk-kitchen-\n  // planner-base.css.\n  function isDrawerMode() {\n    return window.matchMedia('(max-width: 900px)').matches;\n  }\n\n  function clearSelectionIfMatches(kind, id) {\n    if (selectedItem?.kind === kind && selectedItem.id === id) selectItem(null);\n  }\n\n  // The set of cabinets that move when this one is dragged: its whole\n  // group, else the active multi-selection if it's part of it, else\n  // just itself.\n  function resolveMoveSet(cabinet) {\n    let ids;\n    if (cabinet.groupId) {\n      ids = cabinets.filter(c => c.groupId === cabinet.groupId).map(c => c.id);\n    } else if (selectedCabinetIds.has(cabinet.id) && selectedCabinetIds.size > 1) {\n      ids = [...selectedCabinetIds];\n    } else {\n      ids = [cabinet.id];\n    }\n    return ids.map(id => {\n      const cab = cabinets.find(c => c.id === id);\n      const cel = id === cabinet.id ? null : root.querySelector(`[data-cabinet-id=\"${id}\"]`);\n      return cab ? { cab, cel, ox: cab.x, oy: cab.y } : null;\n    }).filter(Boolean);\n  }\n\n  function wireCabinet(cabinet, el, pxPerMm) {\n    // Room Setup is for building the room. Units are drawn there as context -\n    // that is what the Hide units toggle is for - but they are not the thing\n    // being worked on, and leaving them live meant a click meant for a wall\n    // picked up the unit standing in front of it, and a stray drag moved a\n    // unit the user had already placed. Inert here, exactly as a wall section\n    // is inert everywhere else. Every other stage wires them as before.\n    if (currentStep === 'room-setup') {\n      el.style.pointerEvents = 'none';\n      return;\n    }\n    let lastX = null, lastY = null;\n    let didDrag = false;\n    let group = null;   // resolved on first move\n    el.classList.toggle('btk-kp-cabinet--position-locked', !!cabinet.positionLocked);\n\n    const drag = makeDraggable(el, {\n      pxPerMm,\n      getZoom: () => view2d.zoom,\n      onDragMove({ dxMm, dyMm }) {\n        if (Math.hypot(dxMm, dyMm) * pxPerMm > 5) didDrag = true;\n        if (!group) {\n          const members = resolveMoveSet(cabinet);\n          group = { members, multi: members.length > 1,\n                    // POSITION LOCK: a locked unit (or a group holding one) does not drag.\n                    // A walk-in larder set unit moves only with its larder.\n                    locked: members.some(m => m.cab.positionLocked) || !!cabinet.walkInSet };\n        }\n        if (group.locked) {\n          // Say why it isn't moving, once per drag (bug sheet row 72).\n          if (didDrag && !group.lockTold) {\n            group.lockTold = true;\n            designControlsHandle.setStatus(cabinet.walkInSet\n              ? 'This unit is part of the walk-in larder. Move the larder to move it.'\n              : group.multi\n              ? 'A unit in this group is locked. To move it, open Position and click the padlock.'\n              : \"This unit's position is locked. To move it, open Position and click the padlock.\");\n          }\n          return;\n        }\n\n        if (!group.multi) {\n          // Single cabinet - snap + auto-rotate as before.\n          const rawX = cabinet.x + dxMm;\n          const rawY = cabinet.y + dyMm;\n          const isRadius = !!cabinet.radiusUnit;\n          // End-panel / filler snap modes - alignment is RELATIVE to\n          // the nearest real cabinet's rotation (not the wall), so a\n          // panel dropped next to a 90\u00B0-rotated base unit lines up\n          // with that unit no matter which wall the unit sits on:\n          //   none  \u2192 no auto-rotate\n          //   front \u2192 match the neighbour cab's rotation exactly\n          //   sides \u2192 +90\u00B0, panel's long side runs along the cab's side\n          //   back  \u2192 +180\u00B0, panel back faces the cab's front\n          // If no cab is within ROTATION_PROXIMITY_MM, leave rotation\n          // alone - free placement until the user drags near a unit.\n          let desired = null;\n          if (cabinet.rotationLocked) {\n            // ROTATION LOCK - the user has pinned this unit's orientation, so\n            // nothing about where it is dragged may turn it. Manual Rotate\n            // 90\u00B0 still works; only the automatic turn is held off.\n          } else if (cabinet.endPanelFiller) {\n            const snap = cabinet.snapFace || 'none';\n            if (snap !== 'none') {\n              const near = nearestCabinetForPanelSnap(cabinet, rawX, rawY, cabinets, ROTATION_PROXIMITY_MM);\n              if (near) {\n                const offset = snap === 'sides' ? 90 : snap === 'back' ? 180 : 0;\n                desired = (((near.rotationDeg || 0) + offset) % 360 + 360) % 360;\n              }\n            }\n          } else if (cabinet.cornerUnit && cabinet.cornerUnit.placement && cabinet.cornerUnit.placement !== 'auto') {\n            // Peninsula corner unit - orient the void END to the wall\n            // ('peninsulaIn') or the BACK to the wall ('peninsulaAlong')\n            // instead of the in-corner auto-seat. Stash the chosen wall\n            // for the flush snap applied after snapAndClamp below.\n            const pen = cornerUnitPeninsulaPlacement(cabinet, rawX, rawY, cabinet.cornerUnit.placement);\n            desired = pen ? pen.rotationDeg : null;\n            cabinet._penWall = pen ? pen.wall : null;\n          } else {\n            // Auto-rotate for both regular cabinets and radius units \u2014\n            // only fires when within ROTATION_PROXIMITY_MM of a wall,\n            // so drop-in-middle stays put either way.\n            // Hand the drag vector over so a corner picks the wall being\n            // pushed into rather than whichever is marginally nearer.\n            //\n            // RECENT motion, not dxMm/dyMm: those are the travel since the\n            // unit was PICKED UP, so carrying a unit across the room and\n            // then curling it up into a corner still pointed the way it\n            // first set off. What matters is the way it is going now.\n            const _recent = { x: rawX - (cabinet._lastRawX ?? rawX),\n                              y: rawY - (cabinet._lastRawY ?? rawY) };\n            cabinet._lastRawX = rawX;\n            cabinet._lastRawY = rawY;\n            desired = computeAutoRotation(cabinet, rawX, rawY, room, ROTATION_PROXIMITY_MM,\n              getPillarSnapWalls(roomConfig.perimeterItems, cabinet), _recent);\n          }\n          if (desired !== null) {\n            const cur = cabinet.rotationDeg || 0;\n            if (Math.abs(cur - desired) > ROTATION_EPSILON_DEG) {\n              cabinet.rotationDeg = desired;\n              setCabinetRotation(el, desired);\n            }\n          }\n          // L-shape units: flip hand in REAL TIME during the drag so\n          // the body's clip-path updates BEFORE the soft-rotate\n          // animation finishes. Without this, the rotation transition\n          // ends with the old hand, then the post-drop pass flips the\n          // hand and re-renders - which the user sees as a \"snap\"\n          // after the soft rotate. Inline-refresh keeps the same\n          // wrapper element, so its transform transition keeps\n          // animating through the hand flip.\n          // A locked unit keeps its hand too - for these units the hand IS\n          // how they turn to suit a corner.\n          if (cabinet.lShapeUnit && !cabinet.rotationLocked) {\n            let desiredHand = lShapeUnitDesiredHand(cabinet, rawX, rawY, room);\n            // Corner Post + Void stub: the L's outer corner is the\n            // POST (= structural element at the room interior, where\n            // two perpendicular runs' doors meet), and the cutout is\n            // the VOID (= against the walls). This is OPPOSITE to a\n            // regular L-shape base where the outer corner sits at the\n            // wall corner. Flip the auto-selected hand so the post\n            // ends up at the room interior + void at the walls.\n            if (cabinet.lShapeUnit.cornerPostVoid && desiredHand) {\n              desiredHand = ({ NE:'SW', NW:'SE', SE:'NW', SW:'NE' })[desiredHand] || desiredHand;\n            }\n            if (desiredHand && desiredHand !== cabinet.lShapeUnit.hand) {\n              cabinet.lShapeUnit = { ...cabinet.lShapeUnit, hand: desiredHand };\n              refreshLShapeBody(el, cabinet, pxPerMm);\n            }\n          }\n          // Diagonal corner - same in-drag hand flip as L-shape; no\n          // inline body refresh helper yet, so the polygon picks up\n          // the new hand at the next render cycle.\n          if (cabinet.diagonalCornerUnit && !cabinet.rotationLocked) {\n            const desiredHand = diagonalCornerUnitDesiredHand(cabinet, rawX, rawY, room);\n            if (desiredHand && desiredHand !== cabinet.diagonalCornerUnit.hand) {\n              cabinet.diagonalCornerUnit = { ...cabinet.diagonalCornerUnit, hand: desiredHand };\n            }\n          }\n          const others = cabinets.filter(o => o.id !== cabinet.id\n            && !(o.walkInSet && o.walkInSet.hostId === cabinet.id));\n          const obstacles = [...perimeterObstaclesFor(cabinet),\n                             ...epDoorLinePanelObstacles(cabinet.id)];\n          const wallOpenings = roomConfig.wallOpenings || [];\n          let x, y;\n          if (isRadius) {\n            // Hand off room clamp + category-aware overlap push to the\n            // shared snapAndClamp - same engine the other cabinet types\n            // use, so an island radius blocks against base units / corner\n            // units exactly like a standard base would. Whatever auto-\n            // rotation we just applied is on cabinet.rotationDeg, which\n            // snapAndClamp picks up via getCornersAt / snapFootprintAABB\n            // for the rotation-aware clamp + push.\n            const sc = snapAndClamp({ ...cabinet, x: rawX, y: rawY },\n                                    rawX, rawY, room, others, obstacles, wallOpenings);\n            let ox = sc.x, oy = sc.y;\n            // Wall-anchor snap if we just auto-rotated (drop near a\n            // wall \u2192 curve faces the wall AND the back sits flush). No\n            // anchor when not auto-rotating, so a drop in the middle\n            // stays where the user put it. Applied AFTER snapAndClamp\n            // so we override its clamp with a flush-to-wall translation.\n            if (desired !== null) {\n              const rb = getBoundingBox(room);\n              const finalRot = ((cabinet.rotationDeg || 0) % 360 + 360) % 360;\n              const vb2 = visualBbox({ ...cabinet, x: ox, y: oy });\n              if (finalRot === 0)   oy += rb.maxY - vb2.y1;\n              if (finalRot === 90)  ox += rb.minX - vb2.x0;\n              if (finalRot === 180) oy += rb.minY - vb2.y0;\n              if (finalRot === 270) ox += rb.maxX - vb2.x1;\n            }\n            x = ox; y = oy;\n          } else if (cabinet.cornerUnit && cabinet.cornerUnit.placement && cabinet.cornerUnit.placement !== 'auto') {\n            // Peninsula corner unit - clamp + overlap-push via the shared\n            // engine but SKIP its corner-vertex snap (which would yank the\n            // void back into a room corner), then flush the wall-side edge\n            // (void end / back) onto the stashed wall.\n            const sc = snapAndClamp(cabinet, rawX, rawY, room, others, obstacles, wallOpenings, { skipCornerSnap: true });\n            let ox = sc.x, oy = sc.y;\n            if (cabinet._penWall) ({ x: ox, y: oy } = flushCabToWall(cabinet, ox, oy, cabinet._penWall));\n            x = ox; y = oy;\n          } else if (frameLarderUnder(cabinet, rawX, rawY, others)) {\n            // Over a Walk-In Corner Larder Frame: follow the cursor; placed on\n            // mouse-up (onDragEnd).\n            x = rawX; y = rawY;\n            cabinet._dropInFrame = true;\n          } else {\n            cabinet._dropInFrame = false;\n            ({ x, y } = snapAndClamp(cabinet, rawX, rawY, room, others, obstacles, wallOpenings));\n          }\n          // A unit turned to an angle, dragged over a diagonal corner larder\n          // or diagonal corner wall unit, lines its front up with that unit's\n          // angled front (row 60).\n          {\n            const _ds = angledUnitDiagonalSnap(cabinet, rawX, rawY, others);\n            if (_ds) {\n              x = _ds.x; y = _ds.y;\n              if (Math.abs((cabinet.rotationDeg || 0) - _ds.rotationDeg) > 0.01) {\n                cabinet.rotationDeg = _ds.rotationDeg;\n                setCabinetRotation(el, _ds.rotationDeg);\n              }\n              if (_ds.standOn) { cabinet.wallMountLevel = _ds.standOn; cabinet.mountAnchor = 'bottom'; }\n            }\n          }\n          cabinet._penWall = null;\n          lastX = x; lastY = y;\n          el.style.left = `${Math.round(x * pxPerMm)}px`;\n          el.style.top  = `${Math.round(y * pxPerMm)}px`;\n          // Live-refresh the selection panel's Walls-mode distance boxes\n          // as the unit drags (only when this cab's controller is shown).\n          updateDragWallDistInputs(cabinet, x, y);\n          // Sink-base cabs have a sibling \"pose\" div in the sink\n          // overlay layer that mirrors the cab's position +\n          // rotation. Update it in lock-step so the green badge +\n          // sink overlay don't lag behind the cab during drag.\n          const pose = document.querySelector(`.btk-kp-cabinet-sink-pose[data-cabinet-id=\"${cabinet.id}\"]`);\n          if (pose) {\n            pose.style.left = `${Math.round(x * pxPerMm)}px`;\n            pose.style.top  = `${Math.round(y * pxPerMm)}px`;\n          }\n\n          // A walk-in larder's set rides with it (Sales sheet line 111).\n          const _setPoses = isWalkInFrame(cabinet) ? walkInSetLivePoses(cabinet, x, y) : null;\n          if (_setPoses) {\n            for (const [mid, p] of _setPoses) {\n              const mel = root.querySelector(`[data-cabinet-id=\"${mid}\"].btk-kp-cabinet`) || root.querySelector(`[data-cabinet-id=\"${mid}\"]`);\n              if (!mel) continue;\n              mel.style.left = `${Math.round(p.x * pxPerMm)}px`;\n              mel.style.top  = `${Math.round(p.y * pxPerMm)}px`;\n              setCabinetRotation(mel, p.rotationDeg);\n            }\n          }\n          const liveCabs = cabinets.map(o =>\n            o.id === cabinet.id ? { ...o, x, y, rotationDeg: cabinet.rotationDeg || 0 }\n              : (_setPoses && _setPoses.has(o.id)) ? { ...o, ..._setPoses.get(o.id) } : o\n          );\n          refreshDims({ cabinets: liveCabs });\n          scheduleDragHeavy(liveCabs, cabinet.id);   // clearance + worktops, coalesced to 1/frame\n          liveDragCabs = liveCabs;   // expose live position so the live-session push streams the drag\n          return;\n        }\n\n        // Group move - rigid translation, no per-unit snap/rotate, so\n        // the layout (e.g. an island) keeps its shape. Clamp so the\n        // whole group stays inside the room bounding box.\n        const bbox = getBoundingBox(room);\n        let dX = dxMm, dY = dyMm;\n        // Pre-compute each member's visual bbox at its ORIGINAL position.\n        // For rotated cabinets the visual differs from (cab.x, cab.y +\n        // widthMm \u00D7 depthMm) - visualBbox handles the rotation swap.\n        const memberVis = group.members.map(m => {\n          const vb = visualBbox({ ...m.cab, x: m.ox, y: m.oy });\n          return { m, vb };\n        });\n        for (const { vb } of memberVis) {\n          dX = Math.max(dX, bbox.minX - vb.x0);\n          dX = Math.min(dX, bbox.maxX - vb.x1);\n          dY = Math.max(dY, bbox.minY - vb.y0);\n          dY = Math.min(dY, bbox.maxY - vb.y1);\n        }\n        // Polygon-aware room clamp on top of the bbox clamp: for\n        // angled walls the AABB lets the group slip into the\n        // \"AABB-inside-but-polygon-outside\" zone. For each wall (with\n        // its inward normal) compute the most-violating member-corner;\n        // shift the group along that normal so the worst corner sits\n        // ON the wall. Iterate so a fix against one wall doesn't push\n        // the group out through another.\n        const roomWalls = getWalls(room);\n        for (let pass = 0; pass < 4; pass++) {\n          let pushed = false;\n          for (const w of roomWalls) {\n            const wdx = w.to.x - w.from.x, wdy = w.to.y - w.from.y;\n            const wlen = Math.hypot(wdx, wdy);\n            if (wlen === 0) continue;\n            const inwardNx = -wdy / wlen, inwardNy = wdx / wlen;\n            let worst = 0;\n            for (const m of group.members) {\n              const corners = getCornersForPush(m.cab, m.ox + dX, m.oy + dY);\n              for (const c of corners) {\n                const d = (c.x - w.from.x) * inwardNx + (c.y - w.from.y) * inwardNy;\n                if (d < worst) worst = d;\n              }\n            }\n            if (worst < -0.5) {\n              dX += (-worst) * inwardNx;\n              dY += (-worst) * inwardNy;\n              pushed = true;\n            }\n          }\n          if (!pushed) break;\n        }\n        // Prevent the group from being dragged THROUGH non-group\n        // cabinets. Uses OBB SAT MTV so rotated members + rotated\n        // obstacles collide against their REAL footprints, not their\n        // inflated axis-aligned bboxes. Allowed-overlap pairs (a wall\n        // unit mounting above a base, etc.) are skipped.\n        const groupMemberIds = new Set(group.members.map(m => m.cab.id));\n        const obstacles = cabinets.filter(c => !groupMemberIds.has(c.id));\n        for (let pass = 0; pass < 4; pass++) {\n          let adjusted = false;\n          for (const m of group.members) {\n            const itemCorners = getCornersForPush(m.cab, m.ox + dX, m.oy + dY);\n            for (const ob of obstacles) {\n              if (canCabinetsOverlap(m.cab, ob, { x: m.ox + dX, y: m.oy + dY })) continue;\n              // Corner units: collide against the L-post-extended\n              // AABB (corner units are always axis-aligned, so the\n              // AABB IS the OBB). Without this the group could slide\n              // through the post.\n              const obCorners = ob.cornerUnit\n                ? (() => {\n                    const a = snapFootprintAABB(ob, ob.x, ob.y);\n                    return [\n                      { x: a.x,             y: a.y             },\n                      { x: a.x + a.widthMm, y: a.y             },\n                      { x: a.x + a.widthMm, y: a.y + a.depthMm },\n                      { x: a.x,             y: a.y + a.depthMm }\n                    ];\n                  })()\n                : getCornersForPush(ob, ob.x, ob.y);\n              const axes = obbOverlapAxes(itemCorners, obCorners);\n              if (!axes) continue;\n              const ax = axes[0];\n              const eps = 0.5;\n              dX += ax.nx * (ax.depth + eps);\n              dY += ax.ny * (ax.depth + eps);\n              adjusted = true;\n              break;   // re-check all members with the updated dX/dY\n            }\n            if (adjusted) break;\n          }\n          if (!adjusted) break;\n        }\n        for (const m of group.members) {\n          const mel = m.cel || el;\n          mel.style.left = `${Math.round((m.ox + dX) * pxPerMm)}px`;\n          mel.style.top  = `${Math.round((m.oy + dY) * pxPerMm)}px`;\n        }\n        lastX = dX; lastY = dY;   // store the committed delta\n\n        // LIVE wall-snap rotation for radius assemblies. If, given\n        // the cursor's current position, the wall-snap auto-rotate\n        // would put the group in a new orientation, rotate NOW (not\n        // on drop) so the user sees the orientation change under\n        // their cursor. After rotation we update each member's drag\n        // origin (m.ox / m.oy) to the post-rotation position so the\n        // ongoing cursor displacement keeps producing the same\n        // visual position.\n        const groupRadius = group.members\n          .map(m => cabinets.find(c => c.id === m.cab.id))\n          .find(c => c && c.radiusUnit);\n        if (groupRadius && !groupRadius.rotationLocked) {\n          // Compute the GROUP's would-be visual bbox with the live\n          // drag delta applied - see the drag-end note above for\n          // why the proximity check uses the group bbox and not\n          // just the radius unit's bbox.\n          let gMinX = Infinity, gMinY = Infinity, gMaxX = -Infinity, gMaxY = -Infinity;\n          for (const mm of group.members) {\n            const cab2 = cabinets.find(c => c.id === mm.cab.id);\n            if (!cab2) continue;\n            const vb = visualBbox({ ...cab2, x: mm.ox + dX, y: mm.oy + dY });\n            gMinX = Math.min(gMinX, vb.x0); gMaxX = Math.max(gMaxX, vb.x1);\n            gMinY = Math.min(gMinY, vb.y0); gMaxY = Math.max(gMaxY, vb.y1);\n          }\n          const desired = computeAutoRotation(\n            { widthMm: gMaxX - gMinX, depthMm: gMaxY - gMinY },\n            gMinX, gMinY,\n            room, ROTATION_PROXIMITY_MM,\n            getPillarSnapWalls(roomConfig.perimeterItems)\n          );\n          if (desired !== null) {\n            const current = ((groupRadius.rotationDeg || 0) % 360 + 360) % 360;\n            const wantedRot = (((desired % 360) + 360) % 360);\n            let diff = ((wantedRot - current + 540) % 360) - 180;   // signed shortest delta\n            if (Math.abs(diff) > 0.5) {\n              // Commit current drag positions to cabinet data so\n              // rotation operates on the post-drag positions.\n              for (const mm of group.members) {\n                const cab = cabinets.find(c => c.id === mm.cab.id);\n                if (cab) { cab.x = mm.ox + dX; cab.y = mm.oy + dY; }\n              }\n              rotateCabinetGroup(groupRadius.groupId, true, diff);\n              // Flush-snap the group's back-most corner to the wall \u2014\n              // works for ANY wall direction (axis-aligned + angled).\n              snapRadiusGroupFlushToWall(groupRadius.groupId, room);\n              // Re-pin backing + filler to the radius unit's\n              // canonical layout so any drift from intermediate\n              // rotation / snap math gets reset every tick.\n              reAnchorRadiusGroup(cabinets, groupRadius);\n              // Update each member's drag origin to the post-rotation\n              // position so the continuing cursor delta produces the\n              // correct subsequent position. Also push the new\n              // position + rotation back into the DOM right now.\n              for (const mm of group.members) {\n                const cab = cabinets.find(c => c.id === mm.cab.id);\n                if (!cab) continue;\n                mm.ox = cab.x - dX;\n                mm.oy = cab.y - dY;\n                const mel = mm.cel || el;\n                mel.style.left = `${Math.round(cab.x * pxPerMm)}px`;\n                mel.style.top  = `${Math.round(cab.y * pxPerMm)}px`;\n                setCabinetRotation(mel, cab.rotationDeg || 0);\n              }\n            }\n          }\n        }\n\n        const moved = new Map(group.members.map(m => [m.cab.id, { x: m.ox + dX, y: m.oy + dY }]));\n        const liveCabs = cabinets.map(o =>\n          moved.has(o.id) ? { ...o, ...moved.get(o.id) } : o\n        );\n        refreshDims({ cabinets: liveCabs });\n        refreshClearance(liveCabs, group.members.map(m => m.cab.id));\n        refreshWorktops(liveCabs);\n        // Expose the live positions so the live-session push mirrors the drag\n        // in progress (not just the dropped position).\n        liveDragCabs = liveCabs;\n      },\n      onDragEnd() {\n        liveDragCabs = null;   // real array is committed below; stop overlaying\n        if (group && group.locked) { group = null; return; }   // POSITION LOCK - nothing moved\n        if (didDrag && group) {\n          const movedIds = !group.multi\n            ? [cabinet.id]\n            : group.members.map(m => m.cab.id);\n          if (!group.multi && lastX !== null && cabinet._dropInFrame) {\n            // Dropped over a Walk-In Corner Larder Frame: place it now, by its\n            // carcase (its old end panels are re-worked after the drop).\n            const _others = cabinets.filter(o => o.id !== cabinet.id);\n            const _sc = snapAndClamp({ ...cabinet, endPanels: null }, lastX, lastY, room, _others,\n              [...perimeterObstaclesFor(cabinet), ...epDoorLinePanelObstacles(cabinet.id)], roomConfig.wallOpenings || []);\n            lastX = _sc.x; lastY = _sc.y;\n            // Auto end panels: its old ones go; the walks after the drop put back\n            // the ones it needs where it now stands...\n            if (autoEndPanels && cabinet.endPanels) cabinet.endPanels = {\n              ...cabinet.endPanels,\n              left:  { ...(cabinet.endPanels.left  || {}), active: false },\n              right: { ...(cabinet.endPanels.right || {}), active: false } };\n            // ...and so does a breakfast-bar back panel from out in the room: its\n            // reach (up to 302mm) made the side read longer than its neighbour.\n            if (autoEndPanels && cabinet.backPanel && cabinet.backPanel.active)\n              cabinet.backPanel = { ...cabinet.backPanel, active: false };\n          }\n          delete cabinet._dropInFrame;\n          if (!group.multi && lastX !== null) {\n            cabinet.x = lastX; cabinet.y = lastY;\n            if (isWalkInFrame(cabinet)) syncWalkInSets();\n          } else if (group.multi) {\n            for (const m of group.members) {\n              m.cab.x = m.ox + lastX;\n              m.cab.y = m.oy + lastY;\n            }\n            setCabinetSelection(group.members.map(m => m.cab.id));\n            // Wall-snap auto-rotation for radius assemblies. When the\n            // group is dropped near a wall, rotate the whole trio so\n            // its back faces the wall - same idea as the single-\n            // cabinet computeAutoRotation, but applied to the whole\n            // group via repeated 90\u00B0 rotations (the only rotation\n            // step the group supports). Uses the radius unit's bbox\n            // as the proxy for the assembly's orientation.\n            const radiusInGroup = group.members\n              .map(m => cabinets.find(c => c.id === m.cab.id))\n              .find(c => c && c.radiusUnit);\n            if (radiusInGroup && !radiusInGroup.rotationLocked) {\n              // Proximity check uses the GROUP's combined visual bbox\n              // (not just the radius unit's). The radius unit sits at\n              // the FRONT of the assembly (the backing + filler are\n              // behind it, against the wall); using only the radius\n              // unit's position misses the wall by ~270mm because the\n              // radius unit is at the front while the backing's back\n              // edge is at the wall.\n              const gm = cabinets.filter(c => c.groupId === radiusInGroup.groupId);\n              let gMinX = Infinity, gMinY = Infinity, gMaxX = -Infinity, gMaxY = -Infinity;\n              for (const m of gm) {\n                const vb = visualBbox(m);\n                gMinX = Math.min(gMinX, vb.x0); gMaxX = Math.max(gMaxX, vb.x1);\n                gMinY = Math.min(gMinY, vb.y0); gMaxY = Math.max(gMaxY, vb.y1);\n              }\n              const desired = computeAutoRotation(\n                { widthMm: gMaxX - gMinX, depthMm: gMaxY - gMinY },\n                gMinX, gMinY,\n                room, ROTATION_PROXIMITY_MM,\n                getPillarSnapWalls(roomConfig.perimeterItems)\n              );\n              // Wall is within proximity \u2192 rotate AND snap flush.\n              // If no wall is nearby (desired === null), leave the\n              // group where the user dropped it - no auto-snap to\n              // distant walls, so a group placed in the middle of\n              // the room (an island layout) stays in the middle.\n              if (desired !== null) {\n                const current = ((radiusInGroup.rotationDeg || 0) % 360 + 360) % 360;\n                const wantedRot = ((desired % 360) + 360) % 360;\n                const diff = ((wantedRot - current + 540) % 360) - 180;\n                if (Math.abs(diff) > 0.5) {\n                  rotateCabinetGroup(radiusInGroup.groupId, true, diff);\n                }\n                // Flush the group's back-most corner against the wall\n                // (works on any wall direction - axis-aligned + angled).\n                snapRadiusGroupFlushToWall(radiusInGroup.groupId, room);\n                // Re-anchor backing + filler so the trio always lands\n                // as one rigid assembly (see reAnchorRadiusGroup).\n                reAnchorRadiusGroup(cabinets, radiusInGroup);\n              }\n            }\n          }\n          // Corner units - if a unit was dragged into a corner door\n          // first (which would leave the void sticking into the room),\n          // flip it to the opposite hand so the void seats into the\n          // corner and the door faces the room.\n          for (const id of movedIds) {\n            const cab = cabinets.find(c => c.id === id);\n            // Everything below turns a unit to suit where it landed. A\n            // rotation-locked unit keeps the orientation the user gave it.\n            if (cab && cab.rotationLocked) continue;\n            // Skip the in-corner auto-flip for peninsula-mode units - they\n            // keep the user's chosen hand (the void orientation is set by\n            // the peninsula placement, not a room corner).\n            if (cab && cab.cornerUnit\n                && (!cab.cornerUnit.placement || cab.cornerUnit.placement === 'auto')) {\n              const want = cornerUnitDesiredHand(cab, cab.x, cab.y, room, roomConfig.perimeterItems);\n              if (want && want !== cab.cornerUnit.hand) {\n                cab.cornerUnit = { ...cab.cornerUnit, hand: want };\n                syncCornerHandVariant(cab);\n              }\n            }\n            // L-shape units - when dropped near a room inside corner\n            // OR a pillar corner, flip hand so the OUTER L corner seats\n            // in the wall/pillar corner and the cutout faces the room\n            // (mirrors the corner-unit void-into-corner flip above).\n            if (cab && cab.lShapeUnit) {\n              let want = lShapeUnitDesiredHand(cab, cab.x, cab.y, room, roomConfig.perimeterItems);\n              // Corner Post + Void stub: L outer corner is the POST,\n              // sits at the ROOM interior; cutout is the VOID, sits\n              // AT the walls. Opposite of a regular L-shape base.\n              if (cab.lShapeUnit.cornerPostVoid && want) {\n                want = ({ NE:'SW', NW:'SE', SE:'NW', SW:'NE' })[want] || want;\n              }\n              if (want && want !== cab.lShapeUnit.hand) {\n                cab.lShapeUnit = { ...cab.lShapeUnit, hand: want };\n              }\n            }\n            // Diagonal corner units - same hand-flip rule as L-shape:\n            // outer corner seats into the room/pillar corner, diagonal\n            // door faces the room.\n            if (cab && cab.diagonalCornerUnit) {\n              const want = diagonalCornerUnitDesiredHand(cab, cab.x, cab.y, room, roomConfig.perimeterItems);\n              if (want && want !== cab.diagonalCornerUnit.hand) {\n                cab.diagonalCornerUnit = { ...cab.diagonalCornerUnit, hand: want };\n              }\n            }\n            // Radius units - flip hand so the CURVE faces away from\n            // any adjacent cabinet (neighbour on left \u2192 hand=right,\n            // and vice versa). The backing piece also flips its\n            // rotation so its door + plinth stay on the outward\n            // side. (Filler is symmetric - no change needed.)\n            if (cab && cab.radiusUnit) {\n              const want = radiusUnitDesiredHand(cab, cabinets);\n              if (want && want !== cab.radiusUnit.hand) {\n                // Swap to the opposite-hand REAL product (own GLB + basket\n                // line); legacy single-product curved units just flip the\n                // geometry marker.\n                if (!swapRadiusHandProduct(cab, want)) {\n                  cab.radiusUnit = { ...cab.radiusUnit, hand: want };\n                }\n                if (cab.groupId) {\n                  // The backing's UNROTATED rotation is \u00B190 for hand\n                  // right/left (its 260\u00D7300 native frame is turned 90\u00B0\n                  // so its 300mm face runs ALONG the wall). After the\n                  // group itself has been rotated to face a wall, the\n                  // backing's TOTAL rotation is hand-rot + group-rot.\n                  // Setting rotationDeg = \u00B190 alone here would undo\n                  // the group rotation on the backing, putting its\n                  // door on the wrong side on walls A / B / D.\n                  const groupRot = cab.rotationDeg || 0;\n                  const handRot  = want === 'left' ? -90 : 90;\n                  const total    = ((handRot + groupRot) % 360 + 360) % 360;\n                  for (const m of cabinets) {\n                    if (m.groupId === cab.groupId && m.radiusGroup?.role === 'backing') {\n                      m.rotationDeg = total;\n                    }\n                  }\n                }\n              }\n            }\n            // Splay ends + open angled ends - snap to the hand whose DEEP side\n            // meets the run they were dropped against (Left \u2194 Right product).\n            if (cab && angledEndHand(cab)) {\n              const want = splayEndDesiredHand(cab, cabinets);\n              if (want && want !== angledEndHand(cab)) swapSplayHandProduct(cab, want);\n            }\n          }\n          // Step-forward inheritance: a unit dropped front-aligned to a\n          // stepped neighbour joins the step (adopts its setback) BEFORE\n          // settle so its void footprint drives the settle + panel rules.\n          inheritStepForwardFromNeighbour(movedIds);\n          // 1. Run-join (carcase): pull a near-but-not-snapped unit\n          //    flush to the run so auto-detect sees the adjacency.\n          // 2. Auto-detect end panels / fillers.\n          // 3. Settle (effective): nudge each moved unit so its\n          //    effective face meets each neighbour's - closes voids\n          //    from deactivated panels AND pushes out of any\n          //    surviving panel (tall/deeper wins).\n          // 4. Resize fillers to the final settled wall gaps.\n          //\n          // Radius assemblies: settle the RADIUS UNIT (so it snaps to\n          // its neighbour) and propagate the resulting position delta\n          // to its backing + filler - that snaps the WHOLE assembly\n          // flush without splitting the trio apart. Backing + filler\n          // are skipped from settle directly (no independent snap).\n          const settleable = id => {\n            const cab = cabinets.find(c => c.id === id);\n            if (!cab) return false;\n            if (cab.radiusUnit) return false;       // settled in the propagation block below\n            if (cab.radiusGroup) return false;      // moved along with the radius unit\n            return true;\n          };\n          const settleRadiusGroups = (pass2) => {\n            for (const id of movedIds) {\n              const cab = cabinets.find(c => c.id === id);\n              if (!cab || !cab.radiusUnit) continue;\n              const beforeX = cab.x, beforeY = cab.y;\n              settleCabinet(cab.id, pass2);\n              const dx = cab.x - beforeX, dy = cab.y - beforeY;\n              if (!dx && !dy) continue;\n              if (!cab.groupId) continue;\n              for (const m of cabinets) {\n                if (m.id === cab.id) continue;\n                if (m.groupId !== cab.groupId) continue;\n                if (!m.radiusGroup) continue;\n                m.x += dx; m.y += dy;\n              }\n            }\n          };\n          settleRadiusGroups(false);\n          for (const id of movedIds) if (settleable(id)) settleCabinet(id, false);\n          alignBridgingTops(movedIds);   // before the panels: it changes the unit's height band\n          autoDetectEndPanels(movedIds);\n          autoDetectBackPanels();\n          autoDetectRadiusCompanions();   // grow/dissolve the end-of-run set as the curve tracks a wall\n          settleRadiusGroups(true);\n          for (const id of movedIds) if (settleable(id)) settleCabinet(id, true);\n          // Re-anchor every radius group whose members moved so the\n          // backing + filler are guaranteed to be exactly where the\n          // radius unit places them (canonical layout).\n          for (const id of movedIds) {\n            const cab = cabinets.find(c => c.id === id);\n            if (cab && cab.radiusUnit) reAnchorRadiusGroup(cabinets, cab);\n            else if (cab && cab.radiusGroup && cab.groupId) {\n              // A companion was dragged on its own (now individually selectable)\n              // - snap it back to the curve so the assembly stays intact.\n              const curve = cabinets.find(c => c.groupId === cab.groupId && c.radiusUnit);\n              if (curve) reAnchorRadiusGroup(cabinets, curve);\n            }\n          }\n          resizeFillers();\n          // Re-flow item numbers using the new layout, then redraw\n          // (renumberAllCabinets calls rerender, which also handles\n          // dims + clearance + 3D selection).\n          renumberAllCabinets();\n        } else if (group) {\n          // A click with a little wobble: the live preview ran (dims, the\n          // unit's own drawing, clearance, worktops at the snapped preview\n          // spot) but it was too small to count as a move, so nothing was\n          // committed. Redraw from the real positions, or the preview's\n          // numbers stay on the plan. Deferred: this runs on the same\n          // pointerup as the click that selects the unit, and redrawing first\n          // would replace the element before that click is handled.\n          setTimeout(() => rerender(), 0);\n        }\n        group = null;\n      }\n    });\n    renderHandles.push(drag);\n\n    // Click-to-select (raw pointer events; onDragEnd doesn't fire for\n    // short clicks). Shift/Ctrl/Cmd toggles into a multi-selection.\n    let downX = 0, downY = 0, downActive = false;\n    const onDown = e => { downX = e.clientX; downY = e.clientY; downActive = true; };\n    const onUp = e => {\n      if (!downActive) return;\n      downActive = false;\n      if (Math.hypot(e.clientX - downX, e.clientY - downY) >= 5) return;\n\n      // End panel click - child element of the cabinet but selects\n      // separately. Route to the end-panel selection panel instead\n      // of the cabinet's normal selection flow.\n      const epEl = e.target.closest('[data-end-panel-side]');\n      if (epEl) {\n        // The post carries a part ('feature' / 'feature-back') - it is its own\n        // basket line, so clicking it selects the feature, not the panel.\n        const _part = epEl.dataset.endFeature;\n        selectEndPanelFace(\n          epEl.dataset.endPanelCabinetId,\n          epEl.dataset.endPanelSide + (_part ? ':' + _part : '')\n        );\n        return;\n      }\n\n      const additive = e.shiftKey || e.ctrlKey || e.metaKey;\n      if (additive) {\n        // Ctrl/Shift-click rules:\n        //   \u2022 If the unit is in a group \u2192 ungroup THIS unit only\n        //     (the rest of the group stays grouped); also drop it\n        //     from the current selection. A 2-member group dissolves\n        //     naturally via setCabinetSelection's dissolve step.\n        //   \u2022 Otherwise toggle THIS unit in/out of the selection.\n        const next = new Set(selectedCabinetIds);\n        let changedGroup = false;\n        if (cabinet.groupId) {\n          delete cabinet.groupId;\n          changedGroup = true;\n          next.delete(cabinet.id);\n        } else if (next.has(cabinet.id)) {\n          next.delete(cabinet.id);\n        } else {\n          next.add(cabinet.id);\n        }\n        setCabinetSelection([...next]);\n        if (changedGroup) rerender();\n      } else {\n        // Single click: select the whole group (non-radius) or the individual\n        // member (radius end-of-run, so each is inspectable like its own\n        // basket line). See clickSelectIds. On a stack, clicking again steps\n        // down to the unit underneath - see nextInStackColumn.\n        setCabinetSelection(clickSelectIds(nextInStackColumn(cabinet)));\n      }\n    };\n    const onCancel = () => { downActive = false; };\n    el.addEventListener('pointerdown',   onDown);\n    el.addEventListener('pointerup',     onUp);\n    el.addEventListener('pointercancel', onCancel);\n    renderHandles.push({\n      destroy() {\n        el.removeEventListener('pointerdown',   onDown);\n        el.removeEventListener('pointerup',     onUp);\n        el.removeEventListener('pointercancel', onCancel);\n      }\n    });\n\n    // Lock > Rotation / Position - two options, as Step Forward has. A group\n    // locks as one, so a group shows locked when any member is.\n    const lockSubmenu = () => {\n      const grp = cabinet.groupId ? cabinets.filter(c => c.groupId === cabinet.groupId) : [cabinet];\n      const rot = grp.some(c => c.rotationLocked), pos = grp.some(c => c.positionLocked);\n      return { label: 'Lock', submenu: [\n        { label: rot ? 'Unlock Rotation' : 'Rotation', action: () => setCabinetRotationLock(cabinet.id, !rot) },\n        { label: pos ? 'Unlock Position' : 'Position', action: () => setCabinetPositionLock(cabinet.id, !pos) }\n      ] };\n    };\n    const onCtx = e => {\n      e.preventDefault();\n      const inSel   = selectedCabinetIds.has(cabinet.id);\n      const selIds  = [...selectedCabinetIds];\n      const selCount = selIds.length;\n      const items = [];\n\n      // Grouped cabinet \u2192 group menu (Rotate / Delete the whole group)\n      // regardless of how many members are currently selected. A\n      // single click already selects every group member, so this is\n      // the normal path.\n      if (cabinet.groupId) {\n        items.push({ label: 'Rotate 90\u00B0', action: () => rotateCabinetGroup(cabinet.groupId) });\n        items.push(lockSubmenu());\n        // Radius assemblies - Flip Hand swaps the curve to the\n        // other side (left \u2194 right). Useful when auto-detect picked\n        // the wrong side or you want to override.\n        const radiusInGroup = cabinets.find(c => c.groupId === cabinet.groupId && c.radiusUnit);\n        if (radiusInGroup) {\n          items.push({ label: 'Flip Hand', action: () => flipRadiusUnitHand(radiusInGroup) });\n        }\n        items.push({ label: 'Delete',     action: () => deleteCabinetGroup(cabinet.groupId) });\n      } else if (inSel && selCount > 1) {\n        // Ad-hoc multi-selection (not a saved group) - bulk group / delete.\n        const firstGid = cabinets.find(c => c.id === selIds[0])?.groupId;\n        const allSameGroup = !!firstGid && selIds.every(id =>\n          cabinets.find(c => c.id === id)?.groupId === firstGid);\n        if (!allSameGroup) {\n          items.push({ label: `Group ${selCount} units`, action: () => groupSelectedCabinets() });\n        }\n        items.push({ label: 'Delete', action: () => deleteSelectedCabinets() });\n      } else if (cabinet.freestandingAppliance) {\n        // Free-standing appliance - only what applies to a thing we don't\n        // supply: no steps, worktop extension or quote toggle. End panels and\n        // fillers DO apply: the appliance sits between panels that are ours.\n        items.push({ label: 'Snap Left',  action: () => snapCabinetToSide(cabinet.id, 'left')  });\n        items.push({ label: 'Snap Right', action: () => snapCabinetToSide(cabinet.id, 'right') });\n        items.push({ label: (cabinet.backPanel && cabinet.backPanel.active) ? 'End & Back Panels' : 'End Panels & Fillers', action: () => {\n          if (selectionPanelHandle && typeof selectionPanelHandle.openDetail === 'function') {\n            selectionPanelHandle.openDetail(cabinet.id, 'end-panels');\n          }\n        } });\n        if (cabinet.freestandingAppliance.stackable) {\n          const stacked = isApplianceStackMode(cabinet.stackOn);\n          if (stacked) {\n            items.push({ label: 'Take Off Stack', action: () => handleSetPlanApplianceStacked(cabinet.id, null) });\n          } else {\n            items.push({ label: 'Stack on Appliance', action: () => handleSetPlanApplianceStacked(cabinet.id, 'appliance') });\n            items.push({ label: 'Stand on Half-Height Unit', action: () => handleSetPlanApplianceStacked(cabinet.id, 'half-base') });\n          }\n        }\n        items.push({ label: 'Rotate 90\u00B0', action: () => rotateCabinet(cabinet) });\n        items.push({ label: 'Rotate 45\u00B0', action: () => rotateCabinet(cabinet, 45) });\n        items.push(lockSubmenu());\n        items.push({ label: 'Duplicate',  action: () => duplicateCabinet(cabinet) });\n        items.push({ label: 'Delete',     action: () => deleteCabinet(cabinet) });\n      } else {\n        // Single-cabinet menu - mirrors the order of the same\n        // buttons in the selection-panel left menu (Snap Left /\n        // Snap Right / Add Fillers / Step Forward / Extend Worktop /\n        // Rotate / Duplicate / Delete). The popup-opening rows\n        // delegate to selectionPanelHandle.openDetail so the same\n        // editor surface is used wherever it's reached from.\n        const openDetail = (key) => () => {\n          if (selectionPanelHandle && typeof selectionPanelHandle.openDetail === 'function') {\n            selectionPanelHandle.openDetail(cabinet.id, key);\n          }\n        };\n        items.push({ label: 'Snap Left',      action: () => snapCabinetToSide(cabinet.id, 'left')  });\n        items.push({ label: 'Snap Right',     action: () => snapCabinetToSide(cabinet.id, 'right') });\n        items.push({ label: (cabinet.backPanel && cabinet.backPanel.active) ? 'End & Back Panels' : 'End Panels & Fillers', action: openDetail('end-panels') });\n        // Step Forward - 2nd-level presets for step-eligible units.\n        if (isStepEligibleCab(cabinet)) {\n          items.push({ label: 'Step Forward', submenu: [\n            { label: 'Step 50mm',   action: () => handleUpdateCabinetSetback(cabinet.id, 50) },\n            { label: 'Step 100mm',  action: () => handleUpdateCabinetSetback(cabinet.id, 100) },\n            { label: 'Remove Step', danger: true, action: () => handleUpdateCabinetSetback(cabinet.id, 0) },\n          ]});\n        }\n        items.push({ label: 'Extend Worktop', action: openDetail('extend-worktop') });\n        items.push({ label: 'Rotate 90\u00B0',     action: () => rotateCabinet(cabinet) });\n        items.push({ label: 'Rotate 45\u00B0',     action: () => rotateCabinet(cabinet, 45) });\n        items.push(lockSubmenu());\n        items.push({ label: 'Duplicate',      action: () => duplicateCabinet(cabinet) });\n        if (cabinet.radiusUnit) {\n          items.push({ label: 'Flip Hand',    action: () => flipRadiusUnitHand(cabinet) });\n        }\n        {\n          const excluded = !!cabinet.excludeFromQuote;\n          items.push({\n            label: excluded ? 'Include in Quote' : 'Exclude from Quote',\n            danger: !excluded,\n            action: () => setCabinetExcludeFromQuote(cabinet.id)\n          });\n        }\n        // Carcase Only (staff only, sales row 131): sell the unit without its\n        // doors and drawer fronts. Shown in staff mode for any unit with fronts.\n        if (carcaseOnlyOffered(cabinet)) {\n          items.push({\n            label: cabinet.carcaseOnly ? 'Add Doors & Fronts Back' : 'Carcase Only',\n            action: () => setCabinetCarcaseOnly(cabinet.id, !cabinet.carcaseOnly)\n          });\n        }\n        items.push({ label: 'Delete',         action: () => deleteCabinet(cabinet) });\n      }\n      showContextMenu({ x: e.clientX, y: e.clientY, items });\n    };\n    el.addEventListener('contextmenu', onCtx);\n    renderHandles.push({ destroy() { el.removeEventListener('contextmenu', onCtx); } });\n  }\n\n  // Phase 1 worktop-item wiring - translate-only drag clamped to the\n  // room bbox, plus right-click \u2192 Delete. No snapping, no rotation\n  // (yet); the picker spawns them centred and the user nudges them\n  // onto a worktop slab. Selection / rotation come in the panel phase.\n  // ---- Sink / hob auto-snap helpers ----\n  // The user expects sinks + hobs to lock 50 mm in from the visible\n  // worktop FRONT edge and to free-slide along the run. Two helpers:\n  //   1. findItemHost(centreX, centreY)\n  //        Picks the base cabinet whose bbox contains the centre - or\n  //        null when the item is over a gap / island. Used both for\n  //        the position snap and to rotate the item to match the\n  //        run's orientation.\n  //   2. snapItemPosition(item, freeX, freeY, host)\n  //        Given a host, returns the snapped { x, y } locked to the\n  //        front-edge inset. Caller is responsible for falling back\n  //        to the item's previous position when host is null, so the\n  //        hob doesn't jump as the user drags through a small gap.\n  // 30 mm matches WT_WRAPAROUND_MM in engine-worktops - the front\n  // overhang of a wall-aligned worktop slab over its cabinets. The\n  // hob / sink front sits 50 mm behind the VISIBLE worktop edge, so\n  // the inset INTO the cabinet body is 50 \u2212 30 = 20 mm.\n  const WORKTOP_FRONT_OVERHANG_MM   = 30;\n  const WORKTOP_ITEM_FRONT_INSET_MM = 50;\n\n  function roomEdges(r) {\n    const v = (r && r.vertices) || [];\n    const out = [];\n    for (let i = 0; i < v.length; i++) {\n      out.push({ from: v[i], to: v[(i + 1) % v.length] });\n    }\n    return out;\n  }\n\n  function findItemHost(centreX, centreY) {\n    if (!Array.isArray(cabinets) || !cabinets.length) return null;\n    // Same definition the splashback engine uses for \"base-level\n    // cabinet\" - anything that isn't wall / tall / bridging and that\n    // sits on the floor (restMm <= 1). Catches base, sink-base,\n    // belfast, oven-housing and corner units.\n    function isFloorBase(c) {\n      if (!c) return false;\n      if (c.cornerUnit) return true;\n      const cat = c.category || '';\n      if (/^(tall|wall|bridging)/i.test(cat)) return false;\n      if (/base/i.test(cat)) return true;\n      return (c.restMm || 0) <= 1;\n    }\n    for (const c of cabinets) {\n      if (!isFloorBase(c)) continue;\n      const rot = ((c.rotationDeg || 0) % 360 + 360) % 360;\n      const portrait = (rot === 90 || rot === 270);\n      const w = portrait ? (c.depthMm || 0) : (c.widthMm || 0);\n      const d = portrait ? (c.widthMm || 0) : (c.depthMm || 0);\n      if (centreX >= (c.x || 0) && centreX <= (c.x || 0) + w\n       && centreY >= (c.y || 0) && centreY <= (c.y || 0) + d) {\n        return c;\n      }\n    }\n    return null;\n  }\n\n  // Returns { frontSide: 'top'|'right'|'bottom'|'left', vert, frontVal }\n  // for the host cabinet - the side OPPOSITE the wall the host touches.\n  function hostFrontEdge(host) {\n    const rot = ((host.rotationDeg || 0) % 360 + 360) % 360;\n    const portrait = (rot === 90 || rot === 270);\n    const w = portrait ? (host.depthMm || 0) : (host.widthMm || 0);\n    const d = portrait ? (host.widthMm || 0) : (host.depthMm || 0);\n    const x0 = host.x || 0, y0 = host.y || 0;\n    const x1 = x0 + w, y1 = y0 + d;\n    const walls = roomEdges(room);\n    const edges = [\n      { side: 'top',    backY: y0, frontY: y1, vert: false },\n      { side: 'right',  backX: x1, frontX: x0, vert: true  },\n      { side: 'bottom', backY: y1, frontY: y0, vert: false },\n      { side: 'left',   backX: x0, frontX: x1, vert: true  }\n    ];\n    for (const e of edges) {\n      const onWall = walls.some(w2 => {\n        if (e.vert) {\n          return Math.abs(w2.from.x - w2.to.x) < 1\n              && Math.abs(e.backX - w2.from.x) < 5\n              && Math.min(w2.from.y, w2.to.y) - 5 <= y0\n              && Math.max(w2.from.y, w2.to.y) + 5 >= y1;\n        } else {\n          return Math.abs(w2.from.y - w2.to.y) < 1\n              && Math.abs(e.backY - w2.from.y) < 5\n              && Math.min(w2.from.x, w2.to.x) - 5 <= x0\n              && Math.max(w2.from.x, w2.to.x) + 5 >= x1;\n        }\n      });\n      if (onWall) {\n        const frontSide = e.side === 'top' ? 'bottom'\n                       : e.side === 'bottom' ? 'top'\n                       : e.side === 'left' ? 'right' : 'left';\n        return { frontSide, vert: e.vert, frontVal: e.vert ? e.frontX : e.frontY };\n      }\n    }\n    // Free-standing - default to \"front faces +y\" (rotation 0).\n    return { frontSide: 'bottom', vert: false, frontVal: y1 };\n  }\n\n  // Cabinet rotation that places the item's BACK against the host's\n  // wall. Mirrors the cabinet's own rotation so a hob on a top-wall\n  // run is rotation 0 (back faces north), a hob on a left-wall run is\n  // rotation 270 (back faces west), etc.\n  // ---- Taps on sink bases (Arden, 2026-10-15) ----\n  // A sink base's sink, in cab-local mm from its centre (+y = back): the bowl's\n  // centre across the unit and the sink's back edge - as the 2D plan draws it\n  // (appendPlannerSink: Move L/R offset, bowl offset mirrored with the drainer).\n  // Also where a tap chosen for it stands (tapX / tapY, the tap's centre; tapY\n  // null = the 25mm-behind rule in tapDepthLocal) - Arden, 2026-10-24:\n  //   Belfast units: always centred. The notch is measured from the worktop\n  //     front edge (WORKTOP_FRONT_OVERHANG_MM ahead of the carcase).\n  //   Other sinks: the sink's own tap_offset_x_mm (from the sink centre, for\n  //     its native drainer side - mirrored when the drainer is swapped) and\n  //     tap_offset_y_mm (from the cut-out centre), else over the bowl.\n  function sinkBaseSinkLocal(cab) {\n    const sink = (cab && cab.plannerSinkHandle && Catalogue.getPlannerSink)\n      ? Catalogue.getPlannerSink(cab.plannerSinkHandle) : null;\n    const offY = (sink && typeof sink.tapOffsetYMm === 'number') ? sink.tapOffsetYMm : null;\n    // A Belfast unit's bowl fills the U-notch at the front, centred.\n    if (cab && cab.belfastSink) {\n      const notchD = cab.belfastSink.sinkCutoutDepthMm || 450;\n      const frontY = -(cab.depthMm || 0) / 2 - WORKTOP_FRONT_OVERHANG_MM;\n      return { bowlX: 0, backY: frontY + notchD, tapX: 0,\n               tapY: offY != null ? frontY + notchD / 2 + offY : null };\n    }\n    if (!sink || !(sink.cutoutWidthMm > 0) || !(sink.cutoutDepthMm > 0)) return null;\n    const offsetX = (typeof cab.plannerSinkXOffsetMm === 'number') ? cab.plannerSinkXOffsetMm : 0;\n    const nativeSide = String((sink.drainerSide && sink.drainerSide[0]) || 'L').toUpperCase().startsWith('R') ? 'R' : 'L';\n    const chosenSide = String(cab.plannerSinkDrainerSide || nativeSide).toUpperCase();\n    const mirror = sink.reversible && chosenSide !== nativeSide;\n    const sign = mirror ? -1 : 1;\n    const bowlX = offsetX + sign * (sink.bowlOffsetXMm || 0);\n    let tapX = (typeof sink.tapOffsetXMm === 'number') ? offsetX + sign * sink.tapOffsetXMm : bowlX;\n    let tapY = offY;\n    // An inset sink's own tap hole (Arden, 2026-10-24): its centre so many\n    // mm from the sink's BACK edge and from its outside edge on the DRAINER\n    // side - measured from the drainer, so it holds when the drainer is\n    // swapped. The sink is centred on the unit (plus Move L/R), and in this\n    // frame the drainer on the R (as seen from the front) is the -x edge.\n    const W = sink.overallWidthMm, D = sink.overallDepthMm;\n    if (D > 0 && typeof sink.tapFromBackMm === 'number') tapY = D / 2 - sink.tapFromBackMm;\n    const rawSide = String((sink.drainerSide && sink.drainerSide[0]) || '').toUpperCase();\n    if (W > 0 && typeof sink.tapFromDrainerEdgeMm === 'number' && (rawSide === 'L' || rawSide === 'R')) {\n      const drainerSide = mirror ? chosenSide : nativeSide;\n      tapX = offsetX + (drainerSide === 'R' ? (-W / 2 + sink.tapFromDrainerEdgeMm) : (W / 2 - sink.tapFromDrainerEdgeMm));\n    }\n    return { bowlX, backY: sink.cutoutDepthMm / 2, tapX, tapY };\n  }\n  // The taps standing on a unit's worktop (centre over the unit).\n  function tapsOnCabinet(cabId) {\n    const cab = cabinets.find(c => c.id === cabId);\n    if (!cab) return [];\n    const W = cab.widthMm || 0, D = cab.depthMm || 0;\n    const cx = cab.x + W / 2, cy = cab.y + D / 2;\n    const th = ((cab.rotationDeg || 0) * Math.PI) / 180, cs = Math.cos(th), sn = Math.sin(th);\n    return (worktopItems || []).filter(it => {\n      if (!it || it.kind !== 'tap') return false;\n      const dx = it.x + (it.widthMm || 0) / 2 - cx, dy = it.y + (it.depthMm || 0) / 2 - cy;\n      const lx = dx * cs + dy * sn, ly = -dx * sn + dy * cs;\n      return Math.abs(lx) <= W / 2 && Math.abs(ly) <= D / 2 + 40;\n    });\n  }\n  // ONE TAP PER SINK (Arden, 2026-10-22): a tap put on a sink unit - by its\n  // tap \"+\", or dragged / dropped onto it - takes the place of the tap already\n  // there, rather than standing beside it and going on the order too.\n  function cabinetIsSinkUnit(cab) {\n    return !!(cab && (cab.belfastSink || cab.sinkBase || cab.plannerSinkHandle || sinkBaseSinkLocal(cab)));\n  }\n  function replaceTapsOn(cabId, keepId) {\n    const cab = cabinets.find(c => c.id === cabId);\n    if (!cabinetIsSinkUnit(cab)) return;\n    const gone = new Set(tapsOnCabinet(cabId).filter(t => t.id !== keepId).map(t => t.id));\n    if (!gone.size) return;\n    worktopItems = worktopItems.filter(it => !gone.has(it.id));\n    if (selectedItem?.kind === 'worktop-item' && gone.has(selectedItem.id)) selectItem(null);\n  }\n  // The worktop items as the 3D draws them: all of them. A tap left out of the\n  // quote (Exclude Items from Quote) is still drawn - the customer is buying\n  // it elsewhere, and the picture shows the kitchen they will have.\n  function worktopItems3D() {\n    return worktopItems || [];\n  }\n  // Is there a tap on this unit's worktop already (its centre over the unit)?\n  function cabinetHasTap(cabId) {\n    const cab = cabinets.find(c => c.id === cabId);\n    if (!cab) return false;\n    const W = cab.widthMm || 0, D = cab.depthMm || 0;\n    const cx = cab.x + W / 2, cy = cab.y + D / 2;\n    const th = ((cab.rotationDeg || 0) * Math.PI) / 180, cs = Math.cos(th), sn = Math.sin(th);\n    return (worktopItems || []).some(it => {\n      if (!it || it.kind !== 'tap') return false;\n      const dx = it.x + (it.widthMm || 0) / 2 - cx, dy = it.y + (it.depthMm || 0) / 2 - cy;\n      const lx = dx * cs + dy * sn, ly = -dx * sn + dy * cs;\n      return Math.abs(lx) <= W / 2 && Math.abs(ly) <= D / 2 + 40;\n    });\n  }\n  // How far back a tap sits on a unit, in cab-local mm from its centre (+ =\n  // back): just behind the unit's sink, else 10mm short of the back. One rule\n  // for the tap \"+\" and for a tap dragged onto a unit.\n  function tapDepthLocal(cab, td) {\n    const D = cab.depthMm || 0;\n    const sk = sinkBaseSinkLocal(cab);\n    const atBack = D / 2 - td / 2 - 10;\n    if (sk && sk.tapY != null) return Math.min(atBack, sk.tapY);\n    return sk ? Math.min(atBack, sk.backY + td / 2 + 25) : atBack;\n  }\n  // A tap dropped over a unit: that depth, facing the unit, left where it was\n  // dropped along the run (kept on the unit). Null when not over a unit.\n  function snapTapToHost(item) {\n    const tw = item.widthMm || 0, td = item.depthMm || 0;\n    const icx = item.x + tw / 2, icy = item.y + td / 2;\n    const host = findItemHost(icx, icy);\n    if (!host) return null;\n    const W = host.widthMm || 0, D = host.depthMm || 0;\n    const cx = host.x + W / 2, cy = host.y + D / 2;\n    const th = ((host.rotationDeg || 0) * Math.PI) / 180, cs = Math.cos(th), sn = Math.sin(th);\n    const dx = icx - cx, dy = icy - cy;\n    const lx = Math.max(-W / 2 + tw / 2, Math.min(W / 2 - tw / 2, dx * cs + dy * sn));\n    const ly = tapDepthLocal(host, td);\n    const wx = cx + lx * cs - ly * sn, wy = cy + lx * sn + ly * cs;\n    return { x: wx - tw / 2, y: wy - td / 2, rotationDeg: hostFacingRotation(host) };\n  }\n  // The tap \"+\" on a sink base: the chosen tap goes over the sink's bowl, just\n  // behind the sink, facing the way the unit does. Then it is a free worktop\n  // item like any other tap.\n  // Where a tap of this size stands on a sink unit: top-left in plan + facing.\n  function tapSpotOnCabinet(cab, tw, td) {\n    const W = cab.widthMm || 0, D = cab.depthMm || 0;\n    const sk = sinkBaseSinkLocal(cab);\n    let lx = sk ? sk.tapX : 0;\n    let ly = tapDepthLocal(cab, td);\n    let turn = 0;\n    // An L-shape's sink is on one leg, facing out of it (sinkFrameOf): the\n    // tap stands behind it there, short of that leg's back.\n    if (cab.lShapeUnit && sk) {\n      const arm = cab.lShapeUnit.armDepthMm || 570;\n      const fy = sk.tapY != null ? Math.min(arm / 2 - td / 2 - 10, sk.tapY)\n                                 : Math.min(arm / 2 - td / 2 - 10, sk.backY + td / 2 + 25);\n      const p = sinkFramePoint(cab, sk.tapX, fy);\n      lx = p.x; ly = p.y; turn = p.rot;\n    }\n    const th = ((cab.rotationDeg || 0) * Math.PI) / 180, cs = Math.cos(th), sn = Math.sin(th);\n    const wx = cab.x + W / 2 + lx * cs - ly * sn;\n    const wy = cab.y + D / 2 + lx * sn + ly * cs;\n    return { x: wx - tw / 2, y: wy - td / 2, rotationDeg: ((hostFacingRotation(cab) + turn) % 360 + 360) % 360 };\n  }\n  function addTapForCabinet(cabId, entry, opts = {}) {\n    const cab = cabinets.find(c => c.id === cabId);\n    if (!cab || !entry) return;\n    const tw = entry.widthMm || 55, td = entry.depthMm || 55;\n    const spot = tapSpotOnCabinet(cab, tw, td);\n    const def = buildWorktopItemDefinition(entry, {\n      id: `wi-${nextWorktopItemId++}`,\n      x: spot.x,\n      y: spot.y\n    });\n    def.rotationDeg = spot.rotationDeg;\n    anchorTapToCabinet(def, cab);\n    replaceTapsOn(cab.id, null);\n    worktopItems.push(def);\n    if (opts.silent) return;\n    rerender();\n    if (selectedItem?.kind === 'planner-sink' && selectedItem.cabinetId === cabId) selectionPanelHandle?.refresh?.();\n  }\n  // The tap is the customer's choice (Arden, 2026-11-11, Sales bug sheet rows\n  // 87 / 105): a sink unit no longer comes with the shop's default tap. A fitted\n  // sink with no tap shows the green tap \"+\" on the plan to choose one. Plans\n  // saved with the old default tap (Shopify shop metafield\n  // custom.planner_default_tap - AURORA Swan Neck Mixer Tap, Chrome) keep it.\n  function defaultTapEntry() {\n    const h = (typeof window !== 'undefined' && window.BTKKitchenCatalogue) ? window.BTKKitchenCatalogue.defaultTapHandle : null;\n    if (!h) return null;\n    return ((getWorktopItemCatalogue().taps) || []).find(t => t && t.handle === h) || null;\n  }\n  // Add Sinks & Taps > Add to Plan with a tap (Sales bug sheet row 87): the tap\n  // goes on the sink unit it is plainly for - the selected sink unit, else the\n  // only sink unit with no tap yet, else (an older plan) the only one still on\n  // the old default tap, which it replaces. Null = no one unit; placed loose.\n  function tapTargetCabinetId() {\n    const units = cabinets.filter(c => c && (c.sinkBase || c.belfastSink));\n    const selId = selectedItem?.kind === 'planner-sink' ? selectedItem.cabinetId\n      : (selectedCabinetIds.size === 1 ? [...selectedCabinetIds][0] : null);\n    if (selId && units.some(c => c.id === selId)) return selId;\n    const noTap = units.filter(c => c.plannerSinkHandle && !tapsOnCabinet(c.id).length);\n    if (noTap.length === 1) return noTap[0].id;\n    if (noTap.length > 1) return null;\n    const defH = defaultTapEntry()?.handle;\n    if (!defH) return null;\n    const onDefault = units.filter(c => {\n      const t = tapsOnCabinet(c.id);\n      return t.length === 1 && t[0].handle === defH;\n    });\n    return onDefault.length === 1 ? onDefault[0].id : null;\n  }\n  // A tap rides the unit it stands on (Arden, 2026-10-24 - a sink unit gets\n  // its tap the moment it is added, before it is dragged into place): it\n  // keeps its spot in the unit's own frame (hostCabinetId + hostLocal), and\n  // syncTapsToHosts puts it back there on every render, so moving or turning\n  // the unit takes the tap with it. Set when a tap is put on a unit (tap +,\n  // default tap, re-seat, dropped on a unit); cleared when it is dropped\n  // off any unit or its unit goes.\n  function anchorTapToCabinet(it, cab) {\n    if (!it || !cab) return;\n    const W = cab.widthMm || 0, D = cab.depthMm || 0;\n    const th = ((cab.rotationDeg || 0) * Math.PI) / 180, cs = Math.cos(th), sn = Math.sin(th);\n    const dx = it.x + (it.widthMm || 0) / 2 - (cab.x + W / 2), dy = it.y + (it.depthMm || 0) / 2 - (cab.y + D / 2);\n    it.hostCabinetId = cab.id;\n    it.hostLocal = { lx: dx * cs + dy * sn, ly: -dx * sn + dy * cs, rot: (it.rotationDeg || 0) - (cab.rotationDeg || 0) };\n  }\n  function syncTapsToHosts() {\n    for (const it of (worktopItems || [])) {\n      if (!it || it.kind !== 'tap' || !it.hostCabinetId || !it.hostLocal) continue;\n      const cab = cabinets.find(c => c.id === it.hostCabinetId);\n      if (!cab) { delete it.hostCabinetId; delete it.hostLocal; continue; }\n      const W = cab.widthMm || 0, D = cab.depthMm || 0;\n      const th = ((cab.rotationDeg || 0) * Math.PI) / 180, cs = Math.cos(th), sn = Math.sin(th);\n      const { lx, ly } = it.hostLocal;\n      it.x = cab.x + W / 2 + lx * cs - ly * sn - (it.widthMm || 0) / 2;\n      it.y = cab.y + D / 2 + lx * sn + ly * cs - (it.depthMm || 0) / 2;\n      it.rotationDeg = (((cab.rotationDeg || 0) + (it.hostLocal.rot || 0)) % 360 + 360) % 360;\n    }\n  }\n  // The sink unit a tap stands on (with a sink chosen), or null - a tap on a\n  // sink unit is selected together with its sink.\n  // A sink unit's sink + tap, shown (Arden, 2026-10-24): the 3D view, swung\n  // round to the unit, with the pair selected and its panel open - from the\n  // unit's Sink & Tap button and its green sink / tap + on the plan. The 3D\n  // scene builds after the switch, so the camera retries until the unit is in.\n  function showSinkSet(cabId) {\n    const cab = cabinets.find(c => c.id === cabId);\n    if (!cab) return;\n    if (viewMode !== '3d') setViewMode('3d');\n    selectItem({ kind: 'planner-sink', cabinetId: cabId });\n    let tries = 0;\n    const tryFocus = () => {\n      let ok = false;\n      try { ok = !!handle3D?.focusOnCabinet?.(cabId); } catch (_) {}\n      if (!ok && ++tries < 40) setTimeout(tryFocus, 150);\n    };\n    tryFocus();\n  }\n  function sinkUnitForTap(tapId) {\n    return cabinets.find(c => c && c.plannerSinkHandle && (c.sinkBase || c.belfastSink)\n      && tapsOnCabinet(c.id).some(t => t.id === tapId)) || null;\n  }\n  // The tap on a sink unit follows its sink: re-seat it when the sink, its\n  // Move L/R or its drainer side changes (a swapped drainer mirrors the tap).\n  // Call BEFORE the sink change is applied to find the tap on the unit, then\n  // after - so take the tap ids first.\n  function reseatTapsOn(cabId, tapIds) {\n    const cab = cabinets.find(c => c.id === cabId);\n    if (!cab || !cabinetIsSinkUnit(cab) || !tapIds || !tapIds.length) return;\n    const ids = new Set(tapIds);\n    worktopItems = (worktopItems || []).map(it => {\n      if (!it || !ids.has(it.id)) return it;\n      const spot = tapSpotOnCabinet(cab, it.widthMm || 55, it.depthMm || 55);\n      const moved = { ...it, x: spot.x, y: spot.y, rotationDeg: spot.rotationDeg };\n      anchorTapToCabinet(moved, cab);\n      return moved;\n    });\n  }\n\n  function hostFacingRotation(host) {\n    return ((host.rotationDeg || 0) % 360 + 360) % 360;\n  }\n\n  function snapItemPosition(item, freeX, freeY, host) {\n    const itW = item.widthMm || 0;\n    const itD = item.depthMm || 0;\n    const front = hostFrontEdge(host);\n    const INSET = WORKTOP_ITEM_FRONT_INSET_MM - WORKTOP_FRONT_OVERHANG_MM;\n    if (front.vert) {\n      const snappedX = front.frontSide === 'right'\n        ? front.frontVal - INSET - itW\n        : front.frontVal + INSET;\n      return { x: snappedX, y: freeY };\n    } else {\n      const snappedY = front.frontSide === 'bottom'\n        ? front.frontVal - INSET - itD\n        : front.frontVal + INSET;\n      return { x: freeX, y: snappedY };\n    }\n  }\n  function snapLockedAxis(host) {\n    return hostFrontEdge(host).vert ? 'x' : 'y';\n  }\n\n  // Rotation-aware snap: places the hob / sink so its VISIBLE back\n  // edge sits 40 mm inside the host cabinet's front (= 50 mm behind\n  // the visible worktop edge, since the worktop overhangs by 10 mm\n  // at the front). Works for any item rotation by translating between\n  // storage coords (pre-rotation top-left) and visible AABB coords\n  // via getEffectiveAABB - same maths cabinets use for their wall\n  // snap. Returns null when the item isn't over a base cabinet.\n  function snapItemPositionRotationAware(item) {\n    const itAABB = getEffectiveAABB(item, item.x, item.y);\n    const cx = itAABB.x + itAABB.widthMm  / 2;\n    const cy = itAABB.y + itAABB.depthMm / 2;\n    const host = findItemHost(cx, cy);\n    if (!host) return null;\n    const hostAABB = getEffectiveAABB(host, host.x, host.y);\n    // Which side of the host's AABB lies on a room wall? That side\n    // is the BACK; the user-facing FRONT is the opposite side.\n    const sides = [\n      { name: 'top',    coord: hostAABB.y,                       vert: false, sign:  1 },\n      { name: 'bottom', coord: hostAABB.y + hostAABB.depthMm,    vert: false, sign: -1 },\n      { name: 'left',   coord: hostAABB.x,                       vert: true,  sign:  1 },\n      { name: 'right',  coord: hostAABB.x + hostAABB.widthMm,    vert: true,  sign: -1 }\n    ];\n    const walls = roomEdges(room);\n    let backSide = null;\n    for (const s of sides) {\n      const onWall = walls.some(w => {\n        if (s.vert) {\n          return Math.abs(w.from.x - w.to.x) < 1\n              && Math.abs(s.coord - w.from.x) < 5\n              && Math.min(w.from.y, w.to.y) - 5 <= hostAABB.y\n              && Math.max(w.from.y, w.to.y) + 5 >= hostAABB.y + hostAABB.depthMm;\n        } else {\n          return Math.abs(w.from.y - w.to.y) < 1\n              && Math.abs(s.coord - w.from.y) < 5\n              && Math.min(w.from.x, w.to.x) - 5 <= hostAABB.x\n              && Math.max(w.from.x, w.to.x) + 5 >= hostAABB.x + hostAABB.widthMm;\n        }\n      });\n      if (onWall) { backSide = s; break; }\n    }\n    if (!backSide) return null;\n    const hostPerpDepth = backSide.vert ? hostAABB.widthMm : hostAABB.depthMm;\n    const itemPerpDepth = backSide.vert ? itAABB.widthMm   : itAABB.depthMm;\n    const INSET = WORKTOP_ITEM_FRONT_INSET_MM - WORKTOP_FRONT_OVERHANG_MM;\n    const hobBackOffsetFromHostBack = hostPerpDepth - INSET - itemPerpDepth;\n    const desiredVisBack = backSide.coord + backSide.sign * hobBackOffsetFromHostBack;\n    // Current visible-back position along the perpendicular axis.\n    let curVisBack;\n    if (backSide.name === 'top')    curVisBack = itAABB.y;\n    if (backSide.name === 'bottom') curVisBack = itAABB.y + itAABB.depthMm;\n    if (backSide.name === 'left')   curVisBack = itAABB.x;\n    if (backSide.name === 'right')  curVisBack = itAABB.x + itAABB.widthMm;\n    const delta = desiredVisBack - curVisBack;\n    return backSide.vert\n      ? { x: item.x + delta, y: item.y }\n      : { x: item.x, y: item.y + delta };\n  }\n\n  function wireWorktopItem(item, el, pxPerMm) {\n    let lastX = item.x, lastY = item.y;\n    let didDrag = false;\n\n    const drag = makeDraggable(el, {\n      pxPerMm,\n      getZoom: () => view2d.zoom,\n      onDragMove({ dxMm, dyMm }) {\n        if (Math.hypot(dxMm, dyMm) * pxPerMm > 5) didDrag = true;\n        let x = item.x + dxMm;\n        let y = item.y + dyMm;\n        // Clamp the VISIBLE bbox (rotation-aware) to the room - not\n        // the storage bbox. With transform-origin centre, a rotated\n        // item's storage coords differ from its visible coords by\n        // (w-d)/2 on each axis, so a storage clamp made it impossible\n        // to drag the visible back edge against the side walls\n        // (B / D). Clamping the AABB lets the user pull the visible\n        // back right up to the wall.\n        const bbox = getBoundingBox(room);\n        const aabb = getEffectiveAABB(item, x, y);\n        const minX = bbox.minX - (aabb.x - x);\n        const maxX = bbox.maxX - (aabb.x - x) - aabb.widthMm;\n        const minY = bbox.minY - (aabb.y - y);\n        const maxY = bbox.maxY - (aabb.y - y) - aabb.depthMm;\n        x = Math.max(minX, Math.min(maxX, x));\n        y = Math.max(minY, Math.min(maxY, y));\n        // Cabinet-style soft rotation: when any corner is within\n        // ROTATION_PROXIMITY_MM of a wall, smoothly rotate the item\n        // to face that wall (back against it). Position tracks the\n        // cursor 1:1 - only rotation snaps mid-drag.\n        const desired = computeAutoRotation(item, x, y, room, ROTATION_PROXIMITY_MM);\n        if (desired !== null) {\n          const cur = ((item.rotationDeg || 0) % 360 + 360) % 360;\n          if (Math.abs(cur - desired) > 0.5) {\n            item.rotationDeg = desired;\n            setCabinetRotation(el, desired);\n          }\n        }\n        lastX = x; lastY = y;\n        el.style.left = `${Math.round(x * pxPerMm)}px`;\n        el.style.top  = `${Math.round(y * pxPerMm)}px`;\n      },\n      onDragEnd() {\n        if (!didDrag || lastX === null) return;\n        item.x = lastX;\n        item.y = lastY;\n        // 50 mm-from-front snap on release - rotation-aware, so it\n        // works correctly on side walls (B/D) where storage and\n        // visible coords diverge by (w-d)/2. If the user dropped the\n        // item over a base cabinet the visible back lands 40 mm\n        // inside the cabinet's front (50 mm behind the worktop\n        // edge); free-standing drops stay where they are.\n        // A TAP keeps to the tap's spot instead: the same distance from the\n        // wall as the green tap \"+\" puts it (Arden, 2026-10-15).\n        const snapped = item.kind === 'tap' ? snapTapToHost(item) : snapItemPositionRotationAware(item);\n        if (snapped) {\n          item.x = snapped.x;\n          item.y = snapped.y;\n          if (snapped.rotationDeg != null) item.rotationDeg = snapped.rotationDeg;\n        }\n        if (item.kind === 'tap') {\n          const host = findItemHost(item.x + (item.widthMm || 0) / 2, item.y + (item.depthMm || 0) / 2);\n          if (host) replaceTapsOn(host.id, item.id);\n          if (host) anchorTapToCabinet(item, host);\n          else { delete item.hostCabinetId; delete item.hostLocal; }\n        }\n        rerender();\n      }\n    });\n    renderHandles.push(drag);\n\n    const onCtx = e => {\n      e.preventDefault();\n      showContextMenu({\n        x: e.clientX, y: e.clientY,\n        items: [\n          { label: 'Rotate 90\u00B0', action: () => rotateWorktopItem(item.id) },\n          { label: 'Delete',     action: () => deleteWorktopItem(item.id) }\n        ]\n      });\n    };\n    el.addEventListener('contextmenu', onCtx);\n    renderHandles.push({ destroy() { el.removeEventListener('contextmenu', onCtx); } });\n\n    // Click-to-select - short click (no drag) opens the selection\n    // panel. Mirrors the cabinet wiring: raw pointerdown / pointerup\n    // because onDragEnd doesn't fire for a sub-threshold drag.\n    let downX = 0, downY = 0, downActive = false;\n    const onDown = e => { downX = e.clientX; downY = e.clientY; downActive = true; };\n    const onUp = e => {\n      if (!downActive) return;\n      downActive = false;\n      if (Math.hypot(e.clientX - downX, e.clientY - downY) >= 5) return;\n      selectItem({ kind: 'worktop-item', id: item.id });\n    };\n    const onCancel = () => { downActive = false; };\n    el.addEventListener('pointerdown',   onDown);\n    el.addEventListener('pointerup',     onUp);\n    el.addEventListener('pointercancel', onCancel);\n    renderHandles.push({\n      destroy() {\n        el.removeEventListener('pointerdown',   onDown);\n        el.removeEventListener('pointerup',     onUp);\n        el.removeEventListener('pointercancel', onCancel);\n      }\n    });\n  }\n\n  // An extractor in 2D: its outline lets the pointer through (the hob under\n  // it stays easy to grab) and its plan NUMBER is the handle - a click selects\n  // it, a drag moves the hood, and on release it seats back-to-wall against\n  // the nearest wall (seatExtractorOnNearestWall). Right-click to delete.\n  function wireExtractor2D(item, el, pxPerMm) {\n    const target = el.querySelector('.btk-kp-worktop-item-number, .btk-kp-worktop-item-label') || el;\n    let didDrag = false, lastX = item.x, lastY = item.y;\n    const drag = makeDraggable(target, {\n      pxPerMm,\n      getZoom: () => view2d.zoom,\n      onDragMove({ dxMm, dyMm }) {\n        if (Math.hypot(dxMm, dyMm) * pxPerMm > 5) didDrag = true;\n        lastX = item.x + dxMm; lastY = item.y + dyMm;\n        el.style.left = `${Math.round(lastX * pxPerMm)}px`;\n        el.style.top  = `${Math.round(lastY * pxPerMm)}px`;\n      },\n      onDragEnd() {\n        if (!didDrag) return;\n        item.x = lastX; item.y = lastY;\n        seatExtractorOnNearestWall(item);\n        rerender();\n      }\n    });\n    renderHandles.push(drag);\n    let downX = 0, downY = 0, downActive = false;\n    const onDown = e => { downX = e.clientX; downY = e.clientY; downActive = true; };\n    const onUp = e => {\n      if (!downActive) return;\n      downActive = false;\n      if (Math.hypot(e.clientX - downX, e.clientY - downY) >= 5) return;\n      selectItem({ kind: 'worktop-item', id: item.id });\n    };\n    const onCtx = e => {\n      e.preventDefault();\n      showContextMenu({ x: e.clientX, y: e.clientY,\n        items: [{ label: 'Delete', action: () => deleteWorktopItem(item.id) }] });\n    };\n    target.addEventListener('pointerdown', onDown);\n    target.addEventListener('pointerup', onUp);\n    target.addEventListener('contextmenu', onCtx);\n    renderHandles.push({ destroy() {\n      target.removeEventListener('pointerdown', onDown);\n      target.removeEventListener('pointerup', onUp);\n      target.removeEventListener('contextmenu', onCtx);\n    } });\n  }\n\n  function rotateWorktopItem(id) {\n    const it = worktopItems.find(x => x.id === id);\n    if (!it || it.kind === 'extractor' || it.kind === 'canopy') return;   // turns to face its wall / with its wall unit\n    it.rotationDeg = ((it.rotationDeg || 0) + 90) % 360;\n    rerender();\n  }\n\n  function deleteWorktopItem(id) {\n    const i = worktopItems.findIndex(it => it.id === id);\n    if (i === -1) return;\n    worktopItems.splice(i, 1);\n    // Clear the selection panel if it was showing this item.\n    if (selectedItem?.kind === 'worktop-item' && selectedItem.id === id) {\n      selectItem(null);\n    }\n    rerender();\n  }\n\n  // ---- Furniture (free-standing, floor) drag + context actions ----\n  // x/y are the footprint CENTRE. Free dragging across the floor (no\n  // wall-snap), clamped loosely so the centre stays inside the room.\n  function wireFurnitureItem(item, el, pxPerMm, w, d) {\n    let lastX = item.x, lastY = item.y, lastRot = item.rotationDeg || 0;\n    let didDrag = false;\n    // Stools, chairs and tables can't be dragged into a unit. One that starts\n    // inside a unit moves freely until it has been dropped clear.\n    let dragBlockers = null;\n    const drag = makeDraggable(el, {\n      pxPerMm,\n      getZoom: () => view2d.zoom,\n      onDragMove({ dxMm, dyMm }) {\n        if (Math.hypot(dxMm, dyMm) * pxPerMm > 5) didDrag = true;\n        const bbox = getBoundingBox(room);\n        let cx = Math.max(bbox.minX, Math.min(bbox.maxX, item.x + dxMm));\n        let cy = Math.max(bbox.minY, Math.min(bbox.maxY, item.y + dyMm));\n        if (!dragBlockers) {\n          const b = item.furnitureId && furniturePlacement(item) === 'floor' ? furnitureUnitBlockers() : [];\n          dragBlockers = furnitureHitsUnit(item, item.x, item.y, b) ? [] : b;\n        }\n        if (dragBlockers.length) [cx, cy] = slideFurniture(item, lastX, lastY, cx, cy, dragBlockers);\n        // A bed's head goes to the wall too, as a shelf's back does.\n        if (furniturePlacement(item) === 'wall' || item.tableKind === 'bed') {\n          const onWall = furnitureWallSnap(item, cx, cy, FURNITURE_WALL_SNAP_MM);\n          if (onWall) {\n            cx = onWall.x; cy = onWall.y;\n            if (onWall.rotationDeg !== lastRot) {\n              lastRot = onWall.rotationDeg;\n              el.style.transform = `rotate(${lastRot}deg)`;\n            }\n          } else {\n            // No wall here it fits on: at least none of it goes through one.\n            const a = furnitureAABB({ ...item, x: cx, y: cy, rotationDeg: lastRot });\n            cx = Math.max(bbox.minX + a.w / 2, Math.min(bbox.maxX - a.w / 2, cx));\n            cy = Math.max(bbox.minY + a.h / 2, Math.min(bbox.maxY - a.h / 2, cy));\n          }\n        }\n        lastX = cx; lastY = cy;\n        el.style.left = `${Math.round((cx - w / 2) * pxPerMm)}px`;\n        el.style.top  = `${Math.round((cy - d / 2) * pxPerMm)}px`;\n      },\n      onDragEnd() {\n        if (!didDrag) return;\n        item.x = lastX; item.y = lastY; item.rotationDeg = lastRot;\n        // A typed height was for where it stood, so it finds its own level again.\n        delete item.standHeightMm;\n        rerender();\n      }\n    });\n    renderHandles.push(drag);\n\n    el.addEventListener('contextmenu', e => {\n      e.preventDefault();\n      showContextMenu({\n        x: e.clientX, y: e.clientY,\n        items: [\n          { label: 'Rotate 90\u00B0',  action: () => rotateFurniture(item.id) },\n          { label: 'Free rotate', action: () => startFreeRotateFurniture(item.id, el) },\n          { label: 'Duplicate',   action: () => duplicateFurniture(item.id) },\n          { label: 'Delete',      action: () => deleteFurniture(item.id) }\n        ]\n      });\n    });\n\n    // Click-to-select: a short click (no drag) opens the Edit panel with the\n    // rotate / duplicate / delete buttons, so a tablet - which has no right\n    // click - can reach them (bug sheet #218). Same raw pointer wiring as a\n    // worktop item: onDragEnd doesn't fire for a sub-threshold drag.\n    let downX = 0, downY = 0, downActive = false, selectedAtDown = null;\n    // Noted now: the press itself clears the selection on its way up to the plan.\n    const onDown = e => { downX = e.clientX; downY = e.clientY; downActive = true; selectedAtDown = selectedItem; };\n    const onUp = e => {\n      if (!downActive) return;\n      downActive = false;\n      if (Math.hypot(e.clientX - downX, e.clientY - downY) >= 5) return;\n      // Pieces over each other (stacked shelves, a chair under a table): clicking\n      // the selected one again moves on to the next one at that spot.\n      const here = new Set(document.elementsFromPoint(e.clientX, e.clientY)\n        .map(n => n.closest && n.closest('[data-furniture-id]')).filter(Boolean).map(n => n.dataset.furnitureId));\n      const stack = furnitureItems.filter(f => here.has(f.id)).map(f => f.id);\n      const at = selectedAtDown?.kind === 'furniture' ? stack.indexOf(selectedAtDown.id) : -1;\n      selectItem({ kind: 'furniture', id: at >= 0 && stack.length > 1 ? stack[(at + 1) % stack.length] : item.id });\n    };\n    const onCancel = () => { downActive = false; };\n    el.addEventListener('pointerdown',   onDown);\n    el.addEventListener('pointerup',     onUp);\n    el.addEventListener('pointercancel', onCancel);\n    renderHandles.push({\n      destroy() {\n        el.removeEventListener('pointerdown',   onDown);\n        el.removeEventListener('pointerup',     onUp);\n        el.removeEventListener('pointercancel', onCancel);\n      }\n    });\n  }\n\n  function rotateFurniture(id) {\n    const fi = furnitureItems.find(f => f.id === id);\n    if (!fi) return;\n    const wasClear = !furnitureHitsUnit(fi, fi.x, fi.y, furnitureUnitBlockers());\n    fi.rotationDeg = ((fi.rotationDeg || 0) + 90) % 360;\n    if (wasClear) nudgeFurnitureClear(fi);\n    rerender();\n  }\n\n  // Free rotate: the item spins about its centre to follow the mouse.\n  // Move to set the angle, click to lock, Esc to cancel. The 2D footprint\n  // updates live; 3D syncs on commit/cancel via rerender().\n  function startFreeRotateFurniture(id, el) {\n    const fi = furnitureItems.find(f => f.id === id);\n    if (!fi || !el) return;\n    const rect = el.getBoundingClientRect();\n    const cx = rect.left + rect.width / 2;   // footprint centre (screen px) \u2014\n    const cy = rect.top  + rect.height / 2;  // stable: rotation is about centre\n    const startRot = fi.rotationDeg || 0;\n    const wasClear = !furnitureHitsUnit(fi, fi.x, fi.y, furnitureUnitBlockers());\n    let startMouseAngle = null;\n\n    function onMove(e) {\n      const a = Math.atan2(e.clientY - cy, e.clientX - cx) * 180 / Math.PI;\n      if (startMouseAngle === null) startMouseAngle = a;   // no jump on grab\n      let deg = startRot + (a - startMouseAngle);\n      deg = Math.round(((deg % 360) + 360) % 360);\n      fi.rotationDeg = deg;\n      el.style.transform = `rotate(${deg}deg)`;\n    }\n    function finish(commit) {\n      document.removeEventListener('mousemove', onMove, true);\n      document.removeEventListener('click', onClick, true);\n      document.removeEventListener('keydown', onKey, true);\n      if (!commit) fi.rotationDeg = startRot;   // Esc \u2192 revert\n      else if (wasClear) nudgeFurnitureClear(fi);\n      rerender();                               // sync 3D + redraw\n    }\n    function onClick(e) { e.preventDefault(); e.stopPropagation(); finish(true); }\n    function onKey(e) { if (e.key === 'Escape') { e.preventDefault(); finish(false); } }\n\n    document.addEventListener('mousemove', onMove, true);\n    document.addEventListener('keydown', onKey, true);\n    // Defer the click listener so the menu click that triggered this\n    // doesn't immediately commit.\n    setTimeout(() => document.addEventListener('click', onClick, true), 0);\n    designControlsHandle.setStatus('Free rotate: move to spin, click to set, Esc to cancel');\n  }\n\n  function deleteFurniture(id) {\n    furnitureItems = furnitureItems.filter(f => f.id !== id);\n    if (selectedItem?.kind === 'furniture' && selectedItem.id === id) selectItem(null);\n    rerender();\n  }\n\n  function duplicateFurniture(id) {\n    const src = furnitureItems.find(f => f.id === id);\n    if (!src) return;\n    // The copy keeps the original's rotation, so it needs the room its\n    // ROTATED footprint takes - a turned table is deep where it was wide.\n    const fp = furnitureAABB(src);\n    // Search outward from the original so the copy lands in free space\n    // beside it (the original itself is an obstacle).\n    const spot = (furniturePlacement(src) === 'wall' && wallSpotForFurniture(src.widthMm, src.depthMm, src.wallHeightMm, src))\n      || findFreeSpotForFurniture(fp.w, fp.h, src.x, src.y, null);\n    const copyId = `fur-${nextFurnitureItemId++}`;\n    furnitureItems.push({\n      id:          copyId,\n      furnitureId: src.furnitureId,\n      name:        src.name,\n      glbUrl:      src.glbUrl,\n      widthMm:     src.widthMm,\n      depthMm:     src.depthMm,\n      heightMm:    src.heightMm,\n      sizedMm:     src.sizedMm,\n      fitHeightMm: src.fitHeightMm,\n      productHandle: src.productHandle,\n      wallHeightMm: src.wallHeightMm,\n      standHeightMm: src.standHeightMm,\n      colourHex:   src.colourHex,\n      colourName:  src.colourName,\n      partColours: src.partColours,\n      tableKind:   src.tableKind,\n      x:           spot.x,\n      y:           spot.y,\n      rotationDeg: spot.rotationDeg ?? (src.rotationDeg || 0)\n    });\n    rerender();\n    if (selectedItem?.kind === 'furniture') selectItem({ kind: 'furniture', id: copyId });\n  }\n\n  // ---- Furniture free-space placement -----------------------------\n  // Find a footprint-sized spot that doesn't overlap cabinets, other\n  // furniture, or room features - EXCEPT beams + sloped ceilings, which\n  // are overhead and fine to sit under. Spirals outward from a preferred\n  // centre; falls back to the preferred centre if the room is packed.\n  function rectsOverlap(a, b) {\n    return a.x < b.x + b.w && a.x + a.w > b.x && a.y < b.y + b.h && a.y + a.h > b.y;\n  }\n  function furnitureAABB(f) {\n    const sz = furnitureSizeCache[f.furnitureId] || {};\n    const fw = f.widthMm || sz.w || 500;\n    const fh = f.depthMm || sz.d || 500;\n    const rad = ((f.rotationDeg || 0) * Math.PI) / 180;\n    const c = Math.abs(Math.cos(rad)), s = Math.abs(Math.sin(rad));\n    const aw = fw * c + fh * s, ah = fw * s + fh * c;   // rotation-aware AABB\n    return { x: f.x - aw / 2, y: f.y - ah / 2, w: aw, h: ah };\n  }\n  // What a stool, chair or table can't stand in: every unit on the floor, with\n  // its door faces, plus every panel it carries - end panels, posts, breakfast\n  // bar back panels, fillers. A free-placed panel is a unit of its own. Panels\n  // reach past a unit's footprint in ways only the drawing knows (a full-size\n  // end panel, a back panel on standoffs), so they are measured off the plan.\n  // Wall units pass overhead, and a worktop overhang isn't part of a unit, so\n  // furniture can go under both.\n  const FURNITURE_BLOCKING_PANELS = '.btk-kp-cabinet-end-panel, .btk-kp-cabinet-end-panel-post, .btk-kp-cabinet-end-panel-flat, .btk-kp-cabinet-back-panel, .btk-kp-cabinet-filler, .btk-kp-cabinet-media-panel';\n  function furnitureUnitBlockers() {\n    const floorUnits = cabinets.filter(c => !isWallMounted(c) && !isWorktopDresserCab(c));\n    const blockers = floorUnits.map(c => {\n      const a = getVisualFootprintAABB(c, c.x, c.y);\n      return { x: a.x, y: a.y, w: a.widthMm, h: a.depthMm };\n    });\n    const gridEl = currentGridEl, pxPerMm = lastGrid && lastGrid.pxPerMm;\n    if (!gridEl || !pxPerMm || !gridEl.offsetWidth) return blockers;\n    const floorIds = new Set(floorUnits.map(c => String(c.id)));\n    const g = gridEl.getBoundingClientRect();\n    const toMm = (g.width / gridEl.offsetWidth) * pxPerMm;   // screen px per mm, at this zoom\n    gridEl.querySelectorAll(FURNITURE_BLOCKING_PANELS).forEach(el => {\n      const owner = el.closest('.btk-kp-cabinet');\n      if (!owner || !floorIds.has(String(owner.dataset.cabinetId))) return;\n      const r = el.getBoundingClientRect();\n      if (!r.width || !r.height) return;\n      blockers.push({\n        x: (r.left - g.left - gridEl.clientLeft * (g.width / gridEl.offsetWidth)) / toMm,\n        y: (r.top  - g.top  - gridEl.clientTop  * (g.width / gridEl.offsetWidth)) / toMm,\n        w: r.width / toMm,\n        h: r.height / toMm\n      });\n    });\n    return blockers;\n  }\n  // Where a catalogue piece goes: 'floor' (stools, sofas, tables), 'surface'\n  // (a mug, vase or lamp: on whatever is under it) or 'wall' (a shelf). From the\n  // piece's Placement field on 3D Planner Furniture.\n  function furnitureEntry(f) {\n    return (Catalogue.getFurniture?.() || []).find(e => e.id === f.furnitureId) || null;\n  }\n  function furniturePlacement(f) {\n    return (f && f.furnitureId && furnitureEntry(f)?.placement) || 'floor';\n  }\n  function furnitureStandsOnItems() {\n    return furnitureItems.some(f => furniturePlacement(f) === 'surface');\n  }\n  const FURNITURE_WALL_HEIGHT_MM = 1400;   // underside of a shelf, above a worktop\n  const FURNITURE_WALL_HEIGHT_RANGE = [100, 2600];\n  const FURNITURE_WALL_SNAP_MM = 300;\n  // A wall piece's height from the floor, set in the Edit panel. Null for floor\n  // pieces. A surface piece (vase, lamp) stands on what's under it until a height\n  // is typed, so its box starts empty with that height showing faintly.\n  function furnitureWallHeight(f) {\n    if (furniturePlacement(f) === 'surface') {\n      const typed = f.standHeightMm != null;\n      return { mm: Math.round(typed ? f.standHeightMm : (f.elevationMm || 0)), min: 0, max: FURNITURE_WALL_HEIGHT_RANGE[1], auto: !typed };\n    }\n    // A piece with its own Height from floor box has it among its controls.\n    if (furniturePlacement(f) !== 'wall' || furnitureEntry(f)?.sizeRange?.fMin != null) return null;\n    return { mm: f.wallHeightMm || FURNITURE_WALL_HEIGHT_MM, min: FURNITURE_WALL_HEIGHT_RANGE[0], max: FURNITURE_WALL_HEIGHT_RANGE[1] };\n  }\n  // Where a wall piece at this centre would sit with its back flat against the\n  // nearest wall, turned to face the room: chimney breasts and other pillars\n  // count, as do angled walls. Null if no wall long enough for it is within\n  // maxGapMm of its back. onlyRotationDeg keeps it to walls facing that way.\n  // Its back is the model's -Z, the top of the plan at rotation 0.\n  function furnitureWallSnap(f, cx, cy, maxGapMm, onlyRotationDeg = null) {\n    const w = f.widthMm || 500, d = f.depthMm || 500;\n    const verts = room.vertices || [];\n    const pillars = (roomConfig?.perimeterItems || []).map(p => ({ p, walls: getPillarSnapWalls([p]) })).filter(o => o.walls.length);\n    const inPillar = (x, y) => pillars.some(({ p, walls }) => x > p.x && x < p.x + p.widthMm && y > p.y && y < p.y + p.depthMm\n      && walls.every(wall => {\n        const len = Math.hypot(wall.to.x - wall.from.x, wall.to.y - wall.from.y) || 1;\n        return (x - wall.from.x) * -(wall.to.y - wall.from.y) / len + (y - wall.from.y) * (wall.to.x - wall.from.x) / len < 0;\n      }));\n    let best = null;\n    const consider = (wall, isPillar) => {\n      const ex = wall.to.x - wall.from.x, ey = wall.to.y - wall.from.y;\n      const len = Math.hypot(ex, ey);\n      if (len < w) return;\n      const ux = ex / len, uy = ey / len;\n      // The room is on the right of a wall's from-to, a pillar's as well.\n      let nx = -uy, ny = ux;\n      if (!isPillar && !pointInRoomPolygon(wall.from.x + ex / 2 + nx * 5, wall.from.y + ey / 2 + ny * 5, verts)) {\n        nx = -nx; ny = -ny;\n      }\n      const along = (cx - wall.from.x) * ux + (cy - wall.from.y) * uy;\n      if (along < -50 || along > len + 50) return;\n      const dist = (cx - wall.from.x) * nx + (cy - wall.from.y) * ny;\n      // A little behind a wall counts: a drag can push the piece past it.\n      if (dist < -FURNITURE_WALL_SNAP_MM) return;\n      const gap = Math.abs(dist - d / 2);\n      if (gap > maxGapMm || (best && gap >= best.gap)) return;\n      const rotationDeg = (Math.round(Math.atan2(-nx, ny) * 180 / Math.PI * 100) / 100 + 360) % 360;\n      if (onlyRotationDeg != null && rotationDeg !== onlyRotationDeg) return;\n      // Its whole length on the wall, so it can't run through a corner, and the\n      // nearest place along it that is clear of a chimney breast or column.\n      const lo = w / 2, hi = len - w / 2;\n      const start = Math.max(lo, Math.min(hi, along));\n      const clearAt = (at) => {\n        for (let s = -w / 2; s <= w / 2 + 1; s += Math.min(50, w)) {\n          for (const off of [5, d - 5]) {\n            if (inPillar(wall.from.x + ux * (at + s) + nx * off, wall.from.y + uy * (at + s) + ny * off)) return false;\n          }\n        }\n        return true;\n      };\n      let at = null;\n      for (let step = 0; at == null && step * 10 <= len; step++) {\n        const a = start - step * 10, b = start + step * 10;\n        if (a >= lo && clearAt(a)) at = a;\n        else if (b <= hi && clearAt(b)) at = b;\n      }\n      if (at == null) return;\n      best = { gap, x: wall.from.x + ux * at + nx * d / 2, y: wall.from.y + uy * at + ny * d / 2, rotationDeg };\n    };\n    getWalls(room).forEach(wall => consider(wall, false));\n    getPillarSnapWalls(roomConfig?.perimeterItems).forEach(wall => consider(wall, true));\n    return best;\n  }\n  function furnitureIsOnWall(f) {\n    const s = furniturePlacement(f) === 'wall' ? furnitureWallSnap(f, f.x, f.y, 5) : null;\n    return !!s && Math.hypot(s.x - f.x, s.y - f.y) < 5 && s.rotationDeg === ((f.rotationDeg || 0) % 360);\n  }\n  // A spot on the wall nearest `from`, along it from there past any piece\n  // already hung at this height, for a new shelf or a copy of one. Null if\n  // that wall has no room, so it isn't laid exactly over another and hidden.\n  function wallSpotForFurniture(widthMm, depthMm, heightMm, from) {\n    const probe = { widthMm, depthMm };\n    const first = furnitureWallSnap(probe, from.x, from.y, Infinity);\n    if (!first) return null;\n    const height = heightMm || FURNITURE_WALL_HEIGHT_MM;\n    const free = (s) => {\n      const box = furnitureAABB({ ...probe, x: s.x, y: s.y, rotationDeg: s.rotationDeg });\n      return !furnitureItems.some(f => furniturePlacement(f) === 'wall' && (f.wallHeightMm || FURNITURE_WALL_HEIGHT_MM) === height && rectsOverlap(box, furnitureAABB(f)));\n    };\n    if (free(first)) return first;\n    const rad = first.rotationDeg * Math.PI / 180;\n    for (let i = 1; i <= 20; i++) {\n      const off = (i % 2 ? 1 : -1) * Math.ceil(i / 2) * ((widthMm || 500) + 100);\n      const s = furnitureWallSnap(probe, first.x + Math.cos(rad) * off, first.y + Math.sin(rad) * off, Infinity, first.rotationDeg);\n      if (s && free(s)) return s;\n    }\n    return null;\n  }\n  // Is this point on the piece, whatever way it is turned?\n  function furnitureCovers(f, x, y) {\n    const rad = ((f.rotationDeg || 0) * Math.PI) / 180;\n    const dx = x - f.x, dy = y - f.y;\n    return Math.abs(dx * Math.cos(rad) + dy * Math.sin(rad)) <= (f.widthMm || 500) / 2\n      && Math.abs(-dx * Math.sin(rad) + dy * Math.cos(rad)) <= (f.depthMm || 500) / 2;\n  }\n  // A change from the Edit panel's controls (mountFurnitureControls).\n  function updateFurniture(id, patch) {\n    const f = furnitureItems.find(x => x.id === id);\n    if (!f) return;\n    const wasOnWall = furnitureIsOnWall(f);\n    Object.assign(f, patch);\n    if (patch.sizedMm) {\n      f.widthMm = patch.sizedMm.w;\n      f.depthMm = patch.sizedMm.d;\n      if (patch.sizedMm.h) f.heightMm = patch.sizedMm.h;\n    } else if (patch.furnitureId && furnitureSizeCache[patch.furnitureId]) {\n      const sz = furnitureSizeCache[patch.furnitureId];\n      f.widthMm = sz.w; f.depthMm = sz.d; f.heightMm = sz.h;\n    }\n    // A new size grows out from its middle: keep its back on the wall.\n    if (wasOnWall) {\n      const s = furnitureWallSnap(f, f.x, f.y, Infinity, (f.rotationDeg || 0) % 360);\n      if (s) { f.x = s.x; f.y = s.y; }\n    }\n    rerender();\n    if (selectedItem?.kind === 'furniture' && selectedItem.id === id) selectItem({ kind: 'furniture', id });\n  }\n  function setFurnitureWallHeight(id, value) {\n    const f = furnitureItems.find(x => x.id === id);\n    const mm = Math.round(Number(value));\n    if (f && furniturePlacement(f) === 'surface') {\n      if (String(value).trim() === '' || !Number.isFinite(mm) || mm < 0) delete f.standHeightMm;\n      else f.standHeightMm = Math.min(FURNITURE_WALL_HEIGHT_RANGE[1], mm);\n      rerender();\n      if (selectedItem?.kind === 'furniture') selectItem({ kind: 'furniture', id });\n      return;\n    }\n    if (!f || !Number.isFinite(mm) || mm <= 0) { rerender(); return; }\n    f.wallHeightMm = Math.min(FURNITURE_WALL_HEIGHT_RANGE[1], Math.max(FURNITURE_WALL_HEIGHT_RANGE[0], mm));\n    rerender();\n    if (selectedItem?.kind === 'furniture') selectItem({ kind: 'furniture', id });\n  }\n  // How high each piece stands. A surface piece stands on a shelf under its\n  // centre (the top one if they're stacked), else the worktop or table, else the\n  // floor, so dragging it onto a worktop lifts it. A height typed in the Edit\n  // panel beats all of them.\n  function settleFurnitureHeights(slabs) {\n    for (const f of furnitureItems) {\n      if (!f.fitHeightMm && f.furnitureId) f.fitHeightMm = furnitureEntry(f)?.modelHeightMm || undefined;\n      if (!f.colourHex && f.furnitureId) {\n        const first = furnitureColours(furnitureEntry(f))[0];\n        if (first) { f.colourHex = first.hex; f.colourName = first.name; }\n      }\n      const placement = furniturePlacement(f);\n      if (placement === 'wall') { f.elevationMm = f.wallHeightMm || FURNITURE_WALL_HEIGHT_MM; continue; }\n      if (placement !== 'surface') { if (f.elevationMm) f.elevationMm = 0; continue; }\n      if (f.standHeightMm != null) { f.elevationMm = f.standHeightMm; continue; }\n      let shelfTop = 0;\n      for (const t of furnitureItems) {\n        if (t === f || furniturePlacement(t) !== 'wall' || !furnitureCovers(t, f.x, f.y)) continue;\n        const pieceHeight = t.sizedMm?.h || t.heightMm || furnitureEntry(t)?.sizeRange?.h || 30;\n        shelfTop = Math.max(shelfTop, (t.wallHeightMm || FURNITURE_WALL_HEIGHT_MM) + pieceHeight);\n      }\n      if (shelfTop) { f.elevationMm = shelfTop; continue; }\n      let top = 0;\n      for (const s of slabs || []) {\n        if (!s.polygon || !pointInRoomPolygon(f.x, f.y, s.polygon)) continue;\n        top = Math.max(top, (s.restMm || 0) + (s.thicknessMm || 0));\n      }\n      for (const t of furnitureItems) {\n        if (t === f || !t.heightMm || furnitureEntry(t)?.group !== 'Tables') continue;\n        const a = furnitureAABB(t);\n        if (f.x >= a.x && f.x <= a.x + a.w && f.y >= a.y && f.y <= a.y + a.h) top = Math.max(top, t.heightMm);\n      }\n      f.elevationMm = top;\n    }\n  }\n  // A new surface piece lands on a worktop, where it is going, when the plan\n  // has one: the middle of the longest piece of worktop.\n  function worktopSpotForFurniture() {\n    let best = null;\n    for (const s of buildWorktops()) {\n      const xs = (s.polygon || []).map(p => p.x), ys = (s.polygon || []).map(p => p.y);\n      if (xs.length < 3) continue;\n      const cx = (Math.min(...xs) + Math.max(...xs)) / 2, cy = (Math.min(...ys) + Math.max(...ys)) / 2;\n      const len = Math.max(Math.max(...xs) - Math.min(...xs), Math.max(...ys) - Math.min(...ys));\n      if (pointInRoomPolygon(cx, cy, s.polygon) && (!best || len > best.len)) {\n        best = { x: cx, y: cy, len, poly: s.polygon, alongX: Math.max(...xs) - Math.min(...xs) >= Math.max(...ys) - Math.min(...ys) };\n      }\n    }\n    if (!best) return null;\n    // Along the worktop from the middle, past anything already there, so one\n    // piece doesn't land on top of another and hide it.\n    const taken = (x, y) => furnitureItems.some(f => Math.hypot(f.x - x, f.y - y) < 150);\n    for (let i = 0; i <= 40; i++) {\n      const off = (i % 2 ? 1 : -1) * Math.ceil(i / 2) * 200;\n      const x = best.x + (best.alongX ? off : 0), y = best.y + (best.alongX ? 0 : off);\n      if (pointInRoomPolygon(x, y, best.poly) && !taken(x, y)) return { x, y };\n    }\n    return best;\n  }\n  function furnitureHitsUnit(f, cx, cy, blockers) {\n    if (furniturePlacement(f) !== 'floor' || !f.furnitureId) return false;\n    const a = furnitureAABB({ ...f, x: cx, y: cy });\n    return blockers.some(o => rectsOverlap(a, o));\n  }\n  // A dragged piece stops at a unit and slides along it: small steps, so a\n  // quick drag can't jump right over a unit, each axis on its own.\n  function slideFurniture(f, fromX, fromY, toX, toY, blockers) {\n    const steps = Math.ceil(Math.max(Math.abs(toX - fromX), Math.abs(toY - fromY)) / 5);\n    let x = fromX, y = fromY;\n    for (let i = 1; i <= steps; i++) {\n      const nx = fromX + (toX - fromX) * i / steps;\n      const ny = fromY + (toY - fromY) * i / steps;\n      if (!furnitureHitsUnit(f, nx, y, blockers)) x = nx;\n      if (!furnitureHitsUnit(f, x, ny, blockers)) y = ny;\n    }\n    return [x, y];\n  }\n  // Turning a piece beside a unit can swing it into the unit: move it the\n  // shortest way back out.\n  function nudgeFurnitureClear(f) {\n    const blockers = furnitureUnitBlockers();\n    if (!furnitureHitsUnit(f, f.x, f.y, blockers)) return;\n    const bbox = getBoundingBox(room);\n    const a0 = furnitureAABB(f);\n    const inRoom = (cx, cy) => cx - a0.w / 2 >= bbox.minX && cx + a0.w / 2 <= bbox.maxX && cy - a0.h / 2 >= bbox.minY && cy + a0.h / 2 <= bbox.maxY;\n    const step = 10;\n    for (let r = 1; r <= 150; r++) {\n      let best = null;\n      for (let dx = -r; dx <= r; dx++) {\n        for (let dy = -r; dy <= r; dy++) {\n          if (Math.abs(dx) !== r && Math.abs(dy) !== r) continue;\n          const cx = f.x + dx * step, cy = f.y + dy * step;\n          if (!inRoom(cx, cy) || furnitureHitsUnit(f, cx, cy, blockers)) continue;\n          const dist = Math.hypot(dx, dy);\n          if (!best || dist < best.dist) best = { cx, cy, dist };\n        }\n      }\n      if (best) { f.x = best.cx; f.y = best.cy; return; }\n    }\n  }\n  function furnitureObstacles(excludeId) {\n    const obs = [];\n    cabinets.forEach(c => {\n      const a = getVisualFootprintAABB(c, c.x, c.y);\n      obs.push({ x: a.x, y: a.y, w: a.widthMm, h: a.depthMm });\n    });\n    obs.push(...furnitureUnitBlockers());\n    furnitureItems.forEach(f => { if (f.id !== excludeId) obs.push(furnitureAABB(f)); });\n    (roomConfig.perimeterItems || []).forEach(p => {\n      if (p.type === 'beam' || p.type === 'sloped-ceiling'\n       || p.type === 'vaulted-ceiling') return;                       // overhead - ignore\n      obs.push({ x: p.x, y: p.y, w: p.widthMm || p.w || 0, h: p.depthMm || p.d || 0 });\n    });\n    return obs;\n  }\n  function findFreeSpotForFurniture(w, h, preferCx, preferCy, excludeId) {\n    const bbox = getBoundingBox(room);\n    const obs  = furnitureObstacles(excludeId);\n    // First choice: the whole footprint in the room, not just its centre - a\n    // duplicated table landed half through a wall (bug sheet #218, 2026-10-19).\n    const verts = (room && room.vertices) || [];\n    const inside = (x, y) => (verts.length >= 3)\n      ? pointInRoomPolygon(x, y, verts)\n      : (x >= bbox.minX && x <= bbox.maxX && y >= bbox.minY && y <= bbox.maxY);\n    const clear = (a) => !obs.some(o => rectsOverlap(a, o));\n    const whollyInside = (cx, cy) => {\n      const a = { x: cx - w / 2, y: cy - h / 2, w, h };\n      return inside(a.x, a.y) && inside(a.x + w, a.y) && inside(a.x + w, a.y + h) && inside(a.x, a.y + h) && clear(a);\n    };\n    // Fallback, the old rule: its centre in the room and clear of everything\n    // else - better over a wall line than stacked on the original.\n    const centreInside = (cx, cy) => {\n      if (cx < bbox.minX || cx > bbox.maxX || cy < bbox.minY || cy > bbox.maxY) return false;\n      return clear({ x: cx - w / 2, y: cy - h / 2, w, h });\n    };\n    // 50mm rings out to the far side of the room. A step scaled to the item\n    // (0.6 of its short side) stepped straight over the narrow gap a big\n    // table fits in.\n    const step = 50;\n    const maxR = Math.ceil(Math.max(bbox.maxX - bbox.minX, bbox.maxY - bbox.minY) / step) + 1;\n    for (const fits of [whollyInside, centreInside]) {\n      if (fits(preferCx, preferCy)) return { x: preferCx, y: preferCy };\n      for (let r = 1; r <= maxR; r++) {\n        for (let dx = -r; dx <= r; dx++) {\n          for (let dy = -r; dy <= r; dy++) {\n            if (Math.abs(dx) !== r && Math.abs(dy) !== r) continue;   // ring perimeter only\n            const cx = preferCx + dx * step, cy = preferCy + dy * step;\n            if (fits(cx, cy)) return { x: cx, y: cy };\n          }\n        }\n      }\n    }\n    return { x: preferCx, y: preferCy };   // room packed - overlap as a last resort\n  }\n\n  // Put an upright box back upright. A quarter-turn on a plain pillar or nib\n  // is the same shape with its width and depth swapped, and half a turn is the\n  // same shape outright - so this moves nothing, it only clears the flag that\n  // was making the pillar invisible. Corner blocks are left alone: their cut\n  // is described against their own axes, so turning one is not a no-op.\n  function normaliseStructureRotations() {\n    let changed = false;\n    for (const it of (roomConfig.perimeterItems || [])) {\n      if (!it || it.cornerCut) continue;\n      if (it.type !== 'column' && it.type !== 'wall') continue;\n      const r = (((it.rotationDeg || 0) % 360) + 360) % 360;\n      if (r < 0.5) continue;\n      if (Math.abs(r - 180) < 0.5) {\n        it.rotationDeg = 0;\n        changed = true;\n      } else if (Math.abs(r - 90) < 0.5 || Math.abs(r - 270) < 0.5) {\n        const cx = it.x + (it.widthMm || 0) / 2;\n        const cy = it.y + (it.depthMm || 0) / 2;\n        const w = it.depthMm, d = it.widthMm;   // a quarter turn swaps them\n        it.widthMm = w; it.depthMm = d;\n        it.x = cx - w / 2;\n        it.y = cy - d / 2;\n        it.rotationDeg = 0;\n        changed = true;\n      }\n    }\n    return changed;\n  }\n\n  // Which of a free-standing pillar's two runs a click landed on, as the row\n  // key its panel uses - or null for the hollow middle, which still means the\n  // pillar as a whole.\n  //\n  // Read off the element's own rectangle rather than by adding hit shapes over\n  // the faces: those would sit in the wall-hit overlay ABOVE the pillar, and\n  // would then swallow the drag that starts on its edge - which for a 100mm nib\n  // is the whole of it. Doing it here, the same pointer that selects is still\n  // the one that drags.\n  const RUN_EDGE_MM = 100;          // the pillar's own wall thickness\n  function structureRunKeyAt(item, e, el) {\n    if (!item || item.cornerCut || item.pillarCorner) return null;\n    if (item.type !== 'column' && item.type !== 'wall') return null;\n    // An angled nib's rectangle is not its footprint, so don't guess - the\n    // click just means the pillar, as it always did.\n    if (Math.abs(item.rotationDeg || 0) > 0.5) return null;\n    const r = el.getBoundingClientRect();\n    if (!r.width || !r.height) return null;\n    const w = item.widthMm || 0, d = item.depthMm || 0;\n    const fx = (e.clientX - r.left) / r.width;\n    const fy = (e.clientY - r.top)  / r.height;\n    if (fx < 0 || fx > 1 || fy < 0 || fy > 1) return null;\n    // Distance in mm from the click to each of the four faces.\n    const top = fy * d, bottom = (1 - fy) * d;\n    const left = fx * w, right = (1 - fx) * w;\n    const nearest = Math.min(top, bottom, left, right);\n    if (nearest > RUN_EDGE_MM) return null;         // the hollow middle\n    // Run 1 rides the width faces (top / bottom), run 2 the depth faces.\n    return (nearest === top || nearest === bottom) ? 'feat-1' : 'feat-2';\n  }\n\n  // Put every nested corner back on the corner its parent currently makes.\n  //\n  // The slots are derived from the parent, so they move the moment the parent\n  // is resized or dragged - but the child's own x / y does not, and nothing was\n  // putting it back. It stayed where it was while the corner it belonged to\n  // walked off, which is how a splay ended up floating in the middle of the\n  function wirePerimeterItem(item, el, pxPerMm, grid) {\n    // Room features (step block / beam / sloped ceiling / free block)\n    // are draggable + clickable in Room Setup ONLY - that's where the\n    // user composes the room itself. In later stages they render but\n    // are inert so accidental clicks during cabinet work don't pull\n    // the side panel away from the cabinet you're editing.\n    // Pillars and internal walls join them: they now carry their own panel\n    // (width / length / distance from each wall), so they have to be\n    // selectable on the plan rather than only inside the Room Shape preview.\n    // One standing against a wall CLICKS as that wall's section (the wall panel\n    // lists it as one), but it still drags from here - its hit polygon is\n    // click-through for exactly that reason. A free-standing one has no polygon\n    // over it and both clicks and drags as itself.\n    const ROOM_FEATURE_TYPES = ['step-block', 'beam', 'sloped-ceiling', 'vaulted-ceiling',\n                                'free-block', 'cooker-alcove', 'boiler',\n                                'consumer-unit', 'water-tank', 'radiator', 'electrical-point', 'stopcock'];\n    const STRUCTURE_TYPES    = ['column', 'wall'];\n    const isRoomFeature = ROOM_FEATURE_TYPES.includes(item.type);\n    // Once it stands against a room wall it belongs to that wall's panel - it\n    // is one of its sections - so the body sticking into the room must not open\n    // a competing panel of its own. Asking wallSegments is the same test the\n    // wall panel itself uses, so the two can never disagree about which items\n    // it has claimed.\n    // ...and only in ROOM SETUP. A pillar or an internal wall is part of the\n    // room's shape, so it is set up where the room is; once units are going in\n    // it is something to work around, and a stray click on one pulls the panel\n    // away from the cabinet being placed. The same rule its DRAG follows, and\n    // the same one the wall hit polygons follow, so the three never disagree\n    // about when the room is being edited.\n    const isStructureType = STRUCTURE_TYPES.includes(item.type);\n    // WHICH wall section has claimed this item, if any - { wallIndex, segKey }.\n    // Was a boolean that switched the element off entirely, which is why a\n    // pillar could not be MOVED once it stood against a wall: claimed \u2192 no\n    // pointer events and no drag handler. The claim now only decides what a\n    // CLICK does (it opens that wall's panel, where the pillar is one of the\n    // sections - see the pointerup handler); dragging stays available, because\n    // sliding a pillar along the wall is the whole point of having it on the\n    // plan. Its hit polygon is made click-through to match (renderWallHits).\n    const wallClaim = (() => {\n      try {\n        const walls = getWalls(room);\n        for (let wi = 0; wi < walls.length; wi++) {\n          const seg = wallSegments(wi).find(s => s.kind === 'feature' && s.id === item.id);\n          if (seg) return { wallIndex: wi, segKey: seg.key, moveable: !!seg.moveable };\n        }\n      } catch (e) { console.error('[BTK structureHit]', e); }\n      return null;\n    })();\n    // `moveable` is the wall section's own word for this (see wallSegments): a\n    // corner treatment or a corner-anchored pillar is pinned to the corner it\n    // exists to make, so the wall that claims it owns it entirely - the old\n    // rule. A pillar or nib standing mid-wall \"slides freely\", so it stays\n    // interactive and draggable.\n    const isStructure = isStructureType\n      && currentStep === 'room-setup'\n      && !(wallClaim && !wallClaim.moveable);\n    if (!isRoomFeature && !isStructure) {\n      el.style.pointerEvents = 'none';\n      return;\n    }\n    // Cooker alcoves stay clickable in EVERY stage so the user can\n    // re-open their settings (colour, dims, \"From left wall\") from the\n    // side panel after they've moved on to cabinets / worktops. Drag,\n    // rotate and context-menu are still gated to room-setup so we\n    // don't change their footprint by accident during later stages.\n    // Structure is Room Setup only, in every sense - see the note above.\n    // Structure drags like any other room feature, in Room Setup only. It was\n    // held still while pillars and internal walls were placed in the Room Shape\n    // preview and only ever positioned by their measurements; now they are\n    // added straight onto the plan, dragging one into place is the whole point.\n    const dragEnabled = currentStep === 'room-setup' && !isRoomLocked();\n    if (!dragEnabled && item.type !== 'cooker-alcove' && !isStructure) {\n      el.style.pointerEvents = 'none';\n      return;\n    }\n    let lastX = null, lastY = null;\n    let didDrag = false;\n    // dragSpec is a lightweight mirror of the item passed through\n    // snapAndClamp / applyTouchClasses / snapToAngledWall while the\n    // user is dragging. Include `type` so downstream code can tell\n    // which kind of item this is - applyTouchClasses skips wall-\n    // touch / hollow classes for room features, snapAndClamp lets\n    // floor features pass through beams, etc.\n    const dragSpec = {\n      type:        item.type,\n      id:          item.id,\n      widthMm:     item.widthMm,\n      depthMm:     item.depthMm,\n      rotationDeg: item.rotationDeg || 0,\n      customFit:   item.ignoreClash ? { ignoreClash: true } : null\n    };\n\n    const drag = dragEnabled ? makeDraggable(el, {\n      pxPerMm,\n      getZoom: () => view2d.zoom,\n      onDragMove({ dxMm, dyMm }) {\n        if (Math.hypot(dxMm, dyMm) * pxPerMm > 5) didDrag = true;\n        const rawX = item.x + dxMm;\n        const rawY = item.y + dyMm;\n\n        // Beams hold their manual rotation - they're wall-to-wall\n        // along the user-chosen axis and shouldn't auto-rotate to 0\n        // just because no wall snap is found mid-drag. Every other\n        // feature (including cooker alcoves) auto-rotates to match the\n        // wall it's being dragged towards so the UX mirrors how\n        // cabinets snap to walls.\n        // A beam runs ALONG a wall, not against it: it is a span, so the\n        // angle that matters is the wall's own, not the facing rotation every\n        // other feature takes. It used to hold whatever rotation it was given\n        // and stay square while the wall it was laid against ran at 22 degrees.\n        // Handled on release rather than during the drag - see beamWallAngle -\n        // so it does not swing about while being carried across the room.\n        const skipAutoRotate = spansRoom(item);\n        // A pillar or internal wall has NO FRONT. Turning one to face the wall\n        // it is dragged towards says nothing its width and depth do not - but\n        // rotationDeg is read downstream as \"this backs onto an ANGLED wall\",\n        // which is what it meant while pillars could only be placed from the\n        // Room Shape preview. Dragging them on the plan started feeding them\n        // 90 / 180 / 270 from the cabinet rule, and a pillar marked angled\n        // hides its own div expecting the walls SVG to draw it, while the SVG\n        // only draws a rotated pillar that touches the boundary - so a pillar\n        // dragged past a wall and back into the room was drawn by nobody.\n        // snapToAngledWall still applies: sitting a nib on a diagonal wall is\n        // a real angle, and the only one a pillar should ever carry.\n        const skipAxisRotate = skipAutoRotate\n          || item.type === 'column' || item.type === 'wall';\n        // For slope / step / free-block: use the same proximity-based\n        // smooth-rotation cabinets use, so the user sees the item\n        // turn to face the wall when its corner enters the 50 mm\n        // snap zone. snapToAngledWall handles 45\u00B0 splays; the regular\n        // axis walls go through computeAutoRotation.\n        let target = dragSpec.rotationDeg || 0;\n        let snappedX = rawX;\n        let snappedY = rawY;\n        if (!skipAutoRotate) {\n          const angledSnap = snapToAngledWall(dragSpec, rawX, rawY, room, ROTATION_PROXIMITY_MM, getPillarSnapWalls(roomConfig.perimeterItems));\n          if (angledSnap) {\n            target = angledSnap.rotation;\n            snappedX = angledSnap.x;\n            snappedY = angledSnap.y;\n          } else if (!skipAxisRotate) {\n            const axisRot = computeAutoRotation(dragSpec, rawX, rawY, room, ROTATION_PROXIMITY_MM, getPillarSnapWalls(roomConfig.perimeterItems));\n            if (axisRot !== null) target = axisRot;\n          }\n        }\n        if (Math.abs((dragSpec.rotationDeg || 0) - target) > ROTATION_EPSILON_DEG) {\n          dragSpec.rotationDeg = target;\n          el.style.transform = `rotate(${target}deg)`;\n        }\n\n        const otherItems = (roomConfig.perimeterItems || []).filter(it => it.id !== item.id);\n        let { x, y } = snapAndClamp(dragSpec, snappedX, snappedY, room, otherItems, otherItems);\n\n        // A beam is re-cut AS IT MOVES. It spans the room, so its length is\n        // not a property of the beam at all - it is a reading of the room\n        // where the beam currently lies, and the room changes width as you\n        // carry it. Waiting for the release meant the beam kept the old\n        // length the whole way across and then snapped to a new one, which\n        // read as \"it will not resize, and it jumps\".\n        //\n        // Driven from the CENTRE the pointer is at, not from the corner: the\n        // corner moves whenever the length changes, so a corner-based drag\n        // would shove the beam sideways every time the room narrowed.\n        if (spansRoom(item)) {\n          const fit = fitBeamToRoom(\n            dragSpec,\n            item.x + (item.widthMm || 0) / 2 + dxMm,\n            item.y + (item.depthMm || 0) / 2 + dyMm\n          );\n          if (fit) {\n            dragSpec.widthMm    = fit.widthMm;\n            dragSpec.rotationDeg = fit.rotationDeg;\n            x = fit.x; y = fit.y;\n            el.style.width     = `${Math.round(fit.widthMm * pxPerMm)}px`;\n            el.style.transform = `rotate(${fit.rotationDeg}deg)`;\n          }\n        }\n        lastX = x; lastY = y;\n        el.style.left = `${Math.round(x * pxPerMm)}px`;\n        el.style.top  = `${Math.round(y * pxPerMm)}px`;\n\n        applyTouchClasses(el, {\n          type:        dragSpec.type,\n          x, y,\n          widthMm:     dragSpec.widthMm,\n          depthMm:     dragSpec.depthMm,\n          rotationDeg: dragSpec.rotationDeg\n        }, room);\n\n        // Push the live pillar position into the grid SVG so the\n        // wall notch and inner-face bands track the drag. Same\n        // pattern as the openings drag \u2192 grid.updateOpenings.\n        const liveItems = (roomConfig.perimeterItems || []).map(it =>\n          it.id === item.id\n            ? { ...it, x, y, rotationDeg: dragSpec.rotationDeg || 0 }\n            : it\n        );\n        grid.updatePerimeterItems(liveItems);\n        refreshDims({ perimeterItems: liveItems });\n        // A selected Other Item's size and wall distances follow it (row 28).\n        refreshRoomItemMeasure(liveItems.find(it => it.id === item.id));\n      },\n      onDragEnd() {\n        if (didDrag && lastX !== null) {\n          item.x = lastX;\n          item.y = lastY;\n          item.rotationDeg = dragSpec.rotationDeg || 0;\n          // The drag already fitted it; keep what is on screen rather than\n          // measuring again from a different centre and moving it once more.\n          if (spansRoom(item)) {\n            item.widthMm    = dragSpec.widthMm;\n            item.rotationDeg = dragSpec.rotationDeg || 0;\n          }\n          // On a drawn room, a pillar dropped square against a wall becomes\n          // part of the outline (mergePillarIntoDrawnRoom redraws).\n          if (item.type === 'column' && mergePillarIntoDrawnRoom(item.id)) {\n            roomShapeHandle.refresh();\n            return;\n          }\n          // Full re-render so the pillar's mini-dimensions and the\n          // wall dimension tiers all reconcile to the new position.\n          rerender();\n          roomShapeHandle.refresh();\n        } else if (lastX !== null) {\n          // Too small to count as a move, but the preview redrew it and the\n          // dims - put them back (see the unit drag's onDragEnd), after the\n          // click that selects it.\n          setTimeout(() => rerender(), 0);\n        }\n      }\n    }) : null;\n    if (drag) renderHandles.push(drag);\n\n    let downX = 0, downY = 0, downActive = false;\n    const onDown = e => { downX = e.clientX; downY = e.clientY; downActive = true; };\n    const onUp = e => {\n      if (!downActive) return;\n      downActive = false;\n      if (Math.hypot(e.clientX - downX, e.clientY - downY) < 5) {\n        // A pillar / internal wall standing against a room wall is one of that\n        // wall's SECTIONS, so a click opens the WALL's panel with that row -\n        // exactly what the wall's hit polygon used to do before it was made\n        // click-through so the pillar could be dragged. Only the click defers;\n        // the drag above is the item's own.\n        if (isStructureType && wallClaim) {\n          selectItem({ kind: 'wall', wallIndex: wallClaim.wallIndex, segKey: wallClaim.segKey });\n          requestAnimationFrame(() => {\n            try { showWallSegmentSpan(wallClaim.wallIndex, wallClaim.segKey); } catch (_) {}\n          });\n          return;\n        }\n        const segKey = structureRunKeyAt(item, e, el);\n        selectItem({ kind: 'feature', id: item.id, segKey });\n        // Match the plan to the row that just opened - the black band on that\n        // run's two faces, and its ends measured out to the room walls.\n        showFeatureRun(item.id, segKey ? Number(segKey.split('-')[1]) : null);\n      }\n    };\n    const onCancel = () => { downActive = false; };\n    el.addEventListener('pointerdown',   onDown);\n    el.addEventListener('pointerup',     onUp);\n    el.addEventListener('pointercancel', onCancel);\n    renderHandles.push({\n      destroy() {\n        el.removeEventListener('pointerdown',   onDown);\n        el.removeEventListener('pointerup',     onUp);\n        el.removeEventListener('pointercancel', onCancel);\n      }\n    });\n\n    if (dragEnabled) {\n      const onCtx = e => {\n        e.preventDefault();\n        showContextMenu({\n          x: e.clientX, y: e.clientY,\n          items: [\n            { label: 'Rotate 90\u00B0', action: () => rotatePerimeterItem(item) },\n            { label: 'Delete',     action: () => handleRemovePerimeterItem(item.id) }\n          ]\n        });\n      };\n      el.addEventListener('contextmenu', onCtx);\n      renderHandles.push({ destroy() { el.removeEventListener('contextmenu', onCtx); } });\n    }\n  }\n\n  function rotatePerimeterItem(item) {\n    // Cooker alcove: keep widthMm / depthMm AS-IS - they're tied to\n    // leftColumnMm + middleMm + rightColumnMm. Just bump rotationDeg\n    // by 90\u00B0 and re-clamp the position. The 2D renderer / 3D builder\n    // use rotationDeg to draw the alcove turned 90\u00B0 / 180\u00B0 / 270\u00B0.\n    if (item.type === 'cooker-alcove') {\n      item.rotationDeg = (((item.rotationDeg || 0) + 90) % 360 + 360) % 360;\n      const others = (roomConfig.perimeterItems || []).filter(it => it.id !== item.id);\n      const { x, y } = snapAndClamp(\n        { widthMm: item.widthMm, depthMm: item.depthMm, rotationDeg: item.rotationDeg },\n        item.x, item.y, room, others, others\n      );\n      item.x = x;\n      item.y = y;\n      rerender();\n      return;\n    }\n    // Beams stretch wall-to-wall, so on rotate we DON'T just swap\n    // dimensions - we set widthMm to the room's perpendicular axis\n    // length and re-centre the beam on it. Result: rotating a beam\n    // flips which wall pair it spans (horizontal \u2194 vertical) and\n    // it always reaches both walls.\n    if (spansRoom(item)) {\n      // Turn about where it IS, and re-measure the room there. Read the\n      // centre before anything changes - the old code sized the beam from the\n      // room rectangle first and then worked out where to put it, which is\n      // what left it hanging out of both ends of a room with an angled wall.\n      const cx = item.x + (item.widthMm || 0) / 2;\n      const cy = item.y + (item.depthMm || 0) / 2;\n      // Treat any current rotationDeg as \"horizontal\" - rotate to\n      // vertical and back. Toggle 0 \u2194 90 to keep things simple.\n      const cur = ((item.rotationDeg || 0) % 360 + 360) % 360;\n      const goVertical = cur === 0 || cur === 180;\n      item.rotationDeg = goVertical ? 90 : 0;\n      const chord = fitBeamToRoom(item, cx, cy, item.rotationDeg);\n      if (chord) {\n        item.widthMm = chord.widthMm;\n        item.x = chord.x;\n        item.y = chord.y;\n      } else {\n        // Off the room entirely - fall back to the bounding box, centred, and\n        // let the clamp below drag it back in.\n        const params = featureRoomParams();\n        item.widthMm = goVertical ? (params.heightMm || 3500) : (params.widthMm || 5000);\n        item.x = Math.round(cx - item.widthMm / 2);\n        item.y = Math.round(cy - (item.depthMm || 0) / 2);\n      }\n      const put = clampToRoom(\n        { widthMm: item.widthMm, depthMm: item.depthMm, rotationDeg: item.rotationDeg },\n        item.x, item.y, room\n      );\n      item.x = Math.round(put.x);\n      item.y = Math.round(put.y);\n      rerender();\n      return;\n    }\n    // Swap dimensions, pivot around the item's centre, then re-clamp\n    // to keep the rotated item inside the room and out of obstacles.\n    const oldW = item.widthMm;\n    const oldD = item.depthMm;\n    const cx = item.x + oldW / 2;\n    const cy = item.y + oldD / 2;\n    item.widthMm = oldD;\n    item.depthMm = oldW;\n    item.x = cx - item.widthMm / 2;\n    item.y = cy - item.depthMm / 2;\n    item.rotationDeg = 0;\n\n    const others = (roomConfig.perimeterItems || []).filter(it => it.id !== item.id);\n    const { x, y } = snapAndClamp(\n      { widthMm: item.widthMm, depthMm: item.depthMm, rotationDeg: 0 },\n      item.x, item.y, room, others, others\n    );\n    item.x = x;\n    item.y = y;\n\n    rerender();\n  }\n\n  function wireOpening(opening, el, grid, opsHandle) {\n    // Same rule as the wall sections: a door or window is part of the room, so\n    // it is handled where the room is handled and is inert everywhere else.\n    if (currentStep !== 'room-setup') {\n      el.style.pointerEvents = 'none';\n      return;\n    }\n    const hitEl = el.querySelector('.btk-kp-opening__hit') || el;\n    const pxPerMm = grid.pxPerMm;\n\n    let downX = 0, downY = 0, downActive = false;\n    let didDrag = false;\n    let startSegX = 0, startSegY = 0, startAngleDeg = 0;\n    let lastDX = 0, lastDY = 0;\n\n    function snapshotStart() {\n      if (opening.floating) {\n        startSegX = opening.x;\n        startSegY = opening.y;\n        startAngleDeg = 0;\n        return;\n      }\n      const walls = getWalls(room);\n      const wall  = walls[opening.wallIndex];\n      if (!wall) return;\n      const ux = (wall.to.x - wall.from.x) / wall.lengthMm;\n      const uy = (wall.to.y - wall.from.y) / wall.lengthMm;\n      // Snapshot the opening's CENTRE rather than its start edge.\n      // The snap / float maths downstream both centre the opening\n      // on this point, so anchoring it at the centre means the\n      // first mouse-move doesn't cause a jump and the click point\n      // stays under the cursor for the whole drag.\n      const centreOffset = opening.offsetMm + opening.widthMm / 2;\n      // Plus the inset, or grabbing an opening that sits in a pillar face\n      // would snatch it back out to the perimeter on the first mouse-move.\n      const inset = openingInsetMm(opening);\n      startSegX     = wall.from.x + ux * centreOffset + -uy * inset;\n      startSegY     = wall.from.y + uy * centreOffset +  ux * inset;\n      startAngleDeg = Math.atan2(uy, ux) * 180 / Math.PI;\n    }\n    function hideOwnGap() {\n      const others = (roomConfig.wallOpenings || []).filter(o => o.id !== opening.id);\n      grid.updateOpenings(others);\n    }\n    function showAllGaps() {\n      grid.updateOpenings(roomConfig.wallOpenings || []);\n    }\n\n    // While a drag is live the opening has to paint over whatever it passes -\n    // a pillar's band included - but moving the ELEMENT between layers to do\n    // that silently releases its pointer capture (a captured node loses\n    // capture when it is taken out of the document, and appendChild is a\n    // remove-and-insert). The pointerup then never reaches the drag, which\n    // stays armed and follows the mouse with no button held. So the LAYER is\n    // lifted for the duration and the element is only re-parented on drop,\n    // after the capture has been released.\n    const liftLayer = (on) => {\n      const base = opsHandle && opsHandle.layer;\n      if (base) base.classList.toggle('btk-kp-openings-layer--dragging', !!on);\n    };\n\n    const onDown = (e) => {\n      downActive = true;\n      downX = e.clientX;\n      downY = e.clientY;\n      didDrag = false;\n      lastDX = 0;\n      lastDY = 0;\n      snapshotStart();\n      hideOwnGap();\n      liftLayer(true);\n    };\n    const onUp = (e) => {\n      if (!downActive) return;\n      downActive = false;\n      const dist = Math.hypot(e.clientX - downX, e.clientY - downY);\n      if (dist < 5) {\n        // Click, not a drag: restore the gap and open the properties panel.\n        liftLayer(false);\n        showAllGaps();\n        selectItem({ kind: 'opening', id: opening.id });\n      }\n      // Drags: onDragEnd restores the gap at the new position.\n    };\n    const onCancel = () => {\n      downActive = false;\n      liftLayer(false);\n      showAllGaps();\n    };\n\n    hitEl.addEventListener('pointerdown',   onDown);\n    hitEl.addEventListener('pointerup',     onUp);\n    hitEl.addEventListener('pointercancel', onCancel);\n    renderHandles.push({\n      destroy() {\n        hitEl.removeEventListener('pointerdown',   onDown);\n        hitEl.removeEventListener('pointerup',     onUp);\n        hitEl.removeEventListener('pointercancel', onCancel);\n      }\n    });\n\n    const drag = makeDraggable(hitEl, {\n      pxPerMm,\n      getZoom: () => view2d.zoom,\n      onDragMove({ dxMm, dyMm }) {\n        // Room locked: doors / windows are pinned.\n        if (isRoomLocked()) return;\n        lastDX = dxMm;\n        lastDY = dyMm;\n        if (Math.hypot(dxMm, dyMm) * pxPerMm > 5) didDrag = true;\n\n        // Clamp target to room bounding box so the door can't leave the canvas.\n        const bbox = getBoundingBox(room);\n        const targetX = Math.max(0, Math.min(bbox.widthMm,  startSegX + dxMm));\n        const targetY = Math.max(0, Math.min(bbox.heightMm, startSegY + dyMm));\n\n        // Gentle snap: opening floats freely through the room\n        // interior and locks onto a wall only when the cursor is\n        // within SNAP_RANGE_MM of it.\n        const SNAP_RANGE_MM = 250;\n        const proj = projectOpeningToFace(targetX, targetY, opening.widthMm);\n\n        if (proj && proj.distance < SNAP_RANGE_MM) {\n          // Within snap range - lock onto that face, slide to the\n          // nearest free offset (avoiding other openings and any\n          // cabinets that aren't allowed under this opening type),\n          // and rotate to match the wall.\n          const walls = getWalls(room);\n          const wall  = walls[proj.wallIndex];\n          const run   = proj.run;\n          const ux = (wall.to.x - wall.from.x) / wall.lengthMm;\n          const uy = (wall.to.y - wall.from.y) / wall.lengthMm;\n          const desiredOffset = Math.round(Math.max(\n            run.fromMm,\n            Math.min(run.toMm - opening.widthMm, proj.offsetMm - opening.widthMm / 2)\n          ));\n          const otherOpenings = (roomConfig.wallOpenings || []).filter(o =>\n            o.id !== opening.id && o.wallIndex === proj.wallIndex\n          );\n          const freeOffset = findFreeOpeningOffset({\n            wall,\n            openingWidth: opening.widthMm,\n            openingType: opening.type,\n            openingVariant: opening.variant,\n            walls: walls.concat(getPillarSnapWalls(roomConfig.perimeterItems)),\n            desiredOffset,\n            otherOpenings,\n            cabinets,\n            boundsFromMm: run.fromMm,\n            boundsToMm: run.toMm,\n            insetMm: run.insetMm\n          });\n          const newOffset = freeOffset !== null ? freeOffset : desiredOffset;\n          const snapX = wall.from.x + ux * newOffset + -uy * run.insetMm;\n          const snapY = wall.from.y + uy * newOffset +  ux * run.insetMm;\n          const angleDeg = Math.atan2(uy, ux) * 180 / Math.PI;\n          el.style.left      = (snapX * pxPerMm) + 'px';\n          el.style.top       = (snapY * pxPerMm) + 'px';\n          el.style.transform = `rotate(${angleDeg}deg)`;\n        } else {\n          // Out of snap range - float with the cursor sitting on\n          // the opening's geometric centre, keeping the rotation\n          // it had when the drag started.\n          const angleRad = startAngleDeg * Math.PI / 180;\n          const halfW = opening.widthMm / 2;\n          const floatX = targetX - Math.cos(angleRad) * halfW;\n          const floatY = targetY - Math.sin(angleRad) * halfW;\n          el.style.left      = (floatX * pxPerMm) + 'px';\n          el.style.top       = (floatY * pxPerMm) + 'px';\n          el.style.transform = `rotate(${startAngleDeg}deg)`;\n        }\n      },\n      onDragEnd() {\n        if (isRoomLocked()) { liftLayer(false); return; }\n        if (!didDrag) {\n          const insetNow = openingInsetMm(opening);\n          updateOpeningElement(el, opening, room, pxPerMm, insetNow);\n          setOpeningLayer(opsHandle, el, insetNow);\n          liftLayer(false);\n          showAllGaps();\n          return;\n        }\n\n        // Final drop position (clamped to bbox).\n        const bbox = getBoundingBox(room);\n        const dropX = Math.max(0, Math.min(bbox.widthMm,  startSegX + lastDX));\n        const dropY = Math.max(0, Math.min(bbox.heightMm, startSegY + lastDY));\n\n        const proj = projectOpeningToFace(dropX, dropY, opening.widthMm);\n        if (!proj) {\n          // No wall to snap to - a floating opening just stays where\n          // it was dropped, still floating, ready to drag again.\n          if (opening.floating) { opening.x = dropX; opening.y = dropY; }\n          const insetNow = openingInsetMm(opening);\n          updateOpeningElement(el, opening, room, pxPerMm, insetNow);\n          setOpeningLayer(opsHandle, el, insetNow);\n          liftLayer(false);\n          showAllGaps();\n          return;\n        }\n\n        const walls   = getWalls(room);\n        const newWall = walls[proj.wallIndex];\n        const run     = proj.run;\n        const newOffset = Math.round(Math.max(\n          run.fromMm,\n          Math.min(run.toMm - opening.widthMm, proj.offsetMm - opening.widthMm / 2)\n        ));\n\n        // Land at the nearest free offset on the target wall - slides\n        // around other openings and any cabinets the opening can't\n        // sit in front of. If the wall has no free space at all, drop\n        // silently reverts to the previous position.\n        const otherOpenings = (roomConfig.wallOpenings || []).filter(o =>\n          o.id !== opening.id && o.wallIndex === proj.wallIndex\n        );\n        const freeOffset = findFreeOpeningOffset({\n          wall: newWall,\n          openingWidth: opening.widthMm,\n          openingType: opening.type,\n          openingVariant: opening.variant,\n          walls: walls.concat(getPillarSnapWalls(roomConfig.perimeterItems)),\n          desiredOffset: newOffset,\n          otherOpenings,\n          cabinets,\n          boundsFromMm: run.fromMm,\n          boundsToMm: run.toMm,\n          insetMm: run.insetMm\n        });\n\n        if (freeOffset === null) {\n          // Wall is full - keep a floating opening where it was dropped.\n          if (opening.floating) { opening.x = dropX; opening.y = dropY; }\n          const insetNow = openingInsetMm(opening);\n          updateOpeningElement(el, opening, room, pxPerMm, insetNow);\n          setOpeningLayer(opsHandle, el, insetNow);\n          liftLayer(false);\n          showAllGaps();\n          return;\n        }\n\n        const was = { ...opening };\n        if (proj.wallIndex !== opening.wallIndex || freeOffset !== opening.offsetMm) {\n          opening.wallIndex = proj.wallIndex;\n          opening.offsetMm  = freeOffset;\n        }\n        // Now placed on a wall - no longer floating.\n        opening.floating = false;\n        // Unit ends it has just arrived in front of, or left.\n        const endsChanged = epReDecideBesideOpenings([was, opening]);\n\n        const insetNow = openingInsetMm(opening);\n        updateOpeningElement(el, opening, room, pxPerMm, insetNow);\n        setOpeningLayer(opsHandle, el, insetNow);\n        liftLayer(false);\n        showAllGaps();\n        refreshDims();\n        doorsWindowsHandle.refresh();\n        selectionPanelHandle.refresh();\n        if (endsChanged) rerender();\n      }\n    });\n    renderHandles.push(drag);\n  }\n\n  // ---- Room shape handlers ----\n\n  function hasContent() {\n    return cabinets.length > 0 ||\n           (roomConfig.perimeterItems && roomConfig.perimeterItems.length > 0) ||\n           (roomConfig.wallOpenings   && roomConfig.wallOpenings.length > 0);\n  }\n\n  function handleShapeChange(newShapeId) {\n    if (newShapeId === roomConfig.shapeId) return;\n    const newParams = getShapeParamsDefaults(newShapeId);\n    const newItems = [];\n    // Both Pillar and Cut corner shapes start EMPTY. The user adds\n    // pillars / cut-corner pillars by clicking the corner toggle\n    // buttons in the Room Shape popup - one per corner, up to four.\n    roomConfig = {\n      ...roomConfig,\n      shapeId: newShapeId,\n      shapeParams: newParams,\n      perimeterItems: newItems,\n      wallOpenings: []\n    };\n    // Whole room shape replaced, so every unit's relationship to a wall is new\n    // - re-decide panels and fillers rather than carrying the old ones over.\n    // Same sweep and order as handleParamsApply and deleteCabinet.\n    autoDetectEndPanels();\n    autoDetectBackPanels();\n    resizeFillers();\n    rerender();\n  }\n\n  // ---- A pillar dropped on a DRAWN room's wall becomes part of it ----\n  // (Planner Bugs 32, Arden 2026-10-26.) A drawn room keeps pillars as\n  // objects standing in it (featuresJoinWalls), so when its wall lengths were\n  // edited the walls moved and the boxing did not. Now a pillar dropped\n  // square against one wall is cut into it - the wall goes round it, three\n  // new short walls - and one dropped into a square corner notches the\n  // corner. The pillar object goes: its faces are walls, listed and sized in\n  // Edit Custom Room like the rest. Doors and windows ride onto the right new\n  // section; one the pillar would sit across stops the merge, and so does\n  // anything not square to the wall - those stay pillars, as before.\n  const PILLAR_MERGE_TOL_MM = 5;\n  function mergePillarIntoDrawnRoom(itemId) {\n    if (roomConfig.shapeId !== 'freeshape') return false;\n    const it = (roomConfig.perimeterItems || []).find(p => p && p.id === itemId);\n    if (!it || it.type !== 'column' || !(it.widthMm > 0) || !(it.depthMm > 0)) return false;\n    const V = ((room && room.vertices) || []).map(v => ({ x: v.x, y: v.y }));\n    const n = V.length;\n    if (n < 3) return false;\n    const th = (it.rotationDeg || 0) * Math.PI / 180, cs = Math.cos(th), sn = Math.sin(th);\n    const cx = it.x + it.widthMm / 2, cy = it.y + it.depthMm / 2;\n    const hw = it.widthMm / 2, hd = it.depthMm / 2;\n    const R = [[-hw, -hd], [hw, -hd], [hw, hd], [-hw, hd]]\n      .map(([lx, ly]) => ({ x: cx + lx * cs - ly * sn, y: cy + lx * sn + ly * cs }));\n    const tol = PILLAR_MERGE_TOL_MM;\n    // Every wall a SIDE of the pillar lies flat on.\n    const flush = [];\n    for (let i = 0; i < n; i++) {\n      const A = V[i], B = V[(i + 1) % n];\n      const L = Math.hypot(B.x - A.x, B.y - A.y);\n      if (L < 1) continue;\n      const u = { x: (B.x - A.x) / L, y: (B.y - A.y) / L };\n      let nn = { x: -u.y, y: u.x };\n      if ((cx - A.x) * nn.x + (cy - A.y) * nn.y < 0) nn = { x: -nn.x, y: -nn.y };\n      const d = R.map(p => (p.x - A.x) * nn.x + (p.y - A.y) * nn.y);\n      const t = R.map(p => (p.x - A.x) * u.x + (p.y - A.y) * u.y);\n      const on = [0, 1, 2, 3].filter(k => Math.abs(d[k]) <= tol);\n      if (on.length !== 2 || Math.min(...d) < -tol) continue;\n      const t0 = Math.min(t[on[0]], t[on[1]]), t1 = Math.max(t[on[0]], t[on[1]]);\n      if (t1 <= tol || t0 >= L - tol) continue;                 // beside the wall, not on it\n      flush.push({ i, A, L, u, nn, t0: Math.max(0, t0), t1: Math.min(L, t1), depth: Math.max(...d) });\n    }\n    const P = (f, t, d) => ({ x: Math.round(f.A.x + f.u.x * t + f.nn.x * d), y: Math.round(f.A.y + f.u.y * t + f.nn.y * d) });\n    let newVerts, mapOp;\n    if (flush.length === 1) {\n      // Mid-wall: the wall goes round it.\n      const f = flush[0], i = f.i;\n      if (f.t0 <= tol || f.t1 >= f.L - tol) return false;      // runs into a corner that is not square to it\n      newVerts = [...V.slice(0, i + 1), P(f, f.t0, 0), P(f, f.t0, f.depth), P(f, f.t1, f.depth), P(f, f.t1, 0), ...V.slice(i + 1)];\n      mapOp = (op) => {\n        if (op.wallIndex < i) return op;\n        if (op.wallIndex > i) return { ...op, wallIndex: op.wallIndex + 4 };\n        const a = op.offsetMm || 0, b = a + (op.widthMm || 0);\n        if (b <= f.t0 + 1) return op;\n        if (a >= f.t1 - 1) return { ...op, wallIndex: i + 4, offsetMm: Math.round(a - f.t1) };\n        return null;                                            // the pillar would stand across it\n      };\n    } else if (flush.length === 2) {\n      // Into a corner: the two walls must meet at it, the pillar reaching the\n      // end of the first and the start of the second.\n      let [fa, fb] = flush;\n      if ((fb.i + 1) % n === fa.i) [fa, fb] = [fb, fa];\n      const j = (fa.i + 1) % n;\n      if (fb.i !== j || fa.t1 < fa.L - tol || fb.t0 > tol) return false;\n      const R1 = P(fa, fa.t0, 0), Q = P(fa, fa.t0, fa.depth), R2 = P(fb, fb.t1, 0);\n      if (Math.hypot(Q.x - (fb.A.x + fb.u.x * fb.t1 + fb.nn.x * fb.depth), Q.y - (fb.A.y + fb.u.y * fb.t1 + fb.nn.y * fb.depth)) > tol * 2) return false;\n      newVerts = j === 0\n        ? [R1, Q, R2, ...V.slice(1)]\n        : [...V.slice(0, j), R1, Q, R2, ...V.slice(j + 1)];\n      mapOp = (op) => {\n        const a = op.offsetMm || 0, b = a + (op.widthMm || 0);\n        if (op.wallIndex === fa.i && b > fa.t0 + 1) return null;\n        if (op.wallIndex === j) {\n          if (a < fb.t1 - 1) return null;\n          return { ...op, wallIndex: j + 2, offsetMm: Math.round(a - fb.t1) };\n        }\n        return (j === 0 || op.wallIndex > j) ? { ...op, wallIndex: op.wallIndex + 2 } : op;\n      };\n    } else {\n      return false;\n    }\n    const ops = [];\n    for (const op of (roomConfig.wallOpenings || [])) {\n      if (!op || op.floating) { ops.push(op); continue; }\n      const m = mapOp(op);\n      if (!m) return false;\n      ops.push(m);\n    }\n    roomConfig = {\n      ...roomConfig,\n      wallOpenings: ops,\n      perimeterItems: (roomConfig.perimeterItems || []).filter(p => p && p.id !== itemId)\n    };\n    handleParamsApply({ vertices: newVerts });\n    return true;\n  }\n\n  function handleParamsApply(newParams) {\n    const updatedConfig = {\n      ...roomConfig,\n      shapeParams: { ...roomConfig.shapeParams, ...newParams }\n    };\n    // If we're on the Pillar shape and the user edited the pillar\n    // size in the popup (via click-to-edit dim labels), apply the new\n    // size to the existing pillar perimeter item so the saved layout\n    // matches what the user saw in the preview.\n    if (updatedConfig.shapeId === 'pillar' &&\n        ('widthMm' in newParams || 'heightMm' in newParams)) {\n      // Re-anchor each corner-anchored plain pillar so its outer\n      // corner stays on the room corner after the room resizes.\n      updatedConfig.perimeterItems = (updatedConfig.perimeterItems || []).map(it => {\n        if (!(it && it.type === 'column' && !it.cornerCut && it.pillarCorner)) return it;\n        const anchor = cornerAnchorPosition(it.pillarCorner, updatedConfig.shapeParams, it.widthMm, it.depthMm);\n        return { ...it, x: anchor.x, y: anchor.y };\n      });\n    }\n    // Cut-corner shape: propagate width / depth / short-wall changes to\n    // the existing cut-corner pillar. Short walls are stored as cut\n    // amounts (cutX = widthMm \u2212 shortWallX, cutY = depthMm \u2212 shortWallY).\n    // The pillar is anchored to the room corner named by cornerCut.corner\n    // - recompute x / y so the two wall-flush edges stay on that corner's\n    // walls whenever the pillar size changes.\n    if (updatedConfig.shapeId === 'angled-cut' &&\n        ('columnWidthMm' in newParams || 'columnDepthMm' in newParams ||\n         'shortWallXMm'   in newParams || 'shortWallYMm'   in newParams ||\n         'widthMm'        in newParams || 'heightMm'      in newParams)) {\n      updatedConfig.perimeterItems = (updatedConfig.perimeterItems || []).map(it => {\n        if (!(it && it.type === 'column' && it.cornerCut)) return it;\n        const w  = updatedConfig.shapeParams.columnWidthMm ?? it.widthMm;\n        const d  = updatedConfig.shapeParams.columnDepthMm ?? it.depthMm;\n        const cur = it.cornerCut || {};\n        const curCutX = cur.xMm ?? cur.amountMm ?? 0;\n        const curCutY = cur.yMm ?? cur.amountMm ?? 0;\n        const sX = updatedConfig.shapeParams.shortWallXMm\n                   ?? Math.max(0, (it.widthMm || 0) - curCutX);\n        const sY = updatedConfig.shapeParams.shortWallYMm\n                   ?? Math.max(0, (it.depthMm || 0) - curCutY);\n        const corner = cur.corner || 'tr';\n        const { x, y } = cornerAnchorPosition(corner, updatedConfig.shapeParams, w, d);\n        return {\n          ...it,\n          x, y,\n          widthMm: w,\n          depthMm: d,\n          cornerCut: {\n            ...cur,\n            corner,\n            // Clamp so the pentagon never fully collapses - at least\n            // 1 mm of short wall along each axis (visually = zero, but\n            // the inner miter math stays well-formed).\n            xMm: Math.max(0, Math.min(w - 1, w - sX)),\n            yMm: Math.max(0, Math.min(d - 1, d - sY))\n          }\n        };\n      });\n    }\n    const newRoom = buildRoomPolygon(updatedConfig);\n\n    // Re-validate wall openings: drop any that no longer fit on their\n    // new wall length.\n    const newWalls = getWalls(newRoom);\n    updatedConfig.wallOpenings = (updatedConfig.wallOpenings || []).filter(op => {\n      const wall = newWalls[op.wallIndex];\n      if (!wall) return false;\n      return op.offsetMm >= 0 && (op.offsetMm + op.widthMm) <= wall.lengthMm + 0.001;\n    });\n\n    // Re-clamp perimeter items in order so anything that fell outside\n    // the new dimensions gets pushed back inside.\n    const clampedItems = [];\n    (updatedConfig.perimeterItems || []).forEach(it => {\n      const others = clampedItems.filter(other => other.id !== it.id);\n      const { x, y } = snapAndClamp(\n        { widthMm: it.widthMm, depthMm: it.depthMm, rotationDeg: it.rotationDeg || 0 },\n        it.x, it.y, newRoom, others, others\n      );\n      clampedItems.push({ ...it, x, y });\n    });\n    updatedConfig.perimeterItems = clampedItems;\n\n    // Re-clamp cabinets against the new room, clamped items, and\n    // the validated openings.\n    cabinets = cabinets.map(c => {\n      const otherCabs = cabinets.filter(o => o.id !== c.id);\n      const { x, y } = snapAndClamp(c, c.x, c.y, newRoom, otherCabs, clampedItems, updatedConfig.wallOpenings);\n      return { ...c, x, y };\n    });\n\n    roomConfig = updatedConfig;\n    // Room shape just changed - every cabinet's relationship to the\n    // walls and to other cabs is fresh, so re-evaluate back panels...\n    // ...and END PANELS AND FILLERS, which this did not do until 2026-10-01.\n    // A wall move can turn a 20mm gap into a flush face or the reverse, but\n    // nothing re-decided it, so each unit kept whatever it was holding before\n    // the wall moved. Julian's report: a wall unit stuck on a 1mm filler that\n    // only came right when some unrelated delete happened to run a full pass.\n    // No argument = the whole plan, the same sweep deleteCabinet runs, and in\n    // the same order. This is the COMMIT of a wall change, not a drag frame,\n    // so the full sweep is affordable here.\n    autoDetectEndPanels();\n    autoDetectBackPanels();\n    resizeFillers();\n    rerender();\n  }\n\n  function handleCeilingChange(mm) {\n    roomConfig = { ...roomConfig, ceilingHeightMm: mm, ceilingHeightSet: true };\n    // No polygon rebuild needed. Record the applied height below the box + stop\n    // the attention pulse.\n    const card = root.querySelector('[data-btk-kp-ceiling-card]');\n    const rec  = root.querySelector('[data-btk-kp-ceiling-recorded]');\n    const recText = root.querySelector('[data-btk-kp-ceiling-recorded-text]');\n    if (card) card.classList.remove('is-pulsing');\n    if (rec && recText) {\n      recText.textContent = mm + ' mm';\n      rec.hidden = false;\n      rec.classList.remove('is-flash'); void rec.offsetWidth; rec.classList.add('is-flash');\n    }\n  }\n\n  function handleAddColumn({ widthMm, depthMm }) {\n    const pos = getDefaultItemPosition(roomConfig.shapeId, roomConfig.shapeParams, widthMm, depthMm);\n    roomConfig = {\n      ...roomConfig,\n      perimeterItems: [\n        ...(roomConfig.perimeterItems || []),\n        {\n          id: `column-${nextPerimeterItemId++}`,\n          type: 'column',\n          x: pos.x,\n          y: pos.y,\n          widthMm,\n          depthMm\n        }\n      ]\n    };\n    rerender();\n  }\n\n \n\n  // Hold an opening inside the width its style allows. The limits live on the\n  // style, not the type, because a 6-leaf bi-fold and a 2-leaf are the same\n  // type and nothing like the same size. Applied HERE rather than only on the\n  // popup input, so the size box on the wall row is held to it too. A style\n  // with no limits authored is unrestricted.\n  function clampOpeningWidth(variant, styleCode, widthMm) {\n    const style = Catalogue?.getOpeningStyle?.(variant, styleCode);\n    if (!style || !Number.isFinite(widthMm)) return widthMm;\n    let w = widthMm;\n    if (Number.isFinite(style.minWidthMm)) w = Math.max(style.minWidthMm, w);\n    if (Number.isFinite(style.maxWidthMm)) w = Math.min(style.maxWidthMm, w);\n    return w;\n  }\n\n  // Worktop in to Window: only a window whose board is set to Match Worktop,\n  // and not a bay (a bay builds its own board across the bay floor). While it\n  // is on, the window sits on the worktop - its From Floor height is the top\n  // of a standard base unit, whatever was typed - and the height it had\n  // before is kept, so turning it off puts the window back where it was.\n  // Applied on every add and every change, so no path can leave a window\n  // ticked with a board that no longer matches the worktop.\n  function settleWorktopIntoWindow(prev, next) {\n    const can = next.type === 'window' && next.boardColourCode === 'worktop' && !next.bay;\n    if (!can) next.worktopIntoWindow = false;\n    const was = !!(prev && prev.worktopIntoWindow);\n    if (next.worktopIntoWindow) {\n      if (!was) next.cillBeforeWorktopMm = (prev || next).heightFromFloorMm;\n      next.heightFromFloorMm = WT_INTO_WINDOW_CILL_MM;\n    } else if (was) {\n      if (Number.isFinite(next.cillBeforeWorktopMm)) next.heightFromFloorMm = next.cillBeforeWorktopMm;\n      next.cillBeforeWorktopMm = null;\n    }\n    return next;\n  }\n\n  function handleAddOpening({ type, widthMm, heightMm, revealDepthMm, heightFromFloorMm, variant, styleCode, colourCode, boardColourCode, bay, bayWindowWidthMm, cornerRadiusMm, worktopIntoWindow }) {\n    // New openings land floating in the middle of the room. The user\n    // then drags them onto a wall, where they snap into place on drop.\n    const walls = getWalls(room);\n    if (walls.length === 0) return;\n\n    widthMm = clampOpeningWidth(variant, styleCode, widthMm);\n\n    const longest = walls.reduce((m, w) => Math.max(m, w.lengthMm), 0);\n    if (widthMm > longest) {\n      window.BTKKPDialog.alert(`That ${type} is too wide for the longest wall (${Math.round(longest)}mm).`, { title: 'Does not fit', danger: true });\n      return;\n    }\n\n    const bbox = getBoundingBox(room);\n    roomConfig = {\n      ...roomConfig,\n      wallOpenings: [\n        ...(roomConfig.wallOpenings || []),\n        {\n          id: `opening-${nextOpeningId++}`,\n          type: type === 'window' ? 'window' : 'door',\n          variant: variant || null,\n          // Sub-type from the style strip (planner_opening_style). Picks the\n          // GLB the 3D build seats in the wall, and the popup imagery.\n          styleCode: styleCode || null,\n          // Frame colour (planner_opening_colour). Null falls back to the\n          // first authored colour at render time, so openings saved before\n          // colours existed still come up in the default.\n          colourCode: colourCode || null,\n          // Window board: 'match' (follow the frame), 'worktop', or a colour\n          // code. Doors carry null - they have no board. The renderer holds\n          // the resolution rule; this only ever stores the pick.\n          boardColourCode: boardColourCode || null,\n          // Bay: the opening projects outward to a narrower face. widthMm is\n          // always the hole cut through the wall - on a bay that is the FRONT\n          // opening, the wide side seen from the room - and bayWindowWidthMm is\n          // the window on the projecting face. Any type in any style can be one.\n          bay: !!bay,\n          bayWindowWidthMm: bayWindowWidthMm || null,\n          // A leafless opening's head: 0 is square, anything else sweeps both\n          // top corners by that radius. Half the width gives a full arch.\n          cornerRadiusMm: Math.max(0, Math.round(cornerRadiusMm || 0)),\n          widthMm,\n          heightMm: heightMm || null,\n          // `|| null` would swallow a deliberate ZERO - and an internal door's\n          // reveal IS zero, its lining flush with the room face. Stored as null\n          // that reads as \"unset\" and the renderer substitutes its own default\n          // instead. Only a genuinely absent value becomes null.\n          revealDepthMm: Number.isFinite(revealDepthMm) ? revealDepthMm : null,\n          // Windows: bottom of the opening above the floor (e.g.,\n          // 1050 mm for a typical kitchen window). Doors stay at 0.\n          heightFromFloorMm: type === 'window' ? (heightFromFloorMm || 1050) : 0,\n          // The worktop runs in to the reveal as one piece (see\n          // settleWorktopIntoWindow, which also sets the cill for it).\n          worktopIntoWindow: !!worktopIntoWindow,\n          floating: true,\n          x: bbox.minX + bbox.widthMm  / 2,\n          y: bbox.minY + bbox.heightMm / 2\n        }\n      ].map((o, i, all) => (i === all.length - 1 ? settleWorktopIntoWindow(null, o) : o))\n    };\n    rerender();\n  }\n\n  // Copy a door or window, every setting with it: style, colour, board, bay,\n  // reveal, cill height, swing, hinge - the lot. Only the identity and the\n  // position are new, because those are the two things a copy cannot share.\n  //\n  // A copy of something that is ON a wall goes on the same wall, in the first\n  // free space past it, measured on the same FACE - a window cut into a pillar\n  // copies onto that pillar, not onto the wall behind it. If the wall is full\n  // it comes back floating in the middle of the room rather than being refused\n  // or stacked invisibly on top of the original.\n  function handleDuplicateOpening(id) {\n    const src = (roomConfig.wallOpenings || []).find(o => o.id === id);\n    if (!src) return;\n    const copy = { ...src, id: `opening-${nextOpeningId++}` };\n\n    const walls = getWalls(room);\n    const wall  = (!src.floating && walls[src.wallIndex]) || null;\n    let placed = false;\n    if (wall) {\n      const run  = openingFaceRun(src) || { fromMm: 0, toMm: wall.lengthMm, insetMm: 0 };\n      const GAP_MM = 100;\n      const free = findFreeOpeningOffset({\n        wall,\n        openingWidth: src.widthMm,\n        openingType:  src.type,\n        openingVariant: src.variant,\n        walls: walls.concat(getPillarSnapWalls(roomConfig.perimeterItems)),\n        desiredOffset: (src.offsetMm || 0) + (src.widthMm || 0) + GAP_MM,\n        otherOpenings: (roomConfig.wallOpenings || []).filter(o => o.wallIndex === src.wallIndex),\n        cabinets,\n        boundsFromMm: run.fromMm,\n        boundsToMm:   run.toMm,\n        insetMm:      run.insetMm\n      });\n      if (free !== null) {\n        copy.offsetMm = free;\n        placed = true;\n      }\n    }\n    if (!placed) {\n      // Nowhere on the wall for it. Floating is how a new one arrives anyway,\n      // so the user drags it where they want it - and it is plainly there,\n      // which a copy hidden under its original would not be.\n      const bbox = getBoundingBox(room);\n      delete copy.wallIndex;\n      delete copy.offsetMm;\n      copy.floating = true;\n      copy.x = bbox.minX + bbox.widthMm  / 2;\n      copy.y = bbox.minY + bbox.heightMm / 2;\n    }\n\n    roomConfig = {\n      ...roomConfig,\n      wallOpenings: [...(roomConfig.wallOpenings || []), copy]\n    };\n    epReDecideBesideOpenings([copy]);\n    rerender();\n    // Follow the copy, so the panel is editing the thing that just appeared.\n    selectItem({ kind: 'opening', id: copy.id });\n    designControlsHandle.setStatus(placed\n      ? `${copy.type === 'door' ? 'Door' : 'Window'} duplicated on the same wall`\n      : `${copy.type === 'door' ? 'Door' : 'Window'} duplicated - drag it onto a wall`);\n  }\n\n  function handleRemoveOpening(id) {\n    clearSelectionIfMatches('opening', id);\n    const gone = (roomConfig.wallOpenings || []).find(o => o.id === id);\n    roomConfig = {\n      ...roomConfig,\n      wallOpenings: (roomConfig.wallOpenings || []).filter(o => o.id !== id)\n    };\n    if (gone) epReDecideBesideOpenings([gone]);\n    rerender();\n  }\n\n  function handleRemovePerimeterItem(itemId) {\n    clearSelectionIfMatches('feature', itemId);\n    roomConfig = {\n      ...roomConfig,\n      perimeterItems: (roomConfig.perimeterItems || []).filter(it => it.id !== itemId)\n    };\n    rerender();\n  }\n\n  // Add a cut-corner pillar at the named room corner ('tl'|'tr'|'bl'|'br').\n  // If a pillar already exists at that corner the call is a no-op - the\n  // popup uses this as a toggle and routes the \"remove\" case through\n  // handleRemovePerimeterItem instead.\n  // `variant` comes from the corner-treatment menu in the Room Shape\n  // popup: '45' for a true 45\u00B0 splay, 'cut' for an angled cut the user\n  // sizes per side. Defaults to '45' so any older caller is unchanged.\n  function handleAddCornerCut(corner, variant = '45') {\n    if (cornerOccupant(corner)) return;\n    const starter = makeStarterAngledCut(\n      roomConfig.shapeParams || {},\n      `column-${nextPerimeterItemId++}`,\n      corner,\n      variant\n    );\n    roomConfig = {\n      ...roomConfig,\n      perimeterItems: [...(roomConfig.perimeterItems || []), starter]\n    };\n    rerender();\n  }\n\n  // Add an internal wall feature - 100 \u00D7 1000, free-floating at the\n  // room centre. The user drags it to position; on flush against an\n  // outer wall the short edge ends up touching the wall.\n  function handleAddWall() {\n    const starter = makeStarterWall(\n      roomConfig.shapeParams || {},\n      `column-${nextPerimeterItemId++}`\n    );\n    roomConfig = {\n      ...roomConfig,\n      perimeterItems: [...(roomConfig.perimeterItems || []), starter]\n    };\n    rerender();\n  }\n\n  // Shared spawner for the new room-feature types - picks a starter\n  // factory by kind, generates a fresh id, appends to perimeterItems\n  // and rerenders. The kind\u2192factory map keeps a single code path even\n  // as more feature types are added later.\n  // Every room-feature factory sizes and centres itself from\n  // shapeParams.widthMm / heightMm - a starter shape's rectangle. A DRAWN room\n  // has no such pair (its shapeParams hold vertices), so all five fell back to\n  // the hard-coded 5000 x 3500 and were built for a room nobody has: a beam\n  // 5000 long in a 3000 room, a step block centred on a point outside the\n  // walls. Hand them the real extents instead.\n  function featureRoomParams() {\n    const p = roomConfig.shapeParams || {};\n    // Ceiling height lives on the room config, not in the shape params, and a\n    // feature that starts AT the ceiling (a vaulted ceiling) has to be told\n    // it - otherwise every room gets the 2400 fallback.\n    const ceil = { ceilingHeightMm: roomConfig.ceilingHeightMm ?? p.ceilingHeightMm ?? 2400 };\n    if (p.widthMm && p.heightMm) return { ...p, ...ceil };\n    const bb = getBoundingBox(room);\n    return { ...p, ...ceil, widthMm: bb.widthMm, heightMm: bb.heightMm };\n  }\n\n  // A boiler housing is a wall unit MADE to go over a wall-hung boiler, so the\n  // boiler must not shove it away - it is the one unit in the range that is\n  // supposed to be in the same place as one. Every other unit still has to\n  // clear it, and a FLOOR-standing boiler still stops everything: nothing goes\n  // over that.\n  const BOILER_HOUSING_CODES = new Set(['BOILW']);\n  function isBoilerHousing(cab) {\n    if (!cab || !cab.unitTypeId) return false;\n    const ut = Catalogue.getUnitType?.(cab.unitTypeId);\n    return !!ut && BOILER_HOUSING_CODES.has(String(ut.code || '').trim().toUpperCase());\n  }\n  // The perimeter items a given cabinet has to keep out of.\n  //\n  // Two services are routinely boxed in behind cabinetry rather than worked\n  // around, so for the units that do the boxing in they are not obstacles at\n  // all. Everything else in the range still has to clear both.\n  function perimeterObstaclesFor(cab) {\n    const list = roomConfig.perimeterItems || [];\n    const overBoiler = isBoilerHousing(cab);\n    // A consumer unit goes inside a wall unit - any wall unit, not one special\n    // type - so the test is the cabinet's own category group.\n    const group = epCategoryGroup(cab);\n    const overConsumerUnit = (group === 'wall' || group === 'bridging');\n    if (!overBoiler && !overConsumerUnit) return list;\n    return list.filter(o => {\n      if (!o) return true;\n      // A FLOOR-standing boiler still stops everything: nothing goes over that.\n      if (overBoiler && o.type === 'boiler' && o.preset !== 'floor') return false;\n      if (overConsumerUnit && o.type === 'consumer-unit') return false;\n      return true;\n    });\n  }\n\n  function spawnRoomFeature(kind, opts = {}) {\n    const factory = {\n      'step-block':     makeStarterStepBlock,\n      'beam':           makeStarterBeam,\n      'sloped-ceiling': makeStarterSlopedCeiling,\n      'vaulted-ceiling': makeStarterVaultedCeiling,\n      'free-block':     makeStarterFreeBlock,\n      'cooker-alcove':  makeStarterCookerAlcove,\n      'boiler':         makeStarterBoiler,\n      'consumer-unit':  makeStarterConsumerUnit,\n      'water-tank':     makeStarterWaterTank,\n      'radiator':       makeStarterRadiator,\n      'electrical-point': makeStarterElectricalPoint,\n      'stopcock':       makeStarterStopcock\n    }[kind];\n    if (!factory) return;\n    const starter = factory(featureRoomParams(), `feature-${nextPerimeterItemId++}`, opts);\n    // The picker can set ANY of the thing's properties before it is added -\n    // its sizes, a beam's colour, which wall a wedge leans on, how many steps.\n    // Applied here rather than inside five factories, each of which would have\n    // to be taught the same trick: they own the DEFAULTS, this owns what the\n    // user asked for. Only keys the starter already has, so the picker cannot\n    // invent fields on a feature by typo.\n    if (opts.props) {\n      for (const [k, v] of Object.entries(opts.props)) {\n        if (v === undefined || v === null || v === '') continue;\n        if (!(k in starter)) continue;\n        starter[k] = (typeof starter[k] === 'number') ? Math.round(Number(v)) : v;\n      }\n      // A chimney breast's overall width is its two columns plus the recess.\n      // Everything downstream measures the three boxes off that total, so it\n      // has to be re-derived after the parts change - nobody types it.\n      if (kind === 'water-tank') starter.depthMm = starter.widthMm;\n      if (kind === 'cooker-alcove') {\n        starter.widthMm = (starter.leftColumnMm || 0)\n                        + (starter.middleMm || 0)\n                        + (starter.rightColumnMm || 0);\n      }\n      // A faceplate's size is not typed, it is READ OFF the style - so picking\n      // a double socket has to resize the thing, not just redraw it.\n      if (kind === 'electrical-point') {\n        const p = electricalPlateSize(starter);\n        starter.widthMm = p.widthMm;\n        starter.heightMm = p.heightMm;\n        starter.depthMm = p.depthMm;\n      }\n    }\n    // Beams span wall-to-wall so the factory position is correct;\n    // for the floor-mounted features (step / slope / free block)\n    // scan the room for an empty patch first so new items don't\n    // pile up on top of existing units / each other. Fallback to\n    // the factory's default centre position if no patch fits.\n    if (!spansRoom(starter)) {\n      const spot = findFreeSpotForFeature(starter);\n      if (spot) {\n        starter.x = spot.x;\n        starter.y = spot.y;\n      }\n    }\n    // A beam is a span, so it is CUT to the room rather than shuffled into it:\n    // the factory gave it the width of the bounding box, and in a room with an\n    // angled wall the box is wider than the room is at the line the beam lies\n    // on - so it poked out at both ends. Same measurement the drop uses.\n    if (spansRoom(starter)) {\n      const fit = fitBeamToRoom(\n        starter,\n        starter.x + (starter.widthMm || 0) / 2,\n        starter.y + (starter.depthMm || 0) / 2,\n        starter.rotationDeg || 0\n      );\n      if (fit) {\n        starter.widthMm = fit.widthMm;\n        starter.x = fit.x;\n        starter.y = fit.y;\n        // Keep the heading the fit chose. For a beam it is the one it was\n        // given back; for a faced item - a wedge, a vault - it may be the\n        // opposite one, because that is the way round its low side lands on\n        // the wall. Dropping it here left a new vault leaning into the room.\n        starter.rotationDeg = fit.rotationDeg;\n      }\n    }\n    // ...and land it INSIDE the room whatever the factory said.\n    const inRoom = clampToRoom(\n      { widthMm: starter.widthMm, depthMm: starter.depthMm, rotationDeg: starter.rotationDeg || 0 },\n      starter.x, starter.y, room\n    );\n    starter.x = Math.round(inRoom.x);\n    starter.y = Math.round(inRoom.y);\n    roomConfig = {\n      ...roomConfig,\n      perimeterItems: [...(roomConfig.perimeterItems || []), starter]\n    };\n    rerender();\n  }\n\n  // Scan the room polygon's bounding box on a 200mm grid for a\n  // position where the new item's bbox doesn't overlap any existing\n  // cabinet or perimeter item. Returns {x, y} or null if no spot\n  // fits - callers fall back to the factory default in that case.\n  // The angle of the wall a dropped beam is lying against, or null if it is\n  // not near one. Measured to the beam's own centre, and the nearest wall\n  // wins - a beam laid into a corner takes the wall it is closest to.\n  //\n  // Returned in [0, 180): a beam is symmetrical end to end, so 200 degrees and\n  // 20 degrees are the same span, and picking the smaller keeps it from\n  // flipping over when nudged along a wall.\n  // Two things run wall to wall: a beam, and a ceiling wedge asked to. Their\n  // length is not a property they carry - it is a reading of the room at the\n  // line they lie on - so they share the fitting, the live re-cut on drag, and\n  // the \"hold your own heading unless you are against a wall\" rule.\n  const spansRoom = (it) => !!it && (it.type === 'beam' || it.fullWidth === true);\n\n  // Which way round a spanning item that HAS a face should sit. A beam is the\n  // same thing either way up, so the wall's angle is the whole answer for it;\n  // a wedge and a vault are not - their +Z side is the one that belongs\n  // against the wall, and an angle in [0, 180) does not say which of the two\n  // opposite headings puts it there. Left alone, a vault dropped on the top\n  // wall leans the wrong way and its low edge points into the room.\n  const FACED_SPANS = new Set(['sloped-ceiling', 'vaulted-ceiling']);\n  function faceRotationToWall(item, cx, cy, deg) {\n    if (!item || !FACED_SPANS.has(item.type)) return deg;\n    let bx = null, by = null, bestD = Infinity;\n    for (const w of getWalls(room)) {\n      const dx = w.to.x - w.from.x, dy = w.to.y - w.from.y;\n      const l2 = dx * dx + dy * dy;\n      if (!l2) continue;\n      let t = ((cx - w.from.x) * dx + (cy - w.from.y) * dy) / l2;\n      t = Math.max(0, Math.min(1, t));\n      const px = w.from.x + t * dx, py = w.from.y + t * dy;\n      const d = Math.hypot(px - cx, py - cy);\n      if (d < bestD) { bestD = d; bx = px; by = py; }\n    }\n    if (bx === null) return deg;\n    // Turned by `deg`, the +Z side points along (-sin, cos) in plan - the\n    // bottom edge of the unrotated element, which is where the 2D marker and\n    // the 3D builder both put it.\n    const r = deg * Math.PI / 180;\n    const fx = -Math.sin(r), fy = Math.cos(r);\n    return ((fx * (bx - cx) + fy * (by - cy)) >= 0) ? deg : ((deg + 180) % 360);\n  }\n\n  const BEAM_WALL_REACH_MM = 400;\n  function beamWallAngle(beam, cx, cy) {\n    let best = null, bestD = Infinity;\n    for (const w of getWalls(room)) {\n      const dx = w.to.x - w.from.x, dy = w.to.y - w.from.y;\n      const l2 = dx * dx + dy * dy;\n      if (!l2) continue;\n      let t = ((cx - w.from.x) * dx + (cy - w.from.y) * dy) / l2;\n      t = Math.max(0, Math.min(1, t));\n      const d = Math.hypot(w.from.x + t * dx - cx, w.from.y + t * dy - cy);\n      // Half the beam's thickness of standoff on top of the reach, so a beam\n      // whose face is on the wall counts however thick it is.\n      if (d < bestD && d <= BEAM_WALL_REACH_MM + (beam.depthMm || 0) / 2) {\n        bestD = d;\n        best = Math.atan2(dy, dx) * 180 / Math.PI;\n      }\n    }\n    if (best === null) return null;\n    let a = best % 180;\n    if (a < 0) a += 180;\n    return Math.round(a * 10) / 10;\n  }\n\n  // Where a beam sits if you put its CENTRE at (cx, cy): along the wall it is\n  // lying against if there is one, otherwise on the heading it already has -\n  // and cut to the width of the room along that line.\n  //\n  // Taking the CENTRE, not the corner, is what makes this usable while\n  // dragging: the width changes as the beam moves into a narrower part of the\n  // room, and a corner-based position would slide the beam sideways every time\n  // its length changed. The centre is where the pointer is; the ends follow.\n  //\n  // `forceDeg` is for the rotate button, which is choosing the heading itself.\n  function fitBeamToRoom(beam, cx, cy, forceDeg) {\n    const d = beam.depthMm || 0;\n    let near = (forceDeg == null) ? beamWallAngle(beam, cx, cy) : null;\n    // Only a wall running roughly the beam's own way (an angled one) turns it.\n    // Carried towards an end wall, it swung round 90 degrees and re-cut to the\n    // room's other span - a 5000 beam suddenly 3500 (Non Urgent sheet row 33,\n    // Julian). Rotate 90 is how it changes direction.\n    if (near !== null && beamTurnDeg(near, beam.rotationDeg || 0) > 45) near = null;\n    const heading = (forceDeg != null) ? forceDeg\n                  : (near === null ? (beam.rotationDeg || 0) : near);\n    // A 180 turn spans exactly the same chord, so this only ever decides which\n    // way a faced item leans - never how long it is or where it lands.\n    const rotationDeg = faceRotationToWall(beam, cx, cy, heading);\n    const chord = roomChordThrough(cx, cy, rotationDeg, d);\n    if (!chord) return null;\n    const widthMm = Math.max(100, Math.round(chord.lengthMm));\n    return {\n      rotationDeg,\n      widthMm,\n      x: Math.round(chord.x - widthMm / 2),\n      y: Math.round(chord.y - d / 2)\n    };\n  }\n\n  // How far apart two headings are for a span, which reads the same end to\n  // end: 0 to 90 degrees.\n  function beamTurnDeg(a, b) {\n    let t = Math.abs(((a - b) % 180 + 180) % 180);\n    return t > 90 ? 180 - t : t;\n  }\n\n  // How far the room reaches either side of a point, along a heading: the\n  // chord of the polygon through (cx, cy) at `deg`. Returns the length and the\n  // chord's own midpoint, or null if the point is not in the room.\n  //\n  // The nearest crossing each way, not the furthest - a room that bends back on\n  // itself (an L, a nib) is crossed more than twice by the same line, and the\n  // outermost pair would span straight across ground that is not the room.\n  function roomChordThrough(cx, cy, deg, thicknessMm = 0) {\n    const rad = deg * Math.PI / 180;\n    const dx = Math.cos(rad), dy = Math.sin(rad);\n    const V = (room && room.vertices) || [];\n    if (V.length < 3) return null;\n    // How far the room reaches each way from one point along the heading.\n    const reachFrom = (px, py) => {\n      let back = -Infinity, fwd = Infinity;\n      for (let i = 0; i < V.length; i++) {\n        const a = V[i], b = V[(i + 1) % V.length];\n        const ex = b.x - a.x, ey = b.y - a.y;\n        // Ray P + t*D against segment A + u*E, by cross products:\n        //   t = ((A-P) x E) / (D x E)      u = ((A-P) x D) / (D x E)\n        const den = dx * ey - dy * ex;                    // D x E\n        if (Math.abs(den) < 1e-9) continue;               // parallel to this edge\n        const wx = a.x - px, wy = a.y - py;\n        const u  = (wx * dy - wy * dx) / den;\n        if (u < -1e-9 || u > 1 + 1e-9) continue;          // misses the edge\n        const tt = (wx * ey - wy * ex) / den;             // distance along the heading\n        if (tt < -1e-6 && tt > back) back = tt;\n        if (tt >  1e-6 && tt < fwd)  fwd  = tt;\n      }\n      return { back, fwd };\n    };\n    // A beam is not a line - it is a rectangle, and against a wall that leans\n    // the room is shorter at one of its long edges than it is down the middle.\n    // Measure BOTH edges and keep the overlap, or the corner on the leaning\n    // side hangs out past the wall while the centre line fits perfectly.\n    const half = Math.max(0, thicknessMm) / 2;\n    const nx = -dy * half, ny = dx * half;                // across the heading\n    const lines = half > 0\n      ? [reachFrom(cx + nx, cy + ny), reachFrom(cx - nx, cy - ny)]\n      : [reachFrom(cx, cy)];\n    let back = -Infinity, fwd = Infinity;\n    for (const r of lines) {\n      if (!Number.isFinite(r.back) || !Number.isFinite(r.fwd)) return null;\n      back = Math.max(back, r.back);\n      fwd  = Math.min(fwd,  r.fwd);\n    }\n    const lengthMm = fwd - back;\n    if (!(lengthMm > 1)) return null;\n    const mid = (back + fwd) / 2;\n    return { lengthMm, x: cx + dx * mid, y: cy + dy * mid };\n  }\n\n  // Crossing-number test, the same rule the placement engine uses.\n  function pointInRoomPolygon(px, py, verts) {\n    let inside = false;\n    for (let i = 0, j = verts.length - 1; i < verts.length; j = i++) {\n      const xi = verts[i].x, yi = verts[i].y;\n      const xj = verts[j].x, yj = verts[j].y;\n      if (((yi > py) !== (yj > py)) &&\n          (px < ((xj - xi) * (py - yi)) / ((yj - yi) || 1e-9) + xi)) inside = !inside;\n    }\n    return inside;\n  }\n\n  function findFreeSpotForFeature(item) {\n    if (!item || !roomConfig?.shapeParams) return null;\n    const w = item.widthMm  || 600;\n    const d = item.depthMm  || 600;\n    const verts = (room && room.vertices) || [];\n    if (verts.length < 3) return null;\n    const xs = verts.map(v => v.x), ys = verts.map(v => v.y);\n    const bbX0 = Math.min(...xs), bbX1 = Math.max(...xs);\n    const bbY0 = Math.min(...ys), bbY1 = Math.max(...ys);\n    const occupied = [];\n    for (const c of cabinets) {\n      occupied.push({ x: c.x, y: c.y, w: c.widthMm, d: c.depthMm });\n    }\n    for (const it of (roomConfig.perimeterItems || [])) {\n      if (!it || it.id === item.id) continue;\n      occupied.push({ x: it.x, y: it.y, w: it.widthMm, d: it.depthMm });\n    }\n    // The scan walks the BOUNDING BOX, which on anything but a rectangle\n    // includes ground that is not in the room - the outside of an L, the far\n    // side of a nib. An empty patch there is empty because it is not the room.\n    // Every corner has to be inside the polygon as well as clear of everything\n    // else.\n    const inside = (px, py) => pointInRoomPolygon(px, py, verts);\n    const STEP = 200;\n    // Walk the room from top-left to bottom-right looking for the\n    // FIRST empty position. Bias toward \"near top-left\" so multiple\n    // adds land roughly in a row instead of all on top of each other.\n    for (let y = bbY0; y + d <= bbY1; y += STEP) {\n      for (let x = bbX0; x + w <= bbX1; x += STEP) {\n        if (!inside(x, y) || !inside(x + w, y) ||\n            !inside(x + w, y + d) || !inside(x, y + d)) continue;\n        let clash = false;\n        for (const o of occupied) {\n          const overlapX = x < o.x + o.w && x + w > o.x;\n          const overlapY = y < o.y + o.d && y + d > o.y;\n          if (overlapX && overlapY) { clash = true; break; }\n        }\n        if (!clash) return { x: Math.round(x), y: Math.round(y) };\n      }\n    }\n    return null;\n  }\n  // The picker adds by TYPE, with whatever it has been told about size and\n  // preset. The named handlers below stay - they are what the older callers\n  // use - but everything new comes through here.\n  function handleAddRoomFeature(kind, opts = {}) { spawnRoomFeature(kind, opts); }\n\n  function handleAddStepBlock()     { spawnRoomFeature('step-block'); }\n  function handleAddBeam()          { spawnRoomFeature('beam'); }\n  function handleAddSlopedCeiling() { spawnRoomFeature('sloped-ceiling'); }\n  // The same wedge, told to run wall to wall. One type, one 3D builder, one\n  // set of settings - the only difference is who decides its length.\n  function handleAddCeilingWedgeFull() {\n    spawnRoomFeature('sloped-ceiling', { fullWidth: true });\n  }\n  // A sloping ceiling wall to wall. It always spans, so it never asks.\n  function handleAddVaultedCeiling() { spawnRoomFeature('vaulted-ceiling', { fullWidth: true }); }\n  function handleAddFreeBlock()     { spawnRoomFeature('free-block'); }\n  // The same box, low and long, run along the foot of a wall to box in pipes.\n  function handleAddFloorBlock() {\n    spawnRoomFeature('free-block', { preset: 'floor-block' });\n  }\n  function handleAddCookerAlcove(preset) {\n    spawnRoomFeature('cooker-alcove', { preset: preset || 'floor-to-ceiling' });\n  }\n\n  // Add an internal pillar feature - 600 \u00D7 600, free-floating at the\n  // room centre. The user drags it to position; snaps to outer walls\n  // when close.\n  function handleAddPillarFeature() {\n    const starter = makeStarterPillarFeature(\n      roomConfig.shapeParams || {},\n      `column-${nextPerimeterItemId++}`\n    );\n    roomConfig = {\n      ...roomConfig,\n      perimeterItems: [...(roomConfig.perimeterItems || []), starter]\n    };\n    rerender();\n  }\n\n  // Add a plain (rectangular) pillar at the named room corner. Same\n  // toggle semantics as handleAddCornerCut - no-op if a plain pillar\n  // is already anchored to that corner; removal routes through\n  // handleRemovePerimeterItem.\n  function handleAddPillar(corner) {\n    // Only count items with an EXPLICIT pillarCorner - free-floating\n    // walls / pillars (no anchor) should NOT block adding a corner\n    // pillar at the same coordinate.\n    if (cornerOccupant(corner)) return;\n    const starter = makeStarterPillar(\n      roomConfig.shapeParams || {},\n      `column-${nextPerimeterItemId++}`,\n      corner\n    );\n    roomConfig = {\n      ...roomConfig,\n      perimeterItems: [...(roomConfig.perimeterItems || []), starter]\n    };\n    rerender();\n  }\n\n  // opts.exact: the position came from a typed measurement, so it is taken\n  // literally. The usual snap is for dragging - it pulls anything landing\n  // within a few centimetres of a wall flush against it, which silently\n  // overrode the number the user had just entered and merged the pillar into\n  // the wall band. Clamping to the room still applies; nothing may sit outside.\n  function handleUpdateFeature(itemId, updates, opts = {}) {\n    const items = roomConfig.perimeterItems || [];\n    const idx = items.findIndex(it => it.id === itemId);\n    if (idx === -1) return;\n    let updated = { ...items[idx], ...updates };\n    // 10mm, not 100: a 30mm boxing round pipework (Planner Bugs row 56).\n    if (updates.widthMm !== undefined) updated.widthMm = Math.max(10, Math.min(5000, updated.widthMm));\n    if (updates.depthMm !== undefined) updated.depthMm = Math.max(10, Math.min(5000, updated.depthMm));\n    // Cooker alcove - each of leftColumnMm / middleMm / rightColumnMm\n    // is INDEPENDENT. Editing one section never changes the other two;\n    // the overall bbox widthMm = sum of all three. (Earlier version\n    // derived `middleMm` from `widthMm` which made the middle shrink\n    // whenever the user grew a column - that's the bug we're fixing.)\n    if (updated.type === 'cooker-alcove' && (\n      updates.leftColumnMm  !== undefined ||\n      updates.rightColumnMm !== undefined ||\n      updates.middleMm      !== undefined\n    )) {\n      const leftMm  = Math.max(0, updated.leftColumnMm  || 0);\n      const rightMm = Math.max(0, updated.rightColumnMm || 0);\n      const midMm   = Math.max(0, updated.middleMm      || 0);\n      updated.leftColumnMm  = leftMm;\n      updated.rightColumnMm = rightMm;\n      updated.middleMm      = midMm;\n      updated.widthMm       = leftMm + midMm + rightMm;\n    }\n    // Same rule on the way back in: change the style of a socket or a switch\n    // and its plate changes size with it.\n    if (updated.type === 'electrical-point' &&\n        (updates.plateStyle !== undefined || updates.preset !== undefined)) {\n      const p = electricalPlateSize(updated);\n      updated.widthMm  = p.widthMm;\n      updated.heightMm = p.heightMm;\n      updated.depthMm  = p.depthMm;\n    }\n    // Wall-hung and floor-standing boilers are different sizes, so changing\n    // which one it is has to resize it. Wholesale rather than cleverly: the\n    // user has said it is a different kind of boiler, and the default size of\n    // THAT kind is the honest answer.\n    if (updated.type === 'boiler' && updates.preset !== undefined) {\n      Object.assign(updated, boilerDefaults(updated.preset));\n    }\n    // Moving a stopcock from the floor to a wall has to take its height with\n    // it: left at zero it would sit on a wall at floor level, which is not\n    // where anyone puts one.\n    if (updated.type === 'stopcock' && updates.mount !== undefined) {\n      if (updates.mount === 'wall' && !(updated.restMm > 0)) updated.restMm = 500;\n      if (updates.mount === 'floor') updated.restMm = 0;\n    }\n    // A SPLAY cut IS the whole block - one diagonal from wall to wall -\n    // so its two legs are the block's own width and depth. Keep the cut\n    // spanning them whenever either is edited; without this, resizing\n    // would leave the old cut behind and grow back the short returns\n    // the splay exists to avoid.\n    if (updated.cornerCut && updated.cornerCut.mode === 'splay') {\n      updated.cornerCut = {\n        ...updated.cornerCut,\n        xMm: updated.widthMm,\n        yMm: updated.depthMm\n      };\n    }\n    // Corner-anchored pillars (cut-corner OR plain pillar added via\n    // the popup corner squares) need their x/y recomputed whenever\n    // the size or corner-binding changes, so the wall-flush edges\n    // stay against the chosen room corner.\n    const cornerKey = updated.cornerCut?.corner || updated.pillarCorner || null;\n    if (cornerKey &&\n        (updates.cornerCut || updates.pillarCorner ||\n         updates.widthMm !== undefined || updates.depthMm !== undefined)) {\n      const anchor = cornerAnchorPosition(cornerKey, roomConfig.shapeParams || {},\n                                          updated.widthMm, updated.depthMm);\n      updated.x = anchor.x;\n      updated.y = anchor.y;\n    }\n    const others = items.filter((_, i) => i !== idx);\n    const spec = { widthMm: updated.widthMm, depthMm: updated.depthMm, rotationDeg: updated.rotationDeg || 0,\n                   customFit: updated.ignoreClash ? { ignoreClash: true } : null };\n    // A corner block's position is DERIVED - it is wherever its corner is - so\n    // it is never negotiated against the other items. snapAndClamp pushes an\n    // item out of anything it overlaps, which would shove a corner grown wider\n    // clean off its corner and into the middle of the room. Clamping to the\n    // room still applies.\n    // A beam moved by its From Wall boxes is cut to the room where it now\n    // lies, on the heading it has, as a drag cuts it.\n    const beamFit = (spansRoom(updated) && (updates.x !== undefined || updates.y !== undefined))\n      ? fitBeamToRoom(updated, updated.x + (updated.widthMm || 0) / 2,\n                      updated.y + (updated.depthMm || 0) / 2, updated.rotationDeg || 0)\n      : null;\n    if (beamFit) {\n      updated.widthMm = beamFit.widthMm;\n      updated.rotationDeg = beamFit.rotationDeg;\n      updated.x = beamFit.x; updated.y = beamFit.y;\n    } else {\n      const { x, y } = (opts.exact || cornerKey)\n        ? clampToRoom(spec, updated.x, updated.y, room)\n        : snapAndClamp(spec, updated.x, updated.y, room, others, others);\n      updated.x = x; updated.y = y;\n    }\n    const next = [...items];\n    next[idx] = updated;\n    roomConfig = { ...roomConfig, perimeterItems: next };\n    rerender();\n  }\n\n  function handleRotateFeatureById(itemId) {\n    const it = (roomConfig.perimeterItems || []).find(x => x.id === itemId);\n    if (it) rotatePerimeterItem(it);\n  }\n\n  // The stretch of wall the focused measurement refers to, tinted with the\n  // SAME 100mm green band the Room Shape popup uses for a selected wall\n  // (drawWallBand in 2d-grid) on the plan's .btk-kp-grid-svg-overlay.\n  // A LIFTED overlay of our own, mirroring the pillar overlay's trick: the base\n  // walls overlay is the grid's first child at z-auto, so every layer added\n  // afterwards paints - and clicks - over it. Drawing the wall tint and its hit\n  // areas there meant the tint could be covered and the runs were never\n  // clickable. This layer sits above the cabinet layers instead, is\n  // pointer-events:none itself, and lets only the hit polygons opt back in.\n  function planOverlaySvg() {\n    const grid = lastGrid && lastGrid.el;\n    if (!grid) return null;\n    const base = grid.querySelector(\n      '.btk-kp-grid-svg-overlay:not(.btk-kp-grid-svg-overlay--pillars):not(.btk-kp-grid-svg-overlay--wallhits)');\n    if (!base) return null;\n    let svg = grid.querySelector('.btk-kp-grid-svg-overlay--wallhits');\n    if (!svg) {\n      svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');\n      svg.classList.add('btk-kp-grid-svg-overlay', 'btk-kp-grid-svg-overlay--wallhits');\n      svg.style.position = 'absolute';\n      svg.style.overflow = 'visible';\n      grid.appendChild(svg);\n    }\n    // Same box + viewBox as the base overlay so room mm map to the same units -\n    // re-read every time rather than once at creation. The base is REPLACED\n    // whenever the walls are rebuilt, and if it comes back a different size\n    // the hit areas would otherwise keep measuring in the old one's units and\n    // sit somewhere the walls are not.\n    for (const a of ['width', 'height', 'viewBox']) {\n      const v = base.getAttribute(a);\n      if (v != null) svg.setAttribute(a, v);\n    }\n    svg.style.left = base.style.left;\n    svg.style.top  = base.style.top;\n    // Last child, so nothing appended later (the lifted pillar overlay) can\n    // sit over the hit areas and swallow the click.\n    if (grid.lastElementChild !== svg) grid.appendChild(svg);\n    return svg;\n  }\n  function clearOpeningSpan() { clearWallBand(planOverlaySvg()); }\n  function showOpeningSpan(openingId, which) {\n    const svg = planOverlaySvg();\n    if (!svg || !lastGrid) return;\n    clearWallBand(svg);\n    const op = (roomConfig.wallOpenings || []).find(o => o.id === openingId);\n    if (!op || op.floating) return;\n    const wall = getWalls(room)[op.wallIndex];\n    if (!wall) return;\n    const run = openingRuns(op).find(r => r.key === which);\n    if (!run) return;\n    drawWallBand(svg, run.from, run.to, lastGrid.pxPerMm);\n  }\n\n  // The three runs a selected opening's panel can measure: the wall to its\n  // LEFT, the opening's own WIDTH, and the wall to its RIGHT. Returns each as\n  // world-space endpoints so both the tint and the hit areas use one source.\n  // Where an opening's neighbours sit on its wall. prevEnd / nextStart fall\n  // back to the wall ends when there is nothing either side, so a lone opening\n  // behaves exactly as before.\n  function openingNeighbourBounds(op) {\n    const wall = getWalls(room)[op.wallIndex];\n    if (!wall) return null;\n    const wallLen = wall.lengthMm;\n    const start = op.offsetMm || 0;\n    const end   = start + (op.widthMm || 0);\n    let prevEnd = 0, nextStart = wallLen;\n    for (const o of (roomConfig.wallOpenings || [])) {\n      if (!o || o.floating || o.id === op.id || o.wallIndex !== op.wallIndex) continue;\n      const s = o.offsetMm || 0, e = s + (o.widthMm || 0);\n      if (e <= start) prevEnd   = Math.max(prevEnd, e);\n      if (s >= end)   nextStart = Math.min(nextStart, s);\n    }\n    // A pillar or internal wall bounds the gap too. Counting only openings\n    // measured a door's gap from the corner straight through an internal wall,\n    // so typing 1200 threw the door 1200 from the corner and on top of it. One\n    // the opening is cut INTO (it overlaps) is its face, not a neighbour.\n    for (const m of wallStandingItems(op.wallIndex)) {\n      if (m.to <= start + 0.5)   prevEnd   = Math.max(prevEnd, m.to);\n      if (m.from >= end - 0.5)   nextStart = Math.min(nextStart, m.from);\n    }\n    return { wall, wallLen, start, end, prevEnd, nextStart };\n  }\n\n  // The two editable gaps either side of an opening, for the panel. Shared\n  // with the wall runs so the boxes and the plan can't disagree.\n  function getOpeningGaps(openingId) {\n    const op = (roomConfig.wallOpenings || []).find(o => o.id === openingId);\n    if (!op || op.floating) return null;\n    const b = openingNeighbourBounds(op);\n    if (!b) return null;\n    return {\n      leftMm:      Math.max(0, b.start - b.prevEnd),\n      rightMm:     Math.max(0, b.nextStart - b.end),\n      prevEndMm:   b.prevEnd,\n      nextStartMm: b.nextStart,\n      wallLenMm:   b.wallLen\n    };\n  }\n\n  // Everything standing against a wall, measured against it once: how far along\n  // the wall the item reaches (t), how close its nearest face comes (dMin) and\n  // how far its furthest face stands into the room (dMax). dMax is what decides\n  // which face you can see where two items overlap.\n  //\n  // A CORNER IN A CORNER. An item stands on this wall if it is against the wall\n  // itself - or against the room-facing face of something that already is. A\n  // block dropped into the corner that a corner block made sits a block-depth\n  // away from the wall, so the flush test alone never saw it and the step it\n  // created went unnumbered. Repeated to a fixed point, so a step on a step on\n  // a step all count.\n  //\n  // Shared by wallSegments (which numbers the wall) and wallFaceRuns (which\n  // says where the wall's surface actually is) so the two cannot drift.\n  const WALL_FLUSH_TOL_MM = 160;   // wall band is 100 - allow a little standoff\n  // Only a pillar or an internal wall is ever PART of a wall. A step block, a\n  // beam, a slope, a free block, an alcove are objects standing in the room:\n  // they can sit against a wall and be measured to it, and a step still cuts\n  // its doorway, but the wall behind them is still the wall - they never\n  // replace its face or become a numbered section of it. Exactly the standing\n  // an opening has, which is what the wall band being unbroken behind them\n  // already said in 2D and 3D; this makes the wall MODEL agree.\n  const WALL_PART_TYPES = new Set(['column', 'wall']);\n  function wallStandingItems(wallIndex, live) {\n    const wall = getWalls(room)[wallIndex];\n    if (!wall || !wall.lengthMm) return [];\n    // ...and on a DRAWN room not even those - see featuresJoinWalls.\n    if (room && room.featuresJoinWalls === false) return [];\n    const srcItems = (live && live.perimeterItems) || roomConfig.perimeterItems || [];\n    const wallLen = wall.lengthMm;\n    const ux = (wall.to.x - wall.from.x) / wallLen;\n    const uy = (wall.to.y - wall.from.y) / wallLen;\n    const nx = uy, ny = -ux;                       // outward normal\n\n    const measured = [];\n    for (const it of srcItems) {\n      if (!it || !it.widthMm || !it.depthMm) continue;\n      if (!WALL_PART_TYPES.has(it.type || 'column')) continue;\n      const corners = getCornersForPush(it, it.x, it.y);\n      const proj = corners.map(c => {\n        const vx = c.x - wall.from.x, vy = c.y - wall.from.y;\n        return { t: vx * ux + vy * uy, d: vx * nx + vy * ny };\n      });\n      let tMin = Infinity, tMax = -Infinity, dMin = Infinity, dMax = -Infinity;\n      for (const q of proj) {\n        tMin = Math.min(tMin, q.t); tMax = Math.max(tMax, q.t);\n        dMin = Math.min(dMin, Math.abs(q.d));\n        dMax = Math.max(dMax, Math.abs(q.d));\n      }\n      const from = Math.max(0, tMin), to = Math.min(wallLen, tMax);\n      if (to - from <= 1) continue;                // no real overlap\n      measured.push({ it, from, to, dMin, dMax });\n    }\n\n    const onWall = [];\n    for (let pass = 0; pass < 8; pass++) {\n      let added = false;\n      for (const m of measured) {\n        if (onWall.includes(m)) continue;\n        const direct = m.dMin <= WALL_FLUSH_TOL_MM;\n        const stacked = !direct && onWall.some(h =>\n          Math.abs(m.dMin - h.dMax) <= WALL_FLUSH_TOL_MM &&\n          Math.min(m.to, h.to) - Math.max(m.from, h.from) > 1);\n        if (direct || stacked) { onWall.push(m); added = true; }\n      }\n      if (!added) break;\n    }\n    return onWall;\n  }\n\n  // WHERE THE WALL'S SURFACE ACTUALLY IS, run by run along it.\n  //\n  // A pillar or a corner block standing against a wall IS the wall for the\n  // stretch it covers - walk in from outside and its face is the first thing\n  // you meet, and in 3D the perimeter wall behind it is not even built. So the\n  // wall has a stepped face: 0 where it is bare, and the item's depth where one\n  // stands. Same depth-wins rule as wallSegments, so a block on a block reads\n  // its own face rather than the one it is sitting on.\n  //\n  // This is what lets a door or window be cut into a pillar or a corner wall\n  // instead of sliding behind it and landing on the outer perimeter.\n  function wallFaceRuns(wallIndex, live) {\n    const wall = getWalls(room)[wallIndex];\n    if (!wall || !wall.lengthMm) return [];\n    const wallLen = wall.lengthMm;\n    const standing = wallStandingItems(wallIndex, live);\n    if (!standing.length) return [{ fromMm: 0, toMm: wallLen, insetMm: 0, itemId: null }];\n\n    const marks = new Set([0, wallLen]);\n    for (const m of standing) {\n      marks.add(Math.max(0, Math.min(wallLen, m.from)));\n      marks.add(Math.max(0, Math.min(wallLen, m.to)));\n    }\n    const cuts = [...marks].sort((a, b) => a - b);\n    const runs = [];\n    for (let i = 0; i < cuts.length - 1; i++) {\n      const a = cuts[i], b = cuts[i + 1];\n      if (b - a <= 1) continue;\n      const mid = (a + b) / 2;\n      let win = null;\n      for (const m of standing) {\n        if (!(m.from <= mid && m.to >= mid)) continue;\n        if (!win || m.dMax > win.dMax) win = m;\n      }\n      const insetMm = win ? win.dMax : 0;\n      const itemId  = win ? win.it.id : null;\n      const prev = runs[runs.length - 1];\n      if (prev && Math.abs(prev.insetMm - insetMm) < 0.5 && prev.itemId === itemId) {\n        prev.toMm = b;                              // same face, one run\n      } else {\n        runs.push({ fromMm: a, toMm: b, insetMm, itemId });\n      }\n    }\n    return runs.length ? runs : [{ fromMm: 0, toMm: wallLen, insetMm: 0, itemId: null }];\n  }\n\n  // The run a placed opening belongs to - the one its CENTRE sits in, so the\n  // answer is the same every time however the opening straddles a step.\n  function openingFaceRun(opening, live) {\n    if (!opening || opening.floating) return null;\n    const runs = wallFaceRuns(opening.wallIndex, live);\n    if (!runs.length) return null;\n    const mid = (opening.offsetMm || 0) + (opening.widthMm || 0) / 2;\n    return runs.find(r => r.fromMm <= mid && r.toMm >= mid) || runs[0];\n  }\n\n  function openingInsetMm(opening, live) {\n    const run = openingFaceRun(opening, live);\n    return run ? run.insetMm : 0;\n  }\n\n  function wallFaceInsetAt(wallIndex, mm, live) {\n    const run = wallFaceRuns(wallIndex, live).find(r => r.fromMm <= mm && r.toMm >= mm);\n    return run ? run.insetMm : 0;\n  }\n\n  // Every placed opening's resolved face inset, keyed by id, for the 3D\n  // renderer. It builds the pillar and corner-block faces itself but has no\n  // depth-partition of its own, so the plan hands it the answer it already\n  // worked out - which is also what keeps the hole in 3D in the same place as\n  // the hole on the plan.\n  function openingFaceInsetMap() {\n    const out = {};\n    for (const op of (roomConfig.wallOpenings || [])) {\n      if (!op || op.floating) continue;\n      const inset = openingInsetMm(op);\n      if (inset > 0.5) out[op.id] = inset;\n    }\n    return out;\n  }\n\n  // The nearest WALL FACE to a point - the stepped surface wallFaceRuns\n  // describes, not the room polygon. projectToNearestWall measures to the\n  // polygon, so a pillar's face 600mm into the room read as 600mm off the\n  // wall: outside snap range, which is why an opening slid straight past a\n  // pillar and landed on the perimeter behind it.\n  //\n  // Runs too short to hold the opening are skipped rather than clamped, so a\n  // narrow pillar face is simply not a place a 900mm door can go and the door\n  // carries on to the next face that can take it.\n  function projectOpeningToFace(x, y, widthMm, live) {\n    const walls = getWalls(room);\n    let best = null;\n    walls.forEach((wall, wallIndex) => {\n      if (!wall.lengthMm || wall.lengthMm < widthMm) return;\n      const ux = (wall.to.x - wall.from.x) / wall.lengthMm;\n      const uy = (wall.to.y - wall.from.y) / wall.lengthMm;\n      const ix = -uy, iy = ux;                     // inward normal\n      for (const run of wallFaceRuns(wallIndex, live)) {\n        const runLen = run.toMm - run.fromMm;\n        if (runLen < widthMm) continue;\n        const ax = wall.from.x + ux * run.fromMm + ix * run.insetMm;\n        const ay = wall.from.y + uy * run.fromMm + iy * run.insetMm;\n        let t = (x - ax) * ux + (y - ay) * uy;\n        t = Math.max(0, Math.min(runLen, t));\n        const distance = Math.hypot(x - (ax + ux * t), y - (ay + uy * t));\n        if (!best || distance < best.distance) {\n          best = { wallIndex, offsetMm: run.fromMm + t, distance, run };\n        }\n      }\n    });\n    return best;\n  }\n\n  // A wall read left to right: gap, opening, gap, opening, gap. Gaps are kept\n  // even at zero length so the numbering stays put while things move. One\n  // model behind the wall panel AND the clickable runs on the plan.\n  // `live` lets a caller ask about work in progress - refreshDims hands the\n  // dimension engine the dragged positions every frame, and the dims have to\n  // follow the pillar rather than freeze until it is dropped.\n  function wallSegments(wallIndex, live) {\n    const wall = getWalls(room)[wallIndex];\n    if (!wall) return [];\n    const srcOpenings = (live && live.wallOpenings)   || roomConfig.wallOpenings   || [];\n    const wallLen = wall.lengthMm;\n    const ux = (wall.to.x - wall.from.x) / wallLen;\n    const uy = (wall.to.y - wall.from.y) / wallLen;\n\n    // What occupies the wall, in order: openings by their offset, plus any\n    // perimeter item standing against it. A corner treatment is one of those\n    // items, which is why a corner splits its wall without the room polygon\n    // changing at all.\n    const occupants = srcOpenings\n      .filter(o => o && !o.floating && o.wallIndex === wallIndex)\n      .map(o => ({ kind: 'opening', id: o.id, type: o.type,\n                   fromMm: o.offsetMm || 0, toMm: (o.offsetMm || 0) + (o.widthMm || 0) }));\n\n    const onWall = wallStandingItems(wallIndex, live);\n\n    for (const m of onWall) {\n      const it = m.it, from = m.from, to = m.to;\n      const isCorner = !!it.cornerCut;\n      // Which of the item's own dimensions runs ALONG this wall - it depends on\n      // the item's rotation as well as the wall's direction, so compare its\n      // local axes to the wall rather than assuming width is horizontal.\n      const r   = ((it.rotationDeg || 0) * Math.PI) / 180;\n      const lxx = Math.cos(r),  lxy = Math.sin(r);   // local +X in world\n      const lyx = -Math.sin(r), lyy = Math.cos(r);   // local +Y in world\n      const alongX = Math.abs(lxx * ux + lxy * uy);\n      const alongY = Math.abs(lyx * ux + lyy * uy);\n\n      const legProp = alongX >= alongY ? 'widthMm' : 'depthMm';\n      const cutProp = alongX >= alongY ? 'xMm'     : 'yMm';\n      const base = {\n        kind: 'feature', id: it.id,\n        label: isCorner ? 'Corner' : (it.type === 'wall' ? 'Wall nib' : 'Pillar'),\n        sizeProp: legProp, cutProp,\n        depth: m.dMax,         // how far into the room this item's face stands\n        dMin: m.dMin,          // ...and how close its nearest face comes to it\n        // A corner is pinned to the room's corner - moving it along the wall\n        // would just tear it off the corner it exists to make. A pillar or nib\n        // standing mid-wall has no such anchor and slides freely, which is what\n        // lets the stretch of wall beside it be a number you can type.\n        moveable: !isCorner && !it.pillarCorner\n      };\n      const cc     = it.cornerCut || null;\n      const legMm  = Math.max(0, to - from);\n      const cutMm  = cc ? Math.max(0, Math.min(legMm, Number(cc[cutProp]) || 0)) : 0;\n      const isSplay = !!(cc && cc.mode === 'splay');\n\n      if (isSplay || (cc && cutMm >= legMm - 1)) {\n        // The cut takes the whole run - all diagonal, no return.\n        occupants.push({ ...base, fromMm: from, toMm: to, edit: 'cut', inlineFill: true });\n      } else if (cc && cutMm > 1) {\n        // Split by the CUT, not by the footprint: the block's edge on this\n        // wall is unbroken (the cut is taken out of the interior corner), so\n        // measuring the flush edge just gives the whole leg back. The cut sits\n        // at the end AWAY from the room corner - the block has one end on the\n        // wall's own end, and the diagonal starts from the other.\n        const atStart  = from <= 1;\n        const cutSpan  = atStart ? [to - cutMm, to] : [from, from + cutMm];\n        const retSpan  = atStart ? [from, to - cutMm] : [from + cutMm, to];\n        if (retSpan[1] - retSpan[0] > 1) {\n          // The return draws itself too - the block's own band is off, so both\n          // parts of the corner carry the same 50% wall.\n          occupants.push({ ...base, fromMm: retSpan[0], toMm: retSpan[1],\n                           edit: 'return', inlineFill: true });\n        }\n        occupants.push({ ...base, fromMm: cutSpan[0], toMm: cutSpan[1],\n                         edit: 'cut', inlineFill: true });\n      } else {\n        // Square corner / pillar / nib - one straight section. A plain block\n        // still draws its own band, so this one stays an invisible hit area.\n        occupants.push({ ...base, fromMm: from, toMm: to, edit: 'return',\n                         inlineFill: !!cc });\n      }\n    }\n    occupants.sort((a, b) => a.fromMm - b.fromMm);\n\n    // PARTITION THE WALL BY DEPTH. Walking in from the wall at any point, the\n    // face you can see is the one standing FURTHEST into the room - so where a\n    // block sits on a block, the upper one owns the stretch it covers and the\n    // lower one keeps the rest. That is what turns a corner in a corner into\n    // its own numbered section instead of being swallowed by the block beneath\n    // it. Cutting at every boundary and asking who wins each piece also\n    // removes the old running cursor, which silently collapsed anything that\n    // started behind where it had already reached.\n    const marks = new Set([0, wallLen]);\n    for (const oc of occupants) {\n      marks.add(Math.max(0, Math.min(wallLen, oc.fromMm)));\n      marks.add(Math.max(0, Math.min(wallLen, oc.toMm)));\n    }\n    const cuts = [...marks].sort((a, b) => a - b);\n    // An opening is a hole IN the wall, so it wins outright wherever it runs.\n    const winnerAt = (mid) => {\n      const op = occupants.find(o => o.kind === 'opening' && o.fromMm <= mid && o.toMm >= mid);\n      if (op) return op;\n      let best = null;\n      for (const o of occupants) {\n        if (o.kind === 'opening') continue;\n        if (!(o.fromMm <= mid && o.toMm >= mid)) continue;\n        if (!best || (o.depth || 0) > (best.depth || 0)) best = o;\n      }\n      return best;\n    };\n    const runs = [];\n    for (let i = 0; i < cuts.length - 1; i++) {\n      const a = cuts[i], b = cuts[i + 1];\n      if (b - a <= 1) continue;\n      const win = winnerAt((a + b) / 2);\n      const prev = runs[runs.length - 1];\n      if (prev && prev.win === win) prev.b = b;      // same owner, one section\n      else runs.push({ a, b, win });\n    }\n\n    // Everything that isn't a door or window is just another stretch of wall to\n    // the user - a corner's leg included - so gaps and wall-standing items\n    // share ONE \"Wall n\" sequence. Zero-length gaps are dropped: with items in\n    // the run they would show as 0mm sections and push the numbering along.\n    const segs = [];\n    let wallNo = 0;\n    // A stretch that IS the whole wall has a length of its own after all: the\n    // wall's, which the room shape sets. Carrying the key here is what lets the\n    // panel offer a box on a bare wall - on Square and Rectangle, where nothing\n    // stands on any wall, every box was read-only with no way to resize the\n    // room except the Room Shape popup.\n    const wholeWallParam = wallShapeParam(roomConfig.shapeId, wallIndex);\n    const readsBack = ux < -0.5;   // listed flipped - see the reverse at the end\n    // A section's LOCK is keyed to what it is, not to its number, so it stays\n    // on the same stretch while things either side move: an opening or a block\n    // by its id, a plain stretch by the two things it runs between.\n    const lockKey = (w) => w ? `${w.kind === 'opening' ? 'op' : 'ft'}:${w.id}` : null;\n    const pushWall = (fromMm, toMm, extra) => {\n      if (toMm - fromMm <= 1) return;\n      wallNo += 1;\n      const spansWall = fromMm <= 1 && toMm >= wallLen - 1;\n      segs.push({ kind: 'gap', key: `wall-${wallNo}`, label: `Wall ${wallNo}`,\n                  num: wallNo,\n                  fromMm, toMm, sizeMm: toMm - fromMm,\n                  ownerId: null, ownerSide: 'left',\n                  shapeParam: (spansWall && wholeWallParam) || null,\n                  ...(extra || {}) });\n    };\n    runs.forEach((run, i) => {\n      const oc = run.win;\n      if (!oc) {\n        // A plain stretch of wall has no length of its own to set - it is\n        // whatever is left over. So editing it moves the thing beside it\n        // instead, and the stretch becomes the distance TO that thing. The one\n        // after it goes first, the one before it only if there is nothing\n        // after; a corner is never a candidate, so a stretch cornered at both\n        // ends stays read-only because there is genuinely nothing to move.\n        const nextWin = runs[i + 1] && runs[i + 1].win;\n        const prevWin = runs[i - 1] && runs[i - 1].win;\n        const canMove = (win) => !!win &&\n          (win.kind === 'opening' || (win.kind === 'feature' && win.moveable));\n        // A corner cannot be slid along the wall - it is pinned to its corner -\n        // but it CAN be made longer or shorter, and the wall total is fixed, so\n        // the stretch beside it is still a number worth typing: it just resizes\n        // the corner instead of moving it. Without this a plain wall butting a\n        // corner run was read-only with nothing wrong with it.\n        const canResize = (win) => !!win && win.kind === 'feature' && !win.moveable;\n        // \"After\" as the panel lists it, not as the wall is traced. A wall\n        // traced right to left is listed flipped (below), so its next item is\n        // the one BEFORE it here - otherwise C3 moved the door on its left\n        // instead of the internal wall on its right.\n        const after  = readsBack ? { win: prevWin, side: 'right' } : { win: nextWin, side: 'left' };\n        const before = readsBack ? { win: nextWin, side: 'left' }  : { win: prevWin, side: 'right' };\n        const extra = canMove(after.win)\n          ? { ownerId: after.win.id, ownerKind: after.win.kind, ownerSide: after.side }\n          : canMove(before.win)\n            ? { ownerId: before.win.id, ownerKind: before.win.kind, ownerSide: before.side }\n            : canResize(after.win)\n              ? { ownerId: after.win.id, ownerKind: 'feature', ownerSide: after.side, ownerFixed: true }\n              : canResize(before.win)\n                ? { ownerId: before.win.id, ownerKind: 'feature', ownerSide: before.side, ownerFixed: true }\n                : null;\n        const spans = run.a <= 1 && run.b >= wallLen - 1;\n        pushWall(run.a, run.b, {\n          ...(extra || {}),\n          // A whole bare wall is the room's own size, set in Room Shape - a lock\n          // here could not hold it, so it gets none.\n          lockId: spans ? null\n            : `gap:${wallIndex}:${lockKey(runs[i - 1] && runs[i - 1].win) || 'start'}:${lockKey(runs[i + 1] && runs[i + 1].win) || 'end'}`\n        });\n        return;\n      }\n      if (oc.kind === 'opening') {\n        // Doors and windows take their turn in the SAME sequence as the wall\n        // sections, so a wall reads 1, 2, 3, 4 straight through and every part\n        // of it can be named on the plan.\n        wallNo += 1;\n        segs.push({ kind: 'opening', key: `op-${oc.id}`, id: oc.id, type: oc.type,\n                    num: wallNo, lockId: `op:${oc.id}`,\n                    fromMm: run.a, toMm: run.b, sizeMm: run.b - run.a });\n        return;\n      }\n      // The item itself is a numbered wall section, resized along THIS wall.\n      // coveredMm is however much of it another item stands in front of: the\n      // box shows the visible remainder, so resizing has to add that back or\n      // the block would shrink by the part the user cannot even see.\n      wallNo += 1;\n      segs.push({ kind: 'feature', key: `wall-${wallNo}`, id: oc.id,\n                  label: `Wall ${wallNo}`, num: wallNo, moveable: !!oc.moveable,\n                  lockId: `ft:${oc.id}:${oc.edit || 'return'}`,\n                  dMin: oc.dMin,\n                  fromMm: run.a, toMm: run.b, sizeMm: run.b - run.a,\n                  coveredMm: Math.max(0, (oc.toMm - oc.fromMm) - (run.b - run.a)),\n                  sizeProp: oc.sizeProp, cutProp: oc.cutProp,\n                  edit: oc.edit, inlineFill: oc.inlineFill });\n    });\n    // A wall with nothing on it is still one section.\n    if (!segs.length) pushWall(0, wallLen, null);\n    const locks = new Set(roomConfig.sectionLocks || []);\n    for (const sg of segs) sg.locked = !!(sg.lockId && locks.has(sg.lockId));\n\n    // How long each section could be asked to become: its own run plus the\n    // plain wall touching either end. A block anchored to a corner has nothing\n    // behind it, so that side contributes nothing and the block can only grow\n    // forward - which is exactly how far the wall has left. Without this a\n    // nested 500 could be typed up to any number and jumped out of the corner\n    // it was sitting in.\n    const allItems = (live && live.perimeterItems) || roomConfig.perimeterItems || [];\n    const reachFrom = (startIdx, step, family) =>\n      wallPushTrain(segs, startIdx, step, family).reach;\n    for (const sg of segs) {\n      if (sg.kind !== 'feature') continue;\n      // A block split by an opening cut into its face is two rows; its room to\n      // grow is measured across the WHOLE of it, not one of the pieces.\n      const mine = segs.filter(x => x.kind === 'feature' && x.id === sg.id);\n      const t0 = Math.min(...mine.map(x => x.fromMm));\n      const t1 = Math.max(...mine.map(x => x.toMm));\n      // Only the free wall on the side it actually GROWS INTO counts. A block\n      // is pinned at its corner - room corner or the corner its parent makes -\n      // so it can only extend away from that corner, and free wall behind it is\n      // free wall it can never reach.\n      const it = allItems.find(x => x && x.id === sg.id);\n      const o = it ? (it.cornerCut ? (it.cornerCut.corner || 'tr') : it.pillarCorner) : null;\n      const gx = (!o || o === 'tl' || o === 'bl') ? 1 : -1;\n      const gy = (!o || o === 'tl' || o === 'tr') ? 1 : -1;\n      const alongSign = gx * ux + gy * uy;          // one term per axis wall\n      // Corners nested in this one - and in those - travel WITH it: their\n      // anchors are derived from it, so growing it walks the whole run along\n      // and the plain wall at the end of the run gives up the difference. So\n      // the reach is measured past the family, not stopped by the first of\n      // them. Anything that is NOT family still stops it dead.\n      // A block only standing on this wall THROUGH another one - it shows here\n      // because it is the deepest thing at that height, not because it touches\n      // the wall - is not hemmed in by what else is listed on it. Those\n      // neighbours sit BESIDE it at another depth, not in front of it, so\n      // measuring against them stopped a block growing with nothing whatever in\n      // its way. Its own room clamp and its corner anchor still hold it.\n      if ((sg.dMin || 0) > WALL_FLUSH_TOL_MM) { sg.maxMm = Math.round(wallLen); continue; }\n      const reach = reachFrom(segs.indexOf(sg), alongSign >= 0 ? 1 : -1, new Set([sg.id]));\n      sg.maxMm = Math.round((t1 - t0) + reach);\n    }\n    // Walls the room traces RIGHT-TO-LEFT (the bottom wall, C) would number\n    // and list from the right. The panel says \"from left to right\", so flip\n    // those so the rows and names match what the eye does. Vertical walls\n    // (B and D) already read top-to-bottom, which is correct.\n    if (readsBack) {\n      segs.reverse();\n      let n = 0;\n      for (const sg of segs) {\n        n += 1;\n        sg.num = n;\n        if (sg.kind !== 'opening') sg.label = `Wall ${n}`;\n      }\n    }\n    return segs;\n  }\n  function getWallSegments(wallIndex) { return wallSegments(wallIndex); }\n\n  // The wall model as the dimension engine wants it: occupied runs only, since\n  // it fills the gaps itself. One model behind both, so a figure on the plan\n  // and a figure in the menu are the same figure.\n  function wallDimSpans(wallIndex, live) {\n    return wallSegments(wallIndex, live)\n      .filter(sg => sg.kind !== 'gap' && sg.toMm - sg.fromMm > 0.5)\n      .map(sg => ({\n        start: sg.fromMm,\n        end:   sg.toMm,\n        kind:  sg.kind === 'opening'\n          ? (sg.type === 'window' ? 'window' : 'door')\n          : 'pillar'\n      }));\n  }\n\n  // Editing a segment: an opening's own size is its width; a gap is applied\n  // through the opening that owns it, so its neighbours stay put.\n  // A stretch of wall resized by moving the pillar / internal wall beside it.\n  // The shift runs ALONG the wall, so the item keeps its distance from that\n  // wall and only its position on it changes - the same thing dragging it\n  // would do, done to the millimetre.\n  //\n  // It is clamped to the free space either side: a stretch can only grow into\n  // whatever plain wall lies on the far side of the thing being pushed, so the\n  // item can never be shoved through a door or off the end of the wall.\n  // A stretch of wall resized by RESIZING the corner beside it. The wall's\n  // length is fixed, so whatever this stretch gains the corner gives up, and\n  // the corner stays on its corner throughout - it grows and shrinks from the\n  // free end, which is the end this stretch is on.\n  function handleSetGapByResize(wallIndex, seg, valueMm) {\n    const segs = wallSegments(wallIndex);\n    const owner = segs.find(x => x.kind === 'feature' && x.id === seg.ownerId);\n    if (!owner || !owner.sizeProp) return;\n    const it = (roomConfig.perimeterItems || []).find(x => x.id === seg.ownerId);\n    if (!it) return;\n    const delta = valueMm - (seg.toMm - seg.fromMm);\n    if (!delta) return;\n    const leg = Number(it[owner.sizeProp]) || 0;\n    // Whatever the stretch gains, the corner loses. Its own minimum stops it\n    // collapsing; its cap stops it swallowing more wall than there is.\n    let next = leg - delta;\n    next = Math.max(100, next);\n    if (owner.maxMm) next = Math.min(next, owner.maxMm + (leg - (owner.toMm - owner.fromMm)));\n    if (Math.round(next) === Math.round(leg)) return;\n    handleUpdateFeature(it.id, { [owner.sizeProp]: Math.round(next) });\n  }\n\n  function handleSetGapByFeature(wallIndex, seg, valueMm) {\n    const wall = getWalls(room)[wallIndex];\n    if (!wall || !wall.lengthMm) return;\n    const segs = wallSegments(wallIndex);\n    // The mover's WHOLE span, not the row next to the gap: a pillar with a\n    // window cut into its face is two rows with the window between them, and\n    // reading the slack off one of them would stop the pillar a window short\n    // of where it can actually go.\n    const family = new Set([seg.ownerId]);\n    // By key: `seg` came from the caller's own wallSegments() call, so it is\n    // never one of THESE objects and indexOf always missed - a stretch of\n    // wall could not move a pillar or internal wall at all.\n    const here = segs.findIndex(x => x.key === seg.key);\n    if (here < 0) return;\n    // Toward the thing this stretch moves; away from it is the stretch itself.\n    // Read off the list, not ownerSide: ownerSide is along the wall as traced,\n    // and a wall traced right to left is listed flipped, so stepping by it\n    // walked away from the mover and pushed whatever stood on the far side.\n    const toward = (segs[here + 1] && segs[here + 1].id === seg.ownerId) ? 1 : -1;\n    const train = wallPushTrain(segs, here, toward, family);\n    const slackBeyond = train.reach;\n    const slackHere = seg.toMm - seg.fromMm;\n\n    const delta = valueMm - slackHere;\n    let shift = seg.ownerSide === 'left' ? delta : -delta;\n    const lo = seg.ownerSide === 'left' ? -slackHere : -slackBeyond;\n    const hi = seg.ownerSide === 'left' ?  slackBeyond : slackHere;\n    shift = Math.max(lo, Math.min(hi, shift));\n    if (!shift) return;\n\n    const ux = (wall.to.x - wall.from.x) / wall.lengthMm;\n    const uy = (wall.to.y - wall.from.y) / wall.lengthMm;\n    const it = (roomConfig.perimeterItems || []).find(x => x.id === seg.ownerId);\n    if (!it) return;\n    // The mover AND everything standing between it and the plain wall it is\n    // moving into - otherwise the first thing in the way stops the lot.\n    shiftAlongWall(wallIndex, train.push, shift);\n    handleUpdateFeature(it.id, {\n      x: it.x + ux * shift,\n      y: it.y + uy * shift\n    }, { exact: true });\n  }\n\n  // Lock or unlock one section of a wall. Kept on the room so it is saved with\n  // the plan and is still there when the customer comes back.\n  function handleToggleSegmentLock(wallIndex, segKey) {\n    const seg = wallSegments(wallIndex).find(x => x.key === segKey);\n    if (!seg || !seg.lockId) return;\n    const locks = new Set(roomConfig.sectionLocks || []);\n    if (locks.has(seg.lockId)) locks.delete(seg.lockId); else locks.add(seg.lockId);\n    roomConfig = { ...roomConfig, sectionLocks: [...locks] };\n    rerender();\n  }\n\n  // A section resized on a wall that has LOCKED sections. The wall is a row of\n  // lengths that add up to the wall, so whatever this one gains another has to\n  // give: the next unlocked stretch of plain wall, reading left to right, or\n  // failing that the nearest one to the left. Everything between the two slides\n  // along, so every locked number - and every stretch between things that move\n  // together - stays exactly as it was. When no plain stretch can, an\n  // unlocked pillar or internal wall gives by changing its width. Doors and\n  // windows never do: their widths are real product sizes.\n  //\n  // Returns { ok } or { ok: false, reason } for the panel to show.\n  function resizeSectionWithLocks(wallIndex, seg, v) {\n    const wall = getWalls(room)[wallIndex];\n    if (!wall || !wall.lengthMm) return { ok: false };\n    const ux = (wall.to.x - wall.from.x) / wall.lengthMm;\n    const uy = (wall.to.y - wall.from.y) / wall.lengthMm;\n    const listed = wallSegments(wallIndex);\n    // Traced order is what positions are measured in; listed is what the eye\n    // reads. They differ only on a wall traced right to left.\n    const traced = ux < -0.5 ? [...listed].reverse() : listed;\n    const li = listed.findIndex(x => x.key === seg.key);\n    const si = traced.findIndex(x => x.key === seg.key);\n    if (li < 0 || si < 0) return { ok: false };\n    const S = listed[li];\n\n    let delta, op = null, it = null;\n    if (S.kind === 'gap') {\n      delta = v - S.sizeMm;\n    } else if (S.kind === 'opening') {\n      op = (roomConfig.wallOpenings || []).find(o => o.id === S.id);\n      if (!op) return { ok: false };\n      const w = clampOpeningWidth(op.variant, op.styleCode, Math.max(100, v));\n      delta = w - (op.widthMm || 0);\n    } else {\n      it = (roomConfig.perimeterItems || []).find(x => x.id === S.id);\n      if (!it || !S.sizeProp) return { ok: false };\n      delta = Math.max(100, v + (S.coveredMm || 0)) - (Number(it[S.sizeProp]) || 0);\n    }\n    delta = Math.round(delta);\n    if (!delta) return { ok: true };\n\n    // Can things between S and a candidate slide? Doors, windows and free\n    // pillars can; a corner is pinned and stops the walk.\n    const pathClear = (ai) => {\n      const lo = Math.min(si, ai), hi = Math.max(si, ai);\n      for (let k = lo + 1; k < hi; k++) {\n        const x = traced[k];\n        if (x.kind === 'gap' || x.kind === 'opening') continue;\n        if (x.kind === 'feature' && (x.moveable || x.id === S.id)) continue;\n        return false;\n      }\n      return true;\n    };\n    const after  = listed.slice(li + 1);\n    const before = listed.slice(0, li).reverse();\n    const order  = [...after, ...before];\n    const rowsOf = (id) => listed.filter(x => x.kind === 'feature' && x.id === id);\n    let absorber = null;\n    // Plain wall first: an unlocked stretch takes the difference and whatever\n    // stands between slides along.\n    for (const c of order) {\n      if (c.kind !== 'gap' || c.locked || c.key === S.key) continue;\n      if (c.sizeMm - delta < 0) continue;              // would go below nothing\n      const ai = traced.findIndex(x => x.key === c.key);\n      if (pathClear(ai)) { absorber = { seg: c, ai }; break; }\n    }\n    // Every stretch that could is locked: an unlocked pillar or internal wall\n    // gives instead, by changing its own width - lock C1, the door and C5 and\n    // type 1000 into C3, and the internal wall C4 goes from 100 to 300. Never a\n    // door or window (their widths are the products'), never a corner (pinned,\n    // with rules of its own), and only a block showing as ONE whole row - one\n    // split by an opening or partly hidden has no single width to give.\n    let tooThin = null;                // an unlocked block that would drop below 100\n    if (!absorber) {\n      for (const c of order) {\n        if (c.kind !== 'feature' || !c.moveable || c.locked || c.id === S.id || !c.sizeProp) continue;\n        if (rowsOf(c.id).length !== 1 || (c.coveredMm || 0) > 0.5) continue;\n        const bi = (roomConfig.perimeterItems || []).find(x => x.id === c.id);\n        if (!bi) continue;\n        const ai = traced.findIndex(x => x.key === c.key);\n        if (!pathClear(ai)) continue;\n        if ((Number(bi[c.sizeProp]) || 0) - delta < 100) { tooThin = tooThin || c; continue; }\n        absorber = { seg: c, ai, block: bi }; break;\n      }\n    }\n    if (!absorber && tooThin) {\n      return { ok: false, reason: `That would make section ${tooThin.num} thinner than 100 mm. Unlock another section to share the difference, or use a smaller change.` };\n    }\n    if (!absorber) {\n      return { ok: false, reason: 'Nothing unlocked on this wall can take up the difference. Unlock another stretch of wall, a pillar or an internal wall and try again.' };\n    }\n\n    // Toward the absorber, along the wall as traced.\n    const sign = absorber.ai > si ? 1 : -1;\n    const push = [];\n    for (let k = Math.min(si, absorber.ai) + 1; k < Math.max(si, absorber.ai); k++) {\n      const x = traced[k];\n      if (x.kind === 'gap' || x.id === S.id) continue;\n      if (!push.some(p => p.id === x.id)) push.push({ kind: x.kind, id: x.id });\n    }\n    shiftAlongWall(wallIndex, push, sign * delta);\n\n    // Resize a block along this wall and slide it so the end named by `keep`\n    // is back where it was - which end a size change moves depends on the\n    // block's rotation and the wall's direction, so measure rather than guess.\n    const resizeBlock = (block, sizeProp, add, keep) => {\n      const span = () => {\n        const m = wallStandingItems(wallIndex).find(q => q.it.id === block.id);\n        return m ? { from: m.from, to: m.to } : null;\n      };\n      const was = span();\n      block[sizeProp] = Math.max(100, (Number(block[sizeProp]) || 0) + add);\n      const now = span();\n      if (was && now) {\n        const fix = keep === 'from' ? (was.from - now.from) : (was.to - now.to);\n        block.x += ux * fix;\n        block.y += uy * fix;\n      }\n    };\n    // The absorbing block gives up what S gained from its NEAR end; its far\n    // end, and everything beyond it, stays put.\n    if (absorber.block) {\n      resizeBlock(absorber.block, absorber.seg.sizeProp, -delta, sign > 0 ? 'to' : 'from');\n    }\n\n    if (op) {\n      // Grows toward the absorber: its far edge moves, the near one stays.\n      handleUpdateOpening(op.id, {\n        widthMm: (op.widthMm || 0) + delta,\n        offsetMm: sign < 0 ? (op.offsetMm || 0) - delta : (op.offsetMm || 0)\n      });\n    } else if (it) {\n      // Same for a block: the end AWAY from the absorber stays.\n      resizeBlock(it, S.sizeProp, delta, sign > 0 ? 'from' : 'to');\n      rerender();\n    } else {\n      rerender();\n    }\n    return { ok: true };\n  }\n\n  function handleSetSegmentSize(wallIndex, segKey, valueMm) {\n    const seg = wallSegments(wallIndex).find(x => x.key === segKey);\n    if (!seg) return;\n    const v = Math.max(0, Math.round(valueMm));\n    if (seg.locked) return { ok: false, reason: 'This section is locked. Unlock it to change it.' };\n    // A section of a block's face beside a door or window cut INTO that face is\n    // the distance to the opening, so typing it slides the opening along the\n    // face - the same as a plain stretch beside a door. It used to resize the\n    // block instead: on a corner the free end moved, so the door stayed put and\n    // the locked sections above it shifted (Arden, 2026-10-14). The block's own\n    // size is set in Room Shape.\n    if (seg.kind === 'feature') {\n      const segsNow = wallSegments(wallIndex);\n      const at = segsNow.findIndex(x => x.key === seg.key);\n      const rows = segsNow.filter(x => x.kind === 'feature' && x.id === seg.id);\n      const t0 = Math.min(...rows.map(x => x.fromMm));\n      const t1 = Math.max(...rows.map(x => x.toMm));\n      for (const step of [1, -1]) {\n        const o = segsNow[at + step];\n        if (!o || o.kind !== 'opening' || o.fromMm < t0 - 1 || o.toMm > t1 + 1) continue;\n        if (o.locked) return { ok: false, reason: 'The door or window beside this section is locked. Unlock it to move it.' };\n        const op = (roomConfig.wallOpenings || []).find(x => x.id === o.id);\n        if (!op) continue;\n        // In traced millimetres: is this section on the low or the high side?\n        const low = seg.toMm <= o.fromMm + 1;\n        const far = segsNow[at + 2 * step];\n        const width = o.toMm - o.fromMm;\n        // The opening can travel as far as the section on its other side\n        // reaches, and no further - only if that is the same block's face.\n        const farOk = far && far.kind === 'feature' && far.id === seg.id;\n        if (farOk && far.locked) return { ok: false, reason: 'The section on the other side of this opening is locked. Unlock it to move the opening.' };\n        const lo = low ? seg.fromMm : (farOk ? far.fromMm : o.fromMm);\n        const hi = low ? (farOk ? far.toMm : o.toMm) - width : seg.toMm - width;\n        let from = low ? seg.fromMm + v : seg.toMm - v - width;\n        from = Math.max(lo, Math.min(hi, from));\n        const shift = Math.round(from - o.fromMm);\n        if (shift) handleUpdateOpening(op.id, { offsetMm: Math.max(0, Math.round((op.offsetMm || 0) + shift)) });\n        return { ok: true };\n      }\n    }\n    // Once anything on this wall is locked, a change is resolved round the\n    // locks. A wall with none behaves exactly as it always has. A pinned\n    // corner's own sections keep their own rules either way.\n    const pinnedCorner = seg.kind === 'feature' && !seg.moveable;\n    if (!pinnedCorner && wallSegments(wallIndex).some(x => x.locked)) {\n      return resizeSectionWithLocks(wallIndex, seg, v);\n    }\n    if (seg.kind === 'opening') handleUpdateOpening(seg.id, { widthMm: Math.max(100, v) });\n    // The whole wall, on a shape that sets its length: same route the Room\n    // Shape popup takes, so the re-anchoring of corners and pillars it does\n    // happens here too.\n    else if (seg.kind === 'gap' && seg.shapeParam && !seg.ownerId) {\n      handleParamsApply({ [seg.shapeParam]: Math.max(500, v) });\n    }\n    else if (seg.kind === 'gap' && seg.ownerId) {\n      if (seg.ownerFixed) handleSetGapByResize(wallIndex, seg, v);\n      else if (seg.ownerKind === 'feature') handleSetGapByFeature(wallIndex, seg, v);\n      else handleSetOpeningGap(seg.ownerId, seg.ownerSide, v);\n    }\n    // A corner / pillar / nib resizes along the wall it stands against. The\n    // shape is still chosen in Room Shape; only the legs are set here.\n    else if (seg.kind === 'feature' && seg.sizeProp) {\n      const it = (roomConfig.perimeterItems || []).find(x => x.id === seg.id);\n      const cc = (it && it.cornerCut) || null;\n      // Nothing on a wall may be asked for more than the wall has left.\n      const cap = (mm) => seg.maxMm ? Math.min(mm, seg.maxMm) : mm;\n      // Whatever stands between this section and the next plain wall moves by\n      // however much the section changes, so the things beyond it keep their\n      // own measurements and the plain wall takes up the difference.\n      const segsNow = wallSegments(wallIndex);\n      const atIdx = segsNow.findIndex(x => x.key === seg.key);\n      const grew = cap(Math.max(100, v)) - (seg.toMm - seg.fromMm);\n      if (atIdx >= 0 && grew && (seg.dMin || 0) <= WALL_FLUSH_TOL_MM) {\n        const wallNow = getWalls(room)[wallIndex];\n        const uxn = (wallNow.to.x - wallNow.from.x) / wallNow.lengthMm;\n        const uyn = (wallNow.to.y - wallNow.from.y) / wallNow.lengthMm;\n        const itNow = (roomConfig.perimeterItems || []).find(x => x.id === seg.id);\n        const o = itNow ? (itNow.cornerCut ? (itNow.cornerCut.corner || 'tr') : itNow.pillarCorner) : null;\n        const gx = (!o || o === 'tl' || o === 'bl') ? 1 : -1;\n        const gy = (!o || o === 'tl' || o === 'tr') ? 1 : -1;\n        const dir = (gx * uxn + gy * uyn) >= 0 ? 1 : -1;\n        // dir is along the wall as traced; the list runs the other way on a\n        // wall traced right to left, so the walk has to step the other way too.\n        const step = uxn < -0.5 ? -dir : dir;\n        shiftAlongWall(wallIndex,\n          wallPushTrain(segsNow, atIdx, step, new Set([seg.id])).push, grew * dir);\n      }\n      if (seg.edit === 'cut' && cc && cc.mode === 'splay') {\n        // A SPLAY is the whole block - one diagonal wall to wall - so its legs\n        // ARE its width and depth, and handleUpdateFeature keeps the cut\n        // spanning them. Writing the cut here instead was writing a number that\n        // was overwritten on the way in, so the angle never moved: each wall's\n        // section sizes the leg that runs along IT, which is what makes the two\n        // directions independently adjustable.\n        handleUpdateFeature(seg.id, {\n          [seg.sizeProp]: Math.max(100, cap(v + (seg.coveredMm || 0)))\n        });\n      } else if (seg.edit === 'cut' && cc && seg.cutProp) {\n        // The diagonal's run along this wall - at most the leg it is cut from,\n        // less a millimetre so the pentagon never fully collapses.\n        const leg = Math.max(1, Number(it[seg.sizeProp]) || 0);\n        handleUpdateFeature(seg.id, {\n          cornerCut: { ...cc, [seg.cutProp]: Math.max(0, Math.min(leg - 1, v)) }\n        });\n      } else if (seg.edit === 'return' && cc && seg.cutProp && it) {\n        // The straight return: leg = return + cut, so the cut stays put and\n        // the block grows or shrinks by what the return gained or lost.\n        const cut = Math.max(0, Number(cc[seg.cutProp]) || 0);\n        handleUpdateFeature(seg.id, { [seg.sizeProp]: Math.max(100, cap(v + cut)) });\n      } else {\n        // Add back whatever is standing in front of this item: the box shows\n        // the visible remainder, so 400 with a 600 step on it means 1000.\n        handleUpdateFeature(seg.id, {\n          [seg.sizeProp]: Math.max(100, cap(v + (seg.coveredMm || 0)))\n        });\n      }\n    }\n  }\n\n  // Tint one segment on the plan.\n  // The outline to tint / click for a segment: always the 100mm wall band over\n  // that segment's run, whatever stands there. A corner's own block is 1000\n  // deep, so filling its footprint highlighted far more than the wall - only\n  // the wall thickness should light up.\n  function segmentPoints(wallIndex, seg, pxOverride) {\n    if (!lastGrid && !pxOverride) return null;\n    const px = pxOverride || lastGrid.pxPerMm;\n    const wall = getWalls(room)[wallIndex];\n    if (!wall) return null;\n    const ux = (wall.to.x - wall.from.x) / wall.lengthMm;\n    const uy = (wall.to.y - wall.from.y) / wall.lengthMm;\n\n    // A pillar / corner is NOT part of the room's wall band - the renderer\n    // cuts a hole in the band there (findPillarHolesOnEdge) and the item draws\n    // its OWN faces instead. So take the very quad it draws rather than\n    // deriving another one, or the highlight lands a wall thickness off.\n    if (seg.kind === 'feature') {\n      const it = (roomConfig.perimeterItems || []).find(x => x.id === seg.id);\n      // A SPLAY closes the corner with ONE diagonal - it has no square notch\n      // faces, so picking a parallel face highlights an edge that isn't drawn.\n      // Fall through to the plain band, which reads as the stretch of wall the\n      // splay replaces - the line the wall would have run on.\n      // A block with a CUT draws no band of its own, so all of its sections -\n      // return included - sit on the WALL LINE. Only a plain pillar or nib\n      // uses its own face, where the block itself is the wall you see. Without\n      // this the return's fill was painted on the block's face, leaving the\n      // wall line looking uncoloured.\n      if (it && !it.cornerCut && !seg.inlineFill) {\n        // The face that forms the NOTCH - the block's room-facing side - not\n        // the one buried on the original wall line. The room's own band is cut\n        // away where the block stands, so the wall you can see there is this\n        // face; picking the nearest parallel face highlighted the hidden edge\n        // instead, a block-depth away from anything drawn.\n        let best = null, bestD = -Infinity;\n        for (const f of rotatedPillarFaces(it)) {\n          const fx = f.roomB.x - f.roomA.x, fy = f.roomB.y - f.roomA.y;\n          const flen = Math.hypot(fx, fy) || 1;\n          if (Math.abs((fx / flen) * ux + (fy / flen) * uy) < 0.9) continue;  // parallel only\n          const mx = (f.roomA.x + f.roomB.x) / 2 - wall.from.x;\n          const my = (f.roomA.y + f.roomB.y) / 2 - wall.from.y;\n          const d = Math.abs(mx * uy + my * -ux);\n          if (d > bestD) { bestD = d; best = f; }\n        }\n        if (best) {\n          // Clip the face to THIS segment's run. The face spans the block's\n          // whole leg, so a cut corner's return was lighting all 1000mm\n          // instead of stopping where the angle starts.\n          const tA = (best.roomA.x - wall.from.x) * ux + (best.roomA.y - wall.from.y) * uy;\n          const tB = (best.roomB.x - wall.from.x) * ux + (best.roomB.y - wall.from.y) * uy;\n          const span = tB - tA;\n          if (Math.abs(span) < 1) return null;\n          const f0 = Math.min(Math.max((seg.fromMm - tA) / span, 0), 1);\n          const f1 = Math.min(Math.max((seg.toMm   - tA) / span, 0), 1);\n          if (Math.abs(f1 - f0) < 1e-4) return null;\n          const lerp = (P, Q, f) => ({ x: P.x + (Q.x - P.x) * f, y: P.y + (Q.y - P.y) * f });\n          return [lerp(best.roomA, best.roomB, f0), lerp(best.roomA, best.roomB, f1),\n                  lerp(best.innA,  best.innB,  f1), lerp(best.innA,  best.innB,  f0)]\n            .map(pt => `${pt.x * px},${pt.y * px}`).join(' ');\n        }\n      }\n    }\n\n    // A plain stretch of wall: the room's own band, pushed OUTWARD from the\n    // outline exactly as createWallsOverlay does (outX = uy, outY = -ux).\n    //\n    // An OPENING is the exception: cut into a pillar or corner-block face it\n    // sits a block-depth into the room, so its hit area and its black\n    // selection band have to move with it or they land out on the perimeter\n    // behind the block. Only openings - a cut corner's own sections are drawn\n    // on the wall line by the block itself and must stay there.\n    const inset = (seg.kind === 'opening')\n      ? wallFaceInsetAt(wallIndex, (seg.fromMm + seg.toMm) / 2)\n      : 0;\n    const ix = -uy * inset, iy = ux * inset;\n    return wallBandPoints(\n      { x: wall.from.x + ux * seg.fromMm + ix, y: wall.from.y + uy * seg.fromMm + iy },\n      { x: wall.from.x + ux * seg.toMm   + ix, y: wall.from.y + uy * seg.toMm   + iy },\n      px);\n  }\n\n  function showWallSegmentSpan(wallIndex, segKey) {\n    const svg = planOverlaySvg();\n    if (!svg || !lastGrid) return;\n    clearWallBand(svg);\n    const seg = wallSegments(wallIndex).find(x => x.key === segKey);\n    if (!seg || seg.toMm - seg.fromMm <= 0) return;\n    const pts = segmentPoints(wallIndex, seg);\n    // Black rather than the Room Shape green: on the plan this marks WHICH\n    // section you are editing, and the green there means a measurement is\n    // being typed. drawWallShape takes the fill, so the popup keeps its own.\n    const band = pts ? drawWallShape(svg, pts, { fill: '#111111' }) : null;\n    // SVG paints in document order and the band is appended last, so it landed\n    // on top of the very number it is meant to sit behind. Slide it in front of\n    // the first label: above the hit polygons, below every number.\n    if (band) {\n      const firstLabel = svg.querySelector('.btk-kp-wall-hit-label');\n      if (firstLabel) svg.insertBefore(band, firstLabel);\n    }\n  }\n\n  function openingRuns(op) {\n    const b = openingNeighbourBounds(op);\n    if (!b) return [];\n    const { wall, wallLen } = b;\n    const ux = (wall.to.x - wall.from.x) / wallLen;\n    const uy = (wall.to.y - wall.from.y) / wallLen;\n    // Same face the opening itself is on - the runs measure along it.\n    const inset = openingInsetMm(op);\n    const at = (mm) => ({ x: wall.from.x + ux * mm + -uy * inset,\n                          y: wall.from.y + uy * mm +  ux * inset });\n    // Bounded by the NEIGHBOURS, not the wall ends - so a wall carrying a door\n    // and a window reads as five sections: wall | door | wall | window | wall.\n    return [\n      { key: 'left',  fromMm: b.prevEnd, toMm: b.start },\n      { key: 'width', fromMm: b.start,   toMm: b.end },\n      { key: 'right', fromMm: b.end,     toMm: b.nextStart }\n    ].filter(r => r.toMm - r.fromMm > 0)\n     .map(r => ({ key: r.key, from: at(r.fromMm), to: at(r.toMm) }));\n  }\n\n  // Transparent click targets sitting exactly on each run, so clicking a\n  // stretch of wall on the plan tints it and puts the caret in the matching\n  // box - the reverse of focusing the box to light the wall.\n  // ---- Wall features on the plan -----------------------------------------\n  //\n  // Corners are chosen where they live. Arming Corners puts a marker on every\n  // right-angle corner of the room; clicking one opens the same \"Choose Corner\n  // Type\" menu the Room Shape preview used, and the choice lands through the\n  // same handlers. Pillars and internal walls need no mode at all - they spawn\n  // at room centre and are then positioned from their own panel.\n  //\n  // The markers are rebuilt on every render, because the dimension layer they\n  // live in is itself rebuilt on every render.\n  let planFeatureArmed = null;    // 'corner' | null\n  let planCornerMenuAt = null;    // 'tl' | 'tr' | 'bl' | 'br' | null\n\n  const PLAN_CORNER_CHOICES = [\n    { key: 'square', label: 'Square',     title: 'Box the corner in square',\n      path: 'M 18 6 L 54 6 L 54 34 L 6 34 L 6 18 L 18 18 Z' },\n    { key: 'angled', label: 'Angled',     title: 'Close the corner with one angled wall - 45\u00B0 to start, both sides editable',\n      path: 'M 18 6 L 54 6 L 54 34 L 6 34 L 6 20 Z' },\n    { key: 'cut',    label: 'Cut corner', title: 'Square return on each wall with the inside corner chamfered',\n      path: 'M 18 6 L 54 6 L 54 34 L 6 34 L 6 18 L 13 18 L 18 13 Z' }\n  ];\n\n  // Show / hide units lives on the plan, but it only means anything while the\n  // room is being built and only applies to the 2D view - so it appears when\n  // both hold and is out of the way otherwise.\n  function syncUnitsOverlay() {\n    const el = root.querySelector('[data-btk-kp-units-overlay]');\n    if (!el) return;\n    el.classList.toggle('is-on', viewMode === '2d' && currentStep === 'room-setup');\n  }\n\n  // A corner block does not just fill a corner - it MAKES two more, one where\n  // each of its free faces meets the wall it does not stand on. Those are\n  // corners of the room like any other and can be treated like any other, which\n  // is the \"corner in a corner\" the wall numbering already understands (see\n  // wallStandingItems' stacked pass).\n  //\n  // The corner an item occupies, as an orientation - a plain corner pillar and\n  // a cut one record it in different fields.\n  function cornerOrientOf(it) {\n    if (!it) return null;\n    if (it.cornerCut) return it.cornerCut.corner || 'tr';\n    if (it.type === 'column' && it.pillarCorner) return it.pillarCorner;\n    return null;\n  }\n\n  // The corners a treatment can go in: the room's own, one treatment each.\n  //\n  // Corners used to be able to nest inside one another, each block offering\n  // the two sub-corners it had just made. It read well on paper and the first\n  // one behaved, but a chain of derived anchors is only ever as steady as the\n  // block above it: resize or move anything in the run and everything below\n  // re-derived, so what the plan did next was hard to predict. Anything that\n  // needed a stepped shape is better drawn as one - Draw Custom Shape puts a\n  // wall wherever you want it - so the nesting has gone rather than being\n  // shored up.\n  function planCornerSlots() {\n    const out = [];\n    const bb = getBoundingBox(baseRoom);\n    const verts = (baseRoom && baseRoom.vertices) || [];\n    const EPS = 1;\n    const hasVertexAt = (x, y) =>\n      verts.some(v => Math.abs(v.x - x) < EPS && Math.abs(v.y - y) < EPS);\n    for (const c of [\n      { key: 'tl', x: bb.minX, y: bb.minY }, { key: 'tr', x: bb.maxX, y: bb.minY },\n      { key: 'bl', x: bb.minX, y: bb.maxY }, { key: 'br', x: bb.maxX, y: bb.maxY }\n    ]) {\n      if (hasVertexAt(c.x, c.y)) out.push({ ...c, orient: c.key });\n    }\n    return out;\n  }\n\n  // Walking out from a section along the wall: what stands between it and the\n  // next stretch of plain wall, and how much of that wall there is.\n  //\n  // Walking beats measuring. In a run of corners the middle ones are HIDDEN on\n  // a given wall - a deeper one in front wins that stretch - so the family's\n  // own sections stop short of the plain wall and looking for the gap that\n  // starts exactly at their end found nothing at all.\n  //\n  // Three kinds of thing can be in the way:\n  //   - a corner nested in the one being changed. It is anchored to it, so it\n  //     travels along on its own and is only stepped over.\n  //   - anything else that can move - a pillar, an internal wall, a door, a\n  //     window. It is PUSHED, so it is stepped over and collected.\n  //   - a corner belonging to somewhere else. It is pinned and cannot give, so\n  //     the walk stops there with no reach at all.\n  function wallPushTrain(segs, startIdx, step, family) {\n    const push = [];\n    let i = startIdx + step;\n    while (i >= 0 && i < segs.length) {\n      const x = segs[i];\n      if (x.kind === 'gap') return { push, reach: x.toMm - x.fromMm };\n      if (x.kind === 'feature' && family && family.has(x.id)) { i += step; continue; }\n      if (x.kind === 'opening') {\n        if (!push.some(p => p.id === x.id)) push.push({ kind: 'opening', id: x.id });\n        i += step; continue;\n      }\n      if (x.kind === 'feature' && x.moveable) {\n        if (!push.some(p => p.id === x.id)) push.push({ kind: 'feature', id: x.id });\n        i += step; continue;\n      }\n      return { push, reach: 0 };       // pinned - nothing gives\n    }\n    return { push, reach: 0 };         // ran off the end of the wall\n  }\n\n  // Slide those things along the wall. Openings move by their offset, items by\n  // their position; corners nested in what moved are put back by the re-anchor\n  // on the next render, so they are never in this list.\n  function shiftAlongWall(wallIndex, push, mm) {\n    if (!push || !push.length || !mm) return;\n    const wall = getWalls(room)[wallIndex];\n    if (!wall || !wall.lengthMm) return;\n    const ux = (wall.to.x - wall.from.x) / wall.lengthMm;\n    const uy = (wall.to.y - wall.from.y) / wall.lengthMm;\n    for (const p of push) {\n      if (p.kind === 'opening') {\n        const op = (roomConfig.wallOpenings || []).find(o => o && o.id === p.id);\n        if (op) op.offsetMm = Math.max(0, Math.round((op.offsetMm || 0) + mm));\n      } else {\n        const it = (roomConfig.perimeterItems || []).find(x => x && x.id === p.id);\n        if (it) { it.x += ux * mm; it.y += uy * mm; }\n      }\n    }\n  }\n\n\n  // Corner treatments belong to the STARTER shapes. Every one of them is\n  // defined against a rectangle's named corners - the anchor maths reads\n  // widthMm / heightMm off shapeParams - so on a room that was DRAWN they hang\n  // off a bounding box instead of the walls you can see, and the two models\n  // pull against each other. A drawn room has no need of them either: the\n  // builder puts a corner wherever you want one, as a wall, which is the whole\n  // point of drawing it. Pillars and internal walls make no such assumption -\n  // they are free-standing rectangles anywhere in the room - so they stay.\n  //\n  // Anything already placed is left alone: it is the user's geometry, and the\n  // wall panel's Delete Pillar/Wall button still takes it off.\n  function syncRoomFeatureButtons() {\n    const drawn = (roomConfig.shapeId === 'freeshape');\n    const btn = root.querySelector('[data-btk-kp-plan-feature=\"corner\"]');\n    if (btn) {\n      // Greyed, not hidden. A button that vanishes reads as a bug, or as\n      // something the user has lost; one that is plainly there and plainly off\n      // answers the question it raises the moment they press it.\n      btn.classList.toggle('is-disabled', drawn);\n      btn.setAttribute('aria-disabled', drawn ? 'true' : 'false');\n    }\n    if (drawn && planFeatureArmed === 'corner') {\n      planFeatureArmed = null;\n      planCornerMenuAt = null;\n      if (btn) {\n        btn.classList.remove('is-active');\n        if (btn.hasAttribute('aria-pressed')) btn.setAttribute('aria-pressed', 'false');\n      }\n    }\n  }\n\n  function setPlanFeatureArmed(kind) {\n    planFeatureArmed = (planFeatureArmed === kind) ? null : kind;\n    planCornerMenuAt = null;\n    root.querySelectorAll('[data-btk-kp-plan-feature]').forEach(b => {\n      const on = b.dataset.btkKpPlanFeature === planFeatureArmed;\n      b.classList.toggle('is-active', on);\n      if (b.hasAttribute('aria-pressed')) b.setAttribute('aria-pressed', on ? 'true' : 'false');\n    });\n\n    renderPlanCorners();\n    // Arming flashes the markers a couple of times, so it is obvious the next\n    // click goes on the plan rather than in the menu.\n    if (planFeatureArmed === 'corner') {\n      requestAnimationFrame(() => {\n        (lastGrid && lastGrid.el ? lastGrid.el : root)\n          .querySelectorAll('.btk-kp-rs-corner-toggle').forEach(el => {\n            el.classList.remove('is-pulsing');\n            void el.offsetWidth;            // restart the animation\n            el.classList.add('is-pulsing');\n          });\n      });\n    }\n  }\n\n  // What is currently treating this corner, read fresh rather than closed over:\n  // the corner menu stays open across changes, so anything captured at render\n  // time is a render out of date by the time the next choice is made.\n  function cornerOccupant(key) {\n    for (const it of (roomConfig.perimeterItems || [])) {\n      if (!it) continue;\n      if (cornerOrientOf(it) === key) return it;\n    }\n    return null;\n  }\n\n  // ---- Continue the run (2D) --------------------------------------------\n  // One selected unit shows a red + off each open end of its run. Clicking it\n  // opens the Add Units popup; the unit picked there lands butted to that\n  // end with the backs lined up, the end-panel walk moves the panel from the\n  // old end of the run to the new one, and the new unit becomes the selection\n  // so the next + is already there.\n  //\n  // Everything works off an open-end FACE: the carcase line of that end, the\n  // way the run carries on (outward) and the way the back of the run faces\n  // (back). A straight unit's faces are its user-left / user-right sides; a\n  // blank-panel corner has one, its door side (the void side is the corner);\n  // an L-shape or diagonal corner has one per arm end, at right angles to\n  // each other, so a unit added there turns with the run. Curved and\n  // splay-end units finish a run, and panels / stacked units are not the run.\n  function runAddFaces(cab) {\n    if (!cab || cab.endPanelUnit || cab.stackOn || cab.radiusUnit || cab.splayEnd) return [];\n    const w = cab.widthMm, d = cab.depthMm;\n    if (!(w > 0 && d > 0)) return [];\n    const unit = (v) => { const l = Math.hypot(v.x, v.y) || 1; return { x: v.x / l, y: v.y / l }; };\n    if (cab.lShapeUnit || cab.diagonalCornerUnit) {\n      // The arm end's back endpoint is the one on the outer corner of the\n      // bbox, which always lies further from the bbox centre than the\n      // other endpoint (that one sits at the inner cut-out).\n      const cx = cab.x + w / 2, cy = cab.y + d / 2;\n      return ['left', 'right'].map(side => {\n        const f = epLShapeEndFaceWorld(cab, side);\n        const d1 = Math.hypot(f.p1.x - cx, f.p1.y - cy);\n        const d2 = Math.hypot(f.p2.x - cx, f.p2.y - cy);\n        const backPt  = d1 >= d2 ? f.p1 : f.p2;\n        const frontPt = d1 >= d2 ? f.p2 : f.p1;\n        return { side, arm: true, face: f, outward: unit(f.outward),\n                 back: unit({ x: backPt.x - frontPt.x, y: backPt.y - frontPt.y }),\n                 backPt, frontPt };\n      });\n    }\n    const cx = cab.x + w / 2, cy = cab.y + d / 2;\n    const th = ((cab.rotationDeg || 0) * Math.PI) / 180;\n    const cs = Math.cos(th), sn = Math.sin(th);\n    const L2W = (lx, ly) => ({ x: cx + lx * cs - ly * sn, y: cy + lx * sn + ly * cs });\n    // Same door-side rule as the end-panel walk.\n    const sides = cab.cornerUnit\n      ? [cab.cornerUnit.hand === 'right' ? 'right' : 'left']\n      : ['left', 'right'];\n    const faces = sides.map(side => {\n      const sign = side === 'left' ? 1 : -1;          // user-left = local +X\n      return { side, arm: false, outward: { x: sign * cs, y: sign * sn },\n               back: { x: -sn, y: cs },\n               backPt: L2W(sign * w / 2, d / 2), frontPt: L2W(sign * w / 2, -d / 2) };\n    });\n    // A blank-panel corner's OTHER run leaves from the front of its blank\n    // side, turned 90 degrees: its first unit stands on the corner's front\n    // line (post face included - the post is what it butts), across the\n    // blank + void, with its back to the void end. That stretch is the reach\n    // (void + blank = reachMm), so it ends at the post's void-side edge, where\n    // the new run's front lands. The void end is the corner's high-x end for\n    // hand 'right' and low-x for 'left' (see cornerLayout in 2d-cabinets).\n    if (cab.cornerUnit) {\n      const cu = cab.cornerUnit;\n      const vs = cu.hand === 'right' ? 1 : -1;\n      const reach = (cu.reachMm || CORNER_POST_REACH_MM) - (cu.postInMm || 0);\n      const fy = -d / 2 - (cu.postYMm || 0);\n      const backPt  = L2W(vs * w / 2, fy);\n      const frontPt = L2W(vs * (w / 2 - reach), fy);\n      faces.push({ side: 'blank', arm: true, face: { p1: frontPt, p2: backPt },\n                   outward: { x: sn, y: -cs },                   // local -Y: out of the front\n                   back: { x: vs * cs, y: vs * sn },            // towards the void end\n                   backPt, frontPt });\n    }\n    return faces;\n  }\n\n  function runAddFaceFor(cab, side) {\n    return runAddFaces(cab).find(f => f.side === side) || null;\n  }\n\n  // Distance along a ray to a segment, or null if it misses (or runs parallel).\n  function runAddRayHit(p, dir, a, b) {\n    const ex = b.x - a.x, ey = b.y - a.y;\n    const den = dir.x * ey - dir.y * ex;\n    if (Math.abs(den) < 1e-9) return null;\n    const qx = a.x - p.x, qy = a.y - p.y;\n    const t = (qx * ey - qy * ex) / den;\n    const u = (qx * dir.y - qy * dir.x) / den;\n    if (u < -1e-6 || u > 1 + 1e-6) return null;\n    return t;\n  }\n\n  // Clear run past an open-end face: straight out from its front, middle and\n  // back to the nearest room wall, pillar, internal wall or unit in the same\n  // height band. A pillar counts as a wall, filler included. Infinity\n  // when nothing is in the way (an island end). `byWall` says whether that\n  // nearest thing is a room wall - see runAddMaxWidthMm.\n  function runAddSpace(cab, f) {\n    const len = Math.hypot(f.backPt.x - f.frontPt.x, f.backPt.y - f.frontPt.y);\n    const inset = Math.min(5, len / 4);               // a wall along the back is not in the way\n    const at = (t) => ({ x: f.frontPt.x + f.back.x * t, y: f.frontPt.y + f.back.y * t });\n    const origins = [at(inset), at(len / 2), at(len - inset)];\n    const segs = [];\n    const V = (room && room.vertices) || [];\n    for (let i = 0; i < V.length; i++) segs.push([V[i], V[(i + 1) % V.length], true]);\n    const myRange = epVerticalRange(cab);\n    for (const o of cabinets) {\n      if (o.id === cab.id) continue;\n      if (!epRangesOverlap(myRange, epVerticalRange(o))) continue;\n      const sides = epAllSides(o);\n      for (const k of ['front', 'back', 'left', 'right']) segs.push([sides[k].p1, sides[k].p2, false]);\n    }\n    const pillars = (roomConfig.perimeterItems || [])\n      .filter(it => it && (it.type === 'column' || it.type === 'wall') && !it.ignoreClash)\n      .map(epItemEdges);\n    for (const edges of pillars) for (const e of edges) segs.push([e.a, e.b, true]);\n    let best = Infinity, byWall = false;\n    for (const p of origins) {\n      // An end already standing inside a pillar has no space at all: the ray\n      // leaves that pillar through one face, where from outside it meets two.\n      const inPillar = pillars.some(edges => edges.filter(e => {\n        const t = runAddRayHit(p, f.outward, e.a, e.b);\n        return t != null && t > 0;\n      }).length % 2 === 1);\n      if (inPillar) return { mm: 0, byWall: true };\n      for (const [a, b, isWall] of segs) {\n        const t = runAddRayHit(p, f.outward, a, b);\n        if (t == null || t < -1) continue;            // behind the face\n        const d = Math.max(0, t);\n        if (d < best) { best = d; byWall = isWall; }\n      }\n    }\n    return { mm: best, byWall };\n  }\n\n  // The widest unit that fits on that end. Against a WALL the planner fits\n  // a filler, and its first-instance width is FILLER_DEFAULT_MM (20) - so a\n  // unit has to leave at least that: 400mm to the wall takes up to 380, i.e.\n  // a 350 unit. Against another UNIT the two simply butt, so the whole gap\n  // is usable. null = open end, any width.\n  function runAddMaxWidthMm(space) {\n    if (!Number.isFinite(space.mm)) return null;\n    return Math.floor(space.mm - (space.byWall ? FILLER_DEFAULT_MM : 0) + 0.5);\n  }\n\n  function renderRunAddButtons() {\n    const gridEl = lastGrid && lastGrid.el;\n    if (!gridEl) return;\n    const layer = gridEl.querySelector('.btk-kp-dim-layer');\n    if (!layer) return;\n    layer.querySelectorAll('.btk-kp-run-add').forEach(n => n.remove());\n    if (viewMode !== '2d') return;\n    if (!selectedItem || selectedItem.kind !== 'cabinet' || selectedCabinetIds.size !== 1) return;\n    const cab = cabinets.find(c => c.id === selectedItem.id);\n    const faces = runAddFaces(cab);\n    if (!faces.length) return;\n    if (typeof cabinetsHandle.openRunAddPopup !== 'function') return;\n    // The side of the kitchen this run is on, by the same rule the popup\n    // filters with. A unit with no catalogue type (a freestanding appliance)\n    // goes by its placed category. Neither side - a worktop dresser - no +.\n    const ut = cab.unitTypeId && Catalogue.getUnitType ? Catalogue.getUnitType(cab.unitTypeId) : null;\n    let zone = ut && Catalogue.runZoneOf ? Catalogue.runZoneOf(ut) : null;\n    if (!ut) {\n      const g = epCategoryGroup(cab);\n      zone = (g === 'wall' || g === 'bridging') ? 'wall' : (g ? 'floor' : null);\n    }\n    if (!zone) return;\n    // Local, not module consts: this runs from applySelectionVisual, which can\n    // fire before a const further down the closure has been reached.\n    // 200, not 300: further out it landed on the dimension figures of a unit\n    // standing close by.\n    const RUN_ADD_OFFSET_MM    = 200;   // + stands this far off the end\n    const RUN_ADD_MIN_WIDTH_MM = 150;   // narrowest unit sold; nothing fits below it, so no +\n\n    const px = lastGrid.pxPerMm;\n    // The circle is 22px scaled by this layer's label scale, so its radius in\n    // plan mm changes with the zoom. Read the layer's own value (the dimension\n    // layer sets it), not a copy of its formula.\n    const labelScale = parseFloat(layer.style.getPropertyValue('--btk-kp-label-scale')) || 1;\n    const radiusMm = (11 * labelScale) / px;\n    const range = epVerticalRange(cab);\n    for (const f of faces) {\n      // A neighbour on this end means the run carries on already.\n      const nbr = f.arm\n        ? epLShapeFindEndNeighbour(cab, f.face, range, cabinets)\n        : epFindNeighbourOnSide(cab, f.side, range, cabinets);\n      if (nbr) continue;\n      const space = runAddSpace(cab, f);\n      const spaceMm = space.mm;\n      const maxWidthMm = runAddMaxWidthMm(space);\n      if (maxWidthMm != null && maxWidthMm < RUN_ADD_MIN_WIDTH_MM) continue;\n      // Held inside a short gap, so the + never lands in a wall or on a unit.\n      const off = Number.isFinite(spaceMm) ? Math.min(RUN_ADD_OFFSET_MM, spaceMm / 2) : RUN_ADD_OFFSET_MM;\n      // Level with the front: the circle's front edge on the carcase front\n      // line, so it reads as part of the run and stays clear of the\n      // dimension figures along the back.\n      const at = {\n        x: f.frontPt.x + f.back.x * radiusMm + f.outward.x * off,\n        y: f.frontPt.y + f.back.y * radiusMm + f.outward.y * off\n      };\n      const side = f.side;\n\n      const btn = document.createElement('button');\n      btn.type = 'button';\n      btn.className = 'btk-kp-run-add';\n      btn.style.left = `${at.x * px}px`;\n      btn.style.top  = `${at.y * px}px`;\n      btn.title = 'Add a unit here';\n      btn.setAttribute('aria-label', 'Add a unit next to this one');\n      btn.innerHTML = '<svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"3\" stroke-linecap=\"round\" aria-hidden=\"true\"><line x1=\"12\" y1=\"6\" x2=\"12\" y2=\"18\"/><line x1=\"6\" y1=\"12\" x2=\"18\" y2=\"12\"/></svg>';\n      // The plan below treats a press as select / drag / deselect.\n      const stop = (e) => e.stopPropagation();\n      btn.addEventListener('pointerdown', stop);\n      btn.addEventListener('mousedown', stop);\n      btn.addEventListener('touchstart', stop, { passive: true });\n      btn.addEventListener('click', (e) => {\n        e.preventDefault();\n        e.stopPropagation();\n        cabinetsHandle.openRunAddPopup({ anchor: { cabId: cab.id, side }, zone, maxWidthMm });\n      });\n      layer.appendChild(btn);\n    }\n  }\n\n  // Put a just-added unit on the given open end of the run: turned to run on\n  // from that end, backs lined up (so a shallower or deeper unit still sits to\n  // the wall), carcase to carcase. With Auto end panels the walk that follows\n  // takes the end unit's panel off that side; with them off the user's panel\n  // stays, so the unit butts its face instead. Whatever else stands off that\n  // side (a TH grip rail, a freestanding appliance's pull-out gap) is kept. An\n  // L / diagonal arm end keeps a panel it already has - the walk reads a unit\n  // standing off its panel as the arm's neighbour, as it does after a drag.\n  function placeContinuingRun(nc, anchor) {\n    const t = cabinets.find(c => c.id === anchor.cabId);\n    if (!nc || !t) return;\n    const side = (anchor.side === 'right' || anchor.side === 'blank') ? anchor.side : 'left';\n    const f = runAddFaceFor(t, side);\n    if (!f) return;\n    let gap = 0;\n    const ep = t.endPanels && t.endPanels[side];\n    if (f.arm) {\n      gap = ep && ep.active ? endPanelThickMm(ep) : 0;\n    } else {\n      const eff  = epAllSides(t)[side].p1;\n      const carc = epCarcaseSides(t)[side].p1;\n      gap = Math.max(0, (eff.x - carc.x) * f.outward.x + (eff.y - carc.y) * f.outward.y);\n      if (autoEndPanels && !t.freestandingAppliance) {\n        const fil = t.fillers && t.fillers[side];\n        gap -= ep && ep.active ? endPanelThickMm(ep) : (fil && fil.active ? (fil.widthMm || 0) : 0);\n        gap = Math.max(0, gap);\n      }\n    }\n    // The new unit's local +Y (its back) points along the run's back; that\n    // fixes its rotation. Straight ends give the end unit's own rotation back.\n    const deg = Math.atan2(-f.back.x, f.back.y) * 180 / Math.PI;\n    nc.rotationDeg = f.arm ? ((Math.round(deg) % 360) + 360) % 360 : (t.rotationDeg || 0);\n    const along = gap + nc.widthMm / 2;\n    const ncx = f.backPt.x + f.outward.x * along - f.back.x * nc.depthMm / 2;\n    const ncy = f.backPt.y + f.outward.y * along - f.back.y * nc.depthMm / 2;\n    nc.x = ncx - nc.widthMm / 2;\n    nc.y = ncy - nc.depthMm / 2;\n    // A stepped-forward run stays stepped.\n    if (!f.arm && isStepEligibleCab(t) && isStepEligibleCab(nc)) nc.wallSetbackMm = t.wallSetbackMm || 0;\n  }\n\n  function renderPlanCorners() {\n    const gridEl = lastGrid && lastGrid.el;\n    if (!gridEl) return;\n    const layer = gridEl.querySelector('.btk-kp-dim-layer');\n    if (!layer) return;\n    layer.querySelectorAll('.btk-kp-rs-corner-toggle, .btk-kp-rs-corner-menu')\n         .forEach(n => n.remove());\n    // Cleared first, then nothing: a drawn room offers no corner treatments -\n    // see syncRoomFeatureButtons. Returning after the sweep means a room that\n    // BECOMES drawn loses any markers left on screen.\n    if (roomConfig.shapeId === 'freeshape') return;\n\n    const px = lastGrid.pxPerMm;\n    const verts = (baseRoom && baseRoom.vertices) || [];\n    if (!verts.length) return;\n\n    // What already sits in each corner, so a treatment can be taken off again.\n    const occupied = new Map();\n    for (const it of (roomConfig.perimeterItems || [])) {\n      const key = cornerOrientOf(it);\n      if (!key) continue;\n      occupied.set(key, { id: it.id, kind: it.cornerCut ? 'cut-corner' : 'square-corner' });\n    }\n    const corners = planCornerSlots();\n    const icon = (d) =>\n      '<svg viewBox=\"0 0 60 40\" xmlns=\"http://www.w3.org/2000/svg\" aria-hidden=\"true\">' +\n      '<path d=\"' + d + '\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"3\"/></svg>';\n\n    for (const c of corners) {\n      // Markers belong to the MODE, not to the room: leaving them behind once\n      // corners were finished left red selectors sitting on a plan nobody was\n      // editing. Armed shows every corner - free ones to add, treated ones to\n      // take off again; disarmed shows none.\n      const armed = planFeatureArmed === 'corner';\n      if (!armed) continue;\n      const occ = occupied.get(c.key);\n\n      const btn = document.createElement('button');\n      btn.type = 'button';\n      btn.className = 'btk-kp-rs-corner-toggle';\n      btn.dataset.corner = c.orient;    // CSS positions the marker by orientation\n      btn.style.left = `${c.x * px}px`;\n      btn.style.top  = `${c.y * px}px`;\n      if (occ) {\n        // A treated corner shows what the click DOES, not what is already\n        // there - the shape is on the plan to be seen, so a glyph repeating it\n        // only left the user guessing what the marker was for.\n        btn.classList.add('is-active', 'btk-kp-rs-corner-toggle--remove');\n        btn.textContent = 'Remove Corner';\n        btn.title = occ.kind === 'square-corner'\n          ? 'Remove this square corner' : 'Remove this cut corner';\n        btn.addEventListener('click', (e) => {\n          e.stopPropagation();\n          // Both kinds are perimeter items, so one remover covers them.\n          handleRemovePerimeterItem((cornerOccupant(c.key) || occ).id);\n          // Removing DISARMS. Adding is safe to repeat, so the mode stays on\n          // for the next corner; taking one off is not, and leaving the mode\n          // running would put a second Remove Corner under the pointer that\n          // just removed the first. Two removals, two deliberate arms.\n          setPlanFeatureArmed(null);\n        });\n      } else {\n        btn.classList.add('btk-kp-rs-corner-toggle--square');\n        btn.textContent = '\u25A0';\n        btn.title = 'Choose a treatment for this corner';\n        if (planCornerMenuAt === c.key) btn.classList.add('is-open');\n        btn.addEventListener('click', (e) => {\n          e.stopPropagation();\n          planCornerMenuAt = (planCornerMenuAt === c.key) ? null : c.key;\n          renderPlanCorners();\n        });\n      }\n      layer.appendChild(btn);\n\n      if (planCornerMenuAt === c.key) {\n        const menu = document.createElement('div');\n        menu.className = 'btk-kp-rs-corner-menu';\n        menu.dataset.corner = c.orient;\n        menu.style.left = `${c.x * px}px`;\n        menu.style.top  = `${c.y * px}px`;\n        // Right-hand corners open leftwards, bottom ones upwards, so the menu\n        // opens INTO the room rather than off the edge of the plan.\n        if (c.orient === 'tr' || c.orient === 'br') menu.classList.add('is-right');\n        if (c.orient === 'bl' || c.orient === 'br') menu.classList.add('is-bottom');\n        menu.addEventListener('mousedown', e => e.stopPropagation());\n        menu.addEventListener('click', e => e.stopPropagation());\n        const title = document.createElement('p');\n        title.className = 'btk-kp-rs-corner-menu-title';\n        title.textContent = 'Choose Corner Type';\n        menu.appendChild(title);\n        const row = document.createElement('div');\n        row.className = 'btk-kp-rs-corner-menu-row';\n        for (const choice of PLAN_CORNER_CHOICES) {\n          const opt = document.createElement('button');\n          opt.type = 'button';\n          opt.className = 'btk-kp-rs-corner-menu-item';\n          opt.title = choice.title;\n          opt.innerHTML = icon(choice.path) + '<span>' + choice.label + '</span>';\n          opt.addEventListener('click', (e) => {\n            e.preventDefault();\n            e.stopPropagation();\n            // A corner has ONE treatment. Without this, picking a second type\n            // left the first in place and the corner ended up square AND\n            // angled at once.\n            const had = cornerOccupant(c.key);\n            if (had) handleRemovePerimeterItem(had.id);\n            if (choice.key === 'square') handleAddPillar(c.orient);\n            else handleAddCornerCut(c.orient, choice.key);\n            // The menu stays put - the choice can be changed, another corner\n            // picked, or Done pressed to finish. Closing it here is what used\n            // to leave the mode running with no way out of it.\n          });\n          row.appendChild(opt);\n        }\n        menu.appendChild(row);\n        const hint = document.createElement('p');\n        hint.className = 'btk-kp-rs-corner-menu-note';\n        hint.textContent = 'Choose the shape here, then set its sizes in the menu.';\n        menu.appendChild(hint);\n        const doneRow = document.createElement('div');\n        doneRow.className = 'btk-kp-rs-corner-menu-done';\n        const done = document.createElement('button');\n        done.type = 'button';\n        done.className = 'btk-kp-action-btn btk-kp-action-btn--sm btk-kp-action-btn--green';\n        done.innerHTML =\n          '<span class=\"btk-kp-action-btn-icon\" aria-hidden=\"true\">' +\n          '<svg viewBox=\"0 0 24 24\" width=\"18\" height=\"18\" fill=\"none\" stroke=\"currentColor\" ' +\n          'stroke-width=\"2.4\" stroke-linecap=\"round\" stroke-linejoin=\"round\">' +\n          '<polyline points=\"4 11 9 16 20 5\"/></svg></span>' +\n          '<span class=\"btk-kp-action-btn-label\">Done</span>';\n        done.addEventListener('click', (e) => {\n          e.preventDefault();\n          e.stopPropagation();\n          setPlanFeatureArmed(null);\n        });\n        doneRow.appendChild(done);\n        menu.appendChild(doneRow);\n        layer.appendChild(menu);\n      }\n    }\n  }\n\n  function clearWallHits() {\n    const svg = planOverlaySvg();\n    // Section NAMES too - they carry their own class, so a selector matching\n    // only .btk-kp-wall-hit left the previous wall's names on the plan.\n    if (svg) svg.querySelectorAll('.btk-kp-wall-hit, .btk-kp-wall-hit-label')\n                .forEach(n => n.remove());\n  }\n  // Which run of a free-standing pillar has its row open, so the plan can\n  // measure that run's ends to the room walls. Null when nothing is open.\n  let activeFeatureRun = null;\n  function showFeatureRun(id, no) {\n    activeFeatureRun = (no == null) ? null : { id, no };\n    try { renderWallHits(); } catch (e) { console.error('[BTK wallHits]', e); }\n  }\n\n  // Number a free-standing pillar's two runs the way wall sections are\n  // numbered, and - when its row is open - measure that run's ends out to the\n  // room walls. The distances are taken axis-aligned from the item's x / y,\n  // which is what the panel's boxes edit, so the two always agree.\n  function drawStructureRuns(svg, it) {\n    const px = lastGrid.pxPerMm;\n    const w  = it.widthMm || 0, d = it.depthMm || 0;\n    const cx = it.x + w / 2,    cy = it.y + d / 2;\n    const rad = ((it.rotationDeg || 0) * Math.PI) / 180;\n    const rot = (x, y) => ({\n      x: cx + (x - cx) * Math.cos(rad) - (y - cy) * Math.sin(rad),\n      y: cy + (x - cx) * Math.sin(rad) + (y - cy) * Math.cos(rad)\n    });\n    const text = (cls, x, y, txt, angle) => {\n      const t = document.createElementNS('http://www.w3.org/2000/svg', 'text');\n      t.classList.add('btk-kp-wall-hit', cls);\n      t.setAttribute('x', x * px);\n      t.setAttribute('y', y * px);\n      if (angle) t.setAttribute('transform', `rotate(${angle} ${x * px} ${y * px})`);\n      t.setAttribute('text-anchor', 'middle');\n      t.setAttribute('dominant-baseline', 'central');\n      t.style.pointerEvents = 'none';\n      t.textContent = txt;\n      svg.appendChild(t);\n    };\n    const line = (x1, y1, x2, y2) => {\n      const ln = document.createElementNS('http://www.w3.org/2000/svg', 'line');\n      ln.classList.add('btk-kp-wall-hit');\n      ln.setAttribute('x1', x1 * px); ln.setAttribute('y1', y1 * px);\n      ln.setAttribute('x2', x2 * px); ln.setAttribute('y2', y2 * px);\n      ln.setAttribute('stroke', '#999');\n      ln.setAttribute('stroke-width', '1');\n      ln.style.pointerEvents = 'none';\n      svg.appendChild(ln);\n    };\n\n    // The same white disc / red rim / red number the room walls carry, so a\n    // pillar's runs are named on the plan exactly as a wall's sections are.\n    // Upright whatever angle the pillar sits at - the badge is a disc, so the\n    // run's direction sets no baseline.\n    const badge = (x, y, txt) => {\n      const NS = 'http://www.w3.org/2000/svg';\n      const g = document.createElementNS(NS, 'g');\n      g.classList.add('btk-kp-wall-hit-label');\n      g.style.pointerEvents = 'none';\n      const disc = document.createElementNS(NS, 'circle');\n      disc.classList.add('btk-kp-wall-hit-badge');\n      disc.setAttribute('cx', x * px);\n      disc.setAttribute('cy', y * px);\n      disc.setAttribute('r', 9);\n      const t = document.createElementNS(NS, 'text');\n      t.classList.add('btk-kp-wall-hit-num');\n      t.setAttribute('x', x * px);\n      t.setAttribute('y', y * px);\n      t.setAttribute('text-anchor', 'middle');\n      t.setAttribute('dominant-baseline', 'central');\n      t.textContent = txt;\n      g.appendChild(disc);\n      g.appendChild(t);\n      svg.appendChild(g);\n    };\n\n    // The 100mm strip just inside one edge - the pillar's own wall band, and\n    // what the black highlight fills. Built on the UNROTATED box and rotated\n    // at the end, so an angled nib's band follows its faces.\n    const bandOf = (ax, ay, bx, by, inX, inY, thickMm) => {\n      const T = Math.max(1, thickMm);\n      const q = [\n        rot(ax, ay), rot(bx, by),\n        rot(bx + inX * T, by + inY * T),\n        rot(ax + inX * T, ay + inY * T)\n      ];\n      return q.map(pt => `${pt.x * px},${pt.y * px}`).join(' ');\n    };\n\n    const x0 = it.x, y0 = it.y, x1 = it.x + w, y1 = it.y + d;\n    // Run 1 rides the WIDTH edges, run 2 the DEPTH edges - the same two the\n    // panel calls Wall 1 and Wall 2. Opposite faces of a box are the same\n    // length, so they are the same run and carry the same number: selecting\n    // Wall 1 lights the top and the bottom together.\n    const runs = [\n      { no: 1, bands: [bandOf(x0, y0, x1, y0, 0,  1, Math.min(100, d)),\n                       bandOf(x0, y1, x1, y1, 0, -1, Math.min(100, d))],\n               badges: [rot(cx, y0), rot(cx, y1)] },\n      { no: 2, bands: [bandOf(x0, y0, x0, y1,  1, 0, Math.min(100, w)),\n                       bandOf(x1, y0, x1, y1, -1, 0, Math.min(100, w))],\n               badges: [rot(x0, cy), rot(x1, cy)] }\n    ];\n\n    const run = (activeFeatureRun && activeFeatureRun.id === it.id) ? activeFeatureRun.no : null;\n    // Black first, badges after - SVG paints in document order, so the number\n    // has to be appended last to sit on the highlight rather than under it.\n    //\n    // Drawn here rather than through drawWallShape: that clears the previous\n    // band before drawing, which is right for a wall section (there is only\n    // ever one) but would rub out the first of a PAIR. Carrying the wall-hit\n    // class also ties them to this pass, so they are cleared with it.\n    const fillBand = (pts) => {\n      const poly = document.createElementNS('http://www.w3.org/2000/svg', 'polygon');\n      poly.classList.add('btk-kp-wall-hit');\n      poly.setAttribute('points', pts);\n      poly.setAttribute('fill', '#111111');\n      poly.setAttribute('stroke', 'none');\n      poly.style.pointerEvents = 'none';\n      svg.appendChild(poly);\n    };\n    for (const r of runs) {\n      if (r.no !== run) continue;\n      for (const pts of r.bands) fillBand(pts);\n    }\n    for (const r of runs) {\n      for (const b of r.badges) badge(b.x, b.y, String(r.no));\n    }\n\n    if (!run) return;\n    const vs = (room && room.vertices) || [];\n    if (!vs.length) return;\n    const xs = vs.map(v => v.x), ys = vs.map(v => v.y);\n    const minX = Math.min(...xs), maxX = Math.max(...xs);\n    const minY = Math.min(...ys), maxY = Math.max(...ys);\n    const DIM = 'btk-kp-wall-hit-dim';\n    if (run === 1) {\n      // Ends of the width run, out to the left and right walls.\n      line(minX, cy, it.x, cy);\n      line(it.x + w, cy, maxX, cy);\n      text(DIM, (minX + it.x) / 2, cy - 60, String(Math.round(it.x - minX)), 0);\n      text(DIM, (it.x + w + maxX) / 2, cy - 60, String(Math.round(maxX - (it.x + w))), 0);\n    } else {\n      line(cx, minY, cx, it.y);\n      line(cx, it.y + d, cx, maxY);\n      text(DIM, cx, (minY + it.y) / 2, String(Math.round(it.y - minY)), -90);\n      text(DIM, cx, (it.y + d + maxY) / 2, String(Math.round(maxY - (it.y + d))), -90);\n    }\n  }\n\n  function renderWallHits() {\n    clearWallHits();\n    // The room is built in Room Setup. Leaving its walls, doors and windows\n    // selectable through the later stages meant a click meant for a unit could\n    // pull the panel onto a wall section instead - the hit areas sit above the\n    // cabinet layers, so they win any overlap.\n    if (currentStep !== 'room-setup') return;\n    const svg = planOverlaySvg();\n    if (!svg || !lastGrid) return;\n    // EVERY wall, not just the ones carrying an opening - a plain wall is a\n    // single full-length section and selects like any other.\n    const walls = getWalls(room);\n    for (let wi = 0; wi < walls.length; wi++) {\n      const wall = walls[wi];\n      if (!wall) continue;\n      let prevSeg = null;\n      for (const seg of wallSegments(wi)) {\n        if (seg.toMm - seg.fromMm <= 0) continue;\n        const pts = segmentPoints(wi, seg);\n        if (!pts) continue;\n        const poly = document.createElementNS('http://www.w3.org/2000/svg', 'polygon');\n        poly.classList.add('btk-kp-wall-hit');\n        poly.setAttribute('points', pts);\n        // A splay's sections have no wall band of their own - the corner is\n        // closed by the diagonal - so fill them in the wall colour, no border,\n        // so the run reads continuous and there is something to click.\n        // Only a section with NO wall drawn beneath it fills itself - the\n        // angled part of a cut corner, or a splay's run. A return has the\n        // block's own band under it, so its hit area stays invisible.\n        poly.setAttribute('fill', seg.inlineFill ? '#d8d8d8' : 'transparent');\n        poly.setAttribute('fill-opacity', seg.inlineFill ? '0.5' : '1');\n        poly.setAttribute('stroke', 'none');\n        // A section that \"slides freely\" (seg.moveable - a pillar or nib\n        // standing mid-wall) is DRAGGABLE on the plan, and this overlay sits\n        // above it (z-11 vs the structure layer's z-8), so a polygon over it\n        // would swallow the gesture - which is exactly why such a pillar could\n        // not be moved. Let the pointer through to the item; its own handler\n        // opens this same wall section on a click (see wirePerimeterItem).\n        // Pinned sections (a corner treatment, a corner-anchored pillar) and\n        // every ordinary wall run keep their polygon.\n        poly.style.pointerEvents = (seg.kind === 'feature' && seg.moveable) ? 'none' : 'all';\n        poly.style.cursor = 'pointer';\n        // POINTERDOWN, not click: the canvas clears the selection on its own\n        // pointer handling, which would tear the panel down first.\n        // The canvas also acts on click / mouseup, which ran after this and\n        // reset the selection - the section highlighted but the panel snapped\n        // back. Swallow the whole gesture on a wall section.\n        for (const evt of ['click', 'mouseup', 'pointerup']) {\n          poly.addEventListener(evt, (e) => { e.stopPropagation(); e.preventDefault(); });\n        }\n        poly.addEventListener('pointerdown', (e) => {\n          e.stopPropagation();\n          e.preventDefault();\n          // Any segment opens that WALL's panel. Openings still select\n          // themselves so the panel knows which wall to show.\n          // An opening selects itself; a GAP selects the wall. Both open the\n          // same wall panel, but a gap no longer drags an opening's blue\n          // highlight along with it. segKey rides on the selection so the\n          // matching row opens in the same render, and it is re-selected on\n          // every click so moving between sections moves the open row.\n          if (seg.kind === 'opening') {\n            selectItem({ kind: 'opening', id: seg.id, wallIndex: wi, segKey: seg.key });\n          } else {\n            selectItem({ kind: 'wall', wallIndex: wi, segKey: seg.key });\n          }\n          requestAnimationFrame(() => {\n            showWallSegmentSpan(wi, seg.key);\n            const input = root.querySelector(`[data-seg-size=\"${seg.key}\"]`);\n            // preventScroll matters here. Selecting a wall section swaps the\n            // sidebar panel, and that swap slides the incoming panel in with a\n            // transform. Focusing a box inside a transformed panel makes the\n            // browser scroll it into view - sideways, because the panel is\n            // still off to one side - which is the jiggle. Add Units never\n            // showed it because its panel is already up, so nothing slides.\n            if (input) { input.focus({ preventScroll: true }); input.select?.(); }\n          });\n        });\n        svg.appendChild(poly);\n\n        // Thin divider where two sections of the SAME block meet, so the run\n        // reads as one length split in two rather than as two separate walls.\n        if (seg.kind === 'feature' && prevSeg && prevSeg.kind === 'feature' &&\n            prevSeg.id === seg.id && Math.abs(prevSeg.toMm - seg.fromMm) < 1) {\n          const at = seg.fromMm;\n          const wx = wall.from.x + ((wall.to.x - wall.from.x) / wall.lengthMm) * at;\n          const wy = wall.from.y + ((wall.to.y - wall.from.y) / wall.lengthMm) * at;\n          const nvx = (wall.to.y - wall.from.y) / wall.lengthMm;\n          const nvy = -(wall.to.x - wall.from.x) / wall.lengthMm;\n          const T = 100;\n          const ln = document.createElementNS('http://www.w3.org/2000/svg', 'line');\n          ln.classList.add('btk-kp-wall-hit');\n          ln.setAttribute('x1', wx * lastGrid.pxPerMm);\n          ln.setAttribute('y1', wy * lastGrid.pxPerMm);\n          ln.setAttribute('x2', (wx + nvx * T) * lastGrid.pxPerMm);\n          ln.setAttribute('y2', (wy + nvy * T) * lastGrid.pxPerMm);\n          ln.setAttribute('stroke', '#999');\n          ln.setAttribute('stroke-width', '1');\n          ln.style.pointerEvents = 'none';\n          svg.appendChild(ln);\n        }\n        prevSeg = seg;\n      }\n    }\n    // Name each WALL section of the wall the panel is showing, centred in the\n    // band, so the plan and the left menu use the same names. Doors and\n    // windows are recognisable on their own and stay unlabelled.\n    // A free-standing pillar / internal wall carries its own numbering.\n    if (selectedItem && selectedItem.kind === 'feature') {\n      const fit = (roomConfig.perimeterItems || []).find(x => x.id === selectedItem.id);\n      if (fit && !fit.cornerCut && !fit.pillarCorner &&\n          (fit.type === 'column' || fit.type === 'wall')) {\n        drawStructureRuns(svg, fit);\n      }\n    } else if (activeFeatureRun) {\n      activeFeatureRun = null;   // selection moved on\n    }\n\n    // A badge, like the unit numbers: white disc, red rim, red number, sat on\n    // the centre of whatever band is passed in. It reads on the plain wall band\n    // and on the black highlight alike, and the number stays upright whatever\n    // angle the wall runs at.\n    const NSVG = 'http://www.w3.org/2000/svg';\n    const drawBadge = (pts, text, segKey) => {\n      if (!pts || text === '' || text == null) return;\n      const nums = pts.split(' ').map(pair => pair.split(',').map(Number));\n      const x = nums.reduce((a, pt) => a + pt[0], 0) / nums.length;\n      const y = nums.reduce((a, pt) => a + pt[1], 0) / nums.length;\n      const g = document.createElementNS(NSVG, 'g');\n      g.classList.add('btk-kp-wall-hit-label');\n      if (segKey) g.dataset.segKey = segKey;\n      g.style.pointerEvents = 'none';\n      const disc = document.createElementNS(NSVG, 'circle');\n      disc.classList.add('btk-kp-wall-hit-badge');\n      disc.setAttribute('cx', x);\n      disc.setAttribute('cy', y);\n      disc.setAttribute('r', 9);\n      const t = document.createElementNS(NSVG, 'text');\n      t.classList.add('btk-kp-wall-hit-num');\n      t.setAttribute('x', x);\n      t.setAttribute('y', y);\n      t.setAttribute('text-anchor', 'middle');\n      t.setAttribute('dominant-baseline', 'central');\n      t.textContent = String(text);\n      g.appendChild(disc);\n      g.appendChild(t);\n      svg.appendChild(g);\n    };\n\n    // A DRAWN room is listed wall by wall in the left menu, so the plan is\n    // numbered to match: EVERY wall carries its own number, all the time, not\n    // just whichever one is selected. It was numbering the SECTIONS of the\n    // selected wall instead - and a drawn room's wall is one section, so every\n    // wall in turn came up as 1 however far down the list it was.\n    //\n    // A starter shape keeps the section numbering: there the left menu lists\n    // the sections of the wall you clicked, so the plan and that list still\n    // agree. One model each, and each matches its own list.\n    const activeWall = (selectedItem && selectedItem.kind === 'wall')\n      ? selectedItem.wallIndex\n      : (selectedItem && selectedItem.kind === 'opening'\n          ? ((roomConfig.wallOpenings || []).find(o => o.id === selectedItem.id) || {}).wallIndex\n          : null);\n    if (activeWall == null) return;\n\n    // Numbers belong to the selection, not to the plan: a starter shape shows\n    // them only while a wall is being worked on, and a drawn room does the\n    // same. The difference is WHAT gets numbered - the left menu lists every\n    // wall of a drawn room, so once one is picked the plan numbers them all,\n    // and the row you are looking at can be found on the drawing. A starter\n    // shape's menu lists the SECTIONS of the wall you clicked, so the plan\n    // numbers those. One model each, and each matches its own list.\n    if (roomConfig.shapeId === 'freeshape') {\n      const labels = deriveWallLabels(walls);\n      for (let wi = 0; wi < walls.length; wi++) {\n        const w = walls[wi];\n        if (!w || !w.lengthMm) continue;\n        drawBadge(segmentPoints(wi, { kind: 'gap', key: `wall-${wi}`, fromMm: 0, toMm: w.lengthMm }),\n                  labels[wi], `wall-${wi}`);\n      }\n      return;\n    }\n    const wall = walls[activeWall];\n    if (!wall) return;\n    // The badge is a disc with the number upright inside it, so the wall's\n    // direction no longer sets a baseline to keep the right way up.\n    for (const seg of wallSegments(activeWall)) {\n      // Notch sections are named too - they are \"Wall n\" like any other, and\n      // so are doors and windows: everything on the wall carries its number.\n      if (seg.toMm - seg.fromMm <= 0) continue;\n      // Centre of whatever band this section actually highlights, so the name\n      // sits on the green rather than on a band derived a second way.\n      // Just the number on the plan - the left menu carries the name with it.\n      drawBadge(segmentPoints(activeWall, seg), seg.num == null ? '' : seg.num, seg.key);\n    }\n  }\n\n  // Editing a gap moves the opening it belongs to, leaving its neighbours put.\n  function handleSetOpeningGap(openingId, which, valueMm) {\n    const op = (roomConfig.wallOpenings || []).find(o => o.id === openingId);\n    const g  = getOpeningGaps(openingId);\n    if (!op || !g) return;\n    const v = Math.max(0, Math.round(valueMm));\n    const offsetMm = (which === 'left')\n      ? g.prevEndMm + v\n      : g.nextStartMm - (op.widthMm || 0) - v;\n    handleUpdateOpening(openingId, { offsetMm: Math.max(0, offsetMm) });\n  }\n\n  function handleUpdateOpening(openingId, updates) {\n    const openings = roomConfig.wallOpenings || [];\n    const idx = openings.findIndex(o => o.id === openingId);\n    if (idx === -1) return;\n    let updated = settleWorktopIntoWindow(openings[idx], { ...openings[idx], ...updates });\n    updated.widthMm = clampOpeningWidth(updated.variant, updated.styleCode, updated.widthMm);\n    // A head radius is half the width at most - a full arch. Narrowing the\n    // opening has to bring the radius with it, or the stored number stops\n    // matching the shape the renderer draws.\n    if (updated.cornerRadiusMm > 0) {\n      updated.cornerRadiusMm =\n        Math.max(0, Math.min(Math.round(updated.widthMm / 2), Math.round(updated.cornerRadiusMm)));\n    }\n    const wall = getWalls(room)[updated.wallIndex];\n    if (wall) {\n      updated.widthMm  = Math.max(100, Math.min(wall.lengthMm, updated.widthMm));\n      updated.offsetMm = Math.max(0, Math.min(wall.lengthMm - updated.widthMm, updated.offsetMm));\n    }\n    const next = [...openings];\n    next[idx] = updated;\n    roomConfig = { ...roomConfig, wallOpenings: next };\n    // A new width, height or position can put a unit end on view or back\n    // against the wall.\n    epReDecideBesideOpenings([openings[idx], updated]);\n    rerender();\n  }\n\n  // ---- Worktop items (sinks + hobs) ----\n\n  // Spawn a sink or hob on the plan from a catalogue entry - drops\n  // it near the room centre, slightly staggered so successive adds\n  // don't stack on each other. The id is assigned here so the\n  // 2D/3D renderers and persistence have a stable handle.\n  function addWorktopItem(entry) {\n    if (!entry) return;\n    // A sink always goes in a Sink Unit, never loose (Arden, 2026-11-16).\n    if (entry.kind === 'sink') { fitSinkFromPicker(entry); return; }\n    // An undermount or Belfast sink on a faced laminate worktop: never.\n    if (entry.kind === 'sink') {\n      const sk = (entry.handle && Catalogue.getPlannerSink) ? Catalogue.getPlannerSink(entry.handle) : null;\n      const block = sinkWorktopBlock((sk ? Catalogue.plannerSinkMountInfo(sk).fixed : entry.installType), false);\n      if (block) { alertFacedSink(block); return; }\n    }\n    const bbox = getBoundingBox(room);\n    const stagger = (worktopItems.length % 8) * 60;\n    const def = buildWorktopItemDefinition(entry, {\n      id: `wi-${nextWorktopItemId++}`,\n      x: bbox.widthMm  / 2 - (entry.widthMm || 0) / 2 + stagger,\n      y: bbox.heightMm / 2 - (entry.depthMm || 0) / 2 + stagger\n    });\n    // If the initial drop position happens to sit over a base\n    // cabinet, snap to that cabinet's front and rotate to match \u2014\n    // saves the user from having to drag-then-rotate.\n    const cx = def.x + (def.widthMm || 0) / 2;\n    const cy = def.y + (def.depthMm || 0) / 2;\n    const host = findItemHost(cx, cy);\n    if (host) {\n      const snapped = snapItemPosition(def, def.x, def.y, host);\n      def.x = snapped.x;\n      def.y = snapped.y;\n      def.rotationDeg = hostFacingRotation(host);\n    }\n    worktopItems.push(def);\n    rerender();\n  }\n\n  // ---- Extractors (wall hoods over a hob) ----\n  // A wall extractor (Add Appliances \u2192 Extractor fans, appliance_placement\n  // \"wall\" - the chimney / angled / curved-glass / box hoods) is a worktop\n  // item of kind 'extractor' (Arden, 2026-10-11). Added from Add Appliances it\n  // is seated over a hob - the selected one, else one with no hood yet - centred,\n  // back to the wall behind; from then on it is FREE (2026-10-12): dragged by\n  // its number in 2D, it re-seats against the nearest wall on release, and a\n  // hob moving or going leaves it where it is. Being a worktop item it gets a plan\n  // number, a basket line and the selected-item panel like the hob does.\n  // Shopify holds only the width, so the shape is a standard one per style\n  // (3D renderer, buildExtractor) until there are models.\n  const EXTRACTOR_DEPTH_MM = { chimney: 500, angled: 380, curved: 500, box: 500 };\n  function isWallExtractor(a) {\n    return !!a && a.placement === 'wall' && /extractor/i.test(String(a.category || ''));\n  }\n  // Style, width and finish from the product: the Type facet / title words for\n  // the style, \"90cm\" in the title for the width, the first finish word for the\n  // colour. Stainless when nothing says otherwise.\n  function extractorSpec(a) {\n    const title  = String(a.title || '');\n    const facets = a.facets || {};\n    const typeText = [].concat(facets.type || []).join(' ') + ' ' + title;\n    const style = /curved/i.test(typeText) ? 'curved'\n      : /angled/i.test(typeText) ? 'angled'\n      : /\\bbox\\b|linear/i.test(typeText) ? 'box'\n      : 'chimney';\n    const cm = /(\\d{2,3})\\s*cm\\b/i.exec(title)\n      || /(\\d{2,3})\\s*cm\\b/i.exec([].concat(facets.size || []).join(' '));\n    const widthMm = cm ? parseInt(cm[1], 10) * 10 : 600;\n    const f = /(black|white|stainless|steel|silver)/i.exec(title + ' ' + [].concat(facets.colour || []).join(' '));\n    const finish = !f ? 'stainless' : /black/i.test(f[1]) ? 'black' : /white/i.test(f[1]) ? 'white' : 'stainless';\n    return { style, widthMm, depthMm: EXTRACTOR_DEPTH_MM[style], finish };\n  }\n  function handleAddExtractor(appliance) {\n    const hobs = (worktopItems || []).filter(it => it && it.kind === 'hob');\n    if (!hobs.length) {\n      designControlsHandle.setStatus('Add a hob first - the extractor goes on the wall above it');\n      return;\n    }\n    // The selected hob, else the first hob with no hood over it, else the\n    // first hob. \"Over it\" is by position now that a hood moves freely.\n    const hasHood = (h) => worktopItems.some(e => e && e.kind === 'extractor'\n      && Math.hypot((e.x + (e.widthMm || 0) / 2) - (h.x + (h.widthMm || 0) / 2),\n                    (e.y + (e.depthMm || 0) / 2) - (h.y + (h.depthMm || 0) / 2)) < 450);\n    const picked = (selectedItem && selectedItem.kind === 'worktop-item')\n      ? hobs.find(h => h.id === selectedItem.id) : null;\n    const hob = picked || hobs.find(h => !hasHood(h)) || hobs[0];\n    const spec = extractorSpec(appliance);\n    const item = {\n      id:        `wi-${nextWorktopItemId++}`,\n      kind:      'extractor',\n      code:      appliance.handle,\n      name:      appliance.title || appliance.handle,\n      handle:    appliance.handle || null,\n      variantId: appliance.variantId || null,\n      priceCents: (typeof appliance.priceCents === 'number') ? appliance.priceCents : null,\n      compareAtCents: (typeof appliance.compareAtCents === 'number') ? appliance.compareAtCents : null,\n      brand:     appliance.brand || null,\n      imageUrl:  appliance.productImageUrl || appliance.imageUrl || null,\n      productUrl: appliance.handle ? ('/products/' + appliance.handle) : null,\n      glbUrl:    appliance.glbUrl || null,\n      extractorStyle: spec.style,\n      finish:    spec.finish,\n      widthMm:   spec.widthMm,\n      depthMm:   spec.depthMm,\n      x: hob.x, y: hob.y, rotationDeg: hob.rotationDeg || 0\n    };\n    seatExtractorOverHob(item, hob);\n    worktopItems.push(item);\n    rerender();\n    designControlsHandle.setStatus(`Added ${appliance.title || 'extractor'} above the hob - drag its number to move it`);\n  }\n  // First room wall hit going from (cx, cy) along (bx, by); Infinity if none.\n  function distToWallAlong(cx, cy, bx, by) {\n    let dist = Infinity;\n    for (const w of getWalls(room)) {\n      const ex = w.to.x - w.from.x, ey = w.to.y - w.from.y;\n      const den = bx * ey - by * ex;\n      if (Math.abs(den) < 1e-9) continue;\n      const qx = w.from.x - cx, qy = w.from.y - cy;\n      const t = (qx * ey - qy * ex) / den;\n      const s = (qx * by - qy * bx) / den;\n      if (t > 0 && s >= 0 && s <= 1 && t < dist) dist = t;\n    }\n    return dist;\n  }\n  // Initial seat: centred on the hob's width, back to the wall behind the hob\n  // (its local +y). A hob not near a wall (an island) keeps it just behind.\n  function seatExtractorOverHob(e, hob) {\n    const rad = (hob.rotationDeg || 0) * Math.PI / 180;\n    const cx = hob.x + (hob.widthMm || 0) / 2, cy = hob.y + (hob.depthMm || 0) / 2;\n    const bx = -Math.sin(rad), by = Math.cos(rad);\n    const D = e.depthMm || 500;\n    let dist = distToWallAlong(cx, cy, bx, by);\n    if (!(dist < 1200)) dist = (hob.depthMm || 520) / 2 + D / 2;\n    const mx = cx + bx * (dist - D / 2), my = cy + by * (dist - D / 2);\n    e.x = mx - (e.widthMm || 600) / 2;\n    e.y = my - D / 2;\n    e.rotationDeg = hob.rotationDeg || 0;\n  }\n  // After a drag: back flush to the NEAREST wall, facing into the room, the\n  // hood staying where it was dropped along that wall.\n  function seatExtractorOnNearestWall(e) {\n    const W = e.widthMm || 600, D = e.depthMm || 500;\n    const cx = e.x + W / 2, cy = e.y + D / 2;\n    let best = null;\n    for (const w of getWalls(room)) {\n      const ex = w.to.x - w.from.x, ey = w.to.y - w.from.y;\n      const L2 = ex * ex + ey * ey;\n      if (!L2) continue;\n      const t = Math.max(0, Math.min(1, ((cx - w.from.x) * ex + (cy - w.from.y) * ey) / L2));\n      const px = w.from.x + ex * t, py = w.from.y + ey * t;\n      const d = Math.hypot(cx - px, cy - py);\n      if (!best || d < best.d) best = { d, px, py };\n    }\n    if (!best || best.d < 1e-6 || best.d > 1500) return;   // in the open: leave it as dropped\n    const nx = (best.px - cx) / best.d, ny = (best.py - cy) / best.d;   // toward the wall = the hood's back\n    let deg = Math.atan2(-nx, ny) * 180 / Math.PI;\n    const snap = Math.round(deg / 90) * 90;\n    if (Math.abs(deg - snap) < 3) deg = snap;\n    const mx = best.px - nx * (D / 2), my = best.py - ny * (D / 2);\n    e.x = mx - W / 2;\n    e.y = my - D / 2;\n    e.rotationDeg = ((deg % 360) + 360) % 360;\n  }\n  // Hoods placed while they were tied to a hob carry its id: from now on they\n  // stand where they are and move on their own (Arden, 2026-10-12).\n  function syncExtractorsToHobs() {\n    for (const e of (worktopItems || [])) {\n      if (e && e.kind === 'extractor' && e.hobId != null) delete e.hobId;\n    }\n  }\n\n  // ---- Canopy extractors (built into a wall unit) ----\n  // A canopy extractor (appliance_type \"canopy-extractor\") is fitted INSIDE a\n  // wall unit - a top box or a standard wall unit - with its visor showing\n  // under the unit (Arden, 2026-10-12). A worktop item of kind 'canopy' tied\n  // to that unit by hostCabId: seated in it on every render\n  // (syncCanopiesToHosts), moving with it, and dragged in 2D from unit to\n  // unit (wireCanopy2D). Added from Add Appliances it goes straight into the\n  // wall unit over the hob. With no unit it stands free until dropped in one.\n  const CANOPY_DEPTH_MM = 280;\n  const CANOPY_FREE_BOTTOM_MM = 1400;   // a Medium wall unit's underside\n  function isCanopyExtractor(a) {\n    return !!a && a.type === 'canopy-extractor';\n  }\n  // Is plan point (px, py) inside cab's (rotated) footprint?\n  function cabContainsPoint(cab, px, py) {\n    const rad = (cab.rotationDeg || 0) * Math.PI / 180;\n    const dx = px - (cab.x + cab.widthMm / 2), dy = py - (cab.y + cab.depthMm / 2);\n    const lx =  dx * Math.cos(rad) + dy * Math.sin(rad);\n    const ly = -dx * Math.sin(rad) + dy * Math.cos(rad);\n    return Math.abs(lx) <= cab.widthMm / 2 && Math.abs(ly) <= cab.depthMm / 2;\n  }\n  // A unit a canopy can be fitted in: any wall unit EXCEPT an Integrated\n  // Extractor door - that already IS an extractor, so a canopy in it made two\n  // over the one hob (Arden, 2026-10-12).\n  function isExtractorHousingCab(c) {\n    return ((c && c.cutoutSchema && c.cutoutSchema.openings) || [])\n      .some(o => o && /extractor/i.test(String(o.appliance || '')));\n  }\n  function canHostCanopy(c) {\n    return !!c && isWallMounted(c) && !isExtractorHousingCab(c);\n  }\n  function wallCabAt(px, py, accept = canHostCanopy) {\n    const hits = (cabinets || []).filter(c => c && accept(c) && cabContainsPoint(c, px, py));\n    if (!hits.length) return null;\n    // The nearest centre wins where units touch.\n    return hits.sort((a, b) =>\n      Math.hypot(a.x + a.widthMm / 2 - px, a.y + a.depthMm / 2 - py)\n      - Math.hypot(b.x + b.widthMm / 2 - px, b.y + b.depthMm / 2 - py))[0];\n  }\n  // The wall unit over a hob: tested a little behind the hob's centre (toward\n  // the wall, where the shallower wall units sit), then at the centre itself.\n  function wallCabAboveHob(hob) {\n    const rad = (hob.rotationDeg || 0) * Math.PI / 180;\n    const cx = hob.x + (hob.widthMm || 0) / 2, cy = hob.y + (hob.depthMm || 0) / 2;\n    return wallCabAt(cx - Math.sin(rad) * 150, cy + Math.cos(rad) * 150) || wallCabAt(cx, cy);\n  }\n  // An Integrated Extractor door over the hob - the hob already has its extractor.\n  function extractorHousingAboveHob(hob) {\n    const rad = (hob.rotationDeg || 0) * Math.PI / 180;\n    const cx = hob.x + (hob.widthMm || 0) / 2, cy = hob.y + (hob.depthMm || 0) / 2;\n    return wallCabAt(cx - Math.sin(rad) * 150, cy + Math.cos(rad) * 150, isExtractorHousingCab)\n      || wallCabAt(cx, cy, isExtractorHousingCab);\n  }\n  // Centre the canopy across the unit, its back 10mm off the unit's back,\n  // turned with it; its underside on the unit's underside.\n  function seatCanopyInCab(e, cab) {\n    const rad = (cab.rotationDeg || 0) * Math.PI / 180;\n    const W = Math.min(e.canopyWidthMm || 600, cab.widthMm);\n    const D = Math.min(CANOPY_DEPTH_MM, Math.max(100, cab.depthMm - 20));\n    const off = cab.depthMm / 2 - D / 2 - 10;\n    const mx = cab.x + cab.widthMm / 2 - Math.sin(rad) * off;\n    const my = cab.y + cab.depthMm / 2 + Math.cos(rad) * off;\n    e.widthMm = W; e.depthMm = D;\n    e.x = mx - W / 2; e.y = my - D / 2;\n    e.rotationDeg = cab.rotationDeg || 0;\n    e.mountBottomMm = wallUnitVerticalRange(cab).bottom;\n  }\n  // A CEILING BEAM hangs flush under the ceiling - Room Setup offers no height\n  // off the floor for one. Its restMm (the underside) was set once, when it was\n  // added, as ceiling - beam height, and never again: make the beam deeper or\n  // the ceiling lower and it poked through the ceiling (Arden, 2026-10-14: a\n  // 300 beam added at 200 stood 100mm proud of a 2400 ceiling). Re-seated on\n  // every render, so the 3D, the advisories and the room previews all read the\n  // beam where it really is.\n  function syncBeamsToCeiling() {\n    const items = roomConfig && roomConfig.perimeterItems;\n    if (!Array.isArray(items) || !items.some(it => it && it.type === 'beam')) return;\n    const ceil = Number(roomConfig.ceilingHeightMm) || 2400;\n    let changed = false;\n    const next = items.map(it => {\n      if (!it || it.type !== 'beam') return it;\n      const rest = Math.max(0, ceil - (Number(it.heightMm) || 200));\n      if (it.restMm === rest) return it;\n      changed = true;\n      return { ...it, restMm: rest };\n    });\n    if (changed) roomConfig = { ...roomConfig, perimeterItems: next };\n  }\n\n  function syncCanopiesToHosts() {\n    for (const e of (worktopItems || [])) {\n      if (!e || e.kind !== 'canopy') continue;\n      const cab = e.hostCabId ? (cabinets || []).find(c => c && c.id === e.hostCabId && canHostCanopy(c)) : null;\n      if (cab) { seatCanopyInCab(e, cab); continue; }\n      e.hostCabId = null;   // its unit went - it stands free where it was\n      if (typeof e.mountBottomMm !== 'number') e.mountBottomMm = CANOPY_FREE_BOTTOM_MM;\n    }\n  }\n  function handleAddCanopy(appliance) {\n    const spec = extractorSpec(appliance);\n    const hobs = (worktopItems || []).filter(it => it && it.kind === 'hob');\n    const hob = ((selectedItem && selectedItem.kind === 'worktop-item')\n      ? hobs.find(h => h.id === selectedItem.id) : null) || hobs[0] || null;\n    const host = hob ? wallCabAboveHob(hob) : null;\n    const W = spec.widthMm, D = CANOPY_DEPTH_MM;\n    let x, y;\n    if (hob) { x = hob.x + (hob.widthMm || 0) / 2 - W / 2; y = hob.y + (hob.depthMm || 0) / 2 - D / 2; }\n    else {\n      const bbox = getBoundingBox(room);\n      x = bbox.minX + bbox.widthMm / 2 - W / 2; y = bbox.minY + bbox.heightMm / 2 - D / 2;\n    }\n    const item = {\n      id:        `wi-${nextWorktopItemId++}`,\n      kind:      'canopy',\n      hostCabId: host ? host.id : null,\n      code:      appliance.handle,\n      name:      appliance.title || appliance.handle,\n      handle:    appliance.handle || null,\n      variantId: appliance.variantId || null,\n      priceCents: (typeof appliance.priceCents === 'number') ? appliance.priceCents : null,\n      compareAtCents: (typeof appliance.compareAtCents === 'number') ? appliance.compareAtCents : null,\n      brand:     appliance.brand || null,\n      imageUrl:  appliance.productImageUrl || appliance.imageUrl || null,\n      productUrl: appliance.handle ? ('/products/' + appliance.handle) : null,\n      finish:    spec.finish,\n      canopyWidthMm: W,\n      widthMm: W, depthMm: D, x, y, rotationDeg: hob ? (hob.rotationDeg || 0) : 0,\n      mountBottomMm: CANOPY_FREE_BOTTOM_MM\n    };\n    worktopItems.push(item);\n    rerender();\n    const name = appliance.title || 'canopy extractor';\n    designControlsHandle.setStatus(host\n      ? (W > host.widthMm\n          ? `Added ${name} in the wall unit above the hob - it is wider than that unit`\n          : `Added ${name} in the wall unit above the hob`)\n      : (hob && extractorHousingAboveHob(hob))\n        ? `Added ${name} - the hob already has an Integrated Extractor above it, so drag this into another wall unit`\n      : hob\n        ? `Added ${name} - there is no wall unit above the hob, drag it into one`\n        : `Added ${name} - drag it into a wall unit`);\n  }\n  // 2D: dragged from wall unit to wall unit. On release it moves into the wall\n  // unit under its centre, or stands free there if there is none.\n  function wireCanopy2D(item, el, pxPerMm) {\n    let didDrag = false, lastX = item.x, lastY = item.y;\n    const drag = makeDraggable(el, {\n      pxPerMm,\n      getZoom: () => view2d.zoom,\n      onDragMove({ dxMm, dyMm }) {\n        if (Math.hypot(dxMm, dyMm) * pxPerMm > 5) didDrag = true;\n        lastX = item.x + dxMm; lastY = item.y + dyMm;\n        el.style.left = `${Math.round(lastX * pxPerMm)}px`;\n        el.style.top  = `${Math.round(lastY * pxPerMm)}px`;\n      },\n      onDragEnd() {\n        if (!didDrag) return;\n        const cab = wallCabAt(lastX + item.widthMm / 2, lastY + item.depthMm / 2);\n        item.x = lastX; item.y = lastY;\n        item.hostCabId = cab ? cab.id : null;\n        rerender();\n        designControlsHandle.setStatus(cab\n          ? (item.canopyWidthMm > cab.widthMm ? 'Moved into that wall unit - it is wider than the unit' : 'Moved into that wall unit')\n          : (wallCabAt(lastX + item.widthMm / 2, lastY + item.depthMm / 2, isExtractorHousingCab)\n            ? 'That is an Integrated Extractor - a canopy goes in an ordinary wall unit'\n            : 'Not over a wall unit - drop it on one to fit it'));\n      }\n    });\n    renderHandles.push(drag);\n    let downX = 0, downY = 0, downActive = false;\n    const onDown = e => { downX = e.clientX; downY = e.clientY; downActive = true; };\n    const onUp = e => {\n      if (!downActive) return;\n      downActive = false;\n      if (Math.hypot(e.clientX - downX, e.clientY - downY) >= 5) return;\n      selectItem({ kind: 'worktop-item', id: item.id });\n    };\n    const onCtx = e => {\n      e.preventDefault();\n      showContextMenu({ x: e.clientX, y: e.clientY,\n        items: [{ label: 'Delete', action: () => deleteWorktopItem(item.id) }] });\n    };\n    el.addEventListener('pointerdown', onDown);\n    el.addEventListener('pointerup', onUp);\n    el.addEventListener('contextmenu', onCtx);\n    renderHandles.push({ destroy() {\n      el.removeEventListener('pointerdown', onDown);\n      el.removeEventListener('pointerup', onUp);\n      el.removeEventListener('contextmenu', onCtx);\n    } });\n  }\n\n  // Phase 3 - spawn the radius unit AND its auto-group of backing\n  // pieces. Layout (looking at the plan, +y = \"back\" = away from\n  // user / toward wall):\n  //\n  //   end-base group (570mm total depth)\n  //     radius unit  \u2192 300\u00D7300 at (x, y)\n  //     filler       \u2192 300\u00D710  at (x, y + 300)\n  //     backing base \u2192 300\u00D7260 at (x, y + 310)\n  //\n  //   end-wall group (330mm total depth)\n  //     radius wall  \u2192 300\u00D7300 at (x, y)\n  //     filler       \u2192 300\u00D730  at (x, y + 300)\n  //\n  //   island-base \u2192 just the radius unit alone\n  //\n  // All pieces share a groupId so dragging one drags the whole\n  // assembly. Hand auto-detect runs on drag-end (radiusUnitDesiredHand).\n  // Spawn an L-shape corner base unit - a single cabinet (no auto-\n  // group, no backing / filler) with the L-shape marker. Default\n  // hand 'NE' (cutout top-right); the orchestrator's drag handler\n  // can re-pick the hand later based on which room corner the unit\n  // is dropped near (Phase 6).\n  function addLShapeUnit(entry) {\n    if (!entry) { console.warn('[BTK Kitchen Planner] No L-shape unit entry'); return; }\n    const bbox = getBoundingBox(room);\n    const stagger = (cabinets.length % CABINET_STAGGER_WRAP) * CABINET_STAGGER_MM;\n    const baseX   = bbox.widthMm  / 2 - (entry.widthMm || 0) / 2 + stagger;\n    const baseY   = bbox.heightMm / 2 - (entry.depthMm || 0) / 2 + stagger;\n    const styleId = kitchenStyleId || null;\n    const doorColours    = Catalogue.getDoorColoursForStyle(styleId)    || [];\n    const carcaseColours = Catalogue.getCarcaseColoursForStyle(styleId) || [];\n    const defaultDoor    = globalDoorColourHandle    || doorColours[0]?.handle    || null;\n    const defaultCarcase = globalCarcaseColourHandle || carcaseColours[0]?.handle || null;\n    const inheritedFill  = findCatalogueFillForCategory(entry.category);\n\n    const cab = buildLShapeUnitCabinet(entry, {\n      id: `cab-lshape-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 5)}`,\n      x: baseX, y: baseY,\n      hand: 'NE'\n    });\n    cab.kitchenStyleId    = styleId;\n    cab.doorColourHandle  = defaultDoor;\n    cab.carcaseColourHandle = defaultCarcase;\n    if (inheritedFill) cab.planner2D = { fillColour: inheritedFill };\n    cab.displayNumber = nextDisplayNumber();\n    cabinets.push(cab);\n    rerender();\n  }\n\n  // Spawn a diagonal corner base unit - same flow as addLShapeUnit\n  // but with the diagonalCornerUnit marker (pentagon footprint with\n  // a single 45\u00B0 door). All downstream consumers (2D / 3D / worktop /\n  // placement) branch on .diagonalCornerUnit existence and use the\n  // pentagon polygon + diagonal door segment helpers from the engine\n  // module to draw the body and door.\n  function addDiagonalCornerUnit(entry) {\n    if (!entry) { console.warn('[BTK Kitchen Planner] No diagonal corner unit entry'); return; }\n    const bbox = getBoundingBox(room);\n    const stagger = (cabinets.length % CABINET_STAGGER_WRAP) * CABINET_STAGGER_MM;\n    const baseX   = bbox.widthMm  / 2 - (entry.widthMm || 0) / 2 + stagger;\n    const baseY   = bbox.heightMm / 2 - (entry.depthMm || 0) / 2 + stagger;\n    const styleId = kitchenStyleId || null;\n    const doorColours    = Catalogue.getDoorColoursForStyle(styleId)    || [];\n    const carcaseColours = Catalogue.getCarcaseColoursForStyle(styleId) || [];\n    const defaultDoor    = globalDoorColourHandle    || doorColours[0]?.handle    || null;\n    const defaultCarcase = globalCarcaseColourHandle || carcaseColours[0]?.handle || null;\n    const inheritedFill  = findCatalogueFillForCategory(entry.category);\n\n    const cab = buildDiagonalCornerUnitCabinet(entry, {\n      id: `cab-diag-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 5)}`,\n      x: baseX, y: baseY,\n      hand: 'NE'\n    });\n    cab.kitchenStyleId    = styleId;\n    cab.doorColourHandle  = defaultDoor;\n    cab.carcaseColourHandle = defaultCarcase;\n    // Wire the real Shopify metaobject diagonal unit_type onto the stub\n    // geometry: swap identity \u2192 real unitTypeId (so the 3D renderer picks\n    // up its carcase GLB and routes to buildDiagonalCornerUnitGLB) + a real\n    // variant/price so it's orderable. The pentagon geometry block\n    // (armDepth/cutout/hand) stays from the stub. Falls back to geometry-\n    // only stub rendering if the metaobject / product isn't set up yet.\n    // `.trim()` guards the metaobject's trailing-space shape (\"diagonal \").\n    const realDiag = (Catalogue.getUnitTypes?.() || [])\n      .find(u => String(u.planner2D?.shape || '').trim().toLowerCase() === 'diagonal'\n                 && /^base/i.test(u.categoryHandle || ''));\n    if (realDiag) {\n      cab.unitTypeId = realDiag.id;\n      cab.code       = realDiag.code || cab.code;\n      const product  = Catalogue.getProductForUnitInStyle?.(realDiag.id, styleId);\n      const variant  = product?.variants?.[0];\n      if (variant) {\n        cab.variantId  = variant.id;\n        const vinfo    = Catalogue.getVariantInfo?.(variant.id);\n        cab.priceCents = (vinfo && vinfo.priceCents != null) ? vinfo.priceCents : (variant.price || 0);\n        cab.compareAtCents = (vinfo && typeof vinfo.compareAtCents === 'number') ? vinfo.compareAtCents : null;\n      }\n    }\n    if (inheritedFill) cab.planner2D = { fillColour: inheritedFill };\n    cab.displayNumber = nextDisplayNumber();\n    cabinets.push(cab);\n    rerender();\n  }\n\n  // L-shape WALL corner unit - same spawn flow as addLShapeUnit but\n  // the builder sets category 'wall-units' + wallMountLevel from\n  // heightMm so the 3D renderer mounts it at wall height. The\n  // existing L-shape geometry helpers (footprint polygon, door\n  // segments) work unchanged because they read off the cab + the\n  // lShapeUnit struct alone.\n  function addLShapeWallUnit(entry) {\n    if (!entry) { console.warn('[BTK Kitchen Planner] No L-shape wall unit entry'); return; }\n    const bbox = getBoundingBox(room);\n    const stagger = (cabinets.length % CABINET_STAGGER_WRAP) * CABINET_STAGGER_MM;\n    const baseX   = bbox.widthMm  / 2 - (entry.widthMm || 0) / 2 + stagger;\n    const baseY   = bbox.heightMm / 2 - (entry.depthMm || 0) / 2 + stagger;\n    const styleId = kitchenStyleId || null;\n    const doorColours    = Catalogue.getDoorColoursForStyle(styleId)    || [];\n    const carcaseColours = Catalogue.getCarcaseColoursForStyle(styleId) || [];\n    const defaultDoor    = globalDoorColourHandle    || doorColours[0]?.handle    || null;\n    const defaultCarcase = globalCarcaseColourHandle || carcaseColours[0]?.handle || null;\n    const inheritedFill  = findCatalogueFillForCategory(entry.category);\n\n    const cab = buildLShapeWallUnitCabinet(entry, {\n      id: `cab-lshape-wall-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 5)}`,\n      x: baseX, y: baseY,\n      hand: 'NE'\n    });\n    cab.kitchenStyleId      = styleId;\n    cab.doorColourHandle    = defaultDoor;\n    cab.carcaseColourHandle = defaultCarcase;\n    if (inheritedFill) cab.planner2D = { fillColour: inheritedFill };\n    cab.displayNumber = nextDisplayNumber();\n    cabinets.push(cab);\n    rerender();\n  }\n\n  // Spawn a diagonal corner WALL unit - same flow as addLShapeWallUnit\n  // but with the diagonalCornerUnit marker (pentagon body + single 45\u00B0\n  // door) instead of the L-shape marker. The builder picks the right\n  // wallMountLevel from the catalogue entry's heightMm. All 2D / 3D /\n  // placement / trim consumers branch on .diagonalCornerUnit and treat\n  // the wall variant differently via the cab.category check.\n  function addDiagonalCornerWallUnit(entry) {\n    if (!entry) { console.warn('[BTK Kitchen Planner] No diagonal wall unit entry'); return; }\n    const bbox = getBoundingBox(room);\n    const stagger = (cabinets.length % CABINET_STAGGER_WRAP) * CABINET_STAGGER_MM;\n    const baseX   = bbox.widthMm  / 2 - (entry.widthMm || 0) / 2 + stagger;\n    const baseY   = bbox.heightMm / 2 - (entry.depthMm || 0) / 2 + stagger;\n    const styleId = kitchenStyleId || null;\n    const doorColours    = Catalogue.getDoorColoursForStyle(styleId)    || [];\n    const carcaseColours = Catalogue.getCarcaseColoursForStyle(styleId) || [];\n    const defaultDoor    = globalDoorColourHandle    || doorColours[0]?.handle    || null;\n    const defaultCarcase = globalCarcaseColourHandle || carcaseColours[0]?.handle || null;\n    const inheritedFill  = findCatalogueFillForCategory(entry.category);\n\n    const cab = buildDiagonalCornerWallUnitCabinet(entry, {\n      id: `cab-diag-wall-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 5)}`,\n      x: baseX, y: baseY,\n      hand: 'NE'\n    });\n    cab.kitchenStyleId      = styleId;\n    cab.doorColourHandle    = defaultDoor;\n    cab.carcaseColourHandle = defaultCarcase;\n    if (inheritedFill) cab.planner2D = { fillColour: inheritedFill };\n    cab.displayNumber = nextDisplayNumber();\n    cabinets.push(cab);\n    rerender();\n  }\n\n  // Spawn a diagonal corner larder unit - tall diagonal corner with a\n  // SINGLE door across the diagonal face, full-height end panels and\n  // an inline (non-recessed) plinth. The 1013\u00D71013 smaller sibling\n  // of the walk-in (1154\u00D71154 double-door) larder. Shares the same\n  // `diagonalCornerUnit` marker and tall category, so larder\n  // behaviour (inline plinth, panels always on) kicks in via the\n  // category check the renderers use.\n  function addDiagonalCornerLarderUnit(entry) {\n    if (!entry) { console.warn('[BTK Kitchen Planner] No diagonal corner larder entry'); return; }\n    const bbox = getBoundingBox(room);\n    const stagger = (cabinets.length % CABINET_STAGGER_WRAP) * CABINET_STAGGER_MM;\n    const baseX   = bbox.widthMm  / 2 - (entry.widthMm || 0) / 2 + stagger;\n    const baseY   = bbox.heightMm / 2 - (entry.depthMm || 0) / 2 + stagger;\n    const styleId = kitchenStyleId || null;\n    const doorColours    = Catalogue.getDoorColoursForStyle(styleId)    || [];\n    const carcaseColours = Catalogue.getCarcaseColoursForStyle(styleId) || [];\n    const defaultDoor    = globalDoorColourHandle    || doorColours[0]?.handle    || null;\n    const defaultCarcase = globalCarcaseColourHandle || carcaseColours[0]?.handle || null;\n    const inheritedFill  = findCatalogueFillForCategory(entry.category);\n\n    const cab = buildDiagonalCornerLarderUnitCabinet(entry, {\n      id: `cab-diag-larder-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 5)}`,\n      x: baseX, y: baseY,\n      hand: 'NE'\n    });\n    cab.kitchenStyleId      = styleId;\n    cab.doorColourHandle    = defaultDoor;\n    cab.carcaseColourHandle = defaultCarcase;\n    if (inheritedFill) cab.planner2D = { fillColour: inheritedFill };\n    cab.displayNumber = nextDisplayNumber();\n    cabinets.push(cab);\n    rerender();\n  }\n\n  // Spawn a walk-in corner larder unit - tall diagonal corner with\n  // double doors, full-height end panels and an inline (non-recessed)\n  // plinth. Uses the same `diagonalCornerUnit` marker the base / wall\n  // diag variants use so every existing 2D / 3D / placement / trim\n  // path picks it up unchanged; the `walkInLarder: true` flag (set by\n  // the builder) flips on the double-door + inline-plinth renderers.\n  function addWalkInCornerLarderUnit(entry) {\n    if (!entry) { console.warn('[BTK Kitchen Planner] No walk-in larder entry'); return; }\n    const bbox = getBoundingBox(room);\n    const stagger = (cabinets.length % CABINET_STAGGER_WRAP) * CABINET_STAGGER_MM;\n    const baseX   = bbox.widthMm  / 2 - (entry.widthMm || 0) / 2 + stagger;\n    const baseY   = bbox.heightMm / 2 - (entry.depthMm || 0) / 2 + stagger;\n    const styleId = kitchenStyleId || null;\n    const doorColours    = Catalogue.getDoorColoursForStyle(styleId)    || [];\n    const carcaseColours = Catalogue.getCarcaseColoursForStyle(styleId) || [];\n    const defaultDoor    = globalDoorColourHandle    || doorColours[0]?.handle    || null;\n    const defaultCarcase = globalCarcaseColourHandle || carcaseColours[0]?.handle || null;\n    const inheritedFill  = findCatalogueFillForCategory(entry.category);\n\n    const cab = buildWalkInCornerLarderUnitCabinet(entry, {\n      id: `cab-walkin-larder-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 5)}`,\n      x: baseX, y: baseY,\n      hand: 'NE'\n    });\n    cab.kitchenStyleId      = styleId;\n    cab.doorColourHandle    = defaultDoor;\n    cab.carcaseColourHandle = defaultCarcase;\n    if (inheritedFill) cab.planner2D = { fillColour: inheritedFill };\n    cab.displayNumber = nextDisplayNumber();\n    cabinets.push(cab);\n    rerender();\n  }\n\n  // Open base units - door-less base cabs (open shelves). Same spawn\n  // flow as the L-shape wall stub. The builder sets category\n  // 'base-units' + `openCarcase: true`; the 3D renderer's\n  // buildPlaceholder routes that flag to the hollow-carcase placeholder\n  // so the unit reads as an open shelf in 3D without needing a\n  // cutout schema.\n  function addOpenBaseUnit(entry) {\n    if (!entry) { console.warn('[BTK Kitchen Planner] No open-base-unit entry'); return; }\n    const bbox = getBoundingBox(room);\n    const stagger = (cabinets.length % CABINET_STAGGER_WRAP) * CABINET_STAGGER_MM;\n    const baseX   = bbox.widthMm  / 2 - (entry.widthMm || 0) / 2 + stagger;\n    const baseY   = bbox.heightMm / 2 - (entry.depthMm || 0) / 2 + stagger;\n    const styleId = kitchenStyleId || null;\n    const doorColours    = Catalogue.getDoorColoursForStyle(styleId)    || [];\n    const carcaseColours = Catalogue.getCarcaseColoursForStyle(styleId) || [];\n    const defaultDoor    = globalDoorColourHandle    || doorColours[0]?.handle    || null;\n    const defaultCarcase = globalCarcaseColourHandle || carcaseColours[0]?.handle || null;\n    const inheritedFill  = findCatalogueFillForCategory(entry.category);\n    const cab = buildOpenBaseUnitCabinet(entry, {\n      id: `cab-open-base-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 5)}`,\n      x: baseX, y: baseY\n    });\n    cab.kitchenStyleId      = styleId;\n    cab.doorColourHandle    = defaultDoor;\n    cab.carcaseColourHandle = defaultCarcase;\n    if (inheritedFill) cab.planner2D = { fillColour: inheritedFill };\n    cab.displayNumber = nextDisplayNumber();\n    cabinets.push(cab);\n    rerender();\n  }\n\n  // Corner WALL units - wall-category corner units with the blank-\n  // panel construction at wall depth (330mm). Same spawn flow as the\n  // L-shape / bridging stubs. Default hand 'left' (cutout-side void\n  // on the cab's user-LEFT); drag-end auto-flips to match the\n  // dropped room corner via cornerUnitDesiredHand.\n  function addCornerWallUnit(entry) {\n    if (!entry) { console.warn('[BTK Kitchen Planner] No corner-wall-unit entry'); return; }\n    const bbox = getBoundingBox(room);\n    const stagger = (cabinets.length % CABINET_STAGGER_WRAP) * CABINET_STAGGER_MM;\n    // Footprint width = cabinet width + void (computed by the builder).\n    // Use that for initial placement once the cab exists.\n    const styleId = kitchenStyleId || null;\n    const doorColours    = Catalogue.getDoorColoursForStyle(styleId)    || [];\n    const carcaseColours = Catalogue.getCarcaseColoursForStyle(styleId) || [];\n    const defaultDoor    = globalDoorColourHandle    || doorColours[0]?.handle    || null;\n    const defaultCarcase = globalCarcaseColourHandle || carcaseColours[0]?.handle || null;\n    const inheritedFill  = findCatalogueFillForCategory(entry.category);\n    const cab = buildCornerWallUnitCabinet(entry, {\n      id: `cab-cornerwall-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 5)}`,\n      x: 0, y: 0,\n      hand: 'left'\n    });\n    cab.x = bbox.widthMm  / 2 - cab.widthMm  / 2 + stagger;\n    cab.y = bbox.heightMm / 2 - cab.depthMm  / 2 + stagger;\n    cab.kitchenStyleId      = styleId;\n    cab.doorColourHandle    = defaultDoor;\n    cab.carcaseColourHandle = defaultCarcase;\n    if (inheritedFill) cab.planner2D = { fillColour: inheritedFill };\n    cab.displayNumber = nextDisplayNumber();\n    cabinets.push(cab);\n    rerender();\n  }\n\n  // Belfast sink base units - base-category boxes with a lowered\n  // carcase + sink notch (the belfastSink marker). Same spawn flow as\n  // the other stubs; end panels start ON (the builder sets them) and\n  // the auto-detect win rule keeps them against base neighbours.\n  function addBelfastSinkUnit(entry) {\n    if (!entry) { console.warn('[BTK Kitchen Planner] No Belfast-sink-unit entry'); return; }\n    // A Belfast sink unit under a faced laminate worktop: never.\n    const sinkBlock = sinkWorktopBlock(null, true);\n    if (sinkBlock) { alertFacedSink(sinkBlock); return; }\n    const bbox = getBoundingBox(room);\n    const stagger = (cabinets.length % CABINET_STAGGER_WRAP) * CABINET_STAGGER_MM;\n    const baseX   = bbox.widthMm  / 2 - (entry.widthMm || 0) / 2 + stagger;\n    const baseY   = bbox.heightMm / 2 - 570 / 2 + stagger;\n    const styleId = kitchenStyleId || null;\n    const doorColours    = Catalogue.getDoorColoursForStyle(styleId)    || [];\n    const carcaseColours = Catalogue.getCarcaseColoursForStyle(styleId) || [];\n    const defaultDoor    = globalDoorColourHandle    || doorColours[0]?.handle    || null;\n    const defaultCarcase = globalCarcaseColourHandle || carcaseColours[0]?.handle || null;\n    const inheritedFill  = findCatalogueFillForCategory('base-units');\n\n    const cab = buildBelfastSinkUnitCabinet(entry, {\n      id: `cab-belfast-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 5)}`,\n      x: baseX, y: baseY\n    });\n    cab.kitchenStyleId      = styleId;\n    cab.doorColourHandle    = defaultDoor;\n    cab.carcaseColourHandle = defaultCarcase;\n    if (inheritedFill) cab.planner2D = { fillColour: inheritedFill };\n    cab.displayNumber = nextDisplayNumber();\n    cabinets.push(cab);\n    rerender();\n  }\n\n  // Build-under oven housing - base-category box with an oven aperture\n  // over a drawer (the ovenHousing marker). Same spawn flow as the\n  // other base stubs; full base features come from the base category.\n  function addOvenHousingUnit(entry) {\n    if (!entry) { console.warn('[BTK Kitchen Planner] No oven-housing-unit entry'); return; }\n    const bbox = getBoundingBox(room);\n    const stagger = (cabinets.length % CABINET_STAGGER_WRAP) * CABINET_STAGGER_MM;\n    const baseX   = bbox.widthMm  / 2 - (entry.widthMm || 0) / 2 + stagger;\n    const baseY   = bbox.heightMm / 2 - 570 / 2 + stagger;\n    const styleId = kitchenStyleId || null;\n    const doorColours    = Catalogue.getDoorColoursForStyle(styleId)    || [];\n    const carcaseColours = Catalogue.getCarcaseColoursForStyle(styleId) || [];\n    const defaultDoor    = globalDoorColourHandle    || doorColours[0]?.handle    || null;\n    const defaultCarcase = globalCarcaseColourHandle || carcaseColours[0]?.handle || null;\n    const inheritedFill  = findCatalogueFillForCategory('base-units');\n\n    const cab = buildOvenHousingUnitCabinet(entry, {\n      id: `cab-ovh-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 5)}`,\n      x: baseX, y: baseY\n    });\n    cab.kitchenStyleId      = styleId;\n    cab.doorColourHandle    = defaultDoor;\n    cab.carcaseColourHandle = defaultCarcase;\n    if (inheritedFill) cab.planner2D = { fillColour: inheritedFill };\n    cab.displayNumber = nextDisplayNumber();\n    cabinets.push(cab);\n    rerender();\n  }\n\n  // Tall single-oven housing - Tall-category cab with door above +\n  // oven aperture + door below. Same spawn flow as the build-under\n  // oven housing; the `ovenHousing` marker routes the 3D renderer to\n  // buildOvenHousingPlaceholder which handles both base + tall.\n  function addTallOvenHousingUnit(entry) {\n    if (!entry) { console.warn('[BTK Kitchen Planner] No tall-oven-housing-unit entry'); return; }\n    const bbox = getBoundingBox(room);\n    const stagger = (cabinets.length % CABINET_STAGGER_WRAP) * CABINET_STAGGER_MM;\n    const baseX   = bbox.widthMm  / 2 - (entry.widthMm || 0) / 2 + stagger;\n    const baseY   = bbox.heightMm / 2 - (entry.depthMm || 570) / 2 + stagger;\n    const styleId = kitchenStyleId || null;\n    const doorColours    = Catalogue.getDoorColoursForStyle(styleId)    || [];\n    const carcaseColours = Catalogue.getCarcaseColoursForStyle(styleId) || [];\n    const defaultDoor    = globalDoorColourHandle    || doorColours[0]?.handle    || null;\n    const defaultCarcase = globalCarcaseColourHandle || carcaseColours[0]?.handle || null;\n    const inheritedFill  = findCatalogueFillForCategory('tall-units');\n\n    const cab = buildTallOvenHousingUnitCabinet(entry, {\n      id: `cab-toh-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 5)}`,\n      x: baseX, y: baseY\n    });\n    cab.kitchenStyleId      = styleId;\n    cab.doorColourHandle    = defaultDoor;\n    cab.carcaseColourHandle = defaultCarcase;\n    if (inheritedFill) cab.planner2D = { fillColour: inheritedFill };\n    cab.displayNumber = nextDisplayNumber();\n    cabinets.push(cab);\n    rerender();\n  }\n\n  // Set (or clear) the hob that sits on the worktop above an oven\n  // housing. Resolves the placeholder hob record and stores it on the\n  // cabinet; the 3D renderer draws it above the unit.\n  function handleSetCabinetHob(cabinetId, hobCode) {\n    const idx = cabinets.findIndex(c => c.id === cabinetId);\n    if (idx === -1) return;\n    const hobs = (getWorktopItemCatalogue().hobs) || [];\n    const hob  = hobCode ? (hobs.find(h => h.code === hobCode) || null) : null;\n    cabinets[idx] = { ...cabinets[idx], hob };\n    rerender();\n  }\n\n  // Build-under sink base units - single (1 door) + double (2 doors),\n  // base category, with a sink on the worktop above. Same spawn flow.\n  function addSinkBaseUnit(entry) {\n    if (!entry) { console.warn('[BTK Kitchen Planner] No sink-base-unit entry'); return; }\n    const bbox = getBoundingBox(room);\n    const stagger = (cabinets.length % CABINET_STAGGER_WRAP) * CABINET_STAGGER_MM;\n    const baseX   = bbox.widthMm  / 2 - (entry.widthMm || 0) / 2 + stagger;\n    const baseY   = bbox.heightMm / 2 - 570 / 2 + stagger;\n    const styleId = kitchenStyleId || null;\n    const doorColours    = Catalogue.getDoorColoursForStyle(styleId)    || [];\n    const carcaseColours = Catalogue.getCarcaseColoursForStyle(styleId) || [];\n    const defaultDoor    = globalDoorColourHandle    || doorColours[0]?.handle    || null;\n    const defaultCarcase = globalCarcaseColourHandle || carcaseColours[0]?.handle || null;\n    const inheritedFill  = findCatalogueFillForCategory('base-units');\n\n    const cab = buildSinkBaseUnitCabinet(entry, {\n      id: `cab-sinkbase-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 5)}`,\n      x: baseX, y: baseY\n    });\n    cab.kitchenStyleId      = styleId;\n    cab.doorColourHandle    = defaultDoor;\n    cab.carcaseColourHandle = defaultCarcase;\n    if (inheritedFill) cab.planner2D = { fillColour: inheritedFill };\n    cab.displayNumber = nextDisplayNumber();\n    cabinets.push(cab);\n    rerender();\n  }\n\n  // Free-place end panels & fillers. Plain box geometry; the user\n  // can override W/H/D, rotate 90\u00B0, lift it off the floor, or push\n  // it away from the wall via the selection-panel detail fields.\n  // Goes through the standard cabinets[] pipeline so drag, snap,\n  // rotate, and selection all just work via existing machinery.\n  function addEndPanelFiller(entry) {\n    if (!entry) { console.warn('[BTK Kitchen Planner] No end-panel/filler entry'); return; }\n    const bbox = getBoundingBox(room);\n    const stagger = (cabinets.length % CABINET_STAGGER_WRAP) * CABINET_STAGGER_MM;\n    const baseX   = bbox.widthMm  / 2 - (entry.widthMm || 0) / 2 + stagger;\n    const baseY   = bbox.heightMm / 2 - (entry.depthMm || 0) / 2 + stagger;\n    const styleId = kitchenStyleId || null;\n    const doorColours    = Catalogue.getDoorColoursForStyle(styleId)    || [];\n    const carcaseColours = Catalogue.getCarcaseColoursForStyle(styleId) || [];\n    const defaultDoor    = globalDoorColourHandle    || doorColours[0]?.handle    || null;\n    const defaultCarcase = globalCarcaseColourHandle || carcaseColours[0]?.handle || null;\n    // End panels are visible from the room so they should read in\n    // the DOOR colour, not the carcase colour. Plumb that into\n    // planner2D.fillColour so the placeholder-box path picks it up.\n    const doorHex = (doorColours.find(c => c.handle === defaultDoor) || doorColours[0])?.hex || null;\n\n    const cab = buildEndPanelFillerCabinet(entry, {\n      id: `cab-panel-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 5)}`,\n      x: baseX, y: baseY\n    });\n    cab.kitchenStyleId      = styleId;\n    cab.doorColourHandle    = defaultDoor;\n    cab.carcaseColourHandle = defaultCarcase;\n    if (doorHex) cab.planner2D = { fillColour: doorHex };\n    cab.displayNumber = nextDisplayNumber();\n    cabinets.push(cab);\n    rerender();\n  }\n\n  // Free-place Corner Post + Void - a post-only corner stub used to\n  // join two perpendicular runs (e.g. two drawer units) WITHOUT a\n  // dedicated corner cab between them. The post sits at the inner\n  // corner; its geometry is fixed (arms 60mm, cutout 570mm) so no\n  // runtime auto-depth pass is needed.\n  function addCornerPostVoid(entry) {\n    if (!entry) { console.warn('[BTK Kitchen Planner] No corner-post-void entry'); return; }\n    const bbox = getBoundingBox(room);\n    const stagger = (cabinets.length % CABINET_STAGGER_WRAP) * CABINET_STAGGER_MM;\n    const baseX   = bbox.widthMm  / 2 - (entry.widthMm || 0) / 2 + stagger;\n    const baseY   = bbox.heightMm / 2 - (entry.depthMm || 0) / 2 + stagger;\n    const styleId = kitchenStyleId || null;\n    const doorColours    = Catalogue.getDoorColoursForStyle(styleId)    || [];\n    const carcaseColours = Catalogue.getCarcaseColoursForStyle(styleId) || [];\n    const defaultDoor    = globalDoorColourHandle    || doorColours[0]?.handle    || null;\n    const defaultCarcase = globalCarcaseColourHandle || carcaseColours[0]?.handle || null;\n    const inheritedFill  = findCatalogueFillForCategory(entry.category || 'base-units');\n    const cab = buildCornerPostVoidCabinet(entry, {\n      id: `cab-cpv-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 5)}`,\n      x: baseX, y: baseY\n    });\n    cab.kitchenStyleId      = styleId;\n    cab.doorColourHandle    = defaultDoor;\n    cab.carcaseColourHandle = defaultCarcase;\n    if (inheritedFill) cab.planner2D = { fillColour: inheritedFill };\n    cab.displayNumber = nextDisplayNumber();\n    cabinets.push(cab);\n    rerender();\n  }\n\n  // Set (or clear) the sink that sits on the worktop above a sink base.\n  function handleSetCabinetSink(cabinetId, sinkCode) {\n    const idx = cabinets.findIndex(c => c.id === cabinetId);\n    if (idx === -1) return;\n    const sinks = (getWorktopItemCatalogue().sinks) || [];\n    const sink  = sinkCode ? (sinks.find(s => s.code === sinkCode) || null) : null;\n    cabinets[idx] = { ...cabinets[idx], sink };\n    rerender();\n  }\n\n  // Choose Sink - picks a Planner Sink metaobject by handle and\n  // stores its handle on the cab. The 3D renderer reads\n  // cab.plannerSinkHandle and loads the corresponding GLB. Pass\n  // null/empty to clear (= \"None\" in the picker). Panel refresh\n  // explicit so the popup body re-renders with the new selection\n  // highlight (rerender alone only redraws the plan, not the\n  // sidebar).\n  // ---- Sink bowls over unit edges and appliances (Arden, 2026-11-02) ----\n  // Any sink goes on any sink base. Its bowls may run over the unit beside it -\n  // common in smaller kitchens: the fitter cuts both units' sides back so the\n  // bowl drops between them - and the Advisory says so (sinkStraddleWarnings).\n  // A bowl never sits over an appliance, and no part of a ceramic sink does.\n  // Spans are across the unit in cab-local mm from its centre, the frame of\n  // Move L/R (cab.plannerSinkXOffsetMm), the 2D plan and the worktop cut-out.\n  const SINK_EDGE_TOL_MM = 2;\n  function sinkMirrorSign(cab, sink) {\n    const nat = String((sink.drainerSide && sink.drainerSide[0]) || 'L').toUpperCase().startsWith('R') ? 'R' : 'L';\n    const ch = String(cab.plannerSinkDrainerSide || nat).toUpperCase();\n    return (sink.reversible && ch !== nat) ? -1 : 1;\n  }\n  // The sink's bowls as [from, to], the sink centred `offsetMm` along the unit.\n  function sinkBowlSpans(cab, sink, offsetMm) {\n    const sign = sinkMirrorSign(cab, sink);\n    const span = (w, at) => { const c = offsetMm + sign * (at || 0); return [c - w / 2, c + w / 2]; };\n    const out = [];\n    const main = sink.bowlWidthMm || sink.cutoutWidthMm || 0;\n    if (main > 0) out.push(span(main, sink.bowlOffsetXMm));\n    if (sink.halfBowlWidthMm > 0) out.push(span(sink.halfBowlWidthMm, sink.halfBowlOffsetXMm));\n    return out;\n  }\n  function isCeramicSink(sink) {\n    return /ceramic/i.test(String(sink.productTitle || sink.sinkName || ''));\n  }\n  // What has to keep off an appliance: the bowls, or all of a ceramic sink.\n  function sinkKeepOffSpans(cab, sink, offsetMm) {\n    if (!isCeramicSink(sink)) return sinkBowlSpans(cab, sink, offsetMm);\n    const w = sink.overallWidthMm || sink.cutoutWidthMm || 0;\n    return w > 0 ? [[offsetMm - w / 2, offsetMm + w / 2]] : [];\n  }\n  // Where a sink starts on a unit: its bowls centred over it when they fit,\n  // else its main bowl centred - the rest of the sink runs over the unit beside.\n  function sinkStartOffset(cab, sink) {\n    const spans = sinkBowlSpans(cab, sink, 0);\n    if (!spans.length) return 0;\n    const a = Math.min(...spans.map(s => s[0])), b = Math.max(...spans.map(s => s[1]));\n    // A corner Sink Unit (sales row 138): the bowls over its DOOR, the sink\n    // kept on the unit's own cabinet (never over the corner void) - on an\n    // L-shape, on the leg chosen in Make Sink Unit.\n    const door = sinkDoorCentre(cab);\n    if (door != null) {\n      const [lo, hi] = sinkRunRange(cab);\n      const sw = sink.overallWidthMm || sink.cutoutWidthMm || (b - a);\n      let at = door - (a + b) / 2;\n      if (sw >= hi - lo) return (lo + hi) / 2;\n      return Math.max(lo + sw / 2, Math.min(hi - sw / 2, at));\n    }\n    // A straight unit (sales row 153, Arden): the sink's own Start position\n    // (planner_sink start_offset_mm - its centre from the unit's centre,\n    // + towards the drainer), else the sink centred on the unit. Move left /\n    // Move right count from here.\n    return sinkDrainerDir(cab, sink) * (sink.startOffsetMm || 0);\n  }\n  // Which way the drainer lies along the unit, in cab-local x: +1 or -1. A\n  // sink's bowls are on one side of its centre (bowlOffsetXMm, in the sink's\n  // native frame) and its drainer on the other; mirrored with the drainer.\n  function sinkDrainerDir(cab, sink) {\n    const bo = sinkMirrorSign(cab, sink) * (sink.bowlOffsetXMm || 0);\n    return bo > 0 ? -1 : 1;\n  }\n  // An appliance under the worktop: a built-under freestanding one, or a base\n  // unit with an appliance in it (integrated dishwasher or washer door,\n  // built-under oven housing).\n  function isUnderWorktopApplianceCab(c) {\n    if (!c) return false;\n    if (c.freestandingAppliance) return c.freestandingAppliance.kind === 'built-under';\n    if (!/^base/i.test(c.category || '')) return false;\n    return !!(Catalogue.applianceSlotsOf && Catalogue.applianceSlotsOf(c.cutoutSchema).length);\n  }\n  // The appliances beside a sink unit, as { from, to, cab } across it: those\n  // in its run (overlapping its depth by 100mm or more).\n  function appliancesBesideSink(cab) {\n    const w = cab.widthMm || 0, d = cab.depthMm || 0;\n    const cx = cab.x + w / 2, cy = cab.y + d / 2;\n    const th = ((cab.rotationDeg || 0) * Math.PI) / 180, cs = Math.cos(th), sn = Math.sin(th);\n    const out = [];\n    for (const o of cabinets) {\n      if (!o || o.id === cab.id || !isUnderWorktopApplianceCab(o)) continue;\n      const ow = o.widthMm || 0, od = o.depthMm || 0;\n      const ocx = o.x + ow / 2, ocy = o.y + od / 2;\n      const oth = ((o.rotationDeg || 0) * Math.PI) / 180, ocs = Math.cos(oth), osn = Math.sin(oth);\n      let x0 = Infinity, x1 = -Infinity, y0 = Infinity, y1 = -Infinity;\n      for (const [lx, ly] of [[-ow / 2, -od / 2], [ow / 2, -od / 2], [ow / 2, od / 2], [-ow / 2, od / 2]]) {\n        const dx = ocx + lx * ocs - ly * osn - cx, dy = ocy + lx * osn + ly * ocs - cy;\n        const px = dx * cs + dy * sn, py = -dx * sn + dy * cs;\n        x0 = Math.min(x0, px); x1 = Math.max(x1, px); y0 = Math.min(y0, py); y1 = Math.max(y1, py);\n      }\n      if (Math.min(y1, d / 2) - Math.max(y0, -d / 2) < 100) continue;\n      out.push({ from: x0, to: x1, cab: o });\n    }\n    return out;\n  }\n  // The appliance a sink at `offsetMm` would sit over, or null.\n  function sinkOverAppliance(cab, sink, offsetMm, apps) {\n    for (const [a, b] of sinkKeepOffSpans(cab, sink, offsetMm)) {\n      const hit = apps.find(p => Math.min(b, p.to) - Math.max(a, p.from) > SINK_EDGE_TOL_MM);\n      if (hit) return hit.cab;\n    }\n    return null;\n  }\n  // The Move L/R offset nearest `want` that keeps the main bowl's centre over\n  // the unit and the sink off any appliance beside it; null when none does.\n  function sinkOffsetNearest(cab, sink, want) {\n    const [r0, r1] = sinkRunRange(cab);\n    const bo = sinkMirrorSign(cab, sink) * (sink.bowlOffsetXMm || 0);\n    const lo = Math.ceil(r0 - bo), hi = Math.floor(r1 - bo);\n    const t = Math.max(lo, Math.min(hi, Number.isFinite(want) ? want : 0));\n    // An L-shape's sink runs along one of its legs, not the unit's own run,\n    // so the appliances beside the unit are not beside the sink.\n    if (cab.lShapeUnit) return t;\n    const apps = appliancesBesideSink(cab);\n    if (!apps.length) return t;\n    for (let k = 0; k <= hi - lo; k++) {\n      for (const o of k ? [t - k, t + k] : [t]) {\n        if (o >= lo && o <= hi && !sinkOverAppliance(cab, sink, o, apps)) return o;\n      }\n    }\n    return null;\n  }\n  const SINK_OVER_APPLIANCE_TEXT = (sink) => isCeramicSink(sink)\n    ? 'No part of a ceramic sink can sit over an appliance.'\n    : 'A sink bowl can\\'t sit over an appliance.';\n  // For the sink picker: why this sink cannot go on this unit, or null.\n  function sinkApplianceBlock(cabinetId, sinkHandle) {\n    const cab = cabinets.find(c => c.id === cabinetId);\n    const sink = sinkHandle && Catalogue.getPlannerSink ? Catalogue.getPlannerSink(sinkHandle) : null;\n    if (!cab || !sink || cab.belfastSink) return null;\n    const probe = { ...cab, plannerSinkHandle: sinkHandle, plannerSinkDrainerSide: null };\n    if (sinkOffsetNearest(probe, sink, sinkStartOffset(probe, sink)) != null) return null;\n    return isCeramicSink(sink) ? 'Too wide here: it would sit over the appliance beside this unit'\n                               : 'A bowl would sit over the appliance beside this unit';\n  }\n  function alertSinkOverAppliance(cab, sink) {\n    const d = window.BTKKPDialog;\n    const msg = `${SINK_OVER_APPLIANCE_TEXT(sink)} Wherever this sink sits on unit #${cab.displayNumber ?? '?'}, it would be over the appliance beside it. Choose a smaller sink, or move the appliance.`;\n    if (d && typeof d.alert === 'function') d.alert(msg, { title: 'Sink over an appliance' });\n    else window.alert(msg);\n  }\n  // The Advisory: a sink's bowl running over the unit beside it (fine - says\n  // what the fitter does), or - a plan from before these rules, or an\n  // appliance moved up to it since - a bowl or ceramic sink over an appliance.\n  function sinkStraddleWarnings() {\n    const out = [];\n    for (const c of cabinets) {\n      if (!c || !c.sinkBase || c.belfastSink || !c.plannerSinkHandle || c.excludeFromQuote) continue;\n      const sink = Catalogue.getPlannerSink ? Catalogue.getPlannerSink(c.plannerSinkHandle) : null;\n      if (!sink) continue;\n      const off = (typeof c.plannerSinkXOffsetMm === 'number') ? c.plannerSinkXOffsetMm : 0;\n      const n = c.displayNumber ?? '?';\n      const over = sinkOverAppliance(c, sink, off, appliancesBesideSink(c));\n      if (over) {\n        out.push({ ruleId: 'sink-over-appliance', severity: 'warning', itemIds: [c.id, over.id],\n          // A freestanding appliance has no plan number.\n          message: `The sink on unit #${n} sits over ${over.displayNumber != null ? `the appliance at #${over.displayNumber}` : 'the appliance beside it'}. ${SINK_OVER_APPLIANCE_TEXT(sink)} ` +\n                   'Move the sink along the unit (Sink & Tap), choose another sink, or move the appliance.',\n          _signature: 'sink-over-appliance|' + c.id + '|' + over.id });\n        continue;\n      }\n      const w = c.widthMm || 0;\n      if (!sinkBowlSpans(c, sink, off).some(([a, b]) => a < -w / 2 - SINK_EDGE_TOL_MM || b > w / 2 + SINK_EDGE_TOL_MM)) continue;\n      out.push({ ruleId: 'sink-bowl-over-unit-edge', severity: 'warning', itemIds: [c.id],\n        message: `The sink on unit #${n} has a bowl over the edge of the unit beside it. This is a common layout, especially in smaller rooms, and nothing to worry about: ` +\n                 'the fitter cuts back the side panels of both units so the bowl drops down between them. Seal the cut edges before fitting so water can\\'t get into the board.',\n        _signature: 'sink-bowl-over-unit-edge|' + c.id + '|' + c.plannerSinkHandle });\n    }\n    return out;\n  }\n\n  function handleSetCabinetPlannerSink(cabinetId, sinkHandle) {\n    const idx = cabinets.findIndex(c => c.id === cabinetId);\n    if (idx === -1) return;\n    const handle = sinkHandle && Catalogue?.getPlannerSink?.(sinkHandle) ? sinkHandle : null;\n    // An undermount or Belfast sink under a faced laminate worktop: never.\n    const block = handle ? sinkWorktopBlock(Catalogue.plannerSinkMountInfo(Catalogue.getPlannerSink(handle)).fixed, false, cabinets[idx]) : null;\n    if (block) { alertFacedSink(block); return; }\n    const _taps = tapsOnCabinet(cabinetId).map(t => t.id);\n    const _changed = handle !== cabinets[idx].plannerSinkHandle;\n    // The same sink already in the basket: it moves onto the unit, so the\n    // basket does not end up with two (useSpareSink, below).\n    const _offered = spareSinkByCab.get(cabinetId);\n    const _spare = !handle || !_changed ? null\n      : (_offered && _offered.handle === handle) ? _offered\n      : spareSinks().find(s => s.handle === handle) || null;\n    // A newly fitted sink on a sink base starts on its own drainer side, with\n    // its bowls over the unit (sinkStartOffset), then as near there as keeps\n    // them - or any of a ceramic sink - off an appliance beside it. Nowhere\n    // does: it is not fitted, and says why (the picker greys it out first).\n    if (handle && _changed && !cabinets[idx].belfastSink) {\n      const _sk = Catalogue.getPlannerSink(handle);\n      const _cab = { ...cabinets[idx], plannerSinkHandle: handle, plannerSinkDrainerSide: null };\n      const _at = sinkOffsetNearest(_cab, _sk, sinkStartOffset(_cab, _sk));\n      if (_at == null) { alertSinkOverAppliance(_cab, _sk); return; }\n      cabinets[idx] = { ..._cab, plannerSinkXOffsetMm: _at };\n    } else {\n      cabinets[idx] = { ...cabinets[idx], plannerSinkHandle: handle };\n    }\n    if (_spare) useSpareSink(_spare);\n    const _bm = cabinets[idx].belfastSink && Catalogue.getBelfastSinkMarker\n      ? Catalogue.getBelfastSinkMarker(cabinets[idx].unitTypeId, cabinets[idx].widthMm) : null;\n    if (_bm) cabinets[idx] = { ...cabinets[idx], belfastSink: belfastNotchForSink(_bm, cabinets[idx]) };\n    reseatTapsOn(cabinetId, _taps);\n    // No tap is added with a sink: the tap is the customer's choice (tap \"+\").\n    rerender();\n    if (selectionPanelHandle && typeof selectionPanelHandle.refresh === 'function') {\n      selectionPanelHandle.refresh();\n    }\n  }\n\n  // A sink in the basket that no unit has: placed loose on the plan, or added\n  // with Add Other Items (Non Urgent row 27). A sink unit still without a sink\n  // is then offered it - a yellow + and a \"Fit your sink\" tile, opening Add\n  // Sinks & Taps with it on top - instead of being asked to choose another.\n  // A loose sink left out of the quote is being bought elsewhere: not offered.\n  function spareSinks() {\n    const ex = quoteExcludedLines || {};\n    const loose = (worktopItems || [])\n      .filter(it => it && it.kind === 'sink' && it.handle && Catalogue.getPlannerSink?.(it.handle) && !ex['q:wi:sink:' + it.id])\n      .map(it => ({ handle: it.handle, itemId: it.id, x: it.x + (it.widthMm || 0) / 2, y: it.y + (it.depthMm || 0) / 2 }));\n    return loose.concat(extraSinkLines);\n  }\n  // Each spare sink goes to one unit it can fit: a loose one to the nearest, an\n  // Add Other Items one to the lowest numbered. One sink, one yellow +.\n  function refreshSpareSinks() {\n    const offers = new Map();\n    if (!_bootOrdered) {\n      const empty = (cabinets || [])\n        .filter(c => c && (c.sinkBase || c.belfastSink) && !c.plannerSinkHandle)\n        .sort((a, b) => (a.displayNumber ?? 1e9) - (b.displayNumber ?? 1e9));\n      for (const spare of empty.length ? spareSinks() : []) {\n        const sink = Catalogue.getPlannerSink?.(spare.handle);\n        const free = empty.filter(c => !offers.has(c.id) && cabinetsHandle?.sinkFitsUnit?.(spare.handle, c)\n          && !sinkWorktopBlock(sink && Catalogue.plannerSinkMountInfo(sink).fixed, false, c) && !sinkApplianceBlock(c.id, spare.handle));\n        if (!free.length) continue;\n        const away = (c) => spare.x == null ? 0\n          : Math.hypot(c.x + (c.widthMm || 0) / 2 - spare.x, c.y + (c.depthMm || 0) / 2 - spare.y);\n        offers.set(free.reduce((best, c) => away(c) < away(best) ? c : best).id, spare);\n      }\n    }\n    spareSinkByCab = offers;\n  }\n  // Take a spare sink out of the basket as it goes on a unit. The caller rerenders.\n  function useSpareSink(spare) {\n    if (spare.itemId) {\n      worktopItems = worktopItems.filter(it => it.id !== spare.itemId);\n      if (selectedItem?.kind === 'worktop-item' && selectedItem.id === spare.itemId) selectItem(null);\n    } else {\n      extraSinkLines = extraSinkLines.filter(s => s !== spare);\n      removeExtraSinkLine(spare.lineId);\n    }\n  }\n  async function removeExtraSinkLine(lineId) {\n    const api = window.BTKBasketAPI;\n    if (!api) return;\n    try {\n      const project = await api.getProject();\n      const basket = await planBasketIn(project);\n      const section = basket && (basket.sections || []).find(s => s.name === 'Extras');\n      const line = section && (section.items || []).find(it => it.id === lineId);\n      if (!line) return;\n      if (line.quantity > 1) line.quantity -= 1;\n      else section.items = section.items.filter(it => it !== line);\n      api.recalculateLineNumbers(basket);\n      await api.saveBasket(basket);\n      await api.syncToShopifyCart(basket.id);\n      window.BTKCartAdvanced?.reload?.();\n    } catch (e) {\n      console.error('[BTK Kitchen Planner] removing the fitted sink line failed', e);\n    }\n  }\n  // The plan's Add Other Items lines that are sinks, one entry per sink. They\n  // live in the basket, so this runs when the plan opens, one is added, and the\n  // basket redraws (one removed there).\n  async function refreshExtraSinks() {\n    const api = window.BTKBasketAPI;\n    if (!api) return;\n    try {\n      const project = await api.getProject();\n      const basket = await planBasketIn(project);\n      const section = basket && (basket.sections || []).find(s => s.name === 'Extras');\n      const sinks = Catalogue.getPlannerSinks?.() || [];\n      const next = [];\n      for (const it of (section && section.items) || []) {\n        const a = it.attributes || {};\n        const sink = a.manualExtra && !a.freeGift && sinks.find(s => s.variantId && String(s.variantId) === String(it.shopifyVariantId));\n        if (sink) for (let q = 0; q < (it.quantity || 1); q++) next.push({ handle: sink.handle, lineId: it.id });\n      }\n      if (JSON.stringify(next) === JSON.stringify(extraSinkLines)) return;\n      extraSinkLines = next;\n      rerender();\n    } catch (e) {\n      console.error('[BTK Kitchen Planner] reading the basket sinks failed', e);\n    }\n  }\n  window.addEventListener('btk:basket-drawn', () => { refreshExtraSinks(); });\n\n  // Choose the appliance shown in an oven-housing aperture. `openingIndex`\n  // is the cutout-schema opening this appliance sits in (a housing can have\n  // several - oven + microwave). The choice is kept as a per-cabinet map\n  // (c.appliances[openingIndex] = product handle), which the 3D renderer\n  // reads to map the appliance's image onto that aperture; null clears it\n  // back to the auto-default. Persists with the plan (migrateCabinet keeps\n  // the map). See [[appliance-products]].\n  function handleSetCabinetAppliance(cabinetId, openingIndex, applianceHandle) {\n    const idx = cabinets.findIndex(c => c.id === cabinetId);\n    if (idx === -1) return;\n    const cab = cabinets[idx];\n    const appliances = { ...(cab.appliances || {}) };\n    // Just record the CHOICE - the plan item number is derived per-render in\n    // the sequential numbering pass (computeNumberingAndLayout), so it always\n    // reads unit 1 / oven 2 / unit 3 / oven 4 with no gaps or collisions.\n    const valid = applianceHandle && Catalogue?.getAppliance?.(applianceHandle) ? applianceHandle : null;\n    if (valid) appliances[openingIndex] = valid;\n    else       delete appliances[openingIndex];\n    // A single oven (not a compact) in a single-oven slot takes the whole slot:\n    // the warming drawer of a compact + drawer combo goes with it.\n    const _va = valid ? Catalogue.getAppliance(valid) : null;\n    if (Number.isInteger(Number(openingIndex)) && _va && Catalogue.isComboCompact\n        && !Catalogue.isComboCompact(_va) && !Catalogue.isWarmingDrawer(_va)) {\n      delete appliances[Number(openingIndex) + 0.5];\n    }\n    cabinets[idx] = { ...cab, appliances };\n    rerender();\n    if (selectionPanelHandle && typeof selectionPanelHandle.refresh === 'function') {\n      selectionPanelHandle.refresh();\n    }\n  }\n\n  // For the sink's Move left / Move right (sales row 153): how far the sink\n  // can really go each way from where it is now, in cab-local mm (plus = +x),\n  // and what stops it there - 'edge' (the main bowl's centre has to stay over\n  // the unit) or 'appliance' (no bowl over an appliance beside it). `centre`\n  // is Reset to centre: where a new sink starts (main bowl over the unit, or\n  // a corner unit's door), the nearest place it is allowed. `bowlAt` is the\n  // main bowl's centre from the unit's centre.\n  function sinkMoveInfo(cabinetId) {\n    const cab = cabinets.find(c => c.id === cabinetId);\n    const sink = cab && cab.plannerSinkHandle && !cab.belfastSink && Catalogue.getPlannerSink\n      ? Catalogue.getPlannerSink(cab.plannerSinkHandle) : null;\n    if (!sink) return null;\n    const cur = (typeof cab.plannerSinkXOffsetMm === 'number') ? cab.plannerSinkXOffsetMm : 0;\n    const [r0, r1] = sinkRunRange(cab);\n    const bo = sinkMirrorSign(cab, sink) * (sink.bowlOffsetXMm || 0);\n    const lo = Math.ceil(r0 - bo), hi = Math.floor(r1 - bo);\n    const ok = (o) => { const at = sinkOffsetNearest(cab, sink, o); return at != null && Math.abs(at - o) < 0.01; };\n    const reach = (dir) => {\n      let k = 0;\n      while (k < 3000 && ok(cur + dir * (k + 1))) k++;\n      const o = cur + dir * (k + 1);\n      return { mm: k, why: (o < lo || o > hi) ? 'edge' : 'appliance' };\n    };\n    const start = sinkStartOffset(cab, sink);\n    const centre = sinkOffsetNearest(cab, sink, start);\n    return {\n      plus: reach(1), minus: reach(-1),\n      // The sink's starting point - Move left / Move right measure from it.\n      start, cur,\n      centre: centre == null ? cur : centre,\n      bowlAt: cur + bo,\n      straight: !cab.cornerUnit && !cab.lShapeUnit,\n      oneBowl: !(sink.halfBowlWidthMm > 0),\n      applianceText: SINK_OVER_APPLIANCE_TEXT(sink)\n    };\n  }\n\n  // Move L/R offset for a Planner Sink on its host cab. Positive\n  // value shifts the sink RIGHT, negative shifts LEFT. Its bowls may run\n  // over the unit beside it (Arden, 2026-11-02 - the Advisory says so), but\n  // the main bowl's centre stays over this unit, and no bowl (no part of a\n  // ceramic sink) goes over an appliance: the nearest place that keeps them\n  // off it (sinkOffsetNearest). None does: the sink stays where it is.\n  function handleSetCabinetPlannerSinkOffset(cabinetId, offsetMm) {\n    const idx = cabinets.findIndex(c => c.id === cabinetId);\n    if (idx === -1) return;\n    const cab = cabinets[idx];\n    let next = (typeof offsetMm === 'number' && Number.isFinite(offsetMm)) ? offsetMm : 0;\n    const sink = cab.plannerSinkHandle ? Catalogue?.getPlannerSink?.(cab.plannerSinkHandle) : null;\n    if (sink && !cab.belfastSink) {\n      const at = sinkOffsetNearest(cab, sink, next);\n      next = at == null ? ((typeof cab.plannerSinkXOffsetMm === 'number') ? cab.plannerSinkXOffsetMm : 0) : at;\n    }\n    const _taps = tapsOnCabinet(cabinetId).map(t => t.id);\n    cabinets[idx] = { ...cab, plannerSinkXOffsetMm: next };\n    reseatTapsOn(cabinetId, _taps);\n    rerender();\n    if (selectionPanelHandle && typeof selectionPanelHandle.refresh === 'function') {\n      selectionPanelHandle.refresh();\n    }\n  }\n\n  // Drainer L/R override for a Planner Sink choice. Only meaningful\n  // when the chosen sink is `reversible: true`; the 3D renderer\n  // mirrors the GLB when the stored side differs from the sink's\n  // native authored side. null/empty clears the override (= use the\n  // sink's native drainer side).\n  // Each sink unit carries the fitting its sink has on this plan\n  // (cab.plannerSinkMount, see sinkMountFor) so the 3D draws it that way: an\n  // undermount sink under the worktop with the worktop cut to its bowls.\n  function syncSinkMounts() {\n    for (const c of (cabinets || [])) {\n      if (!c || !c.sinkBase) continue;\n      const sk = (c.plannerSinkHandle && Catalogue.getPlannerSink) ? Catalogue.getPlannerSink(c.plannerSinkHandle) : null;\n      const m = sk ? sinkMountFor(c, sk) : null;\n      if (m) c.plannerSinkMount = m; else delete c.plannerSinkMount;\n    }\n  }\n\n  // Inset / Undermount for an Inset or Undermount sink (the sink's panel,\n  // sales row 133). null goes back to the default (see sinkMountFor). An\n  // undermount is refused on a plan with a faced laminate worktop, which\n  // cannot be cut for one.\n  function handleSetCabinetPlannerSinkFitting(cabinetId, fitting) {\n    const idx = cabinets.findIndex(c => c.id === cabinetId);\n    if (idx === -1) return;\n    const v = (fitting === 'under-mount' || fitting === 'top-mount') ? fitting : null;\n    if (v === 'under-mount') {\n      const block = sinkWorktopBlock('under-mount', false, cabinets[idx]);\n      if (block) { window.BTKKPDialog.alert(block, { title: FACED_SINK_TITLE }); return; }\n    }\n    cabinets[idx] = { ...cabinets[idx], plannerSinkFitting: v };\n    rerender();\n    if (selectionPanelHandle && typeof selectionPanelHandle.refresh === 'function') {\n      selectionPanelHandle.refresh();\n    }\n  }\n\n  function handleSetCabinetPlannerSinkDrainer(cabinetId, side) {\n    const idx = cabinets.findIndex(c => c.id === cabinetId);\n    if (idx === -1) return;\n    const norm = (side || '').toString().toUpperCase();\n    const v = (norm === 'L' || norm === 'R') ? norm : null;\n    // The BOWL stays where it is and the drainer goes to the other side\n    // (Arden, 2026-10-24): the sink slides by the change in the bowl's\n    // offset. The offset handler then re-clamps and re-seats the tap.\n    const _eff = (c) => {\n      const sk = c.plannerSinkHandle ? Catalogue?.getPlannerSink?.(c.plannerSinkHandle) : null;\n      if (!sk) return 0;\n      const nat = String((sk.drainerSide && sk.drainerSide[0]) || 'L').toUpperCase().startsWith('R') ? 'R' : 'L';\n      const ch = String(c.plannerSinkDrainerSide || nat).toUpperCase();\n      return ((sk.reversible && ch !== nat) ? -1 : 1) * (sk.bowlOffsetXMm || 0);\n    };\n    const _before = _eff(cabinets[idx]);\n    cabinets[idx] = { ...cabinets[idx], plannerSinkDrainerSide: v };\n    const _shift = _before - _eff(cabinets[idx]);\n    handleSetCabinetPlannerSinkOffset(cabinetId, (cabinets[idx].plannerSinkXOffsetMm || 0) + _shift);\n    rerender();\n    if (selectionPanelHandle && typeof selectionPanelHandle.refresh === 'function') {\n      selectionPanelHandle.refresh();\n    }\n  }\n\n  function addRadiusUnit(entry) {\n    if (!entry) { console.warn('[BTK Kitchen Planner] No radius-unit entry'); return; }\n    const bbox = getBoundingBox(room);\n    // Wrap the per-cabinet stagger so the Nth unit always spawns\n    // somewhere near the middle of the plan. Linear growth runs new\n    // units off-screen after ~40 cabinets in a typical room.\n    const stagger = (cabinets.length % CABINET_STAGGER_WRAP) * CABINET_STAGGER_MM;\n    const baseX   = bbox.widthMm  / 2 - (entry.widthMm || 0) / 2 + stagger;\n    const baseY   = bbox.heightMm / 2 - (entry.depthMm || 0) / 2 + stagger;\n    const styleId = kitchenStyleId || null;\n    const groupId = entry.kind === 'island-base' ? null : genGroupId();\n    const baseSlug = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 5)}`;\n\n    // Default door + carcase colour for the new pieces - same flow as\n    // addCabinet: global picker \u2192 first-available for the style. Without\n    // these the placeholder falls back to DEFAULT_DOOR_HEX (BTK dark\n    // green), which is why a freshly-spawned radius unit was always\n    // rendering green regardless of the kitchen style.\n    const doorColours    = Catalogue.getDoorColoursForStyle(styleId)    || [];\n    const carcaseColours = Catalogue.getCarcaseColoursForStyle(styleId) || [];\n    const defaultDoor    = globalDoorColourHandle    || doorColours[0]?.handle    || null;\n    const defaultCarcase = globalCarcaseColourHandle || carcaseColours[0]?.handle || null;\n\n    // Inherit the plan-view fill colour (planner2D.fillColour) from\n    // a catalogue unit type IN THE SAME CATEGORY as the radius unit,\n    // so curved wall units take the wall-units blue fill and curved\n    // base units take the base-units green fill. Falls back to null\n    // (CSS default = white) if no match.\n    const inheritedFill = findCatalogueFillForCategory(entry.category);\n\n    const tagColours = (cab) => {\n      cab.kitchenStyleId    = styleId;\n      cab.doorColourHandle  = defaultDoor;\n      cab.carcaseColourHandle = defaultCarcase;\n      if (inheritedFill) {\n        cab.planner2D = { ...(cab.planner2D || {}), fillColour: inheritedFill };\n      }\n    };\n\n    // 1. The radius unit itself\n    const radius = buildRadiusUnitCabinet(entry, {\n      id: `cab-radius-${baseSlug}`,\n      x: baseX, y: baseY,\n      hand: 'right'\n    });\n    tagColours(radius);\n    radius.displayNumber  = nextDisplayNumber();\n    if (groupId) radius.groupId = groupId;\n    cabinets.push(radius);\n\n    // 2. Auto-spawn the backing pieces per kind. Layout (plan view,\n    // +y = back / wall direction):\n    //   end-base group \u2192 radius (300) | backing 260 turned 90\u00B0 | filler 10 @ wall  (total 570)\n    //   end-wall group \u2192 radius (300) | filler 30 @ wall                            (total 330)\n    //   island-base    \u2192 radius alone\n    //\n    // The backing's NATIVE size is 260 \u00D7 300 with rotationDeg = \u00B190, so\n    // its ROTATED visual bbox is 300 (along wall) \u00D7 260 (perp). For\n    // the rotated bbox to land at the right plan coords we offset\n    // cab.x by (depthMm - widthMm) / 2 = (300 - 260)/2 = +20 and\n    // cab.y by (widthMm - depthMm) / 2 = (260 - 300)/2 = -20 from\n    // the target visual top-left.\n    if (entry.kind === 'end-base') {\n      // Backing - 300 along wall, 260 perp, behind the radius unit\n      const BACK_VISUAL_Y0 = baseY + entry.depthMm;            // = baseY + 300\n      const BACK_VISUAL_W  = entry.widthMm;                    // = 300 (along wall)\n      const BACK_NATIVE_W  = 260;\n      const BACK_NATIVE_D  = entry.widthMm;                    // = 300 (native depth, becomes wall direction)\n      const backing = buildRadiusBacking(entry, {\n        id: `cab-radius-back-${baseSlug}`,\n        // Rotated bbox top-left = (baseX, BACK_VISUAL_Y0). For a 260W\u00D7300D\n        // cabinet rotated \u00B190, the unrotated div top-left sits offset:\n        x: baseX + (BACK_NATIVE_D - BACK_NATIVE_W) / 2,        // +20\n        y: BACK_VISUAL_Y0 - (BACK_NATIVE_D - BACK_NATIVE_W) / 2, // -20 from BACK_VISUAL_Y0\n        parentId: radius.id,\n        styleId,\n        hand: radius.radiusUnit.hand\n      });\n      tagColours(backing);\n      // Promote the backing to the real single-highline-base-unit (SHB)\n      // catalogue entry at 260W \u00D7 reduced-300D if it's wired up. This\n      // swaps the placeholder box for the real carcase GLB (with the\n      // toe-kick notch + door slab built in) and gives the cart line\n      // a real Shopify variantId. Stub stays if SHB isn't ready.\n      const shb = findSHBBackingForStyle(styleId);\n      if (shb) {\n        backing.unitTypeId = shb.unitType.id;\n        backing.variantId  = shb.variantInfo.variant?.id || shb.variantInfo.id || null;\n        backing.code       = shb.unitType.code || backing.code;\n        backing.name       = shb.unitType.title || backing.name;\n        backing.priceCents = shb.variantInfo.priceCents || 0;\n        // The variant's heightMm may differ from our stub default\n        // (we assumed 870 - carcase 720 + plinth 150). Trust the\n        // real variant so the cabinet aligns vertically with the\n        // rest of the kitchen.\n        if (shb.variantInfo.heightMm != null) backing.heightMm = shb.variantInfo.heightMm;\n      }\n      backing.displayNumber = nextDisplayNumber();\n      backing.groupId = groupId;\n      cabinets.push(backing);\n\n      // Filler - 10mm AGAINST THE WALL, behind the backing\n      const filler = buildRadiusFiller(entry, {\n        id: `cab-radius-fill-${baseSlug}`,\n        x: baseX,\n        y: BACK_VISUAL_Y0 + 260,                               // baseY + 300 + 260 = baseY + 560\n        depthMm: 10,\n        parentId: radius.id,\n        styleId\n      });\n      tagColours(filler);\n      filler.displayNumber = nextDisplayNumber();\n      filler.groupId = groupId;\n      cabinets.push(filler);\n    } else if (entry.kind === 'end-wall') {\n      // Wall end-of-run - radius + 30mm filler at wall (no backing)\n      const filler = buildRadiusFiller(entry, {\n        id: `cab-radius-wallfill-${baseSlug}`,\n        x: baseX,\n        y: baseY + entry.depthMm,\n        depthMm: 30,\n        parentId: radius.id,\n        styleId\n      });\n      tagColours(filler);\n      filler.displayNumber = nextDisplayNumber();\n      filler.groupId = groupId;\n      cabinets.push(filler);\n    }\n    // 'island-base' \u2192 no extras\n\n    rerender();\n  }\n\n  // ---- Auto-detect end-of-run companions for a placed curve --------------\n  // The single \"Curved Base Unit\" popup entry serves BOTH island and\n  // end-of-run: placed freestanding it's a plain curve; slid to the end of a\n  // run against a wall it grows the 260 backing + 10mm filler (grouped, each a\n  // real cart line, backing promoted to the real SHB). These run on every\n  // add/move so the set appears / disappears as the curve tracks the wall.\n\n  // Spawn the backing + filler for an already-placed curve. reAnchorRadiusGroup\n  // positions them relative to the curve's current position + rotation.\n  function spawnRadiusCompanions(curve) {\n    if (!curve || !curve.radiusUnit) return;\n    const styleId = curve.kitchenStyleId || kitchenStyleId || null;\n    const groupId = curve.groupId || genGroupId();\n    curve.groupId = groupId;\n    curve.radiusUnit = { ...curve.radiusUnit, kind: 'end-base' };\n    const hand  = curve.radiusUnit.hand === 'left' ? 'left' : 'right';\n    const entry = { kind: 'end-base', widthMm: 300, depthMm: 300, heightMm: curve.heightMm, category: 'base-units' };\n    const slug  = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 5)}`;\n    const copyColours = (cab) => {\n      cab.kitchenStyleId = styleId;\n      cab.doorColourHandle = curve.doorColourHandle;\n      cab.carcaseColourHandle = curve.carcaseColourHandle;\n      if (curve.planner2D?.fillColour) cab.planner2D = { ...(cab.planner2D || {}), fillColour: curve.planner2D.fillColour };\n    };\n    const backing = buildRadiusBacking(entry, { id: `cab-radius-back-${slug}`, x: 0, y: 0, parentId: curve.id, styleId, hand });\n    if (backing) {\n      copyColours(backing);\n      // Promote the stub box to the real single-highline-base (SHB) product.\n      const shb = findSHBBackingForStyle(styleId);\n      if (shb) {\n        backing.unitTypeId = shb.unitType.id;\n        backing.variantId  = shb.variantInfo.variant?.id || shb.variantInfo.id || null;\n        backing.code       = shb.unitType.code || backing.code;\n        backing.name       = shb.unitType.title || backing.name;\n        backing.priceCents = shb.variantInfo.priceCents || 0;\n        if (shb.variantInfo.heightMm != null) backing.heightMm = shb.variantInfo.heightMm;\n      }\n      backing.displayNumber = nextDisplayNumber();\n      backing.groupId = groupId;\n      cabinets.push(backing);\n    }\n    const filler = buildRadiusFiller(entry, { id: `cab-radius-fill-${slug}`, x: 0, y: 0, depthMm: RADIUS_FILLER_MM + radiusStepOf(curve), parentId: curve.id, styleId });\n    if (filler) {\n      copyColours(filler);\n      filler.displayNumber = nextDisplayNumber();\n      filler.groupId = groupId;\n      cabinets.push(filler);\n    }\n    reAnchorRadiusGroup(cabinets, curve);\n  }\n\n  // Spawn a wall curve's 30mm end-of-run filler (no backing). The wall unit\n  // keeps its 'end-wall' kind; only the filler appears/disappears with the\n  // wall-end test. reAnchorRadiusGroup positions the filler directly behind the\n  // curve (backingOffset 0 for wall).\n  function spawnRadiusWallCompanions(curve) {\n    if (!curve || !curve.radiusUnit) return;\n    // Step forward: seat the curve 30mm off the wall (assembly back flush) so\n    // its front lines up with the run, and the filler lands in the 30mm gap.\n    snapRadiusAssemblyBackToWall(curve);\n    const styleId = curve.kitchenStyleId || kitchenStyleId || null;\n    const groupId = curve.groupId || genGroupId();\n    curve.groupId = groupId;\n    // Filler = the back 30mm of the door on the deep (perpendicular) side flat,\n    // \"cut off\". A door slice standing 90\u00B0 TO THE WALL: 30mm along the door\n    // edge \u00D7 18mm board thickness. widthMm(30) is the along-edge length (drawn\n    // as the door face), depthMm(18) the thickness; reAnchorRadiusGroup rotates\n    // it 90\u00B0 so the door face runs along the side, not across the front.\n    const entry = { kind: 'end-wall', widthMm: 30, depthMm: 18, heightMm: curve.heightMm, category: 'wall-units' };\n    const slug  = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 5)}`;\n    const filler = buildRadiusFiller(entry, { id: `cab-radius-wallfill-${slug}`, x: 0, y: 0, depthMm: 18, parentId: curve.id, styleId });\n    if (filler) {\n      filler.kitchenStyleId      = styleId;\n      filler.doorColourHandle    = curve.doorColourHandle;\n      filler.carcaseColourHandle = curve.carcaseColourHandle;\n      if (curve.planner2D?.fillColour) filler.planner2D = { ...(filler.planner2D || {}), fillColour: curve.planner2D.fillColour };\n      // Mount at the curve's wall level (not the floor).\n      filler.wallMountLevel = curve.wallMountLevel;\n      filler.displayNumber  = nextDisplayNumber();\n      filler.groupId        = groupId;\n      cabinets.push(filler);\n    }\n    reAnchorRadiusGroup(cabinets, curve);\n  }\n\n  // A radius curve CARRIES its companions: the 260 backing, and the 30mm wall\n  // filler that fills the gap behind a curved wall unit. They are spawned by\n  // autoDetectRadiusCompanions, and are deliberately NOT selectable or\n  // draggable - the curve carries them (see the radiusGroup guards in\n  // btk-kitchen-planner-2d-cabinets.js). So deleting the curve on its own left\n  // the filler stuck against the wall with no way to move or delete it.\n  // Return the given ids PLUS every companion that hangs off them.\n  function withRadiusCompanions(ids) {\n    const out = new Set(ids);\n    for (const m of cabinets) {\n      if (m.radiusGroup && out.has(m.radiusGroup.parentId)) out.add(m.id);\n      // A walk-in larder's set goes with the larder (Sales sheet line 111).\n      if (m.walkInSet && out.has(m.walkInSet.hostId)) out.add(m.id);\n    }\n    // ...and a set unit never goes on its own.\n    for (const m of cabinets) {\n      if (m.walkInSet && out.has(m.id) && !out.has(m.walkInSet.hostId)\n          && cabinets.some(h => h.id === m.walkInSet.hostId)) out.delete(m.id);\n    }\n    return out;\n  }\n\n  // Sweep companions whose parent curve has gone. autoDetectRadiusCompanions\n  // only ever walks LIVE curves, so an orphan is never revisited - it would sit\n  // on the plan for ever. Runs on load too, so plans already carrying a\n  // stranded filler heal themselves when they are opened.\n  function pruneOrphanRadiusCompanions() {\n    const live = new Set(cabinets.map(c => c.id));\n    const drop = new Set();\n    for (const c of cabinets) {\n      if (c.radiusGroup && !live.has(c.radiusGroup.parentId)) drop.add(c.id);\n    }\n    if (!drop.size) return false;\n    cabinets = cabinets.filter(c => !drop.has(c.id));\n    selectedCabinetIds = new Set([...selectedCabinetIds].filter(id => !drop.has(id)));\n    return true;\n  }\n\n  // Strip a curve's companions. Base curve \u2192 back to 'island-base'; wall curve\n  // \u2192 stays 'end-wall' (it's always a wall end piece, only the filler toggles).\n  function removeRadiusCompanions(curve) {\n    if (!curve) return;\n    cabinets = cabinets.filter(c => !(c.radiusGroup && c.radiusGroup.parentId === curve.id));\n    const isWall = /^wall/i.test(curve.category || '');\n    curve.radiusUnit = { ...curve.radiusUnit, kind: isWall ? 'end-wall' : 'island-base' };\n    delete curve.groupId;\n    delete curve.radiusStepMm;\n  }\n\n  // End-of-run test: the ASSEMBLY back (curve + 260 backing + 10 filler behind\n  // the curve, in cab-local +Y) sits on a room wall. Uses the same wall-\n  // coincidence check as autoDetectBackPanels.\n  const RADIUS_ASSEMBLY_BACK_MM      = 260 + 10;   // base: backing + nominal filler behind the curve back\n  const RADIUS_WALL_ASSEMBLY_BACK_MM = 30;         // wall: just the 30mm filler (no backing)\n  // STEPPED OFF THE WALL (Arden, 2026-10-27): a base curve's whole set - curve,\n  // 260 backing and filler - steps forward together, and the filler behind the\n  // backing grows by the step to close the gap to the wall (one bigger filler,\n  // not an extra one). Held on the curve as radiusStepMm.\n  const RADIUS_FILLER_MM = 10;\n  function radiusStepOf(curve) {\n    return (curve && !/^wall/i.test(curve.category || '')) ? Math.max(0, Number(curve.radiusStepMm) || 0) : 0;\n  }\n  function radiusAssemblyBackMm(curve) {\n    return /^wall/i.test((curve && curve.category) || '') ? RADIUS_WALL_ASSEMBLY_BACK_MM\n      : RADIUS_ASSEMBLY_BACK_MM + radiusStepOf(curve);\n  }\n  function radiusEndOfRunWalled(curve) {\n    const walls = getWalls(room);\n    if (!walls || !walls.length) return false;\n    const W = curve.widthMm || 0, D = curve.depthMm || 0;\n    const rot = ((curve.rotationDeg || 0) % 360 + 360) % 360;\n    const th = rot * Math.PI / 180, cs = Math.cos(th), sn = Math.sin(th);\n    const cx = (curve.x || 0) + W / 2, cy = (curve.y || 0) + D / 2;\n    const L2W = (lx, ly) => ({ x: cx + (lx - W / 2) * cs - (ly - D / 2) * sn, y: cy + (lx - W / 2) * sn + (ly - D / 2) * cs });\n    const backExtMm = radiusAssemblyBackMm(curve);\n    const backLy = D + backExtMm;                 // assembly back edge in cab-local +Y\n    const line = { p1: L2W(0, backLy), p2: L2W(W, backLy) };\n    for (const wl of walls) {\n      if (epLinesCoincide(line, { p1: wl.from, p2: wl.to }, 60)) return true;\n    }\n    return false;\n  }\n\n  // Step-forward snap: pull the curve so its ASSEMBLY back edge (curve +\n  // companion depth) sits EXACTLY on the coincident wall, instead of relying on\n  // the 60mm detection tolerance. This seats the curve `backExtMm` off the wall\n  // so its FRONT lines up with the run. Same assembly-back geometry as\n  // radiusEndOfRunWalled; no-op when no wall coincides.\n  function snapRadiusAssemblyBackToWall(curve) {\n    if (!curve) return;\n    const walls = getWalls(room);\n    if (!walls || !walls.length) return;\n    const W = curve.widthMm || 0, D = curve.depthMm || 0;\n    const rot = ((curve.rotationDeg || 0) % 360 + 360) % 360;\n    const th = rot * Math.PI / 180, cs = Math.cos(th), sn = Math.sin(th);\n    const cx = (curve.x || 0) + W / 2, cy = (curve.y || 0) + D / 2;\n    const L2W = (lx, ly) => ({ x: cx + (lx - W / 2) * cs - (ly - D / 2) * sn, y: cy + (lx - W / 2) * sn + (ly - D / 2) * cs });\n    const backExtMm = radiusAssemblyBackMm(curve);\n    const backLy = D + backExtMm;\n    const p1 = L2W(0, backLy), p2 = L2W(W, backLy);\n    const M  = { x: (p1.x + p2.x) / 2, y: (p1.y + p2.y) / 2 };\n    for (const wl of walls) {\n      if (!epLinesCoincide({ p1, p2 }, { p1: wl.from, p2: wl.to }, 60)) continue;\n      const wx = wl.to.x - wl.from.x, wy = wl.to.y - wl.from.y;\n      const wlen = Math.hypot(wx, wy) || 1;\n      const nx = -wy / wlen, ny = wx / wlen;                          // wall normal\n      const off = (M.x - wl.from.x) * nx + (M.y - wl.from.y) * ny;    // signed dist of assembly back from wall\n      curve.x -= off * nx;                                           // pull the assembly back flush onto the wall\n      curve.y -= off * ny;\n      return;\n    }\n  }\n\n  // Sweep every placed curve: grow the end-of-run set when it's walled,\n  // dissolve it back to an island when it isn't. Returns true if anything\n  // changed (so callers know to re-number / re-render).\n  function autoDetectRadiusCompanions() {\n    let changed = pruneOrphanRadiusCompanions();\n    const curves = cabinets.filter(c => c.radiusUnit && /^(base|wall)/i.test(c.category || ''));\n    for (const curve of curves) {\n      const isWall  = /^wall/i.test(curve.category || '');\n      const walled  = radiusEndOfRunWalled(curve);\n      const hasComp = cabinets.some(c => c.radiusGroup && c.radiusGroup.parentId === curve.id);\n      if (walled && !hasComp) {\n        (isWall ? spawnRadiusWallCompanions : spawnRadiusCompanions)(curve);\n        changed = true;\n      } else if (!walled && hasComp) {\n        removeRadiusCompanions(curve);\n        changed = true;\n      }\n    }\n    return changed;\n  }\n\n  // Phase 5 catalogue swap - promote the radius-unit BACKING from\n  // the stub `B260-HL` to the real `single-highline-base-unit` (SHB)\n  // catalogue entry at the 260W \u00D7 reduced-300D variant. With this\n  // promotion the backing renders via the GLB path (real carcase\n  // with toe-kick notch + separate door slab) instead of the plain\n  // box placeholder, gets a real priceCents, and carries a real\n  // Shopify variantId for the cart line.\n  //\n  // First catalogue unit type whose categoryHandle matches the given\n  // category prefix AND that carries a NON-DEFAULT planner2D.fillColour.\n  // Used by addRadiusUnit to inherit the right tinted plan fill for\n  // the radius stub (wall radius \u2192 wall blue, base radius \u2192 base\n  // green). Skips white-ish defaults (catalogue fallback) so we don't\n  // pick up a unit that hasn't had a real fill assigned and leave the\n  // radius rendering white. Falls back to a hardcoded category tint\n  // if no non-default catalogue entry can be found.\n  function findCatalogueFillForCategory(categoryHandle) {\n    const HARDCODED_FALLBACK = {\n      base:     '#d4efdf',   // base/tall: light green\n      tall:     '#d4efdf',\n      wall:     '#cfe2f3',   // wall: light blue\n      bridging: '#fcf3cf'    // bridging: light yellow\n    };\n    const isDefaultish = (hex) => {\n      const s = String(hex || '').replace('#', '').toLowerCase();\n      if (s === 'fff' || s === 'ffffff' || s === 'ffffffff') return true;\n      // Also treat catalogue's literal default (white) as no-fill so\n      // we fall through to the next candidate or the hardcoded tint.\n      return false;\n    };\n    if (!categoryHandle) return null;\n    const target = String(categoryHandle).toLowerCase();\n    const prefix = target.split('-')[0];\n    if (Catalogue && typeof Catalogue.getUnitTypes === 'function') {\n      const all = Catalogue.getUnitTypes();\n      const pickFill = (u) =>\n        u && u.planner2D && u.planner2D.fillColour && !isDefaultish(u.planner2D.fillColour)\n          ? u.planner2D.fillColour : null;\n      const exact = all.find(u => (u.categoryHandle || '').toLowerCase() === target && pickFill(u));\n      if (exact) return pickFill(exact);\n      const partial = all.find(u => (u.categoryHandle || '').toLowerCase().startsWith(prefix) && pickFill(u));\n      if (partial) return pickFill(partial);\n    }\n    return HARDCODED_FALLBACK[prefix] || null;\n  }\n\n  // Tolerant of the catalogue layout: tries the conventional id,\n  // then falls back to a name/code scan. Returns null if SHB or its\n  // 260\u00D7300 variant isn't ready in the catalogue (e.g. the metaobject\n  // hasn't been wired up yet) - caller leaves the stub in place.\n  function findSHBBackingForStyle(styleId) {\n    if (!Catalogue || typeof Catalogue.getUnitTypes !== 'function') return null;\n    let ut = Catalogue.getUnitType('single-highline-base-unit');\n    if (!ut) {\n      const all = Catalogue.getUnitTypes();\n      ut = all.find(u =>\n        /^shb$/i.test(u.code || '') ||\n        /single.*highline.*base/i.test(u.title || '') ||\n        /single.*highline.*base/i.test(u.id || '')\n      ) || null;\n    }\n    if (!ut) return null;\n    const info = Catalogue.findVariant({\n      unitTypeId: ut.id,\n      kitchenStyleId: styleId,\n      widthMm: 260,\n      depthMm: 300\n    });\n    if (!info) return null;\n    return { unitType: ut, variantInfo: info };\n  }\n\n  // Decide hand based on what sits to the left / right of the radius\n  // assembly. Hand=right means the curve faces RIGHT (so adjacent\n  // cabinet sits on the LEFT side); hand=left is the mirror.\n  //\n  // Uses the assembly's COMBINED bbox (radius unit + backing + filler\n  // if they share a groupId) rather than just the radius unit's own\n  // bbox - the backing's depth (260mm) reaches further into the wall\n  // direction than the radius unit (300mm), so any same-row run\n  // cabinet may abut the BACKING rather than the radius unit itself.\n  // Tolerance is generous (50mm) so a \"close enough\" drop registers\n  // without requiring a perfectly flush snap.\n  // Also answers for splay / open angled ends (see splayEndDesiredHand),\n  // which read the same neighbour test the other way round.\n  function radiusUnitDesiredHand(cab, allCabs) {\n    if (!cab.radiusUnit && !angledEndHand(cab)) return null;\n    const TOL = 50;\n    // Combined visual bbox of every cabinet in this radius unit's\n    // group. visualBbox is rotation-aware so the bbox matches what\n    // the user sees on the plan (rotated members report the right\n    // footprint).\n    const selfVb = visualBbox(cab);\n    let x0 = selfVb.x0, x1 = selfVb.x1, y0 = selfVb.y0, y1 = selfVb.y1;\n    if (cab.groupId) {\n      for (const m of allCabs) {\n        if (m.groupId !== cab.groupId) continue;\n        const vb = visualBbox(m);\n        x0 = Math.min(x0, vb.x0);\n        y0 = Math.min(y0, vb.y0);\n        x1 = Math.max(x1, vb.x1);\n        y1 = Math.max(y1, vb.y1);\n      }\n    }\n    // Hand is expressed in the radius unit's UNROTATED frame\n    // (hand='right' \u2192 curve at unrot front-RIGHT corner). When the\n    // assembly is rotated to face a wall, the visual \"run\" sides\n    // (where neighbour cabinets abut) are NOT always the visual\n    // left/right - they depend on rotation:\n    //\n    //   rot=0    (back faces +y, wall C): runLeft = visual LEFT\n    //   rot=90   (back faces -x, wall B): runLeft = visual TOP\n    //   rot=180  (back faces -y, wall A): runLeft = visual RIGHT\n    //   rot=270  (back faces +x, wall D): runLeft = visual BOTTOM\n    //\n    // For each rotation, neighbour on \"run-LEFT\" \u2192 hand='right'\n    // (curve on opposite unrot side); neighbour on \"run-RIGHT\" \u2192\n    // hand='left'. We check the appropriate visual axis (x for\n    // horizontal rotations, y for vertical), then map the detected\n    // visual side back to RUN-LEFT / RUN-RIGHT.\n    const rot = (((cab.rotationDeg || 0) % 360) + 360) % 360;\n    // Auto-hand only handles axis-aligned rotations - on an angled-\n    // wall snap the visual-left/right/top/bottom axes don't align\n    // with the run, so we leave the hand alone and let the user pick.\n    const offAxis = Math.min(rot % 90, 90 - (rot % 90));\n    if (offAxis > 1) return null;\n    let horizontalRun, runLeftSide;\n    if (rot === 0)        { horizontalRun = true;  runLeftSide = 'visualLeft';   }\n    else if (rot === 90)  { horizontalRun = false; runLeftSide = 'visualTop';    }\n    else if (rot === 180) { horizontalRun = true;  runLeftSide = 'visualRight';  }\n    else                  { horizontalRun = false; runLeftSide = 'visualBottom'; }\n    let runLeft = false, runRight = false;\n    let runLeftGap = Infinity, runRightGap = Infinity;\n    const noteSide = (isRunLeftHit, gap) => {\n      if (isRunLeftHit) { runLeft  = true; runLeftGap  = Math.min(runLeftGap,  gap); }\n      else              { runRight = true; runRightGap = Math.min(runRightGap, gap); }\n    };\n    for (const o of allCabs) {\n      if (o.id === cab.id) continue;\n      if (o.groupId && cab.groupId && o.groupId === cab.groupId) continue;\n      const ovb = visualBbox(o);\n      if (horizontalRun) {\n        if (ovb.y1 <= y0 || ovb.y0 >= y1) continue;     // no overlap on perpendicular axis\n        const gapVL = Math.abs(ovb.x1 - x0);            // neighbour to our visual LEFT\n        const gapVR = Math.abs(ovb.x0 - x1);            // neighbour to our visual RIGHT\n        if (gapVL <= TOL) noteSide(runLeftSide === 'visualLeft',  gapVL);\n        if (gapVR <= TOL) noteSide(runLeftSide === 'visualRight', gapVR);\n      } else {\n        if (ovb.x1 <= x0 || ovb.x0 >= x1) continue;\n        const gapVT = Math.abs(ovb.y1 - y0);            // neighbour to our visual TOP\n        const gapVB = Math.abs(ovb.y0 - y1);            // neighbour to our visual BOTTOM\n        if (gapVT <= TOL) noteSide(runLeftSide === 'visualTop',    gapVT);\n        if (gapVB <= TOL) noteSide(runLeftSide === 'visualBottom', gapVB);\n      }\n    }\n    // Diagnostic - surfaces why the hand auto-flip did / didn't fire.\n    // The user can grep '[BTK radius hand]' in the browser console.\n    console.log('[BTK radius hand]', {\n      cabId: cab.id, kind: cab.radiusUnit ? cab.radiusUnit.kind : 'splay', currentHand: cab.radiusUnit ? cab.radiusUnit.hand : angledEndHand(cab),\n      rot, horizontalRun, runLeftSide,\n      groupBbox: { x0, x1, y0, y1 },\n      runLeft, runRight, runLeftGap, runRightGap\n    });\n    if (runLeft  && !runRight) return 'right';\n    if (runRight && !runLeft)  return 'left';\n    return null;\n  }\n\n  // ---- Cabinets ----\n\n\n\nfunction addCabinet(def, opts = {}) {\n  if (!def) { console.warn('[BTK Kitchen Planner] No cabinet definition'); return; }\n\n    // Default colour selection: prefer the global pick from the Add\n    // Units panel; if not set, fall back to first-available for the\n    // kitchen style.\n    const doorColours    = Catalogue.getDoorColoursForStyle(def.kitchenStyleId)    || [];\n    // Per UNIT, not per style: a unit sold in only some carcase colours (the\n    // Larder Pantry is Davenport Oak only) must not take the kitchen-wide\n    // colour just because the rest of the plan is in it.\n    const carcaseColours = Catalogue.getCarcaseColoursForUnit(def.unitTypeId, def.kitchenStyleId) || [];\n    const defaultDoor    = globalDoorColourHandle    || doorColours[0]?.handle    || null;\n    // Accessories flagged `no_carcase_colour` (end panels, fillers) carry NO\n    // carcase colour - the selection-panel picker is hidden and 3D paints\n    // them the door colour.\n    const _noCarcaseColour = !!Catalogue.getUnitType?.(def.unitTypeId)?.noCarcaseColour;\n    const _globalAllowed = carcaseColours.some(c => c.handle === globalCarcaseColourHandle);\n    const defaultCarcase = _noCarcaseColour\n      ? null\n      : ((_globalAllowed ? globalCarcaseColourHandle : null) || carcaseColours[0]?.handle || null);\n\n    const bbox = getBoundingBox(room);\n    // Wraps so the Nth cabinet's offset doesn't drift off-screen \u2014\n    // see CABINET_STAGGER_WRAP. Mirrors addRadiusUnit's spawn logic.\n    const stagger = (cabinets.length % CABINET_STAGGER_WRAP) * CABINET_STAGGER_MM;\n    // Wall units default to the mount line matching their own height\n    // variant (Low/Med/High \u2192 1975/2120/2300mm tops). User can change\n    // it later via the selection panel.\n    let defaultMountLevel;\n    // Bridging + top box units are in the wall-units CATEGORY, so the\n    // height rule below read their 290-495mm carcase as a Low wall unit and\n    // hung them from the Low line. Catch them first: Medium, then their top\n    // is matched to the wall unit they first land against (see\n    // alignBridgingTops).\n    const _isBridging = isBridgingDef(def);\n    const _defaultSink = def.plannerSinkHandle || defaultSinkFor(def, (h) => typeof sinkWorktopBlock !== 'function'\n      || !sinkWorktopBlock(Catalogue.plannerSinkMountInfo(Catalogue.getPlannerSink(h)).fixed, false));\n    // Worktop dressers stand on the worktop rather than hang from a line;\n    // their Height (Low / Medium / High) is made for that line.\n    const _isDresser = !!def.dresserUnit;\n    // Behaviour category, so a WALL appliance housing (mixed\n    // appliance-housings category \u2192 resolves to wall-units) also mounts\n    // at wall level rather than sitting on the floor.\n    if (_isDresser) {\n      defaultMountLevel = worktopDresserLevel(def.carcaseHeightMm);\n    } else if (_isBridging) {\n      defaultMountLevel = 'medium';\n    } else if (def.extractorHousing) {\n      // The Integrated Extractor door is 495 tall, which the height rule\n      // reads as a Low wall unit - it hangs from Medium (Arden, 2026-10-12).\n      defaultMountLevel = 'medium';\n    } else if (def.category === 'wall-units') {\n      const h = def.carcaseHeightMm;\n      defaultMountLevel = h <= 600 ? 'low' : (h >= 800 ? 'high' : 'medium');\n    } else if (def.category === 'bridging-units') {\n      // Bridging units bridge above an appliance; default their top to the\n      // medium wall-unit mount line (matching the retired stub). The user\n      // can retune it via the selection panel's mount-line picker.\n      defaultMountLevel = 'medium';\n    }\n    // Bedroom top boxes are wall units: their top lines up with the\n    // wardrobe tops (High line, default top anchor).\n    const _isTopBox = def.categoryHandle === 'top-boxes';\n    if (_isTopBox) defaultMountLevel = 'high';\n\n    // Corner unit (blank-panel type): the variant width is the\n    // CABINET width; the plan footprint adds a reserved corner void.\n    // Build the cornerUnit descriptor and override the footprint\n    // width so dimensions / snapping / collision use the full plan\n    // dimension. depthMm stays the carcase depth (~570mm).\n    let cornerUnit = null;\n    let footprintWidthMm = def.widthMm;\n    // End panels have no size variant - default a thin footprint (panel\n    // thickness along the run) and the base panel depth, so they place +\n    // render. The face + true size come from the style's panel GLB.\n    const _epUt = Catalogue.getUnitType?.(def.unitTypeId);\n    // Free-placeable PANEL products: the end-panels group (base / island / tall /\n    // wall / breakfast-bar, plain + T&G) and the filler-panels group. Both place\n    // as a plain board and are charged through the CUT LIST, not as a unit line.\n    const isEndPanelDef = _epUt?.unitTypeGroupHandle === 'end-panels'\n                       || _epUt?.unitTypeGroupHandle === 'filler-panels';\n    let endPanelDepthMm = def.depthMm;\n    if (_epUt?.unitTypeGroupHandle === 'filler-panels') {\n      // A filler faces forward: its face width (the unit type's 147 / 150)\n      // runs along the line, door-thick front to back.\n      footprintWidthMm = _epUt.defaultDepthMm || 147;\n      endPanelDepthMm  = FILLER_PANEL_THICK_MM;\n    }\n    if (isEndPanelDef) {\n      // A breakfast bar back panel's size comes through as its LENGTH (1200,\n      // 2100) - read as the width it placed as a 1200 x 570 box, like a unit\n      // (Arden, 2026-10-20). A board is never that thick: the length is its\n      // run, the same front-to-back axis an end panel's depth is on.\n      if (_epUt?.unitTypeGroupHandle === 'end-panels' && footprintWidthMm > EP_UNIT_MAX_THICK_MM) {\n        endPanelDepthMm = _epUt.defaultDepthMm || footprintWidthMm;\n        footprintWidthMm = 18;\n      }\n      if (!footprintWidthMm) footprintWidthMm = 18;    // thickness along the run\n      // Default front-to-back depth in open space comes from the unit_type\n      // (`default_depth_mm`) - data-driven, no per-code hardcode. Once\n      // butted against a cabinet the resize rule adopts the host's depth.\n      if (!endPanelDepthMm) endPanelDepthMm = _epUt?.defaultDepthMm || 650;\n    }\n    if (isCornerBlankShape(def.planner2D?.shape)) {\n      const cabinetMm = def.widthMm || CORNER_BLANK_DEFAULTS.cabinetMm;\n      // Door width comes from the variant (\"<cab> Cab / <door> Door\").\n      // Fall back to a derived value only if it wasn't carried.\n      const doorMm = def.doorMm ||\n        Math.min(CORNER_BLANK_DEFAULTS.doorMm,\n          Math.max(200, cabinetMm - CORNER_BLANK_DEFAULTS.postXMm - CORNER_MIN_BLANK_MM));\n      cornerUnit = normaliseCornerUnit({\n        // The hand the picked \"Blank Panel\" side implies - this was a fixed\n        // 'left', so every unit arrived as a Right Panel whatever was chosen.\n        type: 'blankPanel', hand: def.cornerHand || 'left',\n        cabinetMm, doorMm,\n        postXMm: CORNER_BLANK_DEFAULTS.postXMm,\n        postYMm: CORNER_BLANK_DEFAULTS.postYMm,\n        // Void reach = the perpendicular run's depth. WALL corner blanks reach\n        // only the shallow wall depth (~330), not the base 570 - prefer the\n        // unit's own depth, else the category default. Without this the wall\n        // void inherited the base 570 \u2192 a ~310mm void.\n        reachMm: def.depthMm || (def.category === 'wall-units' ? CORNER_POST_REACH_WALL_MM : CORNER_POST_REACH_MM)\n      });\n      // Footprint = fixed cabinet width + void (void grows with the post).\n      footprintWidthMm = cornerUnit.cabinetMm + cornerUnit.voidMm;\n      // ...and the carcase DEPTH is that same reach. A corner wall unit sells\n      // Width + Blank Panel + Height, which is Shopify's three-option ceiling,\n      // so the export drops Depth - see _shopify_option_values, where a corner\n      // WITH a height axis emits the blank-panel side in the slot depth would\n      // have had. The variant therefore carries no depth, buildCabinetDefinition\n      // has nothing to fall back on for a unit type with no default width, and\n      // the cab was created with depthMm NULL: the 3D scaled the carcase to zero\n      // depth and all that remained was the 18mm door slab and the 40mm post\n      // return, which reads as a unit about 30mm deep. reachMm is already the\n      // right number - 330 on a wall corner, 570 on a base one.\n      if (!endPanelDepthMm) endPanelDepthMm = cornerUnit.reachMm;\n    }\n\n    // Diagonal corner base unit (pentagon footprint, single 45\u00B0 door).\n    // The real metaobject carries shape 'diagonal' (trailing-space tolerated)\n    // - attach the diagonalCornerUnit marker so 2D / 3D / worktop / placement\n    // switch to the pentagon + diagonal-door geometry and the 3D renderer\n    // routes to buildDiagonalCornerUnitGLB. Standard 910\u00D7910 outer bbox with\n    // a 570mm arm (mirrors the stub geometry); hand resolves on placement.\n    let diagonalCornerUnit = null;\n    // WALL corner units are shallower than base corners: a wall L-shape /\n    // diagonal is a 630\u00D7630 outer footprint with 330mm arms (the standard wall\n    // depth), NOT the base 910\u00D7910 / 570mm. The marker feeds the 2D outline,\n    // placement, worktop cutout AND the arm-end panel size, so a base-sized\n    // marker on a wall corner made every one of those base-sized - most\n    // visibly the end panels (570mm arm instead of 330 \u2192 huge overhang).\n    const isWallCorner = def.category === 'wall-units';\n    if (String(def.planner2D?.shape || '').trim().toLowerCase() === 'diagonal') {\n      // Footprint from the REAL unit_type/variant dims - was hardcoded 910\u00D7910\n      // (the standard diagonal corner BASE). That mis-sized larger diagonals\n      // like the 1013\u00D71013 Diagonal Corner Larder: the cab read 910 while its\n      // GLB rendered at 1013, so the door face (computed from W/arm) landed on\n      // the wrong plane \u2192 narrow door, exposed carcase, gap. Arm depth is the\n      // base's 570mm / wall's 330mm; the cutout derives from the real width.\n      // Wall diagonal = 630 outer (matches the L-shape wall): with a 330 arm the\n      // cutout is 300, so the 45\u00B0 door face is 300\u00B7\u221A2 \u2248 424mm - fits the 396mm\n      // wall door with an even ~14mm reveal each side.\n      const DIAG_W   = def.widthMm || (isWallCorner ? 630 : 910);\n      // A diagonal corner footprint is ALWAYS SQUARE (910\u00D7910 base, 1013\u00D71013\n      // larder, 630\u00D7630 wall), so the outer depth equals the width - NOT the\n      // variant's Depth option. That option is the ARM/carcase depth (base 570,\n      // wall 330), carried by armDepthMm below; feeding it in here rendered the\n      // base as a 910\u00D7570 box. See [[corner-units-glb-builders]].\n      const DIAG_D   = DIAG_W;\n      const DIAG_ARM = isWallCorner ? 330 : 570;\n      diagonalCornerUnit = {\n        armDepthMm: DIAG_ARM,\n        cutoutMm:   DIAG_W - DIAG_ARM,        // inner corner offset\n        wtCutoutMm: DIAG_W - DIAG_ARM - 30,   // worktop cutout (30mm door overhang)\n        hand:       'NE'\n      };\n      footprintWidthMm = DIAG_W;\n      endPanelDepthMm  = DIAG_D;              // outer bbox depth (reuses the depth var below)\n    }\n\n    // L-shape corner base unit (L footprint, two perpendicular doors). Real\n    // metaobject shape 'lshape' \u2192 attach the lShapeUnit marker so 2D / 3D /\n    // worktop / placement use the L geometry and the 3D renderer routes to\n    // buildLShapeUnitGLB. Standard 910\u00D7910 outer bbox with 570mm arms.\n    let lShapeUnit = null;\n    if (String(def.planner2D?.shape || '').trim().toLowerCase() === 'lshape') {\n      // Base 910\u00D7910 / 570mm arm; WALL 630\u00D7630 / 330mm arm.\n      const LS_W   = isWallCorner ? 630 : 910;\n      const LS_ARM = isWallCorner ? 330 : 570;\n      lShapeUnit = {\n        armDepthMm: LS_ARM,\n        cutoutMm:   LS_W - LS_ARM,            // base 340 / wall 300\n        wtCutoutMm: LS_W - LS_ARM - 30,       // base 310 / wall 270\n        hand:       'NE'\n      };\n      footprintWidthMm = LS_W;\n      endPanelDepthMm  = LS_W;\n    }\n\n    // Curved / radius corner unit (quarter-circle front wrapped by one door\n    // leaf). Attach the radiusUnit marker so 2D / 3D / worktop / plinth /\n    // placement switch to the curved geometry (buildRadiusPlaceholder,\n    // buildRadiusPlinths, worktop arc). Two real-product shapes:\n    //   'radius-island' (base-units)  \u2192 kind 'island-base' (worktop, plinth,\n    //                                    end-of-run backing+filler auto-detect)\n    //   'radius-wall'   (wall-units)  \u2192 kind 'end-wall' (no legs / plinth /\n    //                                    worktop - category-gated everywhere;\n    //                                    curved cornice/pelmet; 30mm wall filler)\n    // Both share the SAME geometry: fixed 200mm radius \u2192 100mm flat tangents on\n    // a 300\u00D7300 unit (flat = size \u2212 radius), one bent openable door leaf,\n    // standardised across door styles.\n    let radiusUnit = null;\n    const _radiusShape = String(def.planner2D?.shape || '').trim().toLowerCase();\n    if (_radiusShape === 'radius-island' || _radiusShape === 'radius-wall') {\n      const RAD = 200;\n      // Real curved units come as left/right PAIRS - separate products whose\n      // codes end in -L / -R. The suffix names WHICH END OF THE RUN the unit\n      // caps (user convention): -L caps the LEFT end, -R the RIGHT end. That's\n      // the INVERSE of the planner's body-frame `hand` (which names the curve\n      // corner): at a back-to-wall run a right-end cap (-R) shows its curve on\n      // the world right, which is the local-front-LEFT corner \u2192 hand 'left'.\n      // So -L \u2192 hand 'right', -R \u2192 hand 'left'. Legacy no-suffix units default\n      // to 'right'. Adjacency still flips it + swaps product (swapRadiusHandProduct).\n      //\n      // Real codes write that suffix WITHOUT a dash and with a trailing\n      // carcase letter - CV30LB / CV30RB (base), CV30LW / CV30RW (wall) - so\n      // the old /-L$/ /-R$/ pair matched none of them and every curved unit\n      // fell through to 'right'. CV30LB looked correct by luck (a left-end\n      // cap IS hand 'right'); CV30RB and CV30RW curved the wrong way.\n      // [BW]? keeps CV30OPB (open, no hand) out: its B follows a P.\n      const codeHand = /-?L[BW]?$/i.test(def.code || '') ? 'right'\n                     : /-?R[BW]?$/i.test(def.code || '') ? 'left'\n                     : 'right';\n      radiusUnit = {\n        kind:            _radiusShape === 'radius-wall' ? 'end-wall' : 'island-base',\n        hand:            codeHand,\n        carcaseRadiusMm: RAD,\n        doorRadiusMm:    RAD\n      };\n      footprintWidthMm = def.widthMm || 300;\n      endPanelDepthMm  = def.depthMm || 300;\n    }\n\n    const __newCabId = `cabinet-${nextCabinetId++}`;\n    cabinets.push({\n      id: __newCabId,\n      displayNumber: nextDisplayNumber(),\n      type: 'cabinet',\n      // New-world identifiers - used for variant lookup, cart adding, pricing\n      unitTypeId:     def.unitTypeId,\n      variantId:      def.variantId,\n      kitchenStyleId: def.kitchenStyleId,\n      // Legacy fields - kept for CSS classes, save format, and basket.\n      // category is the BEHAVIOUR category (base/tall/wall) so every\n      // plinth/cornice/worktop/end-panel/collision gate treats mixed\n      // appliance housings correctly; categoryHandle keeps the literal.\n      code:     def.code,\n      category: def.category || def.categoryHandle,\n      // Plan-view 2D appearance from the unit type's metaobject \u2014\n      // planner2D.fillColour paints the plan rectangle / corner carcase.\n      planner2D: def.planner2D,\n      wallMountLevel: defaultMountLevel,\n      // Bridging: still waiting to take its top from a wall unit it lands\n      // against. Cleared once it has, or when the user picks a mount line.\n      ...(_isBridging ? { alignTopPending: true } : {}),\n      // Position + dimensions\n      x: bbox.widthMm  / 2 - footprintWidthMm / 2 + stagger,\n      y: bbox.heightMm / 2 - endPanelDepthMm / 2 + stagger,\n      widthMm:  footprintWidthMm,\n      depthMm:  endPanelDepthMm,\n      // Belfast sink units sit at standard worktop level (standard base\n      // carcase 720 + plinth) - the lowered 500mm carcase + sink gap is\n      // carried on the belfastSink marker, not the cab height.\n      heightMm: def.belfastSink\n        ? (720 + (def.plinthHeightMm || 150))\n        : (def.carcaseHeightMm || 720) + (def.plinthHeightMm || 0),\n      rotationDeg: 0,\n      // Pricing snapshot (in case the variant is later unavailable)\n      priceCents: def.priceCents,\n      compareAtCents: (typeof def.compareAtCents === 'number') ? def.compareAtCents : null,\n      // Hinge state (only meaningful for hinge-selectable cabinets)\n      hingeSelectable: def.hingeSelectable,\n      hingeSide:       def.hingeSide,\n      drawerCount:     def.drawerCount || 0,\n      // Front-face cutout schema (parsed JSON from the unit-type\n      // metaobject). 2D + 3D renderers read this to split a double-\n      // door (or any side-by-side multi-front) unit into the right\n      // number of front panels. A snapshot is kept on the cabinet so\n      // re-render after a style switch / variant change doesn't need\n      // a catalogue lookup; migrateCabinet refreshes it from the\n      // live catalogue each load.\n      cutoutSchema:    def.cutoutSchema || null,\n      // Belfast sink marker (lowered carcase + sink notch) - null for\n      // every non-Belfast unit. Drives buildBelfastSinkPlaceholder, the\n      // worktop U-notch, and the required-end-panel rule.\n      belfastSink:     def.belfastSink ? belfastNotchForSink(def.belfastSink, { plannerSinkHandle: _defaultSink, widthMm: def.widthMm }) : null,\n      // The sink the unit type loads with (unit_type default_sinks) - the\n      // customer can change it or pick None in Choose Sink.\n      plannerSinkHandle: _defaultSink,\n      // Where it starts along the unit (sinkStartOffset).\n      plannerSinkXOffsetMm: (_defaultSink && def.sinkBase && !def.belfastSink && Catalogue.getPlannerSink(_defaultSink))\n        ? sinkStartOffset({ widthMm: def.widthMm }, Catalogue.getPlannerSink(_defaultSink)) : 0,\n      // Sink-base marker - propagates the unit_type sink_base boolean\n      // (or the stub catalogue's marker) onto the cab so the\n      // selection panel shows the Choose Sink button + the 3D\n      // renderer knows to mount a sink GLB on the worktop above.\n      sinkBase:        def.sinkBase || null,\n      // Appliances fitted into this unit's apertures, keyed by OPENING INDEX\n      // ({ 0: 'cda-sl550bl-\u2026' }). The Add Appliances -> Choose Housing flow\n      // hands addCabinet a definition with these already set, but this object\n      // is built field by field and never copied them - so the housing landed\n      // EMPTY. Everything downstream keys off cab.appliances: the numbering\n      // pass gives each chosen appliance its own line (unit 1, oven 2, unit\n      // 3\u2026), the 2D badge, and the basket line. All of it was silently lost\n      // at the moment of adding.\n      appliances:      def.appliances ? { ...def.appliances } : null,\n      // Midi marker - unit_type is_midi_unit boolean. Midi units live in the\n      // tall category but are worktop-topped (no cornice); drives isMidiUnit()\n      // in the trim + worktop engines. Refreshed from catalogue in migrateCabinet.\n      isMidiUnit:      def.isMidiUnit || false,\n      // Worktop dresser (Larder Dresser Units) - stands on the worktop\n      // against the wall; engine-stack derives its resting height from the\n      // unit under it + the worktop thickness. Refreshed in migrateCabinet.\n      dresserUnit:     _isDresser,\n      // A door-style mirror starts on the worktop of the unit under it, a\n      // headboard at a height of its own (both from the unit type's schema).\n      ...(def.cutoutSchema && def.cutoutSchema.mountAnchor === 'worktop' ? { mountAnchor: 'worktop', onSince: Date.now() } : {}),\n      ...(def.cutoutSchema && def.cutoutSchema.mountBottomMm > 0 ? { mountAnchor: 'set', mountBottomMm: def.cutoutSchema.mountBottomMm } : {}),\n      // Stacking (base + midi units) - 'base' / 'midi' means this unit sits\n      // on top of a unit of that kind sharing its footprint; null = floor-\n      // standing. stackTrim overrides what the unit is finished with\n      // (plinth / worktop / cornice); null = the defaults in engine-stack.\n      // The anchor height itself is DERIVED per render by syncStackAnchors.\n      stackOn:         null,\n      stackTrim:       null,\n      // A unit type whose default plinth is None (the Media Base Units) starts\n      // floating - no plinth or legs - at its plinth height; its Plinth popup\n      // changes both (engine-stack isFloatingUnit).\n      ...(_epUt?.defaultPlinth === 'none' ? { plinthType: 'none' } : {}),\n      // True Handleless HANDED marker - unit_type true_handleless_handed boolean.\n      // When set, the selection panel shows a Rail-side toggle (rail is always\n      // OPPOSITE the hinge) and the line stamps handing so the Odoo import picks\n      // the correct LH/RH product. Refreshed from catalogue in migrateCabinet.\n      trueHandlelessHanded: def.trueHandlelessHanded || false,\n      // End-panel marker - a free-standing end panel picked from the End\n      // Panels category. Drives the door-material red fill in the 2D plan\n      // and the door-colour panel render in 3D.\n      endPanelUnit:    isEndPanelDef || null,\n      // A filler panel starts on the plinth line, the piece it is cut from\n      // kept as its size cap (the Tall Filler's length differs by range) -\n      // and no taller than the room, so a 3m Tall Filler starts at ceiling\n      // height rather than through it.\n      ...(_epUt?.unitTypeGroupHandle === 'filler-panels' ? (() => {\n        const stockH = (def.carcaseHeightMm || 720) + (def.plinthHeightMm || 0);\n        return { fillerFacing: true, heightOffGroundMm: FILLER_PANEL_PLINTH_MM,\n                 heightMm: Math.max(10, Math.min(stockH, roomCeilingMm() - FILLER_PANEL_PLINTH_MM)),\n                 fillerStock: { widthMm: footprintWidthMm, heightMm: stockH } };\n      })() : {}),\n      // Splay end marker (trapezoid geometry) - null for non-splay units.\n      // Drives the angled footprint in 2D / 3D / worktop.\n      splayEnd:        def.splayEnd || null,\n      // Diagonal corner marker (pentagon footprint + single 45\u00B0 door) \u2014\n      // null for non-diagonal units. Drives the 2D pentagon clip-path,\n      // buildDiagonalCornerUnitGLB in 3D, and the worktop cutout.\n      diagonalCornerUnit: diagonalCornerUnit || null,\n      // L-shape corner marker (L footprint + two perpendicular doors) \u2014\n      // null for non-L-shape units. Drives the 2D L clip-path,\n      // buildLShapeUnitGLB in 3D, and the worktop cutout.\n      lShapeUnit:         lShapeUnit || null,\n      // Radius / curved corner marker - null for non-curved units. Drives the\n      // 2D curved clip-path, buildRadiusPlaceholder in 3D, the curved plinth,\n      // the concentric worktop arc, and radius-aware placement / grouping.\n      radiusUnit:         radiusUnit || null,\n      // Colour state - handles into the catalogue. Defaults resolved above.\n      doorColourHandle:    defaultDoor,\n      carcaseColourHandle: defaultCarcase,\n      // End panels - visible side panels finishing the carcase. The\n      // user toggles each side via the selection panel; when active,\n      // sub-options appear (style, inline, pelmet extension).\n      //   active     : on/off\n      //   style      : 'flat' | 'tng'         (T&G) - picks the product\n      //   inline     : base/tall only - raises panel bottom by 150mm\n      //                so the plinth can run THROUGH the unit\n      //   pelmetExt  : wall only - extends panel bottom past the wall\n      //                unit so the pelmet meets it:\n      //                  'none'    = stops at unit bottom\n      //                  'modern'  = extends 32mm past, pelmet stops\n      //                              at the panel face\n      //                  'tangent' = extends 60mm past, fits a ~57mm\n      //                              tangent pelmet running into it\n      endPanels: {\n        left:  { active: false, style: 'flat', inline: false, pelmetExt: 'modern' },\n        right: { active: false, style: 'flat', inline: false, pelmetExt: 'modern' }\n      },\n      // Per-end-panel colour overrides. null = inherit cabinet's\n      // door colour. A master-door-colour handle = paint that panel\n      // in the chosen colour. Set via the End Panel selection panel.\n      endPanelColours: { left: null, right: null },\n      // Fillers - door-material strips between the carcase and the\n      // wall. 1\u2013100mm wide. Mutually exclusive with the end panel\n      // on the same side (auto-detect activates exactly one or\n      // neither). Inherits door colour + style.\n      fillers: {\n        left:  { active: false, widthMm: 20, setBackMm: 0 },\n        right: { active: false, widthMm: 20, setBackMm: 0 }\n      },\n      // Worktop per-unit extension (mm) - pushes this unit's slice of\n      // the run worktop out. left/right 0-1000, front/back 0-300.\n      worktop: { left: 0, right: 0, front: 0, back: 0 },\n      // Step-forward from wall (mm, 0-300). Base + tall only. When\n      // set, the cab is rendered offset forward from its anchor by\n      // this many mm; the gap left behind (= the void) is shown as\n      // a mid-grey hatched fill. Wall-snap + push-out treat the cab\n      // + void together as one footprint, so the back of the void\n      // lands flush against the wall.\n      wallSetbackMm: 0,\n      // Corner unit descriptor (blank-panel type). Present only for\n      // corner units; null/absent for normal rectangular cabinets.\n      ...(cornerUnit ? { cornerUnit } : {})\n    });\n    // From the plan's continue-the-run +: land beside the unit it belongs to\n    // BEFORE the end-panel walk and the render, so the walk settles the pair\n    // and the add is one undo step, not a drop in the middle and then a move.\n    // A walk-in larder set adds several units and places them itself.\n    if (opts && opts.quiet) return __newCabId;\n    const runAnchor = opts && opts.runAnchor;\n    if (runAnchor) placeContinuingRun(cabinets[cabinets.length - 1], runAnchor);\n    // Treat the newly-added cab as \"moved\" so it can claim a setback\n    // filler against any base/wall neighbour within 100mm - same path\n    // as a freshly-dropped cab from a drag. The run's end unit goes in too:\n    // its panel on that side is the one that has to come off.\n    if (runAnchor) {\n      // The drag-drop sequence: join the run, decide the panels, then settle\n      // on the EFFECTIVE faces. Without the settles, a tall unit that keeps\n      // its panel against a base (tall wins) stayed carcase to carcase, its\n      // panel sat inside the base's end, and the worktop still ran to where\n      // the base's own panel had been.\n      settleCabinet(__newCabId, false);\n      alignBridgingTops([__newCabId]);\n      autoDetectEndPanels([__newCabId, runAnchor.cabId]);\n      autoDetectBackPanels();\n      settleCabinet(__newCabId, true);\n    } else {\n      autoDetectEndPanels([__newCabId]);\n      autoDetectBackPanels();\n    }\n    resizeFillers();\n    rerender();\n    // The new unit becomes the selection, so its own + is there to carry on.\n    if (runAnchor) selectItem({ kind: 'cabinet', id: __newCabId });\n    return __newCabId;   // let callers (e.g. the convert tray) tweak the new cab\n  }\n\n  // ---- Island Designer: place a designed island ---------------------------\n  // spec (btk-kitchen-planner-ui-island-designer.js islandPlacement): the\n  // island's units in plan mm (x right, y down, back at the top), each with\n  // its centre, turn, unit type and size, and the depth a 570 is cut to on\n  // site. It lands in the middle of the room as ONE GROUP of ordinary units,\n  // each still editable. The planner's own end panel / back panel rules fit\n  // the panels; the island's end style then goes on every end panel it has,\n  // and the worktop is pushed out to the designed overhangs.\n  // ROOM BESIDE A FREE STANDING APPLIANCE (Arden, 2026-11-19). The unit next\n  // to one takes its own end panel, and the appliance stands its fitting gap\n  // off that panel; at the island's end its own panel stands the gap off it.\n  // Placed touching, the panel stood inside the appliance and the planner\n  // later pushed the appliance out, so the rows no longer lined up and the\n  // back panel split. The front row opens up by the panel and gap there; a\n  // back row behind takes the same as a filler between its units (the side\n  // there is hidden, so no end panel), so both rows still end together.\n  function islandApplianceRoom(spec, styleId) {\n    const isFsa = (u) => /^FSA-/.test(u.unitTypeId || '');\n    const flat = (u) => Math.round((((u.rotationDeg || 0) % 180) + 180) % 180) !== 90;\n    const front = spec.units.filter(u => u.run === 'front' && flat(u)).sort((a, b) => a.cx - b.cx);\n    if (!front.some(isFsa)) return spec;\n    const ks = Catalogue.getKitchenStyle ? Catalogue.getKitchenStyle(styleId) : null;\n    const epSet = ks && ((ks.doorGeometry && ks.doorGeometry.endPanel) || ks.endPanel);\n    const T = (epSet && typeof epSet.thicknessMm === 'number' && epSet.thicknessMm > 0) ? epSet.thicknessMm : 20;\n    const G = FSA_END_PANEL_GAP_MM;\n    const lo = (u) => u.cx - u.widthMm / 2, hi = (u) => u.cx + u.widthMm / 2;\n    const rooms = [];\n    for (let i = 0; i < front.length; i++) {\n      const a = front[i], b = front[i + 1];\n      if (i === 0 && isFsa(a)) rooms.push({ x: lo(a), mm: G });\n      if (b && Math.abs(hi(a) - lo(b)) < 2 && isFsa(a) !== isFsa(b)) rooms.push({ x: hi(a), mm: G + T });\n      if (!b && isFsa(a)) rooms.push({ x: hi(a), mm: G, end: true });\n    }\n    const units = spec.units.map(u => ({ ...u, x0: lo(u) }));\n    const fr = units.filter(u => u.run === 'front' && flat(u));\n    const backs = units.filter(u => /^back/.test(u.run || '') && flat(u)).sort((a, b) => a.cx - b.cx);\n    const joints = [];\n    for (let i = 0; i + 1 < backs.length; i++) if (Math.abs(hi(backs[i]) - lo(backs[i + 1])) < 2) joints.push({ i, x: hi(backs[i]), mm: 0 });\n    for (const rm of rooms) {\n      // Everything in the front row from there on moves along by it.\n      if (!rm.end) for (const u of fr) if (u.x0 >= rm.x - 1) u.cx += rm.mm;\n      // The back row opens at its joint nearest it, so its ends still line up.\n      if (joints.length) joints.reduce((p, q) => (Math.abs(q.x - rm.x) < Math.abs(p.x - rm.x) ? q : p)).mm += rm.mm;\n    }\n    for (const j of joints) {\n      if (!j.mm) continue;\n      for (const u of backs) if (u.x0 >= j.x - 1) u.cx += j.mm;\n      const a = backs[j.i], b = backs[j.i + 1];\n      // A back unit faces up the plan (turned 0): its left (+x) is the drawing's right.\n      const side = Math.cos(((a.rotationDeg || 0) * Math.PI) / 180) > 0 ? 'left' : 'right';\n      a.roomFiller = { side, mm: j.mm };\n      const bs = side === 'left' ? 'right' : 'left';\n      b.offEnds = [...new Set([...(b.offEnds || []), bs])];\n      a.offEnds = [...new Set([...(a.offEnds || []), side])];\n    }\n    for (const u of units) delete u.x0;\n    // At the island's far end the appliance's panel gap leaves the front row\n    // that much longer: the back row's last joint takes it (above, end rooms\n    // only open the back row).\n    const add = rooms.reduce((t, rm) => t + rm.mm, 0);\n    const wt = spec.worktop && { ...spec.worktop, x1: spec.worktop.x1 + add };\n    return { ...spec, units, worktop: wt, widthMm: (spec.widthMm || 0) + add };\n  }\n\n  function addIsland(spec) {\n    if (!spec || !Array.isArray(spec.units) || !spec.units.length || _bootOrdered) return false;\n    const styleId = kitchenStyleId || null;\n    const defs = spec.units.map(u => {\n      // A free standing appliance: product-less, as Add Appliances places it.\n      if (/^FSA-/.test(u.unitTypeId || '')) return planApplianceCab(Catalogue.getFreestandingAppliance?.(u.unitTypeId.slice(4)), {});\n      const info = u.unitTypeId && Catalogue.findVariant({ unitTypeId: u.unitTypeId, kitchenStyleId: styleId, widthMm: u.widthMm, depthMm: u.productDepthMm });\n      return info ? Catalogue.buildCabinetDefinition({ unitTypeId: u.unitTypeId, variantId: info.variant.id, kitchenStyleId: styleId }) : null;\n    });\n    if (defs.some(d => !d)) {\n      if (!_islandDry) designControlsHandle.setStatus('Some of these units are not available in this bedroom range.');\n      return false;\n    }\n    spec = islandApplianceRoom(spec, styleId);\n    const bbox = getBoundingBox(room);\n    let target = { x: bbox.widthMm / 2, y: bbox.heightMm / 2 };\n    let turnBy = 0;\n    if (spec.replaceGroupId) {\n      const old = cabinets.filter(c => c.groupId === spec.replaceGroupId);\n      if (old.length) {\n        let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;\n        for (const m of old) { const vb = visualBbox(m); x0 = Math.min(x0, vb.x0); x1 = Math.max(x1, vb.x1); y0 = Math.min(y0, vb.y0); y1 = Math.max(y1, vb.y1); }\n        target = { x: (x0 + x1) / 2, y: (y0 + y1) / 2 };\n        const front = old.find(c => c.islandRun === 'front');\n        if (front) turnBy = ((((front.rotationDeg || 0) - 180) % 360) + 360) % 360;\n        const gone = new Set(old.map(c => c.id));\n        cabinets = cabinets.filter(c => !gone.has(c.id));\n        selectedCabinetIds = new Set([...selectedCabinetIds].filter(id => !gone.has(id)));\n      }\n    } else {\n      // A new island goes in the nearest clear space to the middle of the\n      // room: dropped on top of units already there (another island added\n      // the same way), the end and back panel walks saw neighbours on every\n      // side and took the island's panels off.\n      target = freeIslandSpot(spec, target, bbox);\n    }\n    // The units' own footprint, centred on the target.\n    let ux0 = Infinity, uy0 = Infinity, ux1 = -Infinity, uy1 = -Infinity;\n    for (const u of spec.units) {\n      const turned = Math.round((((u.rotationDeg || 0) % 180) + 180) % 180) === 90;\n      const w = turned ? u.depthMm : u.widthMm, d = turned ? u.widthMm : u.depthMm;\n      ux0 = Math.min(ux0, u.cx - w / 2); ux1 = Math.max(ux1, u.cx + w / 2);\n      uy0 = Math.min(uy0, u.cy - d / 2); uy1 = Math.max(uy1, u.cy + d / 2);\n    }\n    const ox = Math.round(target.x - (ux0 + ux1) / 2);\n    const oy = Math.round(target.y - (uy0 + uy1) / 2);\n    const gid = genGroupId();\n    const ids = [];\n    const pose = new Map();          // id -> where the design puts it\n    spec.units.forEach((u, i) => {\n      const fsa = !!defs[i].freestandingAppliance;\n      if (fsa) cabinets.push(defs[i]);\n      const id = fsa ? defs[i].id : addCabinet(defs[i], { quiet: true });\n      const cab = cabinets.find(c => c.id === id);\n      if (!cab) return;\n      if (fsa && u.depthMm) {\n        // Its back in line with the units' backs, standing proud at the front.\n        const e = (cab.depthMm - u.depthMm) / 2, th = ((u.rotationDeg || 0) * Math.PI) / 180;\n        u = { ...u, cx: u.cx + Math.sin(th) * e, cy: u.cy - Math.cos(th) * e, depthMm: null };\n      }\n      if (u.depthMm && u.depthMm < cab.depthMm) {\n        cab.siteCut = { productDepthMm: cab.depthMm };\n        cab.depthMm = u.depthMm;\n        cab.customFit = { ignoreClash: false, notes: u.cutNote || '' };\n      }\n      cab.x = Math.round(ox + u.cx - cab.widthMm / 2);\n      cab.y = Math.round(oy + u.cy - cab.depthMm / 2);\n      cab.rotationDeg = u.rotationDeg || 0;\n      cab.groupId = gid;\n      cab.islandRun = u.run;\n      if (/^seat/.test(u.run || '')) cab.cushionTop = true;\n      if (spec.design) cab.islandDesign = spec.design;\n      if (u.hinge && cab.hingeSelectable && (u.hinge === 'left' || u.hinge === 'right')) cab.hingeSide = u.hinge;\n      ids.push(id);\n      pose.set(id, { x: cab.x, y: cab.y, rotationDeg: cab.rotationDeg });\n    });\n    // Each unit back where the design put it, after a pass that settles units\n    // against their neighbours; and the island's outer ends panelled, a\n    // pastry bench's back standing against that panel.\n    const holdIsland = () => {\n      cabinets = cabinets.map(c => pose.has(c.id) ? { ...c, ...pose.get(c.id) } : c);\n      const mine = cabinets.filter(c => pose.has(c.id) && !isPastrySet(c) && carriesWorktop(c)\n        && Math.abs(Math.cos(((c.rotationDeg || 0) * Math.PI) / 180)) > 0.5);\n      if (!mine.length) return;\n      const box = (c) => { const t = Math.round((((c.rotationDeg || 0) % 180) + 180) % 180) === 90;\n        const w = t ? c.depthMm : c.widthMm, cx = c.x + c.widthMm / 2; return { x0: cx - w / 2, x1: cx + w / 2 }; };\n      const minX = Math.min(...mine.map(c => box(c).x0)), maxX = Math.max(...mine.map(c => box(c).x1));\n      cabinets = cabinets.map(c => {\n        if (!mine.includes(c)) return c;\n        const b = box(c), th = ((c.rotationDeg || 0) * Math.PI) / 180;\n        const lx = Math.cos(th);                         // local +x (its left) along world x\n        const sides = [];\n        const tol = c.freestandingAppliance ? FSA_END_PANEL_GAP_MM + 1 : 1;\n        if (b.x0 <= minX + tol) sides.push(lx < -0.5 ? 'left' : 'right');   // world left end\n        if (b.x1 >= maxX - tol) sides.push(lx > 0.5 ? 'left' : 'right');    // world right end\n        if (!sides.length || Math.abs(lx) < 0.5) return c;\n        const ep = { ...(c.endPanels || {}) };\n        for (const sd of sides) if (ep[sd] && !ep[sd].active) ep[sd] = { ...ep[sd], active: true };\n        return { ...c, endPanels: ep };\n      });\n    };\n    syncStackAnchors();\n    autoDetectEndPanels(ids);\n    holdIsland();\n    autoDetectBackPanels();\n    const style = spec.endStyle || 'flat';\n    const idSet = new Set(ids);\n    // The end the pastry bench stands at: its panels are pinned (pastryEnd).\n    const pastryCab = cabinets.find(c => idSet.has(c.id) && isPastrySet(c));\n    const rounded = style === 'radius' || style === 'square';\n    const wbox = (c) => { const t = Math.round((((c.rotationDeg || 0) % 180) + 180) % 180) === 90;\n      const w = t ? c.depthMm : c.widthMm, cx = c.x + c.widthMm / 2; return { x0: cx - w / 2, x1: cx + w / 2 }; };\n    const runUnits = cabinets.filter(c => idSet.has(c.id) && !isPastrySet(c) && carriesWorktop(c)\n      && Math.abs(Math.cos(((c.rotationDeg || 0) * Math.PI) / 180)) > 0.5);\n    // A dog-leg arm (units along y): its far end is an outer end too.\n    const armUnits = cabinets.filter(c => idSet.has(c.id) && /^arm/.test(c.islandRun || ''));\n    const yb = (c) => { const t = Math.round((((c.rotationDeg || 0) % 180) + 180) % 180) === 90;\n      const d = t ? c.widthMm : c.depthMm, cy = c.y + c.depthMm / 2; return { y0: cy - d / 2, y1: cy + d / 2 }; };\n    const aMinY = armUnits.length ? Math.min(...armUnits.map(c => yb(c).y0)) : null;\n    const gMinX = Math.min(...runUnits.map(c => wbox(c).x0)), gMaxX = Math.max(...runUnits.map(c => wbox(c).x1));\n    const outerSide = (c, side) => {\n      const lx = Math.cos(((c.rotationDeg || 0) * Math.PI) / 180) * (side === 'left' ? 1 : -1);\n      if (/^arm/.test(c.islandRun || '') && aMinY != null) {\n        const ly = Math.sin(((c.rotationDeg || 0) * Math.PI) / 180) * (side === 'left' ? 1 : -1);\n        return ly < -0.5 && yb(c).y0 <= aMinY + 1;\n      }\n      const b = wbox(c);\n      const tol = c.freestandingAppliance ? FSA_END_PANEL_GAP_MM + 1 : 1;\n      return lx < -0.5 ? b.x0 <= gMinX + tol : lx > 0.5 ? b.x1 >= gMaxX - tol : false;\n    };\n    cabinets = cabinets.map(c => {\n      if (!idSet.has(c.id) || isPastrySet(c)) return c;\n      const ep = c.endPanels || {};\n      const next = { ...ep };\n      for (const side of ['left', 'right']) {\n        if (!(ep[side] && ep[side].active)) continue;\n        const { wtSquare, ...rest } = ep[side];\n        const outer = outerSide(c, side);\n        let atPastry = false;\n        if (pastryCab && outer) {\n          const lx = Math.cos(((c.rotationDeg || 0) * Math.PI) / 180) * (side === 'left' ? 1 : -1);\n          const pcx = pastryCab.x + pastryCab.widthMm / 2;\n          atPastry = lx < -0.5 ? pcx < gMinX : lx > 0.5 ? pcx > gMaxX : false;\n        }\n        // T&G on a Square End or Radius End Feature's flat board.\n        const tng = rounded ? { tng: !!spec.endTng } : {};\n        next[side] = { ...rest, style, ...tng, ...(rounded && !outer ? { wtSquare: true } : {}), ...(atPastry ? { pastryEnd: true } : {}) };\n      }\n      return { ...c, endPanels: next };\n    });\n    autoDetectBackPanels();\n    // The void behind a row with a back panel (a breakfast bar, a deeper\n    // island): the back panel steps off the units by it, as the Breakfast Bar\n    // Back Panel popup's step off does, and the end panels and worktop follow.\n    // Less void than the full 650mm end panel leaves (a cut unit with a bar or\n    // seating close behind): plain end panels to the back panel instead, so\n    // the back panel sits where the island was designed.\n    const ks = Catalogue.getKitchenStyle ? Catalogue.getKitchenStyle(styleId) : null;\n    const fwd = (ks && ks.doorThicknessMm) || 18;\n    cabinets = cabinets.map(c => {\n      const u = idSet.has(c.id) ? spec.units[ids.indexOf(c.id)] : null;\n      if (!u || u.voidMm == null || !(u.run === 'front' || /^arm/.test(u.run || '')) || !c.backPanel || !c.backPanel.active) return c;\n      const T = c.backPanel.thicknessMm || 20;\n      const fullGap = Math.max(0, BASE_EP_BOARD_MM - fwd - (c.depthMm || 0) - T);\n      const v = Math.max(0, Math.round(u.voidMm));\n      if (v + 1 < fullGap) {\n        return { ...c, useFullSizeEndPanel: false, fullSizeEndPanelUserSet: true,\n                 backPanel: { ...c.backPanel, gapMm: v > 0 ? v : null } };\n      }\n      return { ...c, backPanel: { ...c.backPanel, gapMm: v } };\n    });\n    // Seating: a seat unit's open back (a return's outer side) takes a flush\n    // back panel, never the 650mm full-depth end panels and their void.\n    cabinets = cabinets.map(c => (idSet.has(c.id) && c.cushionTop && c.backPanel && c.backPanel.active)\n      ? { ...c, useFullSizeEndPanel: false, fullSizeEndPanelUserSet: true, backPanel: { ...c.backPanel, gapMm: null } } : c);\n    // The main seats' backs stand against the island's own back panel (a\n    // deeper island's void leaves them uncovered, and they took a second one).\n    cabinets = cabinets.map(c => (idSet.has(c.id) && c.islandRun === 'seat' && c.backPanel && c.backPanel.active)\n      ? { ...c, backPanel: { ...c.backPanel, active: false, userOff: true } } : c);\n    // A unit's panel beside a free standing appliance in the island stops at\n    // its own back (besideAppliance - stampManualEndPanels).\n    {\n      const rectOf = (c) => { const t = Math.round((((c.rotationDeg || 0) % 180) + 180) % 180) === 90;\n        const w = t ? c.depthMm : c.widthMm, d = t ? c.widthMm : c.depthMm, cx = c.x + c.widthMm / 2, cy = c.y + c.depthMm / 2;\n        return { x0: cx - w / 2, x1: cx + w / 2, y0: cy - d / 2, y1: cy + d / 2 }; };\n      const apps = cabinets.filter(c => idSet.has(c.id) && c.freestandingAppliance).map(rectOf);\n      const gapSides = [];\n      if (apps.length) cabinets = cabinets.map(c => {\n        if (!idSet.has(c.id) || c.freestandingAppliance || !c.endPanels) return c;\n        const th = ((c.rotationDeg || 0) * Math.PI) / 180, lx = Math.cos(th), ly = Math.sin(th);   // its left\n        const ep = { ...c.endPanels };\n        let hit = false;\n        for (const side of ['left', 'right']) {\n          if (!(ep[side] && ep[side].active)) continue;\n          const k = (side === 'left' ? 1 : -1) * (c.widthMm / 2 + 40);\n          const px = c.x + c.widthMm / 2 + lx * k, py = c.y + c.depthMm / 2 + ly * k;\n          if (apps.some(r => px > r.x0 && px < r.x1 && py > r.y0 && py < r.y1)) {\n            const { wtSquare, ...rest } = ep[side];\n            ep[side] = { ...rest, style: ['flat', 'tng'].includes(rest.style) ? rest.style : 'flat', besideAppliance: true };\n            hit = true;\n            gapSides.push({ px: c.x + c.widthMm / 2, py: c.y + c.depthMm / 2 });\n          }\n        }\n        return hit ? { ...c, endPanels: ep } : c;\n      });\n      // Each appliance's worktop runs over its fitting gap to the panel.\n      if (gapSides.length) cabinets = cabinets.map(a => {\n        if (!idSet.has(a.id) || !a.freestandingAppliance || a.freestandingAppliance.kind !== 'built-under') return a;\n        const r0 = rectOf(a), th = ((a.rotationDeg || 0) * Math.PI) / 180, lx = Math.cos(th), ly = Math.sin(th);\n        const acx = a.x + a.widthMm / 2, acy = a.y + a.depthMm / 2;\n        const wt = { left: 0, right: 0, front: 0, back: 0, ...(a.worktop || {}) };\n        let hit = false;\n        for (const g of gapSides) {\n          const along = (g.px - acx) * lx + (g.py - acy) * ly, across = -(g.px - acx) * ly + (g.py - acy) * lx;\n          if (Math.abs(across) > (r0.y1 - r0.y0 + r0.x1 - r0.x0) / 2 || Math.abs(along) > a.widthMm / 2 + 700) continue;\n          wt[along > 0 ? 'left' : 'right'] = Math.max(Number(wt[along > 0 ? 'left' : 'right']) || 0, FSA_END_PANEL_GAP_MM);\n          hit = true;\n        }\n        return hit ? { ...a, worktop: wt } : a;\n      });\n      // Its back panel out to the island's line, now the void is set.\n      if (apps.length) autoDetectBackPanels();\n    }\n    // A VOID BETWEEN BACK-TO-BACK ROWS (Arden, 2026-11-18): an overhang under\n    // 150 is no use to sit at, so the Island Designer moves the rows out to\n    // the edges. Neither row takes a back panel into the void; the front\n    // row's worktop runs on over it to the back row's; and a plain / T&G end\n    // panel on the front row reaches back across it (its own size, Extend at\n    // Back), closing the island's end.\n    {\n      const box = (c) => ({ x0: c.x, x1: c.x + c.widthMm, y0: c.y, y1: c.y + c.depthMm });\n      const turn = (c) => Math.round((((c.rotationDeg || 0) % 360) + 360) % 360);\n      const backs = cabinets.filter(c => idSet.has(c.id) && /^back/.test(c.islandRun || '') && turn(c) === 0);\n      const xOver = (a, b) => Math.min(a.x1, b.x1) - Math.max(a.x0, b.x0);\n      const gapBehind = (c) => {\n        const b = box(c);\n        let g = null;\n        for (const o of backs) {\n          const ob = box(o);\n          if (xOver(ob, b) < 50) continue;\n          const v = b.y0 - ob.y1;                      // the front row faces down the plan\n          if (v > 15 && v <= 300 && (g == null || v < g)) g = v;\n        }\n        return g;\n      };\n      const fronts = cabinets.filter(c => idSet.has(c.id) && c.islandRun === 'front' && turn(c) === 180);\n      const gaps = new Map(fronts.map(c => [c.id, gapBehind(c)]).filter(([, g]) => g != null));\n      if (gaps.size) {\n        const backsInVoid = new Set(backs.filter(o => fronts.some(c => gaps.has(c.id) && xOver(box(o), box(c)) >= 50)).map(o => o.id));\n        cabinets = cabinets.map(c => {\n          const g = gaps.get(c.id);\n          if (g == null && !backsInVoid.has(c.id)) return c;\n          let out = c;\n          if (out.backPanel) out = { ...out, backPanel: { ...out.backPanel, active: false, userOff: true } };\n          if (g == null) return out;\n          const ep = { ...(out.endPanels || {}) };\n          let manual = false;\n          for (const sd of ['left', 'right']) {\n            const e = ep[sd];\n            if (!e || !e.active || !(e.style === 'flat' || e.style === 'tng')) continue;\n            ep[sd] = { ...e, manualDepthMm: Math.round(fwd + (out.depthMm || 0) + g), manualDir: 'back' };\n            manual = true;\n          }\n          out = { ...out, endPanels: ep };\n          // An end panel's own size carries the worktop back with it.\n          if (!manual) out = { ...out, worktop: { left: 0, right: 0, front: 0, back: 0, ...(out.worktop || {}), back: Math.max(Number((out.worktop || {}).back) || 0, Math.round(g)) } };\n          return out;\n        });\n      }\n    }\n    // A DOG-LEG ARM meets the island's back panel line, but the panel comes\n    // off where the arm stands against it, leaving the void and panel's depth\n    // between the arm's first unit and the island's units: a filler there,\n    // in line with the arm's doors (Arden, 2026-11-18).\n    {\n      const arms = cabinets.filter(c => idSet.has(c.id) && /^arm/.test(c.islandRun || ''));\n      const fronts = cabinets.filter(c => idSet.has(c.id) && c.islandRun === 'front');\n      const rect = (c) => { const t = Math.round((((c.rotationDeg || 0) % 180) + 180) % 180) === 90;\n        const w = t ? c.depthMm : c.widthMm, d = t ? c.widthMm : c.depthMm, cx = c.x + c.widthMm / 2, cy = c.y + c.depthMm / 2;\n        return { x0: cx - w / 2, x1: cx + w / 2, y0: cy - d / 2, y1: cy + d / 2 }; };\n      if (arms.length && fronts.length) {\n        const near = arms.reduce((a, b) => (rect(b).y1 > rect(a).y1 ? b : a));\n        const ar = rect(near);\n        // What the arm meets: the island's back panel where the units behind\n        // it keep theirs (a deeper island, its void wider than a unit's cover),\n        // else the units' backs.\n        const behind = fronts.filter(f => { const r = rect(f); return Math.min(r.x1, ar.x1) - Math.max(r.x0, ar.x0) > 50; });\n        const face = (f) => {\n          const bp = f.backPanel;\n          return rect(f).y0 - ((bp && bp.active) ? (Number(bp.gapMm) || 0) + (bp.thicknessMm || 18) : 0);\n        };\n        const fy = behind.length ? Math.min(...behind.map(face)) : NaN;\n        const gap = Math.round(fy - ar.y1);\n        // The arm's island end, in its own frame (its left is local +x).\n        const side = Math.sin(((near.rotationDeg || 0) * Math.PI) / 180) > 0 ? 'left' : 'right';\n        if (Number.isFinite(gap) && gap >= 5 && gap <= 200) {\n          cabinets = cabinets.map(c => c.id !== near.id ? c : { ...c, fillers: { ...(c.fillers || {}),\n            [side]: { ...((c.fillers || {})[side] || {}), active: true, widthMm: gap, setBackMm: 0, userSet: true, userWidth: true } } });\n        }\n        // Against the island it takes no end panel there (hidden, still bought).\n        if (Number.isFinite(gap) && gap <= 200) {\n          cabinets = cabinets.map(c => c.id !== near.id ? c : { ...c, endPanels: { ...(c.endPanels || {}),\n            [side]: { ...((c.endPanels || {})[side] || {}), active: false, userSet: true } } });\n        }\n      }\n    }\n    // A seating corner (Arden, 2026-11-18): blank under the cushion. The\n    // return's first unit takes its cushion on over it and (no dog-leg arm\n    // there) its back panel on to the island's; the units' ends inside the\n    // corner take no end panels.\n    cabinets = cabinets.map(c => {\n      const u = idSet.has(c.id) ? spec.units[ids.indexOf(c.id)] : null;\n      if (!u) return c;\n      let out = islandPlinthOn(c, spec.plinth);\n      if (u.roomFiller && u.roomFiller.mm > 0) {\n        const sd = u.roomFiller.side;\n        out = { ...out, fillers: { ...(out.fillers || {}),\n          [sd]: { ...((out.fillers || {})[sd] || {}), active: true, widthMm: u.roomFiller.mm, setBackMm: 0, userSet: true, userWidth: true } } };\n      }\n      if (Array.isArray(u.offEnds)) {\n        const ep = { ...(out.endPanels || {}) };\n        for (const sd of u.offEnds) ep[sd] = { ...(ep[sd] || {}), active: false, userSet: true };\n        out = { ...out, endPanels: ep };\n      }\n      if (Array.isArray(u.innerEnds)) {\n        const ep = { ...(out.endPanels || {}) };\n        for (const sd of u.innerEnds) ep[sd] = { ...(ep[sd] || {}), active: false, userSet: true };\n        out = { ...out, endPanels: ep };\n      }\n      if (u.cushionOver && u.cushionOver.mm > 0) {\n        out = { ...out, worktop: { left: 0, right: 0, front: 0, back: 0, ...(out.worktop || {}), [u.cushionOver.side]: u.cushionOver.mm } };\n      }\n      if (u.backPanelExt && u.backPanelExt.mm > 0 && out.backPanel && out.backPanel.active) {\n        out = { ...out, backPanel: { ...out.backPanel, userExtMm: { ...(out.backPanel.userExtMm || {}), [u.backPanelExt.end]: u.backPanelExt.mm } } };\n      }\n      return out;\n    });\n    if (rounded) {\n      // The side panel runs between the front and back posts, so it is the\n      // designed end depth less the two posts (the back panel then stands\n      // where the design has it).\n      const len = Math.max(1, Math.min(BASE_EP_BOARD_MM, Math.round((Number(spec.endPanelMm) || BASE_EP_BOARD_MM) - 140)));\n      // Not on an end the dog-leg's units carry on behind.\n      const armXs = armUnits.map(wbox);\n      const armMinX = armXs.length ? Math.min(...armXs.map(b => b.x0)) : null;\n      const armMaxX = armXs.length ? Math.max(...armXs.map(b => b.x1)) : null;\n      const armBehind = (c, sd) => {\n        if (armMinX == null) return false;\n        const lx = Math.cos(((c.rotationDeg || 0) * Math.PI) / 180) * (sd === 'left' ? 1 : -1);\n        return lx < -0.5 ? armMinX <= gMinX + 100 : lx > 0.5 ? armMaxX >= gMaxX - 100 : false;\n      };\n      cabinets = cabinets.map(c => {\n        if (!idSet.has(c.id) || c.islandRun !== 'front' || !c.backPanel || !c.backPanel.active) return c;\n        const ep = c.endPanels || {};\n        const outer = ['left', 'right'].some(sd => ep[sd] && ep[sd].active && !ep[sd].wtSquare && outerSide(c, sd) && !armBehind(c, sd));\n        return outer ? { ...c, backEndPost: { ...(c.backEndPost || {}), active: true, panelLengthMm: len } } : c;\n      });\n    }\n    holdIsland();\n    rerender();\n    holdIsland();\n    islandWorktopOverhangs(ids, spec, ox, oy);\n    if (turnBy) rotateCabinetGroup(gid, true, turnBy);\n    // (Radius ends: the worktop's outer corners are rounded by the worktop\n    // engine from the island itself - islandRadius in applyCornerRadii.)\n    resizeFillers();\n    rerender();\n    if (spec.waterfall || spec.barWaterfall) islandWaterfalls(ids, spec);\n    trimSeatCornerCushion(spec, ids, idSet);\n    if (!_islandDry) setCabinetSelection(ids);\n    scheduleBasketResync();\n    return true;\n  }\n  // A seating corner: the return's cushion runs over the blank corner to the\n  // main seats' back line exactly. Measured on the cushion as built, along\n  // the return towards the island (so a turned island too): its end\n  // overhangs vary with what stands beside it (a dog-leg arm), and its reach\n  // does not follow the overhang one for one, so each step is re-measured.\n  function trimSeatCornerCushion(spec, ids, idSet) {\n    const k = spec.units.findIndex(u => u && u.cushionOver);\n    const rid = k >= 0 ? ids[k] : null;\n    const ret = rid && cabinets.find(c => c.id === rid);\n    const seats = cabinets.filter(c => idSet.has(c.id) && c.islandRun === 'seat');\n    if (!ret || !seats.length) return;\n    const side = spec.units[k].cushionOver.side;\n    const th = ((ret.rotationDeg || 0) * Math.PI) / 180;\n    const sg = side === 'left' ? 1 : -1;\n    const vx = Math.cos(th) * sg, vy = Math.sin(th) * sg;          // its island end\n    const dot = (p) => p.x * vx + p.y * vy;\n    const corners = (c) => {\n      const t = ((c.rotationDeg || 0) * Math.PI) / 180, cx = c.x + c.widthMm / 2, cy = c.y + c.depthMm / 2;\n      return [[-1, -1], [1, -1], [1, 1], [-1, 1]].map(([a, b]) => {\n        const lx = a * c.widthMm / 2, ly = b * c.depthMm / 2;\n        return { x: cx + lx * Math.cos(t) - ly * Math.sin(t), y: cy + lx * Math.sin(t) + ly * Math.cos(t) };\n      });\n    };\n    const target = Math.max(...seats.flatMap(c => corners(c).map(dot)));\n    const cur = () => Number(((cabinets.find(c => c.id === rid) || {}).worktop || {})[side]) || 0;\n    const reachOf = () => {\n      const sl = (buildWorktops() || []).find(s => s && s.cushionTop && (s.cabinetIds || []).includes(rid));\n      return sl && sl.polygon ? Math.max(...sl.polygon.map(dot)) : null;\n    };\n    let prev = null, changed = false;\n    for (let pass = 0; pass < 6; pass++) {\n      const x = cur(), y = reachOf();\n      if (y == null) break;\n      const d = y - target;\n      if (Math.abs(d) < 2) break;\n      let slope = 1;\n      if (prev && Math.abs(x - prev.x) >= 1) slope = (y - prev.y) / (x - prev.x);\n      if (!(slope > 0.2 && slope < 5)) slope = 1;\n      prev = { x, y };\n      const next = Math.max(0, Math.round(x - d / slope));\n      if (next === x) break;\n      cabinets = cabinets.map(c => c.id !== rid ? c\n        : { ...c, worktop: { left: 0, right: 0, front: 0, back: 0, ...(c.worktop || {}), [side]: next } });\n      changed = true;\n    }\n    if (changed) rerender();\n  }\n  // The nearest spot to `centre` (spiralling out in 100mm steps) where the\n  // island and 50mm round it clear every floor unit - inside the room's box\n  // when it fits, else wherever is nearest.\n  function freeIslandSpot(spec, centre, bbox) {\n    const W = (Number(spec.widthMm) || 0) + 100, D = (Number(spec.depthMm) || 0) + 100;\n    const boxes = cabinets.filter(c => c && !/^(wall|bridging)/i.test(c.category || '')).map(c => visualBbox(c));\n    const free = (x, y) => !boxes.some(b => b.x0 < x + W / 2 && b.x1 > x - W / 2 && b.y0 < y + D / 2 && b.y1 > y - D / 2);\n    if (free(centre.x, centre.y)) return centre;\n    const reach = Math.max(bbox.widthMm || 0, bbox.heightMm || 0) + Math.max(W, D);\n    const bx0 = Number(bbox.minX) || 0, by0 = Number(bbox.minY) || 0;\n    // Inside the room first; with no room for it there, the nearest clear\n    // spot anywhere - never stacked on top of what is already there.\n    for (const inside of [true, false]) {\n      for (let rr = 100; rr <= reach; rr += 100) {\n        const steps = Math.max(8, Math.round((2 * Math.PI * rr) / 200));\n        for (let k = 0; k < steps; k++) {\n          const a = (k / steps) * 2 * Math.PI;\n          const x = Math.round(centre.x + rr * Math.cos(a)), y = Math.round(centre.y + rr * Math.sin(a));\n          if (inside && (x - W / 2 < bx0 || y - D / 2 < by0 || x + W / 2 > bx0 + bbox.widthMm || y + D / 2 > by0 + bbox.heightMm)) continue;\n          if (free(x, y)) return { x, y };\n        }\n      }\n    }\n    return centre;\n  }\n  // Radius ends go on all four corners and the worktop is rounded to suit\n  // (Arden, 2026-11-18). A corner over a radius end panel is rounded by the\n  // planner already; one standing past the units (a breakfast bar behind,\n  // a bar past an end) takes the same 70mm radius as a worktop corner.\n  function roundIslandWorktopCorners(ids) {\n    const mine = new Set(ids.filter(id => { const c = cabinets.find(x => x.id === id); return c && !isPastrySet(c); }));\n    const slabs = (buildWorktops() || []).filter(sl => sl && !sl.cushionTop && sl.polygon && sl.polygon.length >= 3\n      && (sl.cabinetIds || []).some(id => mine.has(id)));\n    if (!slabs.length) return;\n    const pts = slabs.flatMap(sl => sl.polygon);\n    const X0 = Math.min(...pts.map(p => p.x)), X1 = Math.max(...pts.map(p => p.x));\n    const Y0 = Math.min(...pts.map(p => p.y)), Y1 = Math.max(...pts.map(p => p.y));\n    for (const [k, x, y] of [['tl', X0, Y0], ['tr', X1, Y0], ['bl', X0, Y1], ['br', X1, Y1]]) {\n      for (const sl of slabs) {\n        if (!sl.polygon.some(q => Math.abs(q.x - x) < 1 && Math.abs(q.y - y) < 1)) continue;\n        const cur = worktopCornerRadii[sl.id] || { tl: 0, tr: 0, bl: 0, br: 0 };\n        if (!cur[k]) worktopCornerRadii = { ...worktopCornerRadii, [sl.id]: { ...cur, [k]: 70 } };\n      }\n    }\n  }\n  // Push each unit's slice of the worktop out to the designed outline (a\n  // breakfast bar's 300, the overhang behind back units...). Each unit on an\n  // edge of the island (nothing of the group further out over it) is measured\n  // against its own worktop piece as the planner builds it, so the planner's\n  // own overhangs stay and only the difference is added.\n  function islandWorktopOverhangs(ids, spec, ox, oy) {\n    const want = spec.worktop;\n    if (!want) return;\n    const W = { top: oy + want.y0, bottom: oy + want.y1, left: ox + want.x0, right: ox + want.x1 };\n    const rectOf = (c) => {\n      const turned = Math.round((((c.rotationDeg || 0) % 180) + 180) % 180) === 90;\n      const rw = turned ? c.depthMm : c.widthMm, rh = turned ? c.widthMm : c.depthMm;\n      const cx = c.x + c.widthMm / 2, cy = c.y + c.depthMm / 2;\n      return { x0: cx - rw / 2, x1: cx + rw / 2, y0: cy - rh / 2, y1: cy + rh / 2 };\n    };\n    const group = cabinets.filter(c => ids.includes(c.id) && !isPastrySet(c) && !c.cushionTop && carriesWorktop(c) && !/^arm/.test(c.islandRun || '')).map(c => ({ id: c.id, r: rectOf(c) }));\n    const over = (a0, a1, b0, b1) => Math.min(a1, b1) - Math.max(a0, b0) > 1;\n    // What stands in the island's rows, a range cooker too (it carries its own\n    // top, so no worktop reaches over it from the row behind).\n    const solid = cabinets.filter(c => ids.includes(c.id) && !isPastrySet(c) && !c.cushionTop && !/^arm/.test(c.islandRun || '')\n      && (carriesWorktop(c) || (c.freestandingAppliance && c.freestandingAppliance.kind === 'range'))).map(c => ({ id: c.id, r: rectOf(c) }));\n    // Past an end only from the units at that end of the island.\n    const minX = Math.min(...group.map(g => g.r.x0)), maxX = Math.max(...group.map(g => g.r.x1));\n    const outermost = (g, side) => !group.some(o => o.id !== g.id && (\n      side === 'top'    ? (o.r.y0 < g.r.y0 - 1 && over(o.r.x0, o.r.x1, g.r.x0, g.r.x1)) :\n      side === 'bottom' ? (o.r.y1 > g.r.y1 + 1 && over(o.r.x0, o.r.x1, g.r.x0, g.r.x1)) :\n      side === 'left'   ? (g.r.x0 > minX + 1) :\n                          (g.r.x1 < maxX - 1)));\n    // The longest stretch [x0, x1] of a unit's top / bottom side that\n    // no unit of the island stands further out over (null: none, or under\n    // 100mm - a butt joint's slack, not an opening).\n    const openAt = (g, side) => {\n      const cover = solid.filter(o => o.id !== g.id && (side === 'top' ? o.r.y0 < g.r.y0 - 1 : o.r.y1 > g.r.y1 + 1)\n          && over(o.r.x0, o.r.x1, g.r.x0, g.r.x1))\n        .map(o => [Math.max(g.r.x0, o.r.x0), Math.min(g.r.x1, o.r.x1)]).sort((a, b) => a[0] - b[0]);\n      let x = g.r.x0, best = null;\n      const gap = (a, b) => { if (b - a >= 100 && (!best || b - a > best[1] - best[0])) best = [a, b]; };\n      for (const [a, b] of cover) { gap(x, a); x = Math.max(x, b); }\n      gap(x, g.r.x1);\n      return best;\n    };\n    const slabs = mergeCornerRuns(buildWorktops() || []);\n    cabinets = cabinets.map(c => {\n      const g = group.find(x => x.id === c.id);\n      const sl = g && slabs.find(x => (x.cabinetIds || []).includes(c.id));\n      if (!sl) return c;\n      // How far the worktop reaches straight out from the unit's middle on\n      // each side - its own edge, even on a worktop merged with others.\n      const reach = (vertical, at, pickMin) => {\n        let best = null;\n        const P = sl.polygon;\n        for (let i = 0; i < P.length; i++) {\n          const p = P[i], q = P[(i + 1) % P.length];\n          const a0 = vertical ? p.x : p.y, a1 = vertical ? q.x : q.y;\n          if ((a0 - at) * (a1 - at) > 0 || a0 === a1) continue;\n          const t = (at - a0) / (a1 - a0);\n          const v = vertical ? p.y + (q.y - p.y) * t : p.x + (q.x - p.x) * t;\n          if (best == null || (pickMin ? v < best : v > best)) best = v;\n        }\n        return best;\n      };\n      const ucx = (g.r.x0 + g.r.x1) / 2, ucy = (g.r.y0 + g.r.y1) / 2;\n      // Measured where this unit's side is open: a front unit that runs\n      // past the end of the back units (a split back whose units do not\n      // break where the bar starts) is open behind its part under the bar,\n      // and takes the bar's overhang there (Arden, 2026-11-18: a 1000 front\n      // unit with 200 of it under the bar had no worktop behind that 200).\n      const at = { top: openAt(g, 'top'), bottom: openAt(g, 'bottom') };\n      const xs = sl.polygon.map(p => p.x), ys = sl.polygon.map(p => p.y);\n      // Across the open stretch the worktop may fall short only in part (a\n      // notch beside the next unit's end panel), so the shortest reach counts.\n      const worst = (span, pickMin) => {\n        if (!span) return null;\n        // Open all along: measured at its middle, as ever (an edge sample would\n        // catch a rounded corner).\n        if (span[0] <= g.r.x0 + 1 && span[1] >= g.r.x1 - 1) return reach(true, ucx, pickMin);\n        let v = null;\n        for (let i = 0; i <= 8; i++) {\n          const r0 = reach(true, span[0] + 2 + (span[1] - span[0] - 4) * i / 8, pickMin);\n          if (r0 != null && (v == null || (pickMin ? r0 > v : r0 < v))) v = r0;\n        }\n        return v;\n      };\n      const got = { top: worst(at.top, true) ?? Math.min(...ys), bottom: worst(at.bottom, false) ?? Math.max(...ys),\n                    left: reach(false, ucy, true) ?? Math.min(...xs), right: reach(false, ucy, false) ?? Math.max(...xs) };\n      const short = { top: got.top - W.top, bottom: W.bottom - got.bottom, left: got.left - W.left, right: W.right - got.right };\n      const th = ((c.rotationDeg || 0) * Math.PI) / 180;\n      const fx = Math.sin(th), fy = -Math.cos(th);    // its front\n      const lx = Math.cos(th), ly = Math.sin(th);     // its left (+x)\n      const localOf = (dx, dy) => {\n        const fd = dx * fx + dy * fy;\n        if (Math.abs(fd) > 0.5) return fd > 0 ? 'front' : 'back';\n        return (dx * lx + dy * ly) > 0 ? 'left' : 'right';\n      };\n      const wt = { left: 0, right: 0, front: 0, back: 0, ...(c.worktop || {}) };\n      let touched = false;\n      for (const [side, dx, dy] of [['top', 0, -1], ['bottom', 0, 1], ['left', -1, 0], ['right', 1, 0]]) {\n        if (Math.abs(short[side]) < 3) continue;   // a mm or two of rounding, not an overhang\n        if ((side === 'top' || side === 'bottom') ? at[side] == null : !outermost(g, side)) continue;\n        const k = localOf(dx, dy);\n        const v = Math.max(0, Math.min(k === 'front' || k === 'back' ? 300 : 1000, Math.round((Number(wt[k]) || 0) + short[side])));\n        if (v !== (Number(wt[k]) || 0)) { wt[k] = v; touched = true; }\n      }\n      return touched ? { ...c, worktop: wt } : c;\n    });\n  }\n\n  function deleteCabinet(c)    {\n    if (c && c.walkInSet && cabinets.some(h => h.id === c.walkInSet.hostId)) {\n      designControlsHandle.setStatus('This unit is part of the walk-in larder. Use Customise Walk-in Larder to change it.');\n      return;\n    }\n    clearSelectionIfMatches('cabinet', c.id);\n    const gone = withRadiusCompanions([c.id]);\n    cabinets = cabinets.filter(x => !gone.has(x.id));\n    autoDetectEndPanels();\n    autoDetectBackPanels();\n    resizeFillers();\n    rerender();\n  }\n  function duplicateCabinet(c) {\n    if (c && c.walkInSet) {\n      designControlsHandle.setStatus('This unit is part of the walk-in larder. Duplicate the larder to copy it.');\n      return;\n    }\n    const __dupId = `cabinet-${nextCabinetId++}`;\n    // A duplicate is an INDEPENDENT unit - never inherit the source's groupId\n    // (that locked a duplicated radius assembly to the original). A radius\n    // curve duplicate starts as a plain island; autoDetectRadiusCompanions\n    // grows its OWN backing + filler once it's slid to a wall.\n    const spot = freeSpotForDuplicate(c);\n    const dup = { ...c, id: __dupId,\n                  x: spot ? spot.x : c.x + CABINET_STAGGER_MM, y: spot ? spot.y : c.y + CABINET_STAGGER_MM,\n                  displayNumber: nextDisplayNumber() };\n    delete dup.groupId;\n    if (dup.radiusUnit) dup.radiusUnit = { ...dup.radiusUnit, kind: 'island-base' };\n    const _dupSet = dup.walkInSetKey && walkInSetMembers(c.id).length ? dup.walkInSetKey : null;\n    delete dup.walkInSetKey;\n    cabinets.push(dup);\n    if (_dupSet) applyWalkInSet(__dupId, _dupSet);\n    autoDetectEndPanels([__dupId]);\n    autoDetectBackPanels();\n    autoDetectRadiusCompanions();\n    resizeFillers();\n    rerender();\n    // Selected, so the copy is picked out on the plan and ready to move.\n    selectItem({ kind: 'cabinet', id: __dupId });\n    revealNewItems([__dupId]);\n  }\n  // A duplicate lands in FREE space, never on top of its original or anything\n  // else (Arden, 2026-10-12): a small part - a filler, a post - dropped a\n  // stagger away into a busy layout was all but impossible to find. Tried\n  // first right beside the original (right, left, in front, behind), then in\n  // rings outward from it, as duplicated furniture is. Its footprint has to\n  // clear every unit, piece of furniture and room feature (beams and ceilings\n  // are overhead, so not in the way) and lie inside the room - not in the\n  // outside corner of an L. A room with no space left keeps the old stagger.\n  function freeSpotForDuplicate(c) {\n    const a = getEffectiveAABB(c, c.x, c.y);\n    const w = a.widthMm, h = a.depthMm;\n    if (!(w > 0) || !(h > 0)) return null;\n    const offX = a.x - c.x, offY = a.y - c.y;   // footprint corner -> unit position\n    const verts = (room && room.vertices) || [];\n    const obs = furnitureObstacles(null);\n    const inside = (x, y) => verts.length < 3 || pointInRoomPolygon(x, y, verts);\n    const fits = (x, y) => inside(x, y) && inside(x + w, y) && inside(x + w, y + h) && inside(x, y + h)\n      && !obs.some(o => rectsOverlap({ x, y, w, h }, o));\n    const at = (x, y) => ({ x: Math.round(x - offX), y: Math.round(y - offY) });\n    const GAP = 50;\n    for (const [x, y] of [[a.x + w + GAP, a.y], [a.x - w - GAP, a.y], [a.x, a.y + h + GAP], [a.x, a.y - h - GAP]]) {\n      if (fits(x, y)) return at(x, y);\n    }\n    const step = Math.max(100, Math.min(w, h) * 0.5);\n    for (let r = 1; r <= 80; r++) {\n      for (let dx = -r; dx <= r; dx++) {\n        for (let dy = -r; dy <= r; dy++) {\n          if (Math.abs(dx) !== r && Math.abs(dy) !== r) continue;   // the ring only\n          const x = a.x + dx * step, y = a.y + dy * step;\n          if (fits(x, y)) return at(x, y);\n        }\n      }\n    }\n    return null;\n  }\n\n  // ---- Item numbering ----\n\n  function nextDisplayNumber() {\n    let max = 0;\n    for (const c of cabinets) if ((c.displayNumber || 0) > max) max = c.displayNumber;\n    return max + 1;\n  }\n\n  // For a cabinet, project its 4 (rotated) corners onto a wall to\n  // decide if its back edge is within ~60mm of that wall, and at\n  // what along-wall midpoint it sits. Used to order wall-flush units\n  // clockwise around the room. Mirrors the dimension-engine logic.\n  function projectCabinetOntoWall(cab, wall, tolMm) {\n    const w = cab.widthMm, d = cab.depthMm;\n    if (!(w > 0) || !(d > 0)) return null;\n    const len = wall.lengthMm;\n    if (len < 1) return null;\n    const cx = cab.x + w / 2, cy = cab.y + d / 2;\n    const th = ((cab.rotationDeg || 0) * Math.PI) / 180;\n    const cs = Math.cos(th), sn = Math.sin(th);\n    const ux = (wall.to.x - wall.from.x) / len;\n    const uy = (wall.to.y - wall.from.y) / len;\n    const nx = uy, ny = -ux;\n    let minT = Infinity, maxT = -Infinity, minP = Infinity, maxP = -Infinity;\n    for (const [lx, ly] of [[-w/2,-d/2],[w/2,-d/2],[w/2,d/2],[-w/2,d/2]]) {\n      const X = cx + lx * cs - ly * sn;\n      const Y = cy + lx * sn + ly * cs;\n      const t = (X - wall.from.x) * ux + (Y - wall.from.y) * uy;\n      const p = (X - wall.from.x) * nx + (Y - wall.from.y) * ny;\n      if (t < minT) minT = t; if (t > maxT) maxT = t;\n      if (p < minP) minP = p; if (p > maxP) maxP = p;\n    }\n    if (maxP > tolMm || maxP < -tolMm) return null;\n    if (minP > maxP - 1) return null;\n    const lo = Math.max(0, minT), hi = Math.min(len, maxT);\n    if (hi - lo < 1) return null;\n    return { t: (lo + hi) / 2 };\n  }\n\n  // Selecting an end-panel number selects that end-panel face - the\n  // left selection panel then shows its cut plan (above the colour\n  // swatches) and the existing end-panel selection visual highlights\n  // the panel piece on the plan. We also flag the matching number badge.\n  // A face key is 'cabId:side' for a panel or filler, and carries a part on\n  // the end - 'left:feature' / 'left:feature-back' - for the radius or square\n  // post, which is its own basket line. Splits one from the other.\n  function epFacePart(rawSide) {\n    const m = String(rawSide || '').match(/^(.*):(feature(?:-back)?)$/);\n    return m ? { side: m[1], part: m[2] } : { side: rawSide, part: null };\n  }\n\n  // A True Handleless vertical PROFILE (\"rail\") is its own piece: selected,\n  // highlighted (2D strip, 3D mesh, its number) and shown in the left menu as\n  // itself - not as the unit it stands on (Arden, 2026-10-21).\n  function railNumberOf(c, side) {\n    if (!c) return null;\n    if (c.railSecondSide === side && c.railGripSide !== side) return c.railSecondNumber ?? null;\n    return c.railGripSide === side ? (c.railNumber ?? null) : null;\n  }\n  // A shared (grip-to-grip) profile is drawn + numbered by its OWNER unit, so\n  // a key naming the partner's side resolves to the owner's.\n  function railOwnerFace(cabId, side) {\n    const c = cabinets.find(x => String(x.id) === String(cabId));\n    if (c && c.railType === 'intermediate' && !c.railOwnsShared && c.railGripSide === side && c.railPartnerId) {\n      const o = cabinets.find(x => x.id === c.railPartnerId);\n      if (o && o.railGripSide) return { cabId: o.id, side: o.railGripSide };\n    }\n    return { cabId: c ? c.id : cabId, side };\n  }\n  function selectRail(cabId, side) {\n    const f = railOwnerFace(cabId, side);\n    selectItem({ kind: 'rail', cabinetId: f.cabId, side: f.side });\n    focusBasketLineForFace(f.cabId, 'rail-' + f.side);\n  }\n\n  // A TH External Corner Post ('left' / 'right', 'front' / 'back') - its own\n  // piece, like a profile: selected and shown as itself, not as its unit.\n  function cornerPostNumberOf(c, side, pos) {\n    return (c && c.cornerPostNumbers && c.cornerPostNumbers[`${side}:${pos}`]) ?? null;\n  }\n  // Plan numbers of the lines excluded in the basket's Exclude popup\n  // (quoteExcludedLines, keyed by the line id): their badges are drawn without\n  // a number. A board / end-feature line carries its number in its id; a\n  // profile or corner-post line is found on its unit (Arden, 2026-10-21).\n  // A board's / end-feature length's quote-line key, from the pieces cut from\n  // it (\"cabId:side\" face keys, sorted) - NOT its plan number. A line's id is\n  // what an exclusion or a free line is saved against, and the plan is\n  // renumbered whenever something is added or moved: a number-based id let an\n  // exclusion drop off, or land on another piece that took the number (Julian's\n  // excluded \"board 27\" became a unit's number). Arden, 2026-10-21.\n  function boardLineKey(board) {\n    const faces = (board && board.pieces || [])\n      .map(p => ((p.face && p.face.cabIds) || []).map(id => `${id}:${p.face.side}`)).flat()\n      .filter(k => !k.endsWith(':undefined') && !k.endsWith(':null'));\n    return faces.length ? 'b:' + [...new Set(faces)].sort().join(',')\n      : 'b:' + ((board && board.ownerCabId) || 'x') + ':' + (board && board.itemNumber);\n  }\n  function featureLineKey(faces, ownerCabId, number) {\n    const f = (faces || []).filter(Boolean);\n    return f.length ? 'ef:' + [...new Set(f)].sort().join(',') : 'ef:' + (ownerCabId || 'x') + ':' + number;\n  }\n\n  function excludedPlanNumbers() {\n    const out = new Set();\n    try {\n      // Boards and end-feature lengths: by their piece keys, against the\n      // current layout.\n      const ex = quoteExcludedLines || {};\n      for (const b of ((endPanelLayout && endPanelLayout.boards) || [])) {\n        if (b.itemNumber != null && ex['q:' + boardLineKey(b)]) out.add(Number(b.itemNumber));\n      }\n      for (const bin of ((endPanelLayout && endPanelLayout.endFeatureBins) || [])) {\n        const faces = (bin.items || []).map(i => i.focusKey || i.faceKey);\n        if (bin.number != null && ex['q:' + featureLineKey(faces, bin.ownerCabId, bin.number)]) out.add(Number(bin.number));\n      }\n      for (const k of Object.keys(ex)) {\n        let m;\n        if ((m = k.match(/^q:rl:(.+):(left|right)$/))) {\n          const n = railNumberOf(cabinets.find(c => c.id === m[1]), m[2]);\n          if (n != null) out.add(Number(n));\n          continue;\n        }\n        if ((m = k.match(/^q:cp:(.+):(left|right):(front|back)$/))) {\n          const n = cornerPostNumberOf(cabinets.find(c => c.id === m[1]), m[2], m[3]);\n          if (n != null) out.add(Number(n));\n        }\n      }\n    } catch (e) { /* show every number rather than fail */ }\n    return out;\n  }\n  // After a line is excluded / put back: redraw the plan's piece numbers.\n  // Read-only look at the panel boards (support / testing): each board, its\n  // number and the pieces cut from it.\n  window.__btkEpBoards = () => ((endPanelLayout && endPanelLayout.boards) || []).map(b => ({\n    n: b.itemNumber, owner: b.ownerCabId, code: b.code, key: boardLineKey(b),\n    pieces: (b.pieces || []).map(p => ({ role: p.role, side: p.face && p.face.side, cabIds: p.face && p.face.cabIds }))\n  }));\n  function refreshHiddenPlanNumbers() {\n    try {\n      const hid = excludedPlanNumbers();\n      root.querySelectorAll('.btk-kp-cabinet-th-corner-post > .btk-kp-cabinet-number').forEach(b => {\n        b.style.display = hid.has(Number(b.textContent.trim())) ? 'none' : '';\n      });\n      relayoutBadgesSoon();\n    } catch (e) { /* cosmetic */ }\n  }\n\n  function selectCornerPost(cabId, side, pos) {\n    selectItem({ kind: 'cpost', cabinetId: cabId, side, pos });\n    focusBasketLineForFace(cabId, `${side}:cpost${pos === 'back' ? '-back' : ''}`);\n  }\n\n  function selectEndPanelFace(cabId, side) {\n    // A profile reaches here from a 3D click on its mesh ('rail-left').\n    const _rm = String(side || '').match(/^rail-(left|right)$/);\n    if (_rm) { selectRail(cabId, _rm[1]); return; }\n    const _cm = String(side || '').match(/^(left|right):cpost(-back)?$/);\n    if (_cm) { selectCornerPost(cabId, _cm[1], _cm[2] ? 'back' : 'front'); return; }\n    selectItem({ kind: 'end-panel', cabinetId: cabId, side });\n    // Reverse of clicking a basket line: slide the matching panel / feature\n    // line into view and open it, the same as clicking a unit does.\n    focusBasketLineForFace(cabId, side);\n  }\n\n  // Order room walls clockwise starting from the TOP wall (Wall A), so\n  // the numbering sweep + basket sections both begin top-left and run\n  // clockwise (top \u2192 right \u2192 bottom \u2192 left). Screen coords are y-DOWN,\n  // so ascending atan2 walks clockwise as drawn.\n  function wallOrderClockwiseFromTop(walls) {\n    const idx = walls.map((_, i) => i);\n    if (idx.length <= 1) return idx;\n    const mids = walls.map(w => ({ x: (w.from.x + w.to.x) / 2, y: (w.from.y + w.to.y) / 2 }));\n    const cx = mids.reduce((s, m) => s + m.x, 0) / mids.length;\n    const cy = mids.reduce((s, m) => s + m.y, 0) / mids.length;\n    idx.sort((a, b) =>\n      Math.atan2(mids[a].y - cy, mids[a].x - cx) - Math.atan2(mids[b].y - cy, mids[b].x - cx));\n    // Rotate so the sweep starts at the TOP-most wall (smallest mid y;\n    // leftmost on a tie) - the top-left start the user expects.\n    let startK = 0, best = Infinity;\n    idx.forEach((wi, k) => {\n      const score = mids[wi].y * 1e6 + mids[wi].x;   // top first, then left\n      if (score < best) { best = score; startK = k; }\n    });\n    return idx.slice(startK).concat(idx.slice(0, startK));\n  }\n\n  // Which wall (index + position t along it) a cab sits against - radius-group\n  // aware. A radius end-of-run CURVE has its own footprint ~270mm off the wall\n  // (the backing reaches it), so it projects as an island on its own; inherit\n  // the wall of a group companion that IS against a wall, positioned by the\n  // curve's own plan centre. Shared by item numbering AND basket sectioning so\n  // both treat the whole assembly as one wall run. Returns { wi, t } or null.\n  function cabWallSlot(cab, cabs, walls, order) {\n    for (const i of order) {\n      const info = projectCabinetOntoWall(cab, walls[i], 60);\n      if (info) return { wi: i, t: info.t };\n    }\n    if (cab.radiusUnit && cab.groupId) {\n      for (const m of cabs) {\n        if (m.id === cab.id || m.groupId !== cab.groupId) continue;\n        for (const i of order) {\n          if (!projectCabinetOntoWall(m, walls[i], 60)) continue;\n          const w = walls[i], dx = w.to.x - w.from.x, dy = w.to.y - w.from.y;\n          const len = Math.hypot(dx, dy) || 1;\n          const aabb = getEffectiveAABB(cab, cab.x, cab.y);\n          const cx = aabb.x + aabb.widthMm / 2, cy = aabb.y + aabb.depthMm / 2;\n          return { wi: i, t: ((cx - w.from.x) * dx + (cy - w.from.y) * dy) / len };\n        }\n      }\n    }\n    return null;\n  }\n\n  // SINGLE source of truth for item numbering. One clockwise sweep from\n  // the bottom-left: for each wall, every unit on it (ANY category) by\n  // position, and immediately after each unit its end-panel BOARD(s)\n  // (first-seen) - so a panel's number sits with its unit and the wall-\n  // grouped basket reads sequentially. Islands (+ their panels) come\n  // last. Sets cab.displayNumber + board.itemNumber + board.ownerCabId\n  // and returns the end-panel layout (boards + lookups).\n\n  // True Handleless tall unit's GRIP (non-hinge) side, or null if the cab\n  // isn't a TH tall unit. Grip = the side opposite the hinge (hingeSide left \u2192\n  // grip right, & vice-versa). Depends ONLY on the cab, so it's safe to call\n  // for a neighbour before that neighbour's own rail fields are stamped.\n  function thGripSide(cab) {\n    if (!cab) return null;\n    const isTH = /^tall/i.test(cab.category || '')\n      && !!(Catalogue.isStyleTrueRail && Catalogue.isStyleTrueRail(cab.kitchenStyleId));\n    if (!isTH) return null;\n    return (String(cab.hingeSide || '').toLowerCase() === 'left') ? 'right' : 'left';\n  }\n\n  // True Handleless base fronts are 685 high, under the 37mm rail band at the\n  // top of the carcase - as the Single Highline Base Unit's schema has them\n  // (y 37, height 685). Several base unit types are authored full height\n  // (y 2, height 716: pull-outs, bin stores, the single sink base) or 685 from\n  // the top (y 2: bin store, LAVA / Planero corners), and the integrated\n  // dishwasher doors are shared by every range, so in a True Handleless range\n  // those fronts came out 715 with no rail gap (bug sheet, Julian, 2026-10-19).\n  // A front that starts at the top and reaches the bottom of a 720 base\n  // carcase on a plinth is moved under the rail band. Blanks, open shelves,\n  // fillers and appliance apertures are left as authored; other ranges, wall\n  // and tall units never change. Idempotent (a moved front no longer starts\n  // at the top), so it only allocates the first time. The authored schema\n  // rides along (not saved): a restyle keeps the unit's schema, so a shared\n  // unit (the dishwasher door) moved to a handled range gets it back here.\n  const TH_BASE_FRONT_TOP_MM = 37;\n  const TH_BASE_FRONT_H_MM = 685;\n  const TH_BASE_FRONT_TYPES = new Set(['door', 'drawer', 'topdrawer', 'glass']);\n  function thBaseFrontSchema(cab) {\n    const sch = cab && cab.cutoutSchema;\n    if (!sch || !Array.isArray(sch.openings)) return sch;\n    const ut = cab.unitTypeId && Catalogue.getUnitType ? Catalogue.getUnitType(cab.unitTypeId) : null;\n    const plinth = (ut && ut.plinthHeightMm) || 0;\n    if (!cab.isTrueRail || plinth <= 0 || Math.abs((cab.heightMm || 0) - plinth - 720) > 5) {\n      return sch._thAuthored || sch;\n    }\n    let changed = false;\n    const openings = sch.openings.map(o => {\n      if (!o || !TH_BASE_FRONT_TYPES.has(o.type)) return o;\n      const y = Number(o.y), h = Number(o.height);\n      if (!(y < TH_BASE_FRONT_TOP_MM - 5) || !(y + h >= 680)) return o;\n      changed = true;\n      return { ...o, y: TH_BASE_FRONT_TOP_MM, height: TH_BASE_FRONT_H_MM };\n    });\n    if (!changed) return sch;\n    const out = { ...sch, openings };\n    Object.defineProperty(out, '_thAuthored', { value: sch, enumerable: false });\n    return out;\n  }\n\n  // The door hand used to ride a Shopify Hinge VARIANT, which re-resolved the\n  // cutout schema's door openings per hand. Hinge is no longer a variant, so a\n  // freshly resolved schema carries only its AUTHORED (default) hand. Stamp the\n  // live hand onto the snapshot's hinged door openings so the MULTI-door render\n  // paths that read op.hingeSide (2D `doorRelative` swings + 3D multi-door\n  // leaves) follow the toggle, like the rail already does via railGripSide.\n  //\n  // CONVENTION: for a multi-door leaf both renderers use op.hingeSide as\n  // DOOR-LOCAL (\"left\" = the door's own local/CSS-left edge) with NO\n  // user->local flip - and door-local is the OPPOSITE of the user-perspective\n  // cab.hingeSide (a user-LEFT hinge sits on the door's local-RIGHT edge). So\n  // stamp the OPPOSITE side. Single-door units read cab.hingeSide directly and\n  // ignore op.hingeSide, so stamping them is harmless (kept simple: stamp all).\n  //\n  // Restricted to hinge-SELECTABLE units: corner posts and asymmetric\n  // fixed-hand pairs keep their authored side; fixed/dummy fronts and\n  // top/bottom (flap) hangs are untouched. Idempotent once aligned (returns the\n  // same schema), so it only allocates on an actual hinge change.\n  function hingeStampedSchema(cab) {\n    const sch = cab && cab.cutoutSchema;\n    if (!cab || !cab.hingeSelectable || !sch || !Array.isArray(sch.openings)) return sch;\n    const userSide = String(cab.hingeSide || '').toLowerCase();\n    if (userSide !== 'left' && userSide !== 'right') return sch;   // flap / unset: nothing to stamp\n    const localSide = (userSide === 'left') ? 'right' : 'left';    // door-local = opposite user\n    let changed = false;\n    const openings = sch.openings.map(o => {\n      if (!o || o.type !== 'door' || o.fixed === true || o.dummy === true) return o;\n      const os = String(o.hingeSide || '').toLowerCase();\n      if (os === 'top' || os === 'bottom') return o;       // authored flap - no L/R hand\n      if (os === localSide) return o;\n      changed = true;\n      return { ...o, hingeSide: localSide };\n    });\n    return changed ? { ...sch, openings } : sch;\n  }\n\n  // ---- CEILING FILLER (Customise > Cornice, Pelmet & Plinth) ----\n  // Instead of a cornice: a continuous filler panel, flush with the doors, from\n  // the top of each wall / bridging / tall unit up to the room's ceiling height;\n  // the wall and tall end panels run up to the ceiling too. Pieces are joined\n  // over a unit joint (never longer than a 2400 board), and go through the end\n  // panel cut list like any panel, so they are numbered, priced and drawn the\n  // same way (Arden, 2026-10-21). Flat ceiling height only - a sloped ceiling\n  // over a run gets an Advisory to measure on site.\n  const CEILING_FILLER = 'ceiling-filler';\n  const CEILING_FILLER_MAX_MM = 2400;\n  function ceilingFillerOn() { return (featureStyles || {}).cornice === CEILING_FILLER; }\n  function roomCeilingMm() { return Number(roomConfig && roomConfig.ceilingHeightMm) || 2400; }\n  function buildCeilingFillerFaces(cabsAll, doorT, epFaces) {\n    const out = { faces: [], topByCab: new Map() };\n    const trim = computeTrimRuns({\n      cabinets: cabsAll,\n      featureStyles: { ...(featureStyles || {}), cornice: 'modern' },   // the cornice PATH\n      roomVertices: room?.vertices || [],\n      perimeterItems: roomConfig?.perimeterItems || [],\n      doorThicknessMm: doorT || 18\n    });\n    const cr = trim && trim.cornice;\n    if (!cr || !cr.runs) return out;\n    const ceil = roomCeilingMm();\n    // A cornice segment's line is its slab's CENTRE (front face less half the\n    // profile depth); the filler's line is its FRONT face, on the door front,\n    // flush with the doors (Arden, 2026-10-21: it sat back at the carcase front).\n    const shift = (doorT || 18) - ((cr.frontOffMm || 0) - (cr.profileDepthMm || 0) / 2);\n    // Every front segment's line, to tell an OPEN end (stops at the end panel)\n    // from one meeting another run at an internal corner (runs on into it).\n    const allFronts = [];\n    for (const run of cr.runs) for (const sg of (run.segments || [])) {\n      if (sg.kind === 'front' && !sg._suppress) allFronts.push(sg);\n    }\n    const meetsOther = (seg, pt) => allFronts.some(o => {\n      if (o === seg || (seg.members && seg.members.has(o))) return false;\n      const dx = o.p2.x - o.p1.x, dy = o.p2.y - o.p1.y, L = Math.hypot(dx, dy) || 1;\n      // a corner only: a run in line (a wall unit beside a tall one) is met by\n      // the tall unit's end panel, so it still stops\n      if (Math.abs((o.nx || 0) * (seg.ny || 0) - (o.ny || 0) * (seg.nx || 0)) < 0.5) return false;\n      const t = ((pt.x - o.p1.x) * dx + (pt.y - o.p1.y) * dy) / L;\n      const off = Math.abs((pt.x - o.p1.x) * dy - (pt.y - o.p1.y) * dx) / L;\n      return off < 80 && t > -80 && t < L + 80;\n    });\n    // Where the filler stops at a unit's side facing (dx, dy) - along the run,\n    // past the carcase side - when a real end panel stands there: one in the\n    // priced end-panel faces (a side flagged active but hidden inside a corner\n    // unit doesn't count). The panel's inside face is out past the carcase by\n    // a True Handleless vertical profile (TH_RAIL_GAP_MM) on that side and a\n    // freestanding appliance's fitting gap. null = no panel.\n    // (Cabinet-local +X is the panel the customer calls LEFT.)\n    const panelStandOff = (c, dx, dy) => {\n      if (!c) return null;\n      const th = ((c.rotationDeg || 0) * Math.PI) / 180;\n      const side = (dx * Math.cos(th) + dy * Math.sin(th)) > 0 ? 'left' : 'right';\n      const real = (epFaces || []).some(f => (f.role === 'wall' || f.role === 'tall') && f.side === side\n        && (f.cabIds || []).includes(c.id));\n      if (!real) return null;\n      const rail = (c.railGripSide === side || c.railSecondSide === side) ? TH_RAIL_GAP_MM : 0;\n      return rail + Math.max(0, Number(c.endPanelGapMm) || 0);\n    };\n    // Every real end panel on plan, as a rectangle in its unit's frame (local\n    // +X = the LEFT panel, -Y = front; door-deep, standing off the carcase as\n    // panelStandOff says). A filler line crossing one is cut back to it - a\n    // panel goes up to the ceiling, so nothing runs through it.\n    const panelRects = [];\n    for (const f of (epFaces || [])) {\n      if ((f.role !== 'wall' && f.role !== 'tall') || f.featureKind) continue;\n      for (const id of (f.cabIds || [])) {\n        const c = cabsAll.find(x => x.id === id);\n        if (!c) continue;\n        const th = ((c.rotationDeg || 0) * Math.PI) / 180, cs = Math.cos(th), sn = Math.sin(th);\n        const w = c.widthMm, d = c.depthMm;\n        const so = panelStandOff(c, f.side === 'left' ? cs : -cs, f.side === 'left' ? sn : -sn) || 0;\n        const T = endPanelThickMm((c.endPanels || {})[f.side] || 'flat');\n        const x0 = w / 2 + so, x1 = x0 + T;\n        panelRects.push({ cx: c.x + w / 2, cy: c.y + d / 2, cs, sn,\n                          lx0: f.side === 'left' ? x0 : -x1, lx1: f.side === 'left' ? x1 : -x0,\n                          ly0: d / 2 - (d + (doorT || 18)), ly1: d / 2 });\n      }\n    }\n    // The stretch [lo, hi] of the line P + U*t that runs inside rectangle r.\n    const throughRect = (P0, ux, uy, r) => {\n      const toL = (x, y) => ({ x: (x - r.cx) * r.cs + (y - r.cy) * r.sn, y: -(x - r.cx) * r.sn + (y - r.cy) * r.cs });\n      const p = toL(P0.x, P0.y), q = toL(P0.x + ux, P0.y + uy);\n      const dx = q.x - p.x, dy = q.y - p.y;\n      let lo = -Infinity, hi = Infinity;\n      for (const [pv, dv, mn, mx] of [[p.x, dx, r.lx0, r.lx1], [p.y, dy, r.ly0, r.ly1]]) {\n        if (Math.abs(dv) < 1e-9) { if (pv <= mn + 0.5 || pv >= mx - 0.5) return null; continue; }\n        let t0 = (mn - pv) / dv, t1 = (mx - pv) / dv;\n        if (t0 > t1) [t0, t1] = [t1, t0];\n        lo = Math.max(lo, t0); hi = Math.min(hi, t1);\n      }\n      return hi - lo > 0.5 ? { lo, hi } : null;\n    };\n    // The filler lines: front segments, at the door front. Segments in line on\n    // the same band with only a small gap between them - the slot of a True\n    // Handleless vertical profile between two tall units - are ONE line, so\n    // the filler runs on over the profile (Arden, 2026-10-21).\n    const lines = [];\n    for (const run of cr.runs) {\n      for (const seg of (run.segments || [])) {\n        for (const id of (seg.cabinetIds || [])) out.topByCab.set(id, Math.max(out.topByCab.get(id) || 0, run.bandY || 0));\n        // Fronts only: an exposed end is closed by its end panel, which runs\n        // to the ceiling - so no return, and no external corner.\n        if (seg.kind !== 'front' || seg._suppress) continue;\n        const nx = seg.nx || 0, ny = seg.ny || 0;\n        const a = { x: seg.p1.x + nx * shift, y: seg.p1.y + ny * shift };\n        const b = { x: seg.p2.x + nx * shift, y: seg.p2.y + ny * shift };\n        if (!(Math.hypot(b.x - a.x, b.y - a.y) > 1)) continue;\n        const host = lines.find(o => {\n          if (Math.abs(o.bandY - (run.bandY || 0)) > 1 || (o.nx * nx + o.ny * ny) < 0.999) return false;\n          const oL = Math.hypot(o.b.x - o.a.x, o.b.y - o.a.y) || 1;\n          const ox = (o.b.x - o.a.x) / oL, oy = (o.b.y - o.a.y) / oL;\n          if (Math.abs((a.x - o.a.x) * oy - (a.y - o.a.y) * ox) > 2) return false;     // not in line\n          const t1 = (a.x - o.a.x) * ox + (a.y - o.a.y) * oy, t2 = (b.x - o.a.x) * ox + (b.y - o.a.y) * oy;\n          return Math.min(t1, t2) <= oL + 60 && Math.max(t1, t2) >= -60;              // a gap of 60 at most\n        });\n        if (!host) {\n          lines.push({ a, b, p1: seg.p1, p2: seg.p2, nx, ny, bandY: run.bandY || 0,\n                       id: seg.id || (run.id + '-' + lines.length),\n                       cabinetIds: [...(seg.cabinetIds || [])], members: new Set([seg]) });\n          continue;\n        }\n        const oL = Math.hypot(host.b.x - host.a.x, host.b.y - host.a.y) || 1;\n        const ox = (host.b.x - host.a.x) / oL, oy = (host.b.y - host.a.y) / oL;\n        const ts = [0, oL, (a.x - host.a.x) * ox + (a.y - host.a.y) * oy, (b.x - host.a.x) * ox + (b.y - host.a.y) * oy];\n        const lo = Math.min(...ts), hi = Math.max(...ts);\n        const A0 = { ...host.a }, P0 = { ...host.p1 };   // the raw ends follow, for the corner test\n        host.a  = { x: A0.x + ox * lo, y: A0.y + oy * lo };\n        host.b  = { x: A0.x + ox * hi, y: A0.y + oy * hi };\n        host.p1 = { x: P0.x + ox * lo, y: P0.y + oy * lo };\n        host.p2 = { x: P0.x + ox * hi, y: P0.y + oy * hi };\n        host.cabinetIds.push(...(seg.cabinetIds || []));\n        host.members.add(seg);\n      }\n    }\n    for (const seg of lines) {\n      {\n        const gapMm = ceil - seg.bandY;\n        if (!(gapMm > 0)) continue;\n        const run = { bandY: seg.bandY, id: seg.id };\n        const nx = seg.nx, ny = seg.ny, a = seg.a, b = seg.b;\n        let L = Math.hypot(b.x - a.x, b.y - a.y);\n        if (!(L > 1)) continue;\n        const ux = (b.x - a.x) / L, uy = (b.y - a.y) / L;\n        const cabsHere = [...new Set(seg.cabinetIds)].map(id => cabsAll.find(c => c.id === id)).filter(Boolean);\n        if (!cabsHere.length) continue;\n        // Each unit's span along the run - its edges are the unit joints.\n        const spans = cabsHere.map(c => {\n          const bb = getEffectiveAABB(c, c.x, c.y);\n          const ts = [[bb.x, bb.y], [bb.x + bb.widthMm, bb.y], [bb.x, bb.y + bb.depthMm], [bb.x + bb.widthMm, bb.y + bb.depthMm]]\n            .map(([px, py]) => (px - a.x) * ux + (py - a.y) * uy);\n          return { c, t0: Math.min(...ts), t1: Math.max(...ts) };\n        });\n        const joints = [...new Set(spans.flatMap(s => [s.t0, s.t1]).map(t => Math.round(t)))]\n          .filter(t => t > 1 && t < L - 1).sort((p, q) => p - q);\n        // An open end stops at the inside face of its end panel - the cornice\n        // ran over the panel; the panel now runs to the ceiling (Arden,\n        // 2026-10-21). Only when that unit's side is at the end (a unit tucked\n        // behind a corner unit's return isn't). An end meeting another run\n        // carries on into the corner.\n        const sp0 = spans.reduce((m, sp) => (!m || sp.t0 < m.t0 ? sp : m), null);\n        const sp1 = spans.reduce((m, sp) => (!m || sp.t1 > m.t1 ? sp : m), null);\n        let s0 = 0, s1 = L;\n        if (!meetsOther(seg, seg.p1) && Math.abs(sp0.t0) <= 80) {\n          const so = panelStandOff(sp0.c, -ux, -uy);\n          if (so != null) s0 = Math.min(L, sp0.t0 - so);\n        }\n        if (!meetsOther(seg, seg.p2) && Math.abs(sp1.t1 - L) <= 80) {\n          const so = panelStandOff(sp1.c, ux, uy);\n          if (so != null) s1 = Math.max(0, sp1.t1 + so);\n        }\n        // Stop at every end panel standing across the line - at an end, or\n        // between two units mid-run - and carry on past it (tested through\n        // the middle of the filler board, 9mm behind its face).\n        let ranges = [[s0, s1]];\n        {\n          const mid = { x: a.x - nx * 9, y: a.y - ny * 9 };\n          for (const r of panelRects) {\n            const hit = throughRect(mid, ux, uy, r);\n            if (!hit) continue;\n            ranges = ranges.flatMap(([r0, r1]) => (hit.hi <= r0 + 0.5 || hit.lo >= r1 - 0.5) ? [[r0, r1]]\n              : [[r0, Math.min(r1, hit.lo)], [Math.max(r0, hit.hi), r1]].filter(([q0, q1]) => q1 - q0 > 1));\n          }\n          // a sliver left past a panel (a unit's filler stub poking through it)\n          // isn't a piece anyone would cut. A panel across the WHOLE line\n          // leaves no range at all - nothing to fill (a hand-placed wall end\n          // panel hung over Jonathan Print's units read ranges[0] of none and\n          // stopped the plan loading, 2026-10-23).\n          if (ranges.length !== 1 || ranges[0][0] !== s0 || ranges[0][1] !== s1) ranges = ranges.filter(([q0, q1]) => q1 - q0 >= 25);\n        }\n        let k = 0;\n        for (const [r0, r1] of ranges) {\n        L = r1;\n        let start = r0;\n        while (L - start > 1 && k < 50) {\n          let end = L;\n          if (L - start > CEILING_FILLER_MAX_MM) {\n            // Joined over a unit joint: the farthest one a board still reaches.\n            const ok = joints.filter(t => t > start + 1 && t <= start + CEILING_FILLER_MAX_MM);\n            end = ok.length ? ok[ok.length - 1] : start + CEILING_FILLER_MAX_MM;\n          }\n          const mid = (start + end) / 2;\n          const owner = (spans.find(s => mid >= s.t0 - 1 && mid <= s.t1 + 1) || spans[0]).c;\n          const side = 'ceil-' + String(seg.id || (run.id + '-' + k)).replace(/[^a-z0-9-]/gi, '_') + '-' + k;\n          out.faces.push({\n            id: `${owner.id}:${side}`, role: 'ceiling',\n            depthMm: Math.round(gapMm), heightMm: Math.round(end - start),\n            side, cabIds: [owner.id],\n            styleId: owner.kitchenStyleId || null,\n            colour: owner.doorColourHandle || globalDoorColourHandle || null,\n            finish: 'plain',\n            px: a.x + ux * mid, py: a.y + uy * mid,\n            ceil: { x1: a.x + ux * start, y1: a.y + uy * start, x2: a.x + ux * end, y2: a.y + uy * end,\n                    nx, ny, bottomY: run.bandY || 0, topY: ceil }\n          });\n          start = end; k++;\n        }\n        }\n      }\n    }\n    return out;\n  }\n  // Wall and tall end panels run up to the ceiling. One a single board can't\n  // hold (over 2400) is joined at the top of the unit line: the panel as it is,\n  // plus a piece from there to the ceiling.\n  function extendEndPanelsToCeiling(faces, topByCab) {\n    const ceil = roomCeilingMm();\n    const out = [];\n    for (const f of faces) {\n      if ((f.role !== 'wall' && f.role !== 'tall') || f.featureKind) { out.push(f); continue; }\n      const top = Math.max(0, ...(f.cabIds || []).map(id => topByCab.get(id) || 0));\n      if (!(top > 0) || !(ceil > top + 0.5)) { out.push(f); continue; }\n      const extra = ceil - top;\n      if (f.heightMm + extra <= CEILING_FILLER_MAX_MM + 0.5) { out.push({ ...f, heightMm: f.heightMm + extra }); continue; }\n      out.push(f);\n      out.push({ ...f, id: f.id + ':ceil', side: f.side + ':ceil', heightMm: Math.round(extra) });\n    }\n    return out;\n  }\n  // The plan's priced cost of a nesting (boards that can't be priced, or\n  // pieces that fit no board, count heavily) - to pick the cheaper way.\n  function nestCostCents(n) {\n    let t = 0;\n    for (const b of (n.boards || [])) {\n      const p = endPanelBoardProduct(b, b.styleId);\n      t += (p && typeof p.priceCents === 'number') ? p.priceCents : 1e7;\n    }\n    return t + ((n.unplaced || []).length * 1e7);\n  }\n\n  function computeNumberingAndLayout() {\n    stampFreestandingPanels(cabinets);\n    // Stamp True-Handleless on every cab so 2D/3D read it directly (like\n    // railGripSide) without threading the catalogue through the renderers.\n    for (const _c of cabinets) {\n      _c.isTrueRail = !!(Catalogue.isStyleTrueRail && Catalogue.isStyleTrueRail(_c.kitchenStyleId));\n      // PER-RANGE end-panel thickness. Stamped onto each SIDE (not just the\n      // cab) because every consumer - 2D, 3D, worktops, trims, the settle /\n      // adjacency maths - calls endPanelThickMm(side) and would otherwise fall\n      // back to the hardcoded 20mm. Radius / square / TH ignore it (fixed\n      // assembly sizes); only plain + T&G vary by range.\n      {\n        const _ks  = Catalogue.getKitchenStyle && Catalogue.getKitchenStyle(_c.kitchenStyleId);\n        const _epSet = _ks && ((_ks.doorGeometry && _ks.doorGeometry.endPanel) || _ks.endPanel);\n        const _tRaw = _epSet && _epSet.thicknessMm;\n        const _t = (typeof _tRaw === 'number' && _tRaw > 0) ? _tRaw : null;\n        const _eps = _c.endPanels;\n        if (_eps) {\n          if (_eps.left)  _eps.left.thickMm  = _t;\n          if (_eps.right) _eps.right.thickMm = _t;\n        }\n        stampManualEndPanels(_c, _ks);\n        // How far this unit's doors / drawer fronts stand proud of the carcase\n        // (the range's door thickness), for the placement engine, which has no\n        // catalogue: a free-placed end panel lines up with the door front as\n        // well as the carcase front. 0 for anything without a front.\n        const _hasFront = !_c.endPanelUnit && !_c.endPanelFiller && !_c.freestandingAppliance\n          && !!(_c.cutoutSchema && Array.isArray(_c.cutoutSchema.openings) && _c.cutoutSchema.openings.length);\n        _c.doorFaceMm = _hasFront ? ((_ks && _ks.doorThicknessMm) || 18) : 0;\n      }\n      // Keep the door openings' hand in sync with the live hinge toggle (see\n      // hingeStampedSchema) - now that hinge isn't a variant re-resolving it.\n      _c.cutoutSchema = hingeStampedSchema(_c);\n      _c.cutoutSchema = thBaseFrontSchema(_c);\n    }\n    // FILLER CORNER MITRES. Two fillers that meet in a corner are drawn cut\n    // to the mitre. Derived like thickMm above - recomputed from where the\n    // units are now, never trusted from a save - and stamped per side as the\n    // lengths of the filler's two long edges, measured out from the carcase\n    // side: `frontMm` on the door face, `backMm` on the carcase front. 2D,\n    // 3D and the worktop rebuild the mitred strip from those two numbers.\n    {\n      const _mitres = activeFillerCorners({ reaching: true });\n      for (const _c of cabinets) {\n        const _f = _c.fillers;\n        if (!_f) continue;\n        for (const _s of ['left', 'right']) {\n          if (!_f[_s]) continue;\n          const _h = _mitres.get(_c.id + ':' + _s);\n          if (_h) {\n            _f[_s].mitre = { frontMm: _h.frontMm, backMm: _h.backMm,\n                             partner: _h.partner, pFront: _h.pFront, pBack: _h.pBack };\n          } else if (_f[_s].mitre) {\n            delete _f[_s].mitre;\n          }\n        }\n      }\n    }\n    const { doorThicknessMm, hasPanelProduct, backPanelStock } = panelFaceOpts();\n    let faces  = collectEndPanelFaces(cabinets, { doorThicknessMm, hasPanelProduct, backPanelStock });\n    // A DOOR END PANEL (Sales sheet line 110) is drawn as an inline panel but\n    // bought as the range's door (doorEndItemsOwnedBy), not cut from a board.\n    faces = faces.filter(f => f.role === 'filler' || !f.side || !(f.cabIds || [String(f.id || '').split(':')[0]]).some(id => {\n      const c = cabinets.find(x => x && x.id === id);\n      return !!(c && c.endPanels && c.endPanels[f.side] && c.endPanels[f.side].doorEnd);\n    }));\n    // CEILING FILLER: taller wall / tall end panels + the filler pieces.\n    for (const c of cabinets) { if (c) { c.ceilingFillerPieces = null; c.ceilingFillerTop = null; } }\n    let _ceilFaces = [];\n    if (ceilingFillerOn()) {\n      const _cf = buildCeilingFillerFaces(cabinets, doorThicknessMm || 18, faces);\n      faces = extendEndPanelsToCeiling(faces, _cf.topByCab).concat(_cf.faces);\n      _ceilFaces = _cf.faces;\n      const _ceil = roomCeilingMm();\n      for (const [id, top] of _cf.topByCab) {\n        const c = cabinets.find(x => x.id === id);\n        if (c && _ceil > top) c.ceilingFillerTop = _ceil;   // 3D: end panels to here\n      }\n    }\n    // Media Wall rear panels: Tall End Panel pieces nest with the rest; an\n    // acoustic one is billed below like a breakfast bar acoustic back.\n    faces = faces.concat(mediaPanelFaces(cabinets));\n    // A plinth over 150mm (row 95) is cut from Tall End Panel boards.\n    faces = faces.concat(tallPlinthFaces(cabinets));\n    // Filler source stock from the filler unit_types (data-driven, no\n    // hardcoded dims): each carries unit_type_code + carcase_height_mm +\n    // stock_width_mm. Smallest \u2192 largest so the cheaper source is used\n    // first. Board code = the filler's code so it prices via its product.\n    const fillerStock = (Catalogue.getUnitTypes?.() || [])\n      .filter(u => u.unitTypeGroupHandle === 'filler-panels' && u.code && u.carcaseHeightMm > 0 && u.stockWidthMm > 0)\n      .map(u => ({ type: 'filler', code: u.code, depthMm: u.stockWidthMm, heightMm: u.carcaseHeightMm }))\n      .sort((a, b) => (a.depthMm * a.heightMm) - (b.depthMm * b.heightMm));\n    // Back-panel SEGMENTS onto each cabinet, so 2D and 3D draw (and highlight)\n    // each panel of a split run separately rather than one slab per unit.\n    stampBackPanelSegments(cabinets, faces);\n    // Acoustic panelling backs (backPanelFinish 'acoustic') are bought in whole\n    // panels, not cut from the range's boards: kept out of the nester, and each\n    // added below as a board of its own so it is numbered, owned by a unit and\n    // billed like one (boardItemFor -> acousticItemsFor).\n    let nested = nestPanels(faces.filter(f => !f.acoustic), { fillerStock });\n    // CEILING FILLER pieces are panels (cut from end panel boards) - or, where\n    // the gap is no deeper than a plinth length, plinth stock. Whichever the\n    // whole cut list prices cheaper is used (Arden: \"whichever works out best\").\n    if (_ceilFaces.length && fillerStock.length) {\n      const _maxW = Math.max(...fillerStock.map(s => s.depthMm || 0));\n      const _asFiller = faces.map(f => (f.role === 'ceiling' && f.depthMm <= _maxW) ? { ...f, role: 'filler' } : f);\n      if (_asFiller.some((f, i) => f !== faces[i])) {\n        const _alt = nestPanels(_asFiller.filter(f => !f.acoustic), { fillerStock });\n        if (nestCostCents(_alt) < nestCostCents(nested)) { nested = _alt; faces = _asFiller; }\n      }\n    }\n    if (_ceilFaces.length && (nested.unplaced || []).some(f => String(f.side || '').startsWith('ceil'))) {\n      console.warn('[BTK ceiling filler] pieces too big for any board - NOT charged:',\n        nested.unplaced.filter(f => String(f.side || '').startsWith('ceil')).map(f => f.id));\n    }\n    for (const f of faces) {\n      if (!f.acoustic) continue;\n      nested.boards.push({ type: 'acoustic', acoustic: true, code: 'ACOUSTIC', finish: 'acoustic',\n                           styleId: f.styleId || null, colour: null,\n                           acousticHandle: f.acousticHandle || null,\n                           runMm: f.runMm || 0, heightMm: f.panelHeightMm || 0,\n                           pieces: [{ face: f, role: 'acoustic-back' }] });\n    }\n    const boardOf = new Map();        // face.id \u2192 board\n    for (const b of nested.boards) { b.itemNumber = null; b.ownerCabId = null; for (const p of b.pieces) boardOf.set(p.face.id, b); }\n\n\n    // Set window.BTK_FILLER_DEBUG = true in the console then nudge a unit to\n    // re-render: this prints why fillers do / don't become their own basket\n    // line (empty stock, absorbed into an off-cut, or no matching product).\n    if (typeof window !== 'undefined' && window.BTK_FILLER_DEBUG) {\n      const fillerFaces = faces.filter(f => f.role === 'filler');\n      const placement = {};\n      for (const b of nested.boards)\n        for (const p of b.pieces)\n          if (String(p.face.id).includes(':filler:'))\n            placement[p.face.id] = { boardType: b.type, boardCode: b.code };\n      console.log('[BTK_FILLER_DEBUG] fillerStock (from filler-panels unit_types):', fillerStock);\n      console.log('[BTK_FILLER_DEBUG] filler faces detected:', fillerFaces.length,\n        fillerFaces.map(f => ({ id: f.id, depthMm: f.depthMm, heightMm: f.heightMm })));\n      console.log('[BTK_FILLER_DEBUG] own filler-stock boards opened:',\n        nested.boards.filter(b => b.type === 'filler').length);\n      console.log('[BTK_FILLER_DEBUG] where each filler landed:', placement);\n      console.log('[BTK_FILLER_DEBUG] unplaced faces:', (nested.unplaced || []).map(f => f.id));\n    }\n\n    const walls = getWalls(room);\n    const order = wallOrderClockwiseFromTop(walls);\n    const rankByWall = new Map(order.map((wi, k) => [wi, k]));\n    // A cabinet's wall + position along it (null = island / free unit).\n    const cabLoc = (cab) => {\n      const slot = cabWallSlot(cab, cabinets, walls, order);\n      return slot ? { rank: rankByWall.get(slot.wi), wi: slot.wi, t: slot.t } : null;\n    };\n    // Position of a plan point along a wall.\n    const pointT = (px, py, wi) => {\n      const w = walls[wi]; const dx = w.to.x - w.from.x, dy = w.to.y - w.from.y;\n      const len = Math.hypot(dx, dy) || 1;\n      return ((px - w.from.x) * dx + (py - w.from.y) * dy) / len;\n    };\n    const unitLocById = new Map();\n    for (const cab of cabinets) {\n      if (cab.excludeFromQuote) { cab.displayNumber = null; continue; }\n      unitLocById.set(cab.id, cabLoc(cab));\n    }\n\n    // ONE flat list of numberable pieces - every unit AND every face\n    // (end panel / back panel / filler). A face takes its primary unit's\n    // wall, positioned by the face's own plan point so it sorts where it\n    // actually sits in the run.\n    const entries = [];\n    for (const cab of cabinets) {\n      if (cab.excludeFromQuote) continue;\n      // Radius fillers are numbered as a FACE (a small off-cut), not a unit \u2014\n      // skip them here so they don't get a SECOND (unit) number in the 2D plan.\n      if (cab.radiusGroup && cab.radiusGroup.role === 'filler') { cab.displayNumber = null; continue; }\n      // Free-placed panels / fillers are likewise numbered by the BOARD they're\n      // cut from - stamped back onto the cab below, so the 2D badge on the panel\n      // and its basket line show the same number.\n      if (cab.endPanelUnit) { cab.displayNumber = null; continue; }\n      const aabb = getEffectiveAABB(cab, cab.x, cab.y);\n      entries.push({ kind: 'unit', cab, loc: unitLocById.get(cab.id),\n                     ix: aabb.x + aabb.widthMm / 2, iy: aabb.y + aabb.depthMm / 2 });\n    }\n    for (const f of faces) {\n      const ul = (f.cabIds && f.cabIds.length) ? unitLocById.get(f.cabIds[0]) : null;\n      const loc = ul ? { rank: ul.rank, t: pointT(f.px, f.py, ul.wi) } : null;\n      entries.push({ kind: 'face', face: f, loc, ix: f.px, iy: f.py });\n    }\n    // Sweep order: wall rank (islands last), then position along the wall;\n    // islands top-to-bottom then left-to-right.\n    entries.sort((a, b) => {\n      const ar = a.loc ? a.loc.rank : Infinity, br = b.loc ? b.loc.rank : Infinity;\n      if (ar !== br) return ar - br;\n      if (a.loc && b.loc) return a.loc.t - b.loc.t;\n      return (a.iy - b.iy) || (a.ix - b.ix);\n    });\n\n    // END FEATURES have to be packed BEFORE numbering starts, because each\n    // stock length is a line that takes its number AT ITS FIRST PIECE in the\n    // sweep. Numbering them afterwards is what pushed a feature at the front of\n    // the plan out to a high number while unit 1 sat next to it.\n    const endFeatureBins = [];\n    const binByFirstFace = {};\n    {\n      let seq = 0;\n      const order = {};\n      for (const e of entries) {\n        if (e.kind === 'face' && e.face && e.face.featureKind) order[e.face.id] = ++seq;\n      }\n      const pools = new Map();\n      for (const e of entries) {\n        const f = (e.kind === 'face') ? e.face : null;\n        if (!f || !f.featureKind) continue;\n        const cab = cabinets.find(c => c.id === (f.cabIds || [])[0]);\n        if (!cab) continue;\n        // End Panels to Floor: the whole drop, floor to the top of the unit.\n        const floorEnd = cab.endPanels && cab.endPanels[f.side] && cab.endPanels[f.side].toFloor;\n        const need = floorEnd ? f.heightMm : endFeatureLengthMm(cab, f.role);\n        if (!(need > 0)) continue;\n        // Pooled by COLOUR too: a stock length comes in one colour, so only\n        // posts of the same colour can share one (and its line + number). A\n        // post takes its END's colour - the end panel it belongs to.\n        const colour = (cab.endPanelColours && cab.endPanelColours[f.side]) || cab.doorColourHandle || globalDoorColourHandle || null;\n        // A Pastry Bench Set's legs are cut for that set alone (its lines run\n        // together after the unit), so they get a pool of their own.\n        const _psCab = f.noBoard && isPastrySet(cab) ? cab.id : null;\n        const key = (f.styleId || kitchenStyleId || '') + '|' + f.featureKind + '|' + (colour || '') + (_psCab ? '|pastry:' + _psCab : '');\n        if (!pools.has(key)) pools.set(key, { key, styleId: f.styleId, kind: f.featureKind, colour, items: [], pastryCabId: _psCab });\n        const ord = order[f.id] || 0;\n        // `faceKey` numbers the badge; `focusKey` is what a basket line\n        // highlights. They MUST differ from the panel's plain `cabId:side`,\n        // or clicking either row lights both the panel and the feature.\n        const push = (suffix) => pools.get(key).items.push({\n          lengthMm: need, order: ord, cabId: cab.id, faceId: f.id,\n          faceKey: `${cab.id}:${f.side}${suffix}`,\n          focusKey: `${cab.id}:${f.side}:feature${suffix === ':back' ? '-back' : ''}`,\n          key: f.id + suffix });\n        push('');\n        // 'Radius/Square on Back of Unit' - the matching post at this side's\n        // back-outer corner. Its own piece, its own badge key.\n        if (cab.backEndPost && cab.backEndPost.active) push(':back');\n      }\n      for (const pool of pools.values()) {\n        const prod = endFeatureProduct(pool.kind, pool.styleId);\n        const stock = (prod && typeof prod.lengthMm === 'number' && prod.lengthMm > 0)\n          ? prod.lengthMm : 0;\n        const bins = stock\n          ? packEndFeatureBins(pool.items, stock)\n          : pool.items.map(it => ({ items: [it], order: it.order, stockMm: 0,\n                                    usedMm: it.lengthMm, remaining: 0 }));\n        for (const bin of bins) {\n          bin.poolKey = pool.key; bin.styleId = pool.styleId; bin.kind = pool.kind; bin.colour = pool.colour || null;\n          bin.number = null;\n          bin.ownerCabId = (bin.items[0] || {}).cabId || null;\n          bin.pastryCabId = pool.pastryCabId || null;\n          endFeatureBins.push(bin);\n        }\n      }\n      endFeatureBins.sort((a, b) => (a.order || 0) - (b.order || 0));\n      for (const bin of endFeatureBins) {\n        const fid = (bin.items[0] || {}).faceId;\n        if (fid && !binByFirstFace[fid]) binByFirstFace[fid] = bin;\n      }\n    }\n\n    // Number: units take the next number; a board takes the number of its\n    // FIRST piece reached and reuses it on later pieces.\n    // A line taken out of the quote (Exclude Items from Quote) takes NO number,\n    // so the numbers close up round it on the plan, in the basket and on the\n    // order (Arden, 2026-10-30). Keyed as the basket line is (derivedId).\n    const _exLines = quoteExcludedLines || {};\n    const _out = (key) => !!_exLines['q:' + key];\n    let n = 1;\n    const faceToNumber = {};\n    const _psFaces = [];\n    for (const e of entries) {\n      if (e.kind === 'unit') {\n        const _cid = e.cab.id;\n        e.cab.displayNumber = (_out('u:' + _cid) || _out('fsa:' + _cid)) ? null : n++;\n        // A built-under double oven's fitting panels are their OWN numbered\n        // line, right after the oven (Arden, 2026-11-05).\n        e.cab.fittingKitNumber = (fittingKitFor(e.cab) && !_out('fp:' + _cid)) ? n++ : null;\n        // Carcase-only, so they start in the plan's carcase colour and the\n        // oven's panel can change it.\n        if (e.cab.freestandingAppliance?.fittingPanels && !e.cab.carcaseColourHandle) e.cab.carcaseColourHandle = globalCarcaseColourHandle || null;\n        // Chosen appliances in this unit's oven apertures are their OWN\n        // numbered lines - take the next numbers immediately after the\n        // housing, in aperture (opening-index) order, so units + appliances\n        // form ONE sequence (unit 1, oven 2, unit 3, oven 4\u2026). Derived here\n        // so the 2D badges, basket lines and numbering never disagree.\n        const chosen = e.cab.appliances;\n        const keys = chosen ? Object.keys(chosen).filter(k => chosen[k]).sort((a, b) => Number(a) - Number(b)) : [];\n        if (keys.length) {\n          const nums = {};\n          for (const k of keys) if (!_out('ap:' + _cid + ':' + k)) nums[k] = n++;\n          e.cab.applianceNumbers = nums;\n        } else if (e.cab.applianceNumbers) {\n          e.cab.applianceNumbers = {};\n        }\n        // A chosen Planner Sink on a sink-base unit is ALSO its own\n        // numbered line - its own green badge number in 2D + its own\n        // basket line - taken right after the housing, same pattern as\n        // appliances. Only allocated when a sink is actually chosen (an\n        // empty sink base is just a \"Choose Sink\" prompt, not a line).\n        if ((e.cab.sinkBase || e.cab.belfastSink) && e.cab.plannerSinkHandle) {\n          e.cab.sinkNumber = _out('sk:' + _cid) ? null : n++;\n        } else if (e.cab.sinkNumber != null) {\n          e.cab.sinkNumber = null;\n        }\n        // A 2 drawer base Sink Unit's drawer insert: its own line, after the sink.\n        e.cab.sinkInsertNumber = (sinkInsertFor(e.cab) && !_out('si:' + _cid)) ? n++ : null;\n        // A Pastry Bench Set's side fronts, plinth frame and shelf: their own\n        // lines, right after the unit (its legs and back panel are numbered\n        // as end features and boards).\n        // Its legs (end feature lengths) and back panel board come first, so\n        // the whole set reads in one run of numbers after the unit.\n        if (e.cab.pastryParts) {\n          for (const _bin of endFeatureBins) {\n            if (_bin.pastryCabId !== _cid || _bin.number != null || _bin.quoteExcluded) continue;\n            if (_out(featureLineKey((_bin.items || []).map(i => i.focusKey || i.faceKey), _bin.ownerCabId, null))) _bin.quoteExcluded = true;\n            else _bin.number = n++;\n          }\n          const _pb = boardOf.get(_cid + ':pastry-back');\n          if (_pb && _pb.itemNumber == null && !_pb.quoteExcluded) {\n            _pb.ownerCabId = _cid;\n            if (_out(boardLineKey(_pb))) _pb.quoteExcluded = true;\n            else _pb.itemNumber = n++;\n          }\n          const _pn = {};\n          for (const ch of pastryCharges(e.cab)) if (!_out('ps:' + _cid + ':' + ch.part)) _pn[ch.part] = n++;\n          e.cab.pastryNumbers = _pn;\n        } else if (e.cab.pastryNumbers) {\n          e.cab.pastryNumbers = null;\n        }\n        // True Handleless TALL units carry a VERTICAL RAIL on their GRIP\n        // (non-hinge) side - a 30mm aluminium profile that sticks into the run\n        // = a real PLAN dimension (like a filler / end panel), so it's its OWN\n        // numbered line (taken right after the housing, same as sinks). Two TH\n        // tall units butted GRIP-to-GRIP share ONE Intermediate rail (one 30mm,\n        // one number); a lone grip side (against a hinge / end panel / exposed)\n        // gets a Lateral. Detection is MUTUAL - each unit's grip-side neighbour\n        // must be the other. Stamped on the cab so 2D + 3D read it directly.\n        const _gs = thGripSide(e.cab);\n        if (_gs) {\n          e.cab.railGripSide = _gs;\n          const _nb   = epFindNeighbourOnSide(e.cab, _gs, epVerticalRange(e.cab), cabinets);\n          const _nbGs = thGripSide(_nb);\n          const _gripGrip = !!(_nb && _nbGs\n            && epFindNeighbourOnSide(_nb, _nbGs, epVerticalRange(_nb), cabinets) === e.cab\n            && thRailHeightsMatch(e.cab, _nb));\n          if (_gripGrip) {\n            e.cab.railType      = 'intermediate';\n            e.cab.railPartnerId = _nb.id;\n            // ONE shared rail: the lower-id unit OWNS it (draws + numbers); the\n            // partner defers, so the pair shows a single 30mm + single number.\n            e.cab.railOwnsShared = String(e.cab.id) < String(_nb.id);\n            e.cab.railNumber     = (e.cab.railOwnsShared && !_out('rl:' + _cid + ':' + _gs)) ? n++ : null;\n          } else {\n            e.cab.railType       = 'lateral';\n            e.cab.railPartnerId  = null;\n            e.cab.railOwnsShared = false;\n            e.cab.railNumber     = _out('rl:' + _cid + ':' + _gs) ? null : n++;\n          }\n        } else {\n          e.cab.railGripSide   = null;\n          e.cab.railType       = null;\n          e.cab.railPartnerId  = null;\n          e.cab.railOwnsShared = false;\n          e.cab.railNumber     = null;\n        }\n        // RAIL ON BOTH SIDES (Arden, 2026-10-20): ticked on a TH tall unit, a\n        // second Lateral rail goes on its HINGE side too - a customer's choice\n        // for the ends of a tall bank, no rule. Only at the END of a bank: with\n        // another TH tall unit against that side the two would meet as a shared\n        // double rail, which the grip pairing above already decides.\n        // railSecondEligible says whether the tick can apply here.\n        if (_gs) {\n          const _other = _gs === 'left' ? 'right' : 'left';\n          // The END of a run: an end panel finishes that side (whatever stands\n          // beyond it - Jonathan Print's fridge housing has its panel and then a\n          // pull-out base), or nothing stands beside it at all.\n          const _otherEp = (e.cab.endPanels || {})[_other];\n          e.cab.railSecondEligible = !!(_otherEp && _otherEp.active) || !thSideHasUnit(e.cab, _other);\n          const _on = !!e.cab.railBothSides && e.cab.railSecondEligible;\n          e.cab.railSecondSide   = _on ? _other : null;\n          e.cab.railSecondNumber = (_on && !_out('rl:' + _cid + ':' + _other)) ? n++ : null;\n        } else {\n          e.cab.railSecondEligible = false;\n          e.cab.railSecondSide     = null;\n          e.cab.railSecondNumber   = null;\n        }\n        // TH corner posts - each front-outer L-post (+ back-outer on an island)\n        // is its OWN numbered line (sold per corner), right after the unit's rail.\n        const _cpNums = {};\n        if (e.cab.isTrueRail) {\n          const _eps = e.cab.endPanels || {};\n          const _island = !!(e.cab.backPanel && e.cab.backPanel.active && e.cab.backPanel.thProfile);\n          for (const _s of ['left', 'right']) {\n            const _ep = _eps[_s];\n            if (_ep && _ep.active && /^th-/.test(String(_ep.style || ''))) {\n              if (!_out('cp:' + _cid + ':' + _s + ':front')) _cpNums[`${_s}:front`] = n++;\n              if (_island && !_out('cp:' + _cid + ':' + _s + ':back')) _cpNums[`${_s}:back`] = n++;\n            }\n          }\n        }\n        e.cab.cornerPostNumbers = Object.keys(_cpNums).length ? _cpNums : null;\n        // Door end panels (Sales sheet line 110): each its own numbered line.\n        const _deNums = {};\n        for (const _s of ['left', 'right']) {\n          const _de = ((e.cab.endPanels || {})[_s] || {}).doorEnd;\n          if (_de && _de.variantId && !_out('de:' + _cid + ':' + _s)) _deNums[_s] = n++;\n        }\n        e.cab.doorEndNumbers = Object.keys(_deNums).length ? _deNums : null;\n        // Make Base Unit: its leg pack, its own numbered line.\n        e.cab.legsNumber = (e.cab.asBase && !_out('legs:' + _cid)) ? n++ : null;\n        // Worktop Pantry Unit: its fitters panels, their own numbered line.\n        e.cab.pantryPanelsNumber = (isPantryCab(e.cab) && window.BTKFittersPanel && !_out('pp:' + _cid)) ? n++ : null;\n        continue;\n      }\n      // A Pastry Bench Set's leg and back panel faces take their set's\n      // numbers, given out with its unit (above) - see _psFaces below.\n      if (e.face.noBoard || e.face.side === 'pastry-back') { _psFaces.push(e.face); continue; }\n      const b = boardOf.get(e.face.id);\n      if (b) {\n        if (b.itemNumber == null && !b.quoteExcluded) {\n          b.ownerCabId = (e.face.cabIds || [])[0] || null;\n          if (_out(boardLineKey(b))) b.quoteExcluded = true;\n          else b.itemNumber = n++;\n        }\n        faceToNumber[e.face.id] = b.itemNumber;\n      } else { faceToNumber[e.face.id] = n++; }\n      // An end-feature LINE takes the next number right here, at its first\n      // piece, so it reads in sequence with the units around it.\n      const _bin = binByFirstFace[e.face.id];\n      if (_bin && _bin.number == null && !_bin.quoteExcluded) {\n        if (_out(featureLineKey((_bin.items || []).map(i => i.focusKey || i.faceKey), _bin.ownerCabId, null))) _bin.quoteExcluded = true;\n        else _bin.number = n++;\n      }\n    }\n    for (const b of nested.boards) {\n      if (b.itemNumber != null || b.quoteExcluded) continue;\n      if (_out(boardLineKey(b))) b.quoteExcluded = true;\n      else b.itemNumber = n++;\n    }\n    for (const f of _psFaces) {\n      const b = boardOf.get(f.id);\n      const bin = b ? null : endFeatureBins.find(x => (x.items || []).some(i => i.faceId === f.id));\n      faceToNumber[f.id] = b ? b.itemNumber : (bin ? bin.number : null);\n    }\n    // END FEATURES: ends of the same style + kind are cut from shared stock\n    // lengths, so they are ONE basket line and take ONE number - which every\n    // corner that line covers then shows, exactly like a filler or a panel\n    // board shared across units. Highlighting the row lights all of them.\n    // Every corner cut from a length shows that length's number, so\n    // highlighting the basket row lights all of them.\n    const cabSideToFeatureNumber = {};\n    for (const bin of endFeatureBins) {\n      if (bin.number == null && !bin.quoteExcluded) {   // safety: never unnumbered\n        if (_out(featureLineKey((bin.items || []).map(i => i.focusKey || i.faceKey), bin.ownerCabId, null))) bin.quoteExcluded = true;\n        else bin.number = n++;\n      }\n      for (const it of bin.items) {\n        if (it.faceKey) cabSideToFeatureNumber[it.faceKey] = bin.number;\n      }\n    }\n    // Free-placed WORKTOP ITEMS backed by a real product (hobs / sinks / taps)\n    // each take the next plan number, continuing the sequence after all units /\n    // faces / features. Stamped on the item so its 2D badge and its basket line\n    // always show the SAME number. Ordered back-to-front, left-to-right.\n    const _placedWI = (worktopItems || [])\n      .filter(it => it && it.variantId)\n      .sort((a, b) => (a.y - b.y) || (a.x - b.x));\n    for (const it of _placedWI) {\n      const _k = 'wi:' + (it.kind === 'canopy' ? 'extractor' : it.kind) + ':' + (it.id || it.variantId);\n      it.planLineNumber = _out(_k) ? null : n++;\n    }\n    for (const it of (worktopItems || [])) {\n      if (!(it && it.variantId)) it.planLineNumber = null;\n    }\n    const cabSideToNumber = {}, cabSideToFace = {};\n    for (const f of faces) {\n      const num = faceToNumber[f.id];\n      if (num == null) continue;\n      for (const cabId of (f.cabIds || [])) if (f.side) {\n        cabSideToNumber[`${cabId}:${f.side}`] = num;\n        cabSideToFace[`${cabId}:${f.side}`]   = f.id;   // a merged stacked face maps several sides \u2192 ONE id\n      }\n      // A FREE-PLACED panel is its own cabinet, so give the cab the number of\n      // the board it was cut from - the 2D badge on the panel then matches its\n      // basket line (which is that board), instead of the panel showing no\n      // number at all now it no longer takes a unit number.\n      if (f.side === 'unit') {\n        const owner = cabinets.find(c => c.id === (f.cabIds || [])[0]);\n        if (owner) owner.displayNumber = num;\n      }\n    }\n    // CEILING FILLER pieces onto their unit, numbered, for the 3D (drawn) and\n    // the 2D plan (badged).\n    for (const f of faces) {\n      if (!f.ceil) continue;\n      const owner = cabinets.find(c => c.id === (f.cabIds || [])[0]);\n      if (!owner) continue;\n      (owner.ceilingFillerPieces = owner.ceilingFillerPieces || []).push({\n        side: f.side, num: faceToNumber[f.id] ?? null, colour: f.colour || null, ...f.ceil });\n    }\n    return { ...nested, faces, cabSideToNumber, cabSideToFace, faceToNumber,\n             cabSideToFeatureNumber, endFeatureBins };\n  }\n\n  // Numbering now lives in rerender() (computeNumberingAndLayout) so it\n  // stays consistent; callers just trigger a re-render.\n  function renumberAllCabinets() { rerender(); }\n\n  // Toggle a cabinet's \"Exclude from Quote\" state. Excluded cabinets stay\n  // on the plan (movable / recolourable) but drop out of auto-numbering,\n  // the quote drawer, the quote total and the cart - and show a red \u2715\n  // badge instead of a number. renumberAllCabinets() reassigns the 1..N\n  // sequence over the remaining included cabinets and rerenders (which\n  // refreshes the 2D badges + quote drawer); the flag persists with the\n  // cabinet via the normal design serialisation.\n  // Carcase Only (see carcaseOnlyVariant): staff mode, a unit with fronts.\n  function carcaseOnlyOffered(cab) {\n    const staff = !!(window.BTKBasketAPI && typeof window.BTKBasketAPI.isStaffMode === 'function'\n      && window.BTKBasketAPI.isStaffMode());\n    if (!staff || !cab || !cab.variantId || cab.endPanelUnit || cab.freestandingAppliance) return false;\n    if (cab.carcaseOnly) return true;\n    const openings = (cab.cutoutSchema && cab.cutoutSchema.openings) || [];\n    return openings.some(op => /door|drawer|glass|bifold/i.test(String(op.type || '')));\n  }\n  // Turn Carcase Only on (staff's permission + the unit's hidden product) or\n  // off. Refused, with a message, when the unit has no carcase-only version.\n  async function setCabinetCarcaseOnly(id, on) {\n    const cab = cabinets.find(c => c.id === id);\n    if (!cab) return;\n    const say = (text) => window.BTKKPDialog.alert(text, { title: 'Carcase Only' });\n    if (!on) {\n      delete cab.carcaseOnly;\n      rerender();\n      refreshQuoteLocally();\n      return;\n    }\n    if (!carcaseOnlyOffered(cab)) return;\n    try {\n      const byId = await ensureCarcaseOnlyProduct(cab.unitTypeId);\n      const info = Catalogue.getVariantInfo(cab.variantId);\n      const oid = info && info.variant && odooIdOfSku(info.variant.sku);\n      if (!byId || !oid || !byId.get(oid)) {\n        say('This unit is not available as Carcase Only.');\n        return;\n      }\n      const basket = window.BTKCartAdvanced && window.BTKCartAdvanced.getBasket && window.BTKCartAdvanced.getBasket();\n      const perm = await window.BTKBasketAPI.carcaseOnlyPermission((basket && basket.id) || 'planner', oid);\n      if (!perm || !perm.token) throw new Error('no permission');\n      cab.carcaseOnly = { token: perm.token, expiresAt: perm.expiresAt || null };\n      rerender();\n      refreshQuoteLocally();\n    } catch (e) {\n      console.error('[BTK Kitchen Planner] Carcase Only failed', e);\n      say('Carcase Only could not be set - please try again.');\n    }\n  }\n\n  function setCabinetExcludeFromQuote(id, excluded) {\n    const cab = cabinets.find(c => c.id === id);\n    if (!cab) return;\n    // Nothing to buy - always out of the quote. A wine cooler we sell is the\n    // exception: it can be taken out like any unit.\n    if (cab.freestandingAppliance && !cab.freestandingAppliance.productHandle) return;\n    const next = (excluded == null) ? !cab.excludeFromQuote : !!excluded;\n    if (cab.excludeFromQuote === next) return;\n    cab.excludeFromQuote = next;\n    renumberAllCabinets();\n  }\n\n  // Update a cab's wall-setback (0\u2013300mm). Also shifts the cab body\n  // FORWARD by the delta so the \"back of void\" stays where the cab's\n  // back used to be - wall snap then keeps treating the back of the\n  // void as the snap point. Body anchor (cab.x / cab.y) is the cab's\n  // visual top-left so we move that.\n  //   cab-local forward direction in world per rotation:\n  //     rot=0   \u2192 (0, -1)     rot=180 \u2192 (0, +1)\n  //     rot=90  \u2192 (+1, 0)     rot=270 \u2192 (-1, 0)\n  //   == (sin(rot), -cos(rot))\n  function handleUpdateCabinetSetback(cabId, newSb) {\n    if (cabPositionLocked(cabId)) return;   // POSITION LOCK - stays where it is\n    const idx = cabinets.findIndex(c => c.id === cabId);\n    if (idx === -1) return;\n    const cab = cabinets[idx];\n    const clamped = Math.max(0, Math.min(300, Math.round(newSb || 0)));\n    // An end-of-run BASE CURVE with its backing + filler: the set steps as one\n    // and the filler grows to the wall (see radiusStepOf) - no setback void.\n    const radFiller = (cab.radiusUnit && cab.groupId && !/^wall/i.test(cab.category || ''))\n      ? cabinets.find(m => m.groupId === cab.groupId && m.radiusGroup && m.radiusGroup.role === 'filler')\n      : null;\n    if (radFiller) {\n      const oldStep = radiusStepOf(cab);\n      if (clamped === oldStep) return;\n      const d = clamped - oldStep;\n      const rr = (cab.rotationDeg || 0) * Math.PI / 180;\n      cabinets[idx] = { ...cab, radiusStepMm: clamped,\n                        x: cab.x + Math.sin(rr) * d, y: cab.y - Math.cos(rr) * d };\n      radFiller.depthMm = RADIUS_FILLER_MM + clamped;\n      reAnchorRadiusGroup(cabinets, cabinets[idx]);\n      autoDetectEndPanels([cabId]);\n      autoDetectBackPanels();\n      resizeFillers();\n      rerender();\n      return;\n    }\n    const oldSb = cab.wallSetbackMm || 0;\n    if (clamped === oldSb) return;\n    const delta = clamped - oldSb;\n    const rotRad = (cab.rotationDeg || 0) * Math.PI / 180;\n    cabinets[idx] = {\n      ...cab,\n      wallSetbackMm: clamped,\n      x: cab.x + Math.sin(rotRad) * delta,\n      y: cab.y - Math.cos(rotRad) * delta\n    };\n    // Re-evaluate panel rules + push out of overlaps caused by the\n    // setback change: the stepped cab now wins the panel keep against\n    // a flush neighbour, and its newly-active 50mm radius/square (or\n    // 20mm flat) panel would intrude into the neighbour body without\n    // an effective-settle pass to push it clear.\n    autoDetectEndPanels([cabId]);\n    autoDetectBackPanels();\n    settleCabinet(cabId, true);\n    resizeFillers();\n    rerender();\n  }\n\n  // Find the signed distance from `cab`'s `side` to the closest\n  // parallel face (cabinet OR wall) in the outward direction. Returns\n  // the smallest POSITIVE signed gap (= \"how far would I move in the\n  // outward direction to meet that face\"), or null when no parallel\n  // face shares any meaningful length overlap with this side. Unlike\n  // epLinesCoincide, perpendicular distance is UNBOUNDED - works\n  // even when the neighbour is a metre away.\n  // includeTouching (with directionalOnly): keep a face it is ALREADY on, so a\n  //   unit against a wall measures 0 rather than reading as nothing there. A\n  //   snap must still skip it - there is nowhere to move to - which is why it\n  //   is an option rather than the rule.\n  // includeRoomFeatures: count the pillars / internal walls / chimney breasts\n  //   a drag already snaps to. Off for snapping and fillers, which measure\n  //   unit-to-unit and unit-to-wall.\n  function epClosestForwardGap(cab, side, { fromCarcase = false, allowZero = false, directionalOnly = false, includeTouching = false, includeRoomFeatures = false, includePanels = false } = {}) {\n    // mySide must be the PANEL face (or carcase when no panel) so the\n    // snap leaves room for our own 50mm radius / square (or 20mm flat\n    // / T&G) panel in the gap to the neighbour. Snapping carcase-to-\n    // carcase pushed the panel INTO the neighbour body.\n    //\n    // fromCarcase=true measures CARCASE-to-CARCASE/wall instead - used\n    // by the manual \"Fill\" button, where the filler replaces any end\n    // panel and must span the full carcase-to-wall gap (measuring from\n    // the panel face would leave the filler one panel-thickness short).\n    const mySide = (fromCarcase ? epCarcaseSides(cab) : epAllSides(cab))[side];\n    const outward = epUserSideOutward(cab, side);\n    const myRange = epVerticalRange(cab);\n    const sdx = mySide.p2.x - mySide.p1.x;\n    const sdy = mySide.p2.y - mySide.p1.y;\n    const slen = Math.hypot(sdx, sdy);\n    if (slen < 1) return null;\n    const sux = sdx / slen, suy = sdy / slen;\n    // Track the smallest signed gap in the outward direction,\n    // INCLUDING near-zero / negative values. We need to know if\n    // anything's already-touching so we can return null (no snap\n    // needed) rather than skip past it to a further face.\n    let bestSigned = Infinity;\n    let bestAbs    = Infinity;\n\n    const consider = (otherSide) => {\n      const wdx = otherSide.p2.x - otherSide.p1.x;\n      const wdy = otherSide.p2.y - otherSide.p1.y;\n      const wlen = Math.hypot(wdx, wdy);\n      if (wlen < 1) return;\n      const wux = wdx / wlen, wuy = wdy / wlen;\n      if (Math.abs(sux * wuy - suy * wux) > 0.06) return;\n      // The other side must overlap mine in length by at least\n      // OVERLAP_MIN_MM, so a face on a totally different stretch\n      // of wall doesn't get matched.\n      const OVERLAP_MIN_MM = 50;\n      const tA = (otherSide.p1.x - mySide.p1.x) * sux + (otherSide.p1.y - mySide.p1.y) * suy;\n      const tB = (otherSide.p2.x - mySide.p1.x) * sux + (otherSide.p2.y - mySide.p1.y) * suy;\n      const lo = Math.max(0, Math.min(tA, tB));\n      const hi = Math.min(slen, Math.max(tA, tB));\n      if (hi - lo < OVERLAP_MIN_MM) return;\n      const signed = epSignedGap(mySide, otherSide, outward);\n      if (directionalOnly) {\n        // Only obstacles AHEAD in the outward (clicked) direction - so a\n        // directional snap goes to the wall/neighbour you pointed at, not\n        // the nearest one behind. Smallest positive gap wins.\n        if (signed < (includeTouching ? -0.5 : 0.5)) return;\n        if (signed < bestAbs) { bestAbs = signed; bestSigned = signed; }\n      } else {\n        // Smallest |signed| wins - a face I'm already touching\n        // (signed \u2248 0) blocks the search from looking past it, so\n        // snap doesn't tunnel onto a further cab.\n        if (Math.abs(signed) < bestAbs) { bestAbs = Math.abs(signed); bestSigned = signed; }\n      }\n    };\n\n    for (const other of cabinets) {\n      if (other.id === cab.id) continue;\n      const grp = epCategoryGroup(other);\n      // A free-placed panel carries the 'doors-panels-accessories' category, so\n      // it groups to nothing and the gate below drops it. It is still a real\n      // obstacle - a filler dropped beside one has to stop at its face - so\n      // callers that care can ask for panels to count (see the filler fit).\n      const otherIsPanel = includePanels && !!(other.endPanelUnit || other.endPanelFiller);\n      if (!otherIsPanel &&\n          grp !== 'base' && grp !== 'tall' && grp !== 'midi' && grp !== 'wall' && grp !== 'bridging' && !other.cornerUnit) continue;\n      if (!epRangesOverlap(myRange, epVerticalRange(other))) continue;\n      // Snap target = neighbour's PANEL face when it has one, else its\n      // carcase (epAllSides returns the carcase line for sides with no\n      // active panel/filler). This matters when the neighbour keeps a\n      // chunky 50mm radius/square panel - snapping to the carcase let\n      // the panel intrude into our body. Works for any category: tall\n      // keeps its panel (snap lands at panel face); base without panel\n      // collapses to carcase same as before.\n      const oSides = (fromCarcase ? epCarcaseSides(other) : epAllSides(other));\n      for (const key of ['front', 'back', 'left', 'right']) consider(oSides[key]);\n      // A DOOR LINE tall end panel blocks the return like a wall - snap to it,\n      // and measure the filler gap to it.\n      for (const f of epDoorLinePanelFaces(other)) consider(f);\n    }\n    const verts = room?.vertices || [];\n    for (let i = 0; verts && i < verts.length; i++) {\n      consider({ p1: verts[i], p2: verts[(i + 1) % verts.length] });\n    }\n    // Things standing in the room that are not units and not the room's own\n    // wall - pillars, internal walls, chimney breasts. Same faces a drag\n    // snaps to; getPillarSnapWalls leaves out what you walk under (beams,\n    // ceiling wedges) and anything turned off-axis.\n    if (includeRoomFeatures) {\n      for (const w of getPillarSnapWalls(roomConfig?.perimeterItems)) {\n        consider({ p1: w.from, p2: w.to });\n      }\n    }\n    if (bestSigned === Infinity) return null;\n    // Skip ONLY when the face is already touching (|signed| ~ 0). A\n    // negative signed value means our panel face has overshot past the\n    // neighbour's - push back outward to resolve the overlap. The Walls\n    // distance readout passes allowZero so a touching face still reports\n    // its (\u22480) gap and can be pushed off it.\n    if (!allowZero && Math.abs(bestSigned) < 0.5) return null;\n    return bestSigned;\n  }\n\n  // Manual snap: shift the cab so its `side` carcase face meets the\n  // closest parallel face in the outward direction. Works at any\n  // distance (no tolerance ceiling).\n  function snapCabinetToSide(cabId, side) {\n    if (cabPositionLocked(cabId)) return;   // POSITION LOCK - stays where it is\n    const idx = cabinets.findIndex(c => c.id === cabId);\n    if (idx === -1) return;\n    const cab = cabinets[idx];\n    // directionalOnly: snap to the nearest wall/neighbour AHEAD in the\n    // clicked direction (never one behind), so the unit moves the way\n    // the arrow points and stays inside the room.\n    const signed = epClosestForwardGap(cab, side, { directionalOnly: true });\n    if (signed == null) return;\n    const outward = epUserSideOutward(cab, side);\n    cabinets[idx] = { ...cab, x: cab.x + outward.x * signed, y: cab.y + outward.y * signed };\n    autoDetectEndPanels([cabId]);\n    autoDetectBackPanels();\n    resizeFillers();\n    rerender();\n  }\n\n  // Manual position nudge - move a cabinet by `mm` in the unit-relative\n  // direction ('left'/'right'/'forward'/'back'). Then settle out of any\n  // overlap (like the Step-Forward setback does), re-evaluate panels and\n  // re-render. Direction vectors come from epUserSideOutward so a nudge\n  // tracks the same axes as the Snap buttons.\n  function handleNudgeCabinet(cabId, dir, mm) {\n    if (cabPositionLocked(cabId)) return;   // POSITION LOCK - stays where it is\n    const idx = cabinets.findIndex(c => c.id === cabId);\n    if (idx === -1) return;\n    const amt = Math.round(Number(mm) || 0);\n    if (amt <= 0) return;\n    const cab = cabinets[idx];\n    const v = epUserSideOutward(cab, dir);\n    if (v.x === 0 && v.y === 0) return;\n    cabinets[idx] = { ...cab, x: cab.x + v.x * amt, y: cab.y + v.y * amt };\n    autoDetectEndPanels([cabId]);\n    autoDetectBackPanels();\n    settleCabinet(cabId, true);\n    resizeFillers();\n    rerender();\n  }\n\n  // 'left'/'right'/'forward'/'back' (UI) \u2192 the epAllSides face key.\n  const NUDGE_SIDE_KEY = { left: 'left', right: 'right', forward: 'front', back: 'back' };\n\n  // Distance (mm) from the cabinet's face in `dir` to the ROOM WALL in\n  // front of that face - NOT to neighbouring units. Returns { gap, outward }\n  // or null. Axis-aligned units only (rotation 0/90/180/270); the outward\n  // vector is cardinal.\n  // The wall is the nearest room wall segment ahead of the face across the\n  // unit's own width (an angled wall counts where it crosses that width).\n  // It used to be the room's bounding box edge, which is only the wall in a\n  // rectangular room: in Anthony Rogers' 12-wall room a corner unit 45mm off\n  // the wall read 60 / 1920 / 7452 (Arden, 2026-10-14). The box edge stays as\n  // the fallback when no wall segment is found ahead.\n  function roomWallAheadGap(vb, o) {\n    const horiz = Math.abs(o.x) > Math.abs(o.y);\n    const sgn  = horiz ? Math.sign(o.x) : Math.sign(o.y);\n    const face = horiz ? (o.x > 0 ? vb.x1 : vb.x0) : (o.y > 0 ? vb.y1 : vb.y0);\n    // Across the face, kept 1mm in from its ends so a wall running exactly\n    // along the unit's side does not count as one in front of it.\n    const lo = (horiz ? vb.y0 : vb.x0) + 1, hi = (horiz ? vb.y1 : vb.x1) - 1;\n    let best = Infinity;\n    for (const w of getWalls(room)) {\n      const a = horiz ? { s: w.from.y, t: w.from.x } : { s: w.from.x, t: w.from.y };\n      const b = horiz ? { s: w.to.y,   t: w.to.x }   : { s: w.to.x,   t: w.to.y };\n      if (Math.abs(b.s - a.s) < 1) continue;             // runs the same way as the move\n      const s0 = Math.max(lo, Math.min(a.s, b.s)), s1 = Math.min(hi, Math.max(a.s, b.s));\n      if (s1 < s0) continue;                              // not in front of this face\n      const tAt = (sv) => a.t + (b.t - a.t) * (sv - a.s) / (b.s - a.s);\n      for (const sv of [s0, s1]) {\n        const g = (tAt(sv) - face) * sgn;\n        if (g >= -1 && g < best) best = g;\n      }\n    }\n    return Number.isFinite(best) ? Math.max(0, best) : null;\n  }\n  function cabinetWallGap(cab, dir) {\n    const rb = getBoundingBox(room);\n    if (!rb) return null;\n    const o  = epUserSideOutward(cab, NUDGE_SIDE_KEY[dir]);\n    if (!o || (o.x === 0 && o.y === 0)) return null;\n    const vb = visualBbox(cab);\n    let gap = roomWallAheadGap(vb, o);\n    if (gap == null) {\n      if (Math.abs(o.x) > Math.abs(o.y)) {\n        gap = o.x > 0 ? (rb.maxX - vb.x1) : (vb.x0 - rb.minX);\n      } else {\n        gap = o.y > 0 ? (rb.maxY - vb.y1) : (vb.y0 - rb.minY);\n      }\n    }\n    return { gap, outward: o };\n  }\n\n  // While dragging, push live wall distances into the selection panel's\n  // Walls-mode boxes for the dragged cab (no-op in Nudge mode / when a\n  // different cab's panel is open).\n  function updateDragWallDistInputs(cab, x, y) {\n    if (!cab) return;\n    const ctrl = document.querySelector('[data-pos-cab]');\n    if (!ctrl || String(ctrl.dataset.posCab) !== String(cab.id)) return;\n    const inputs = ctrl.querySelectorAll('[data-wall-dist],[data-near-dist]');\n    if (!inputs.length) return;\n    const probe = { ...cab, x, y };\n    inputs.forEach(input => {\n      const near = input.dataset.nearDist;\n      const r = near ? cabinetNearestGap(probe, near) : cabinetWallGap(probe, input.dataset.wallDist);\n      input.value = r ? Math.max(0, Math.round(r.gap)) : '';\n    });\n  }\n\n  // Live distance from each face to the room wall on that side - drives\n  // the Walls-mode readout. In a closed room every side has a wall, so\n  // all four prefill.\n  // The gap a filler on this side would need to close - CARCASE to the next\n  // unit or wall, the same measurement fillCabinetSide commits. Read-only, so\n  // the popup can show and pre-fill it before anything is applied.\n  function getCabinetFillGap(cabId, side) {\n    const cab = cabinets.find(c => c.id === cabId);\n    if (!cab) return null;\n    // A corner end has no wall or unit to measure to - its filler meets the\n    // other unit's across the void. The gap is the board that mitred filler\n    // is cut from. Returning nothing here made the popup lock whatever width\n    // was in the box as a custom size, so the filler never reached the mitre.\n    const corner = fillerCornerCandidates(cabinets).get(cabId + ':' + side);\n    if (corner) {\n      return Math.max(1, Math.min(FILLER_MAX_GAP_MM, Math.round(fillerCornerBoardMm(corner))));\n    }\n    // Ahead of this side only, like Snap. Measuring both ways let the wall a\n    // unit stands against win over a neighbour further off on the other side\n    // (a 600 unit in a corner, 610 from the next one, read -600 \u2192 a 1mm\n    // filler). includeTouching keeps a face it is already on, so a flush side\n    // still reads as no gap rather than measuring past it.\n    const signed = epClosestForwardGap(cab, side, { fromCarcase: true, directionalOnly: true, includeTouching: true });\n    if (signed == null) return null;\n    return Math.max(1, Math.min(FILLER_MAX_GAP_MM, Math.round(signed)));\n  }\n\n  // Nearest Object mode: the distance from each face to the closest thing\n  // ahead of it - another unit, a panel it carries, a pillar or other room\n  // feature, or a wall - measured carcase to carcase, and 0 when it is\n  // already against it. Outer Walls (above) always measures the room's own\n  // wall, however much stands between.\n  function cabinetNearestGap(cab, dir) {\n    const signed = epClosestForwardGap(cab, NUDGE_SIDE_KEY[dir], {\n      fromCarcase: true, allowZero: true, directionalOnly: true,\n      includeTouching: true, includeRoomFeatures: true\n    });\n    if (signed == null || !isFinite(signed)) return null;\n    return { gap: Math.max(0, signed), outward: epUserSideOutward(cab, NUDGE_SIDE_KEY[dir]) };\n  }\n  function getCabinetNearestGaps(cabId) {\n    const cab = cabinets.find(c => c.id === cabId);\n    if (!cab) return null;\n    const out = {};\n    for (const dir of ['left', 'right', 'forward', 'back']) {\n      const r = cabinetNearestGap(cab, dir);\n      out[dir] = r ? Math.round(r.gap) : null;\n    }\n    return out;\n  }\n\n  // Typing in a Nearest Object box: move the unit until that distance is what\n  // was typed. Same move as the Outer Walls setter, measured to whatever is\n  // actually there.\n  function handleSetCabinetNearestDistance(cabId, dir, targetMm) {\n    if (cabPositionLocked(cabId)) return;   // POSITION LOCK - stays where it is\n    const idx = cabinets.findIndex(c => c.id === cabId);\n    if (idx === -1) return;\n    const cab = cabinets[idx];\n    const r = cabinetNearestGap(cab, dir);\n    if (!r) return;\n    const target = Math.max(0, Math.round(Number(targetMm) || 0));\n    const move = r.gap - target;\n    if (Math.abs(move) < 0.5) return;\n    let nx = cab.x + r.outward.x * move;\n    let ny = cab.y + r.outward.y * move;\n    const rb = getBoundingBox(room);\n    if (rb) {\n      const vb = visualBbox({ ...cab, x: nx, y: ny });\n      if (vb.x0 < rb.minX) nx += rb.minX - vb.x0;\n      if (vb.x1 > rb.maxX) nx -= vb.x1 - rb.maxX;\n      if (vb.y0 < rb.minY) ny += rb.minY - vb.y0;\n      if (vb.y1 > rb.maxY) ny -= vb.y1 - rb.maxY;\n    }\n    cabinets[idx] = { ...cab, x: nx, y: ny };\n    autoDetectEndPanels([cabId]);\n    autoDetectBackPanels();\n    resizeFillers();\n    rerender();\n  }\n\n  // The distance box you are in, drawn on the plan: the same green measure\n  // bar the Room Shape and opening panels use (drawFocusBar), from the middle\n  // of that face out to whatever it is measured to.\n  function showPositionSpan(cabId, dir, mode) {\n    const svg = planOverlaySvg();\n    if (!svg || !lastGrid) return;\n    clearFocusBar(svg);\n    const cab = cabinets.find(c => c.id === cabId);\n    if (!cab) return;\n    const r = (mode === 'nearest') ? cabinetNearestGap(cab, dir) : cabinetWallGap(cab, dir);\n    if (!r || !isFinite(r.gap)) return;\n    const vb = visualBbox(cab);\n    const o  = r.outward;\n    // Middle of the face the measurement leaves from.\n    const a = (Math.abs(o.x) > Math.abs(o.y))\n      ? { x: o.x > 0 ? vb.x1 : vb.x0, y: (vb.y0 + vb.y1) / 2 }\n      : { x: (vb.x0 + vb.x1) / 2,     y: o.y > 0 ? vb.y1 : vb.y0 };\n    const b = { x: a.x + o.x * r.gap, y: a.y + o.y * r.gap };\n    drawFocusBar(svg, a, b, lastGrid.pxPerMm);\n  }\n  function clearPositionSpan() {\n    const svg = planOverlaySvg();\n    if (svg) clearFocusBar(svg);\n  }\n\n  // ---- Group position (Arden, 2026-10-12) -------------------------------\n  // A selected group (an island, a run picked together) gets the same\n  // Position controls as a single unit, moving every unit in it as one. Its\n  // directions are the PLAN's - left, right, top, bottom as the plan is\n  // drawn - because a group's units can face any way (an island is usually\n  // back to back), so \"forward\" means nothing for the group as a whole.\n  // Measured from the group's outline, the union of its units' footprints.\n  const GROUP_DIRS = { left: { x: -1, y: 0 }, right: { x: 1, y: 0 }, top: { x: 0, y: -1 }, bottom: { x: 0, y: 1 } };\n  function groupMembersOf(ids) {\n    const want = new Set(ids || []);\n    return cabinets.filter(c => want.has(c.id));\n  }\n  function groupBbox(members) {\n    let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;\n    for (const m of members) {\n      const vb = visualBbox(m);\n      x0 = Math.min(x0, vb.x0); y0 = Math.min(y0, vb.y0);\n      x1 = Math.max(x1, vb.x1); y1 = Math.max(y1, vb.y1);\n    }\n    return { x0, y0, x1, y1 };\n  }\n  // Outer Walls: to the room's own wall, as a unit measures it.\n  function groupWallGap(members, dir) {\n    const rb = getBoundingBox(room);\n    if (!rb || !members.length) return null;\n    const bb = groupBbox(members);\n    return dir === 'left' ? bb.x0 - rb.minX : dir === 'right' ? rb.maxX - bb.x1\n      : dir === 'top' ? bb.y0 - rb.minY : rb.maxY - bb.y1;\n  }\n  // Nearest Object: the closest thing ahead of that side of the group - a\n  // wall, a unit that is not in the group and shares its height band, or a\n  // room feature standing on the floor (beams and ceilings are overhead) -\n  // facing it across at least 50mm of the side. 0 when already against it.\n  function groupNearestGap(members, dir) {\n    if (!members.length) return null;\n    const bb = groupBbox(members);\n    const horiz = dir === 'left' || dir === 'right';\n    const span = horiz ? [bb.y0, bb.y1] : [bb.x0, bb.x1];\n    const overlaps = (a0, a1) => Math.min(span[1], a1) - Math.max(span[0], a0) >= 50;\n    const ahead = (r) => dir === 'left' ? bb.x0 - r.x1 : dir === 'right' ? r.x0 - bb.x1\n      : dir === 'top' ? bb.y0 - r.y1 : r.y0 - bb.y1;\n    let best = Infinity;\n    const take = (g) => { if (g >= -0.5 && g < best) best = g; };\n    // Walls running across this side.\n    for (const w of getWalls(room)) {\n      const vert = Math.abs(w.to.x - w.from.x) < 1, flat = Math.abs(w.to.y - w.from.y) < 1;\n      if (horiz && vert && overlaps(Math.min(w.from.y, w.to.y), Math.max(w.from.y, w.to.y))) {\n        take(ahead({ x0: w.from.x, x1: w.from.x, y0: 0, y1: 0 }));\n      } else if (!horiz && flat && overlaps(Math.min(w.from.x, w.to.x), Math.max(w.from.x, w.to.x))) {\n        take(ahead({ x0: 0, x1: 0, y0: w.from.y, y1: w.from.y }));\n      }\n    }\n    // Other units in the same height band.\n    const memberIds = new Set(members.map(m => m.id));\n    let vb0 = Infinity, vb1 = -Infinity;\n    for (const m of members) { const r = epVerticalRange(m); vb0 = Math.min(vb0, r.bottom); vb1 = Math.max(vb1, r.top); }\n    for (const o of cabinets) {\n      if (memberIds.has(o.id)) continue;\n      if (!epRangesOverlap({ bottom: vb0, top: vb1 }, epVerticalRange(o))) continue;\n      const r = visualBbox(o);\n      if (horiz ? overlaps(r.y0, r.y1) : overlaps(r.x0, r.x1)) take(ahead(r));\n    }\n    // Room features standing on the floor.\n    for (const p of (roomConfig.perimeterItems || [])) {\n      if (!p || p.type === 'beam' || p.type === 'sloped-ceiling' || p.type === 'vaulted-ceiling') continue;\n      if (p.type === 'free-block') {\n        const fb = Math.max(0, Number(p.restMm) || 0), ft = fb + (Number(p.heightMm) || 0);\n        if (!epRangesOverlap({ bottom: vb0, top: vb1 }, { bottom: fb, top: ft })) continue;\n      }\n      const w = p.widthMm || 0, d = p.depthMm || 0;\n      if (!(w > 0) || !(d > 0)) continue;\n      const th = ((p.rotationDeg || 0) * Math.PI) / 180;\n      const aw = Math.abs(w * Math.cos(th)) + Math.abs(d * Math.sin(th));\n      const ad = Math.abs(w * Math.sin(th)) + Math.abs(d * Math.cos(th));\n      const cx = p.x + w / 2, cy = p.y + d / 2;\n      const r = { x0: cx - aw / 2, x1: cx + aw / 2, y0: cy - ad / 2, y1: cy + ad / 2 };\n      if (horiz ? overlaps(r.y0, r.y1) : overlaps(r.x0, r.x1)) take(ahead(r));\n    }\n    return Number.isFinite(best) ? Math.max(0, best) : groupWallGap(members, dir);\n  }\n  function getGroupGaps(ids, mode) {\n    const members = groupMembersOf(ids);\n    const out = {};\n    for (const dir of Object.keys(GROUP_DIRS)) {\n      const g = mode === 'nearest' ? groupNearestGap(members, dir) : groupWallGap(members, dir);\n      out[dir] = (g == null || !isFinite(g)) ? null : Math.max(0, Math.round(g));\n    }\n    return out;\n  }\n  // Move every unit of the group by the same amount, kept inside the room's\n  // outline, then let panels and fillers follow as a single unit's move does.\n  function moveGroupBy(ids, dx, dy) {\n    const members = groupMembersOf(ids);\n    if (!members.length) return;\n    if (members.some(m => m.positionLocked)) return;   // POSITION LOCK\n    const rb = getBoundingBox(room);\n    if (rb) {\n      const bb = groupBbox(members);\n      if (bb.x0 + dx < rb.minX) dx = rb.minX - bb.x0;\n      if (bb.x1 + dx > rb.maxX) dx = rb.maxX - bb.x1;\n      if (bb.y0 + dy < rb.minY) dy = rb.minY - bb.y0;\n      if (bb.y1 + dy > rb.maxY) dy = rb.maxY - bb.y1;\n    }\n    if (Math.abs(dx) < 0.5 && Math.abs(dy) < 0.5) return;\n    for (const m of members) { m.x += dx; m.y += dy; }\n    autoDetectEndPanels(members.map(m => m.id));\n    autoDetectBackPanels();\n    resizeFillers();\n    rerender();\n  }\n  function handleSetGroupDistance(ids, dir, mode, targetMm) {\n    const members = groupMembersOf(ids);\n    const v = GROUP_DIRS[dir];\n    if (!members.length || !v) return;\n    const gap = mode === 'nearest' ? groupNearestGap(members, dir) : groupWallGap(members, dir);\n    if (gap == null || !isFinite(gap)) return;\n    const move = gap - Math.max(0, Math.round(Number(targetMm) || 0));\n    moveGroupBy(ids, v.x * move, v.y * move);\n  }\n  function handleNudgeGroup(ids, dir, mm) {\n    const v = GROUP_DIRS[dir];\n    const amt = Math.round(Number(mm) || 0);\n    if (!v || amt <= 0) return;\n    moveGroupBy(ids, v.x * amt, v.y * amt);\n  }\n  // Snap: up against whatever is nearest on that side.\n  function handleSnapGroup(ids, dir) { handleSetGroupDistance(ids, dir, 'nearest', 0); }\n  // The distance box in use, drawn on the plan as for a unit.\n  function showGroupSpan(ids, dir, mode) {\n    const svg = planOverlaySvg();\n    if (!svg || !lastGrid) return;\n    clearFocusBar(svg);\n    const members = groupMembersOf(ids);\n    const v = GROUP_DIRS[dir];\n    if (!members.length || !v) return;\n    const gap = mode === 'nearest' ? groupNearestGap(members, dir) : groupWallGap(members, dir);\n    if (gap == null || !isFinite(gap)) return;\n    const bb = groupBbox(members);\n    const a = v.x ? { x: v.x > 0 ? bb.x1 : bb.x0, y: (bb.y0 + bb.y1) / 2 }\n                  : { x: (bb.x0 + bb.x1) / 2, y: v.y > 0 ? bb.y1 : bb.y0 };\n    drawFocusBar(svg, a, { x: a.x + v.x * gap, y: a.y + v.y * gap }, lastGrid.pxPerMm);\n  }\n  function groupIdOf(ids) {\n    const m = groupMembersOf(ids)[0];\n    return m ? m.groupId || null : null;\n  }\n\n  function getCabinetWallGaps(cabId) {\n    const cab = cabinets.find(c => c.id === cabId);\n    if (!cab) return null;\n    const out = {};\n    for (const dir of ['left', 'right', 'forward', 'back']) {\n      const r = cabinetWallGap(cab, dir);\n      out[dir] = r ? Math.max(0, Math.round(r.gap)) : null;\n    }\n    return out;\n  }\n\n  // Walls mode: move the cabinet so its distance to the room wall on\n  // `dir` equals `targetMm`. Moving outward by (currentGap - target)\n  // closes the gap to the target.\n  function handleSetCabinetWallDistance(cabId, dir, targetMm) {\n    if (cabPositionLocked(cabId)) return;   // POSITION LOCK - stays where it is\n    const idx = cabinets.findIndex(c => c.id === cabId);\n    if (idx === -1) return;\n    const cab = cabinets[idx];\n    const r = cabinetWallGap(cab, dir);\n    if (!r) return;\n    const target = Math.max(0, Math.round(Number(targetMm) || 0));\n    const move = r.gap - target;\n    if (Math.abs(move) < 0.5) return;\n    let nx = cab.x + r.outward.x * move;\n    let ny = cab.y + r.outward.y * move;\n    // Clamp inside the room bbox so an over-large distance can't push the\n    // unit out through the opposite wall.\n    const rb = getBoundingBox(room);\n    if (rb) {\n      const vb = visualBbox({ ...cab, x: nx, y: ny });\n      if (vb.x0 < rb.minX) nx += rb.minX - vb.x0;\n      if (vb.x1 > rb.maxX) nx -= vb.x1 - rb.maxX;\n      if (vb.y0 < rb.minY) ny += rb.minY - vb.y0;\n      if (vb.y1 > rb.maxY) ny -= vb.y1 - rb.maxY;\n    }\n    cabinets[idx] = { ...cab, x: nx, y: ny };\n    autoDetectEndPanels([cabId]);\n    autoDetectBackPanels();\n    resizeFillers();\n    rerender();\n  }\n\n  // Manual fill: add a filler on the chosen side sized to the\n  // current gap, capped at 100mm, with the standard 20mm setback.\n  function fillCabinetSide(cabId, side) {\n    const idx = cabinets.findIndex(c => c.id === cabId);\n    if (idx === -1) return;\n    const cab = cabinets[idx];\n    // Measure CARCASE-to-wall - the filler replaces any end panel on\n    // this side and must span the whole gap. Measuring from the panel\n    // face would leave the filler one panel-thickness (20mm) short.\n    // Ahead only - same measure as getCabinetFillGap.\n    const signed = epClosestForwardGap(cab, side, { fromCarcase: true, directionalOnly: true, includeTouching: true });\n    if (signed == null) return;\n    const width = Math.max(1, Math.min(FILLER_MAX_GAP_MM, Math.round(signed)));\n    const epDefault  = { active: false, style: 'flat', inline: false, pelmetExt: 'modern' };\n    const filDefault = { active: false, widthMm: FILLER_DEFAULT_MM, setBackMm: 0 };\n    const ep  = cab.endPanels || { left: { ...epDefault },  right: { ...epDefault } };\n    const fil = cab.fillers   || { left: { ...filDefault }, right: { ...filDefault } };\n    cabinets[idx] = {\n      ...cab,\n      endPanels: { ...ep,  [side]: { ...epDefault, ...ep[side],  active: false } },\n      // Auto fill measured this width, so it is NOT a custom size - clear the\n      // lock so it keeps re-fitting if the unit moves.\n      fillers:   { ...fil, [side]: { ...filDefault, ...fil[side], active: true, widthMm: width, setBackMm: FILLER_TALL_SETBACK_MM, userWidth: false } }\n    };\n    rerender();\n  }\n\n  // Auto-detect the breakfast-bar back panel for every base / corner-\n  // base cabinet. A base unit's back counts as \"exposed\" - and so\n  // gets a back panel attached - when it is NOT flush with:\n  //   * a room wall (cab against an outer wall - typical layout)\n  //   * another cabinet's face (back-to-back islands, neighbour cab\n  //     in front of this one, etc.)\n  //   * a pillar / internal wall (column feature)\n  // Tolerance is BB_BACK_GAP_MM so the detection is forgiving - a\n  // cab dropped within ~10cm of a wall still counts as against it.\n  // The host unit's side end-panel depth is bumped in the renderer\n  // by reading cab.backPanel.thicknessMm at draw time; this function\n  // only owns the active flag + thickness data.\n  // Is a free-standing appliance standing at this corner unit's DOOR end with\n  // its own panel on that side? Then that panel finishes the joint and the\n  // corner unit's would be a second one beside it (Arden, 2026-10-13). The\n  // carcases may be two panels and a fitting gap apart, so up to 110mm.\n  function cornerDoorEndAtAppliance(cab, scope) {\n    if (!cab || !cab.cornerUnit || /^wall/i.test(cab.category || '')) return false;\n    const doorSide = cab.cornerUnit.hand === 'right' ? 'right' : 'left';\n    const line = epCarcaseSides(cab)[doorSide];\n    return (scope || cabinets).some(o => o && o.id !== cab.id && o.freestandingAppliance\n      && ['left', 'right'].some(k => epFaceIsFinished(o, k)\n        && epLinesCoincide(line, epCarcaseSides(o)[k], 110)));\n  }\n  // The same rule, applied wherever the back panels are worked out - on load\n  // and after every change - so a plan drawn before it, or an appliance that\n  // arrived without the end-panel walk reaching the corner unit, is put right\n  // without having to move anything. A side the user set by hand is theirs.\n  function dropCornerPanelsAtAppliances() {\n    let changed = false;\n    cabinets = cabinets.map(cab => {\n      if (!cab || !cab.cornerUnit) return cab;\n      const doorSide = cab.cornerUnit.hand === 'right' ? 'right' : 'left';\n      const ep = (cab.endPanels || {})[doorSide];\n      if (!ep || !ep.active || epSideUserSet(cab, doorSide)) return cab;\n      if (!cornerDoorEndAtAppliance(cab)) return cab;\n      changed = true;\n      return { ...cab, endPanels: { ...cab.endPanels, [doorSide]: { ...ep, active: false } } };\n    });\n    return changed;\n  }\n\n  // What a free-standing appliance's island back panel copies from the unit\n  // beside it (see faBackPanel): its range, colour, finish and height - and\n  // which unit that is (fromCabId), so the copy can follow that unit's later\n  // restyles and recolours (syncApplianceBackMaterials).\n  function applianceBackMaterial(cab, o) {\n    const om = o && o.freestandingAppliance ? ((o.backPanel && o.backPanel.material) || {}) : null;\n    const m = o\n      ? { styleId: om ? (om.styleId || null) : (o.kitchenStyleId || null),\n          colour:  om ? (om.colour || null) : backPanelColour(o),\n          finish:  om ? (om.finish || 'plain') : backPanelFinish(o),\n          heightMm: om ? (om.heightMm || null) : (o.heightMm || null),\n          fromCabId: o.id }\n      : { styleId: null, colour: null, finish: 'plain', heightMm: null, fromCabId: null };\n    // Up to the worktop line beside it, never short of its own top.\n    m.heightMm = Math.max((cab && cab.heightMm) || 0, m.heightMm || 0) || null;\n    return m;\n  }\n  // Every render: re-copy each appliance's back panel material from the unit\n  // it copies (Arden, 2026-10-13: restyling the plan to Darlington left the\n  // Dishwasher's panel in the old range's dark green). The copy used to be\n  // refreshed only when the back panels were re-detected, which a style or\n  // colour change does not do. Material only - the geometry stays with\n  // autoDetectBackPanels. Twice, so an appliance copying another appliance\n  // follows it in the same render.\n  function syncApplianceBackMaterials() {\n    for (let pass = 0; pass < 2; pass++) {\n      let moved = false;\n      cabinets = cabinets.map(cab => {\n        const bp = cab && cab.freestandingAppliance && cab.backPanel;\n        if (!bp || !bp.active || !bp.material || !bp.material.fromCabId) return cab;\n        const o = cabinets.find(x => x && x.id === bp.material.fromCabId);\n        if (!o) return cab;\n        const next = applianceBackMaterial(cab, o);\n        if (JSON.stringify(next) === JSON.stringify(bp.material)) return cab;\n        moved = true;\n        return { ...cab, backPanel: { ...bp, material: next } };\n      });\n      if (!moved) break;\n    }\n  }\n\n  // A unit BACKED ON to the end of a breakfast-bar run (Sales sheet line 110,\n  // PLN101055): its back against the end side of the run's last unit, one of\n  // its sides in line with the run's back. That side is part of the breakfast\n  // bar panel - the run's panel carries on along it, as far as the unit's\n  // front - and takes no end panel of its own. E.g. an open base unit set\n  // across the end of a peninsula. -> { side, hostId, end: 'lo' | 'hi', extMm }\n  // or null. Purely geometric, so the end panel and back panel passes agree.\n  const BACKED_ON_TOL_MM = 30;     // back against the host's side (an end panel's width)\n  const BACKED_ON_LINE_MM = 80;    // its side this close to the host's back line\n  function backedOnBbSide(U, list = cabinets) {\n    if (!U || U.endPanelUnit || U.freestandingAppliance || isStacked(U)) return null;\n    const isBaseCab = (c) => /^base/i.test(c.category || '') && !c.stackOn;\n    if (!isBaseCab(U)) return null;\n    const uSides = epCarcaseSides(U, { noBackPanelReach: true });\n    const distTo = (p, l) => {\n      const dx = l.p2.x - l.p1.x, dy = l.p2.y - l.p1.y, len = Math.hypot(dx, dy) || 1;\n      return Math.abs((p.x - l.p1.x) * dy - (p.y - l.p1.y) * dx) / len;\n    };\n    const mid = (l) => ({ x: (l.p1.x + l.p2.x) / 2, y: (l.p1.y + l.p2.y) / 2 });\n    for (const E of (list || [])) {\n      if (!E || E.id === U.id || !isBaseCab(E) || !(E.backPanel && E.backPanel.active)) continue;\n      if ((E.heightMm || 0) - (U.heightMm || 0) > 100) continue;\n      const run = backPanelRunOf(list, E.id);\n      if (!run || !run.length) continue;\n      const eSides = epCarcaseSides(E, { noBackPanelReach: true });\n      for (const [side, end] of [['right', 'lo'], ['left', 'hi']]) {\n        if ((end === 'lo' ? run[0] : run[run.length - 1]).id !== E.id) continue;\n        // A unit moved out for a door end's void (doorVoidMm) still counts.\n        if (!epLinesCoincide(eSides[side], uSides.back, BACKED_ON_TOL_MM + (Number(U.doorVoidMm) || 0))) continue;\n        // Which of U's sides runs along the host's back line.\n        let best = null;\n        for (const s of ['left', 'right']) {\n          const l = uSides[s];\n          const d = Math.max(distTo(l.p1, eSides.back), distTo(l.p2, eSides.back));\n          if (d <= BACKED_ON_LINE_MM && (!best || d < best.d)) best = { s, d };\n        }\n        if (!best) continue;\n        const extMm = Math.round(distTo(mid(uSides.front), eSides[side]));\n        if (!(extMm > 0)) continue;\n        return { side: best.s, hostId: E.id, end, extMm };\n      }\n    }\n    return null;\n  }\n\n  function autoDetectBackPanels() {\n    if (!autoEndPanels) return;   // manual mode: breakfast-bar back panels are panels too - leave the user's choices untouched\n    // First, so the back runs below see the corner unit without that panel.\n    const cornerPanelsDropped = dropCornerPanelsAtAppliances();\n    const walls = getWalls(room);\n    const perim = roomConfig.perimeterItems || [];\n    const pillarEdges = [];\n    for (const p of perim) {\n      if (!p || p.type !== 'column') continue;\n      for (const e of epItemEdges(p)) pillarEdges.push(e);\n    }\n    // A FREE-STANDING APPLIANCE in an island or peninsula (Arden, 2026-10-13):\n    // a washer or wine cooler on an open back leaves a hole in the island's\n    // back panel, so it takes the panel too, in the material of the unit\n    // beside it in the run. That unit: same way round, back on the same line\n    // (within 40mm), within 80mm along the run - the appliance stands off its\n    // neighbours by its own end panels and fitting gaps. A unit beats an\n    // appliance; an appliance only lends what it borrowed itself.\n    const faBackOf = (c) => {\n      const b = epCarcaseSides(c, { noBackPanelReach: true }).back;\n      return { x: (b.p1.x + b.p2.x) / 2, y: (b.p1.y + b.p2.y) / 2 };\n    };\n    // How far past its carcase back a unit's back panel's OUTER face sits, in\n    // the same three placements the 2D / 3D build it.\n    const faPanelReach = (o) => {\n      const bp = o.backPanel || {};\n      const T = bp.thicknessMm || BB_BACK_PANEL_THICK_MM;\n      if (bp.standOffMm != null) return Math.max(T, bp.standOffMm);\n      const bep = o.backEndPost;\n      if (bep && bep.active) {\n        const E = Math.max(0, Math.min(650, Number(bep.panelLengthMm) || 650));\n        return Math.max(T, E + 120 - (o.depthMm || 0));\n      }\n      // Stepped off its back (Breakfast Bar Back Panel popup, an island's\n      // service void): the panel's outer face is the gap and the panel past it.\n      if (bp.gapMm != null && Number.isFinite(Number(bp.gapMm))) return Math.max(T, Number(bp.gapMm) + T);\n      const so = o.epManualBack ? o.epManualBack.standOffMm\n        : o.useFullSizeEndPanel ? Math.max(0, 650 - 18 - (o.depthMm || 0)) : 0;\n      return Math.max(T, so);\n    };\n    const faRunNeighbour = (cab) => {\n      const th = ((cab.rotationDeg || 0) * Math.PI) / 180;\n      const ax = Math.cos(th), ay = Math.sin(th);\n      const nx = -Math.sin(th), ny = Math.cos(th);   // out of the back\n      const pa = faBackOf(cab);\n      const ca = { x: cab.x + cab.widthMm / 2, y: cab.y + cab.depthMm / 2 };\n      let best = null;\n      for (const o of cabinets) {\n        if (!o || o.id === cab.id || !o.backPanel || !o.backPanel.active) continue;\n        if (o.freestandingAppliance && !o.backPanel.material) continue;\n        if (o.lShapeUnit || o.diagonalCornerUnit || o.backPanel.thProfile) continue;\n        if (Array.isArray(o.backPanel.spans) && o.backPanel.spans.length) continue;\n        const dr = ((((o.rotationDeg || 0) - (cab.rotationDeg || 0)) % 360) + 360) % 360;\n        if (dr > 1 && dr < 359) continue;\n        const po = faBackOf(o);\n        const off = (po.x - pa.x) * nx + (po.y - pa.y) * ny;\n        if (Math.abs(off) > 40) continue;\n        const co = { x: o.x + o.widthMm / 2, y: o.y + o.depthMm / 2 };\n        const gap = Math.abs((co.x - ca.x) * ax + (co.y - ca.y) * ay) - (cab.widthMm + o.widthMm) / 2;\n        if (gap > 80) continue;\n        const score = gap + (o.freestandingAppliance ? 1000 : 0);\n        if (!best || score < best.score) best = { o, off, score };\n      }\n      return best;\n    };\n    // Which of the appliance's ends the island's back panel run carries on\n    // past: a unit (or another panelled appliance) with its back panel on,\n    // same way round, back on the same line, within 80mm along the run on\n    // that side. lo = its local x < 0 end (user-right), hi = the far end.\n    const faRunSides = (cab) => {\n      const th = ((cab.rotationDeg || 0) * Math.PI) / 180;\n      const ax = Math.cos(th), ay = Math.sin(th);\n      const nx = -Math.sin(th), ny = Math.cos(th);\n      const pa = faBackOf(cab);\n      const ca = { x: cab.x + cab.widthMm / 2, y: cab.y + cab.depthMm / 2 };\n      const out = { lo: false, hi: false, gap: { lo: null, hi: null } };\n      for (const o of cabinets) {\n        if (!o || o.id === cab.id || !o.backPanel || !o.backPanel.active) continue;\n        if (o.lShapeUnit || o.diagonalCornerUnit) continue;\n        const dr = ((((o.rotationDeg || 0) - (cab.rotationDeg || 0)) % 360) + 360) % 360;\n        if (dr > 1 && dr < 359) continue;\n        const po = faBackOf(o);\n        if (Math.abs((po.x - pa.x) * nx + (po.y - pa.y) * ny) > 40) continue;\n        const co = { x: o.x + o.widthMm / 2, y: o.y + o.depthMm / 2 };\n        const along = (co.x - ca.x) * ax + (co.y - ca.y) * ay;\n        const g = Math.abs(along) - (cab.widthMm + o.widthMm) / 2;\n        if (g > 80) continue;\n        const k = along > 0 ? 'hi' : 'lo';\n        out[k] = true;\n        if (out.gap[k] == null || g < out.gap[k]) out.gap[k] = Math.max(0, g);\n      }\n      return out;\n    };\n    // The appliance's back panel when its back is open: borrowed material,\n    // reach to the run's panel line, and widened over its end panels + gaps.\n    const faBackPanel = (cab) => {\n      const T = BB_BACK_PANEL_THICK_MM;\n      const nb = faRunNeighbour(cab);\n      const o = nb && nb.o;\n      const material = applianceBackMaterial(cab, o);\n      const standOffMm = o ? Math.round(Math.max(T, faPanelReach(o) + nb.off)) : T;\n      const gapMm = Math.max(0, Number(cab.endPanelGapMm) || 0);\n      const ep = cab.endPanels || {};\n      // Its END PANELS run back to this panel (Arden, 2026-10-13: they stopped\n      // at the appliance's own back, a gap short of it). Where the run carries\n      // on past a side (runOn), the back panel carries on behind that end\n      // panel, which stops at the panel's inner face; at the END of the run\n      // the end panel runs to the panel's outer face and covers its edge, as a\n      // unit's full-size end panel does, so the back panel stops at the gap.\n      const runOn = faRunSides(cab);\n      // Where the run carries on, up to the next unit's back panel, whatever\n      // stands between (its own panel, or the next unit's and the gap).\n      const sideExt = (side, k) => (runOn[k] && runOn.gap[k] != null)\n        ? Math.round(runOn.gap[k])\n        : (ep[side] && ep[side].active) ? gapMm + (runOn[k] ? endPanelThickMm(ep[side]) : 0) : 0;\n      const { gap: _g, ...runOnSides } = runOn;\n      return { active: true, thicknessMm: T, spans: null, standOffMm,\n               extMm: { lo: sideExt('right', 'lo'), hi: sideExt('left', 'hi') },\n               runOn: runOnSides, material };\n    };\n    // The saved shape, less the per-pass segments, for \"has it changed\".\n    const faBpSig = (bp) => {\n      if (!bp || !bp.active) return 'off';\n      const { segments, ...rest } = bp;\n      return JSON.stringify(rest);\n    };\n    let changed = false;\n    const faOpen = new Set();   // appliances whose back is open - see below\n    cabinets = cabinets.map(cab => {\n      // A Pastry Bench Set has its own back panel between its back legs\n      // (syncPastrySets), never the breakfast-bar one.\n      if (isPastrySet(cab)) return cab;\n      // Radius / curved units (and their auto-group pieces) never get a\n      // breakfast-bar back panel - the curved carcase IS the finished back on\n      // an island, and the backing covers it end-of-run. autoDetectEndPanels\n      // already skips them; mirror that here (they'd otherwise qualify as\n      // base-units and pick up an auto back panel on an exposed island back).\n      if (cab.radiusUnit || cab.radiusGroup) {\n        const hadActive = !!(cab.backPanel && cab.backPanel.active);\n        const hadFull   = !!cab.useFullSizeEndPanel;\n        if (hadActive || hadFull) {\n          changed = true;\n          return { ...cab, backPanel: { ...(cab.backPanel || {}), active: false }, useFullSizeEndPanel: false };\n        }\n        return cab;\n      }\n      // A free-standing appliance takes no back panel unless it stands in the\n      // base run under the worktop line, on the floor (see faBackPanel) - a\n      // tall fridge or a stacked dryer never does.\n      if (cab.freestandingAppliance) {\n        const fa = cab.freestandingAppliance;\n        if (fa.kind === 'tall' || isStacked(cab) || isApplianceStackMode(cab.stackOn)\n            || !/^base/i.test(cab.category || '')) {\n          if (cab.backPanel && cab.backPanel.active) {\n            changed = true;\n            return { ...cab, backPanel: { ...cab.backPanel, active: false } };\n          }\n          return cab;\n        }\n      }\n      // STACKED units never auto-get a breakfast-bar back panel or the\n      // full-size end panel (the battened stand-off back). Both finish\n      // an island's exposed BACK at floor level - a unit sitting on top\n      // of another one isn't an island edge, and the batten build only\n      // makes sense on a floor-standing carcase. Force both off, the\n      // same way radius units are handled above, so a unit that picks\n      // them up and is THEN stacked drops them.\n      if (isStacked(cab)) {\n        const hadActive = !!(cab.backPanel && cab.backPanel.active);\n        const hadFull   = !!cab.useFullSizeEndPanel;\n        if (hadActive || hadFull) {\n          changed = true;\n          return { ...cab, backPanel: { ...(cab.backPanel || {}), active: false }, useFullSizeEndPanel: false };\n        }\n        return cab;\n      }\n      // Back-panel auto-detect applies to BASE + corner-BASE units\n      // only. Wall-category corner units never get a back panel.\n      const cabCat = cab.category || '';\n      const isBase = (/^base/i.test(cabCat)) ||\n                     ((!!cab.cornerUnit || !!cab.lShapeUnit || !!cab.diagonalCornerUnit)\n                       && !/^wall/i.test(cabCat) && !/^bridging/i.test(cabCat) && !/^tall/i.test(cabCat));\n      if (!isBase) {\n        // Wall / tall / bridging never get a breakfast-bar back panel.\n        const hadActive = !!(cab.backPanel && cab.backPanel.active);\n        const hadFull   = !!cab.useFullSizeEndPanel;\n        if (hadActive || hadFull) {\n          changed = true;\n          return {\n            ...cab,\n            backPanel: { ...(cab.backPanel || {}), active: false },\n            useFullSizeEndPanel: false\n          };\n        }\n        return cab;\n      }\n      // Is a single edge LINE exposed (open to the room) - i.e. NOT flush\n      // against a wall, a same-or-taller neighbour cab, or a pillar? Shared\n      // by the single-back check and the L/diagonal per-outer-edge check.\n      const cabH = cab.heightMm || 0;\n      // `line` is the panel-extended edge (used for NEIGHBOUR adjacency so a\n      // cab flush against a breakfast-bar panel's outer face reads as touching).\n      // `solidLine` is the edge tested against WALLS and PILLARS - callers pass\n      // the true carcase edge there so a reduced-depth unit's own panel reach\n      // can't push the line past the wall and hide it (see epCarcaseSides'\n      // noBackPanelReach note). Defaults to `line` when not supplied.\n      // The front and back edges of a unit's active side FILLERS. A filler\n      // stands in the run beside its unit, so a back facing one is covered -\n      // an island's back row behind a filler took a small breakfast-bar panel\n      // piece where nothing was open (Arden, 2026-10-19). Cab-local +X is\n      // user-left, as the fillers' own left / right are.\n      const fillerEdges = (other) => {\n        const fil = other.fillers || {};\n        const W = other.widthMm || 0, D = other.depthMm || 0;\n        const cx = (other.x || 0) + W / 2, cy = (other.y || 0) + D / 2;\n        const th = ((other.rotationDeg || 0) * Math.PI) / 180;\n        const cs = Math.cos(th), sn = Math.sin(th);\n        const P = (lx, ly) => ({ x: cx + lx * cs - ly * sn, y: cy + lx * sn + ly * cs });\n        const out = [];\n        for (const [side, sign] of [['left', 1], ['right', -1]]) {\n          const f = fil[side];\n          const fw = (f && f.active) ? (Number(f.widthMm) || 0) : 0;\n          if (!(fw > 0)) continue;\n          const a = sign * (W / 2), b = sign * (W / 2 + fw);\n          const front = -D / 2 + Math.max(0, Number(f.setBackMm) || 0);\n          out.push({ p1: P(a, D / 2), p2: P(b, D / 2) });       // back\n          out.push({ p1: P(a, front), p2: P(b, front) });       // front\n        }\n        return out;\n      };\n      const edgeExposed = (line, solidLine = line) => {\n        for (const wl of walls) {\n          if (epLinesCoincide(solidLine, { p1: wl.from, p2: wl.to }, BB_BACK_GAP_MM)) return false;\n        }\n        for (const other of cabinets) {\n          if (other.id === cab.id) continue;\n          if ((other.heightMm || 0) < cabH - 100) continue;\n          const sides = epCarcaseSides(other);\n          if (epLinesCoincide(line, sides.front, BB_BACK_GAP_MM)) return false;\n          if (epLinesCoincide(line, sides.back,  BB_BACK_GAP_MM)) return false;\n          if (epLinesCoincide(line, sides.left,  BB_BACK_GAP_MM)) return false;\n          if (epLinesCoincide(line, sides.right, BB_BACK_GAP_MM)) return false;\n          for (const fe of fillerEdges(other)) if (epLinesCoincide(line, fe, BB_BACK_GAP_MM)) return false;\n        }\n        for (const e of pillarEdges) {\n          if (epLinesCoincide(solidLine, { p1: e.a, p2: e.b }, BB_BACK_GAP_MM)) return false;\n        }\n        return true;\n      };\n      // Which STRETCHES of a straight unit's back are open to the room, as\n      // [from, to] mm along the back from cab-local x = 0. A unit running\n      // along a wall that stops part-way across it - the wall turning back on\n      // itself to make a peninsula - is walled for part of its back and open\n      // for the rest, and only the open part takes the breakfast-bar panel and\n      // battens (Arden, 2026-10-05). Covers within BB_BACK_GAP_MM are ignored\n      // exactly as epLinesCoincide ignores them, and so is an open stretch\n      // that short, so a unit that was fully open or fully walled before\n      // still is.\n      const openStretches = (line, solidLine) => {\n        const len = Math.hypot(solidLine.p2.x - solidLine.p1.x, solidLine.p2.y - solidLine.p1.y);\n        const cov = [];\n        const add = (s) => { if (s && s[1] - s[0] > BB_BACK_GAP_MM) cov.push(s); };\n        for (const wl of walls) add(epCoveredSpan(solidLine, { p1: wl.from, p2: wl.to }, BB_BACK_GAP_MM));\n        // Another unit's cover counts from the same 40mm an open stretch does:\n        // with BB_BACK_GAP_MM (100) a back-to-back island whose rows break at\n        // different places (400/1000/400 against 500/800/500) lost the 100mm\n        // overlaps at each end, read those as open, and took a back panel and\n        // full-depth end panels there (Arden, 2026-11-18).\n        const addUnit = (s) => { if (s && s[1] - s[0] > BB_BACK_OPEN_MIN_MM) cov.push(s); };\n        for (const other of cabinets) {\n          if (other.id === cab.id) continue;\n          if ((other.heightMm || 0) < cabH - 100) continue;\n          const sides = epCarcaseSides(other);\n          for (const k of ['front', 'back', 'left', 'right']) addUnit(epCoveredSpan(line, sides[k], BB_BACK_GAP_MM));\n          for (const fe of fillerEdges(other)) addUnit(epCoveredSpan(line, fe, BB_BACK_GAP_MM));\n        }\n        for (const e of pillarEdges) add(epCoveredSpan(solidLine, { p1: e.a, p2: e.b }, BB_BACK_GAP_MM));\n        cov.sort((a, b) => a[0] - b[0]);\n        const open = [];\n        let at = 0;\n        for (const [lo, hi] of cov) {\n          if (lo > at) open.push([at, lo]);\n          at = Math.max(at, hi);\n        }\n        if (at < len) open.push([at, len]);\n        return { len, open: open.filter(([a, b]) => b - a > BB_BACK_OPEN_MIN_MM) };\n      };\n      // L/diagonal islands have TWO independent outer edges (opposite the\n      // cutout) - detect each against walls/neighbours separately so a corner\n      // (both against walls) drops the breakfast bar entirely and a peninsula\n      // (one wall) keeps the exposed side. Non-L cabs use the single back edge.\n      const lsU = cab.lShapeUnit || cab.diagonalCornerUnit;\n      let exposed, edgeExp = null;\n      // Open stretches of a PARTLY walled back, or null when the whole back\n      // is open (or none of it is) - see openStretches.\n      let openSpans = null;\n      if ((cab.wallSetbackMm || 0) > 0) {\n        exposed = false;\n        if (lsU) edgeExp = { sy: false, sx: false };\n      } else if (lsU) {\n        const W = cab.widthMm, D = cab.depthMm;\n        const hand = (lsU.hand || 'NE').toUpperCase();\n        const sy = (hand === 'NE' || hand === 'NW') ? 1 : -1;\n        const sx = (hand === 'NW' || hand === 'SW') ? 1 : -1;\n        const cx = cab.x + W / 2, cy = cab.y + D / 2;\n        const th = ((cab.rotationDeg || 0) * Math.PI) / 180;\n        const cs = Math.cos(th), sn = Math.sin(th);\n        const L2W = (lx, ly) => ({ x: cx + (lx - W / 2) * cs - (ly - D / 2) * sn,\n                                   y: cy + (lx - W / 2) * sn + (ly - D / 2) * cs });\n        const syLine = { p1: L2W(0, sy > 0 ? D : 0),   p2: L2W(W, sy > 0 ? D : 0) };\n        const sxLine = { p1: L2W(sx > 0 ? W : 0, 0),   p2: L2W(sx > 0 ? W : 0, D) };\n        const expSy = edgeExposed(syLine);\n        const expSx = edgeExposed(sxLine);\n        edgeExp  = { sy: expSy, sx: expSx };\n        exposed  = expSy || expSx;\n      } else {\n        // Wall / pillar test uses the TRUE carcase back (no breakfast-bar\n        // reach) so a reduced-depth unit seated against a wall is correctly\n        // read as wall-backed and its full-size panel + breakfast bar switch\n        // off; neighbour adjacency keeps the panel-extended back line.\n        const { len, open } = openStretches(\n          epCarcaseSides(cab).back,\n          epCarcaseSides(cab, { noBackPanelReach: true }).back\n        );\n        exposed = open.length > 0;\n        const whole = open.length === 1 && open[0][0] <= 1 && open[0][1] >= len - 1;\n        if (exposed && !whole) {\n          openSpans = open.map(([a, b]) => ({ fromMm: Math.round(a), toMm: Math.round(b) }));\n        }\n      }\n      // None, chosen on the Back Panel tile (Sales bug sheet row 92, Annabel):\n      // no back panel on this unit, as though its back were against a wall -\n      // e.g. a unit set against the back of a peninsula. The rest of the run\n      // keeps its panel.\n      // On an L / diagonal both outer edges go, as though it sat in a corner.\n      if (cab.backPanel && cab.backPanel.userOff) {\n        exposed = false; openSpans = null;\n        if (lsU) edgeExp = { sy: false, sx: false };\n      }\n      // A free-standing appliance: on when any of its back is open (a part-\n      // walled one is rare enough to take the whole width), in its neighbour's\n      // material - see faBackPanel. Nothing else about it changes.\n      // Its panel is worked out AFTER this pass (below), once the units\n      // beside it have theirs - it copies them.\n      if (cab.freestandingAppliance) {\n        if (exposed) { faOpen.add(cab.id); return cab; }\n        if (!(cab.backPanel && cab.backPanel.active)) return cab;\n        changed = true;\n        return { ...cab, backPanel: { ...cab.backPanel, active: false } };\n      }\n      const spansSame = JSON.stringify((cab.backPanel && cab.backPanel.spans) || null)\n        === JSON.stringify(openSpans);\n      // A blank-panel corner unit has a second open end: the VOID end.\n      // autoDetectBackPanels only ever tested the BACK, so `exposed` (and\n      // with it useFullSizeEndPanel) said nothing about that end - yet the\n      // 2D/3D renderers wrap the breakfast-bar finish round it whenever\n      // the back is exposed. Butt the void end to a wall (peninsula) and\n      // the wrap - void extension, side panel, batten - stood ~62mm proud\n      // of that wall with no way to switch off. Measure it the same way\n      // the back is measured and let the renderers read the answer.\n      //\n      // Which bbox side the void is on: cab-local +X is user-LEFT, so\n      // hand 'right' \u2192 void on user-LEFT and vice versa - the same\n      // mapping the end-panel normaliser uses for voidSide.\n      let voidExp = null;\n      if (cab.cornerUnit) {\n        const vSide = cab.cornerUnit.hand === 'right' ? 'left' : 'right';\n        voidExp = edgeExposed(epCarcaseSides(cab)[vSide]);\n      }\n      const voidSame = !cab.cornerUnit\n        || (cab.cornerUnit.voidEdgeExposed === voidExp);\n      const wasActive   = !!(cab.backPanel && cab.backPanel.active);\n      const wasFull     = !!cab.useFullSizeEndPanel;\n      // Full depth end panel (Arden, 2026-10-18): on by default for an open\n      // back, but a unit where it was chosen in the panel keeps that choice -\n      // Standard puts the back panel flush on the unit, no battens, and the\n      // worktop stays a standard depth. It used to be re-ticked here on every\n      // pass, so a choice of Standard lasted only until the next move or load.\n      const wantFull    = cab.fullSizeEndPanelUserSet ? !!cab.useFullSizeEndPanel : exposed;\n      const wasBackPost = !!(cab.backEndPost && cab.backEndPost.active);\n      const prevEdge    = cab.lShapeEdgeExposed || null;\n      const edgeSame    = !lsU || (prevEdge && prevEdge.sy === edgeExp.sy && prevEdge.sx === edgeExp.sx);\n      // useFullSizeEndPanel auto-ticks ON when the back is exposed\n      // (island / breakfast bar - supplied 650mm end panel stays\n      // uncut; back panel stands off the cab back to line up) and\n      // OFF for back-to-back / wall-against cases where the cut\n      // edge of the panel is hidden anyway.\n      //\n      // backEndPost is user-controlled (no auto-tick) but force-\n      // OFF when the back is no longer exposed - the back post\n      // construction only makes sense on a freestanding island.\n      const nextBackPost = exposed\n        ? (cab.backEndPost || null)\n        : (wasBackPost ? { ...(cab.backEndPost || {}), active: false } : (cab.backEndPost || null));\n      // A freestanding TH unit whose back panel is already active but never\n      // received the thProfile DEFAULT (undefined) must still fall through to\n      // the rebuild below so it gets set - otherwise the stable-state early\n      // return leaves thProfile undefined forever and the TH back never renders.\n      const needsThProfileDefault = exposed\n        && (cab.backPanel == null || cab.backPanel.thProfile == null)\n        && !!(Catalogue.isStyleTrueRail && Catalogue.isStyleTrueRail(cab.kitchenStyleId));\n      if (\n        exposed === wasActive &&\n        wantFull === wasFull &&\n        (!wasBackPost || exposed) &&\n        edgeSame &&\n        voidSame &&\n        spansSame &&\n        !needsThProfileDefault\n      ) {\n        return cab;\n      }\n      changed = true;\n      return {\n        ...cab,\n        backPanel: {\n          ...(cab.backPanel || {}),\n          active:        exposed,\n          thicknessMm:   BB_BACK_PANEL_THICK_MM,\n          // Only these stretches of the back take the panel (null = all of it).\n          spans:         openSpans,\n          // True Handleless freestanding units: the exposed back mirrors the\n          // FRONT (top/mid rail + external corner posts + door-thick/drawer-split\n          // panel) by DEFAULT. The user can toggle it off \u2192 plain breakfast-bar\n          // panel (extended over the side end panels). Preserve an explicit choice.\n          thProfile: (cab.backPanel && cab.backPanel.thProfile != null)\n            ? cab.backPanel.thProfile\n            : (exposed && !!(Catalogue.isStyleTrueRail && Catalogue.isStyleTrueRail(cab.kitchenStyleId)))\n        },\n        useFullSizeEndPanel: wantFull,\n        ...(nextBackPost ? { backEndPost: nextBackPost } : {}),\n        ...(lsU ? { lShapeEdgeExposed: edgeExp } : {}),\n        ...(cab.cornerUnit\n          ? { cornerUnit: { ...cab.cornerUnit, voidEdgeExposed: voidExp } }\n          : {})\n      };\n    });\n    // The open-backed appliances, now the units round them are settled. Twice,\n    // so one beside another appliance can copy what that one copied.\n    for (let pass = 0; pass < 2 && faOpen.size; pass++) {\n      cabinets = cabinets.map(cab => {\n        if (!faOpen.has(cab.id)) return cab;\n        const next = faBackPanel(cab);\n        if (faBpSig(next) === faBpSig(cab.backPanel)) return cab;\n        changed = true;\n        return { ...cab, backPanel: next };\n      });\n    }\n    // BACKED-ON UNITS (backedOnBbSide): the host run's panel carried on along\n    // the unit's side, as the Breakfast Bar Back Panel popup's extension does\n    // by hand. Marked autoExt so it goes again when the unit is moved away; an\n    // extension the user set is theirs and is never changed.\n    {\n      const want = new Map();     // hostId -> { lo, hi }\n      const offSide = new Map();  // unit id -> side\n      for (const U of cabinets) {\n        const r = backedOnBbSide(U, cabinets);\n        if (!r) continue;\n        const w = want.get(r.hostId) || {};\n        w[r.end] = Math.min(BACK_PANEL_EXT_MAX_MM, Math.max(w[r.end] || 0, r.extMm));\n        want.set(r.hostId, w);\n        offSide.set(U.id, r.side);\n      }\n      cabinets = cabinets.map(cab => {\n        let out = cab;\n        if (cab.backPanel && (want.has(cab.id) || cab.backPanel.autoExt)) {\n          const w = want.get(cab.id) || {};\n          const ux = { ...(cab.backPanel.userExtMm || {}) };\n          const ax = { ...(cab.backPanel.autoExt || {}) };\n          let touched = false;\n          for (const end of ['lo', 'hi']) {\n            if (w[end] && (!(Number(ux[end]) > 0) || ax[end])) {\n              if (ux[end] !== w[end] || !ax[end]) { ux[end] = w[end]; ax[end] = true; touched = true; }\n            } else if (!w[end] && ax[end]) {\n              delete ux[end]; delete ax[end]; touched = true;\n            }\n          }\n          if (touched) out = { ...out, backPanel: { ...out.backPanel, userExtMm: ux, autoExt: ax } };\n        }\n        const s = offSide.get(cab.id);\n        if (s && cab.endPanels && cab.endPanels[s] && cab.endPanels[s].active && !epSideUserSet(cab, s)) {\n          out = { ...out, endPanels: { ...out.endPanels, [s]: { ...out.endPanels[s], active: false } } };\n        }\n        if (out !== cab) changed = true;\n        return out;\n      });\n    }\n    const voidExtChanged = detectCornerVoidExtensions();\n    return changed || voidExtChanged || cornerPanelsDropped;\n  }\n\n  // When a corner unit's connected run neighbour has 'Radius/Square on\n  // Back of Unit' (backEndPost) set, that neighbour's breakfast-bar back\n  // panel reaches further out than a standard full-size one. Extend the\n  // corner unit's void + side panel by that extra reach so the two meet.\n  // Writes cornerUnit.neighbourBackExtMm, consumed by the 2D/3D renderers.\n  // ext = 0 (no bep neighbour) leaves existing layouts untouched.\n  function detectCornerVoidExtensions() {\n    let changed = false;\n    cabinets = cabinets.map(cab => {\n      const cu = cab.cornerUnit;\n      if (!cu) return cab;\n      // The connected run unit's back panel lines up with the corner\n      // unit's void side panel - so it shows up as a collinear neighbour\n      // on one of the corner unit's edges. Scan every side and take the\n      // first neighbour that itself has 'Radius/Square on Back' set.\n      const range = epVerticalRange(cab);\n      let nb = null;\n      for (const side of ['left', 'right', 'front', 'back']) {\n        const cand = epFindNeighbourOnSide(cab, side, range, cabinets);\n        if (cand && cand.id !== cab.id && cand.backEndPost && cand.backEndPost.active) {\n          nb = cand;\n          break;\n        }\n      }\n      let ext = 0;\n      if (nb) {\n        const flatLen = Math.max(0, Math.min(650, Number(nb.backEndPost.panelLengthMm) || 650));\n        // Extra reach of the bep breakfast bar beyond the standard full-\n        // size (650) one: (120 + flatLen) \u2212 (650 \u2212 18) = flatLen \u2212 512.\n        ext = Math.max(0, flatLen - 512);\n      }\n      if ((cu.neighbourBackExtMm || 0) === ext) return cab;\n      changed = true;\n      return { ...cab, cornerUnit: { ...cu, neighbourBackExtMm: ext } };\n    });\n    return changed;\n  }\n\n  // POSITION LOCK (Arden, 2026-10-15). A locked unit stays exactly where it\n  // is: no drag, nudge, snap, distance box or Step Forward moves it, and the\n  // planner's own tidying (settling into a run, the end-panel / filler\n  // nudges) leaves it alone. Rotate 90\u00B0 still turns it. Set on the whole group.\n  function cabPositionLocked(cabId) {\n    const c = cabinets.find(x => x.id === cabId);\n    return !!(c && c.positionLocked);\n  }\n  function setCabinetPositionLock(cabId, locked) {\n    const cab = cabinets.find(c => c.id === cabId);\n    if (!cab) return;\n    const ids = cab.groupId\n      ? new Set(cabinets.filter(c => c.groupId === cab.groupId).map(c => c.id))\n      : new Set([cabId]);\n    cabinets = cabinets.map(c => (ids.has(c.id) ? { ...c, positionLocked: !!locked } : c));\n    rerender();\n    if (selectionPanelHandle && typeof selectionPanelHandle.refresh === 'function') {\n      selectionPanelHandle.refresh();\n    }\n  }\n\n  // ROTATION LOCK. Units turn themselves to suit the wall or corner they\n  // are dragged to; a locked unit keeps the orientation it has. Only the\n  // automatic turn is held off - Rotate 90\u00B0 still turns it. A group turns\n  // as one, so the lock is set on every member together.\n  function setCabinetRotationLock(cabId, locked) {\n    const cab = cabinets.find(c => c.id === cabId);\n    if (!cab) return;\n    const ids = cab.groupId\n      ? new Set(cabinets.filter(c => c.groupId === cab.groupId).map(c => c.id))\n      : new Set([cabId]);\n    cabinets = cabinets.map(c => (ids.has(c.id) ? { ...c, rotationLocked: !!locked } : c));\n    rerender();\n    // The Rotate button carries the lock marker - redraw the panel so it\n    // shows without waiting for a re-selection.\n    if (selectionPanelHandle && typeof selectionPanelHandle.refresh === 'function') {\n      selectionPanelHandle.refresh();\n    }\n  }\n\n  // A unit turned to an angle (Rotate 45\u00B0, row 60) whose middle is dragged\n  // over a diagonal corner larder or diagonal corner wall unit snaps onto that\n  // unit's angled face: turned to face the same way, its front flush with the\n  // face and centred on it - e.g. a 360 high unit on top of a corner larder.\n  // A wall unit that would run down into the larder is stood on its top\n  // (standOn: the mount line at the larder's top, bottom anchor). -> { x, y,\n  // rotationDeg } or null. Walk-in larders (a room you step into) and\n  // diagonal base units (a wall unit over one sits back on the wall) are left out.\n  function angledUnitDiagonalSnap(cab, rawX, rawY, others) {\n    if (!cab || cab.diagonalCornerUnit || cab.lShapeUnit || cab.cornerUnit || cab.groupId) return null;\n    const rot = (((cab.rotationDeg || 0) % 360) + 360) % 360;\n    if (Math.min(rot % 90, 90 - (rot % 90)) < 1) return null;   // square to the walls\n    const W = cab.widthMm || 0, D = cab.depthMm || 0;\n    const px = rawX + W / 2, py = rawY + D / 2;\n    for (const h of others || []) {\n      const dc = h && h.diagonalCornerUnit;\n      if (!dc || isWalkInLarder(h)) continue;\n      if (h.category !== 'tall-units' && h.category !== 'wall-units') continue;\n      const HW = h.widthMm || 0, HD = h.depthMm || 0, A = dc.armDepthMm || 570;\n      const hr = (h.rotationDeg || 0) * Math.PI / 180, cs = Math.cos(hr), sn = Math.sin(hr);\n      const hcx = (h.x || 0) + HW / 2, hcy = (h.y || 0) + HD / 2;\n      const toWorld = (p) => ({ x: hcx + (p.x - HW / 2) * cs - (p.y - HD / 2) * sn,\n                                y: hcy + (p.x - HW / 2) * sn + (p.y - HD / 2) * cs });\n      const poly = diagonalCornerFootprintPolygon(HW, HD, A, dc.hand).map(toWorld);\n      // Middle of the dragged unit inside the corner unit's outline?\n      let inside = true, sign = 0;\n      for (let i = 0; i < poly.length && inside; i++) {\n        const a = poly[i], b = poly[(i + 1) % poly.length];\n        const cr = (b.x - a.x) * (py - a.y) - (b.y - a.y) * (px - a.x);\n        if (Math.abs(cr) < 1e-9) continue;\n        if (!sign) sign = Math.sign(cr); else if (Math.sign(cr) !== sign) inside = false;\n      }\n      if (!inside) continue;\n      const seg = diagonalCornerDoorSegment(HW, HD, A, dc.hand);\n      const p1 = toWorld(seg.p1), p2 = toWorld(seg.p2);\n      const nx = seg.outwardX * cs - seg.outwardY * sn, ny = seg.outwardX * sn + seg.outwardY * cs;\n      // Front (cab-local -Y) turned by r points (sin r, -cos r): face along n.\n      const rotationDeg = ((Math.atan2(nx, -ny) * 180 / Math.PI) % 360 + 360) % 360;\n      const mx = (p1.x + p2.x) / 2, my = (p1.y + p2.y) / 2;\n      // A wall unit that would hang down into a corner LARDER stands on its\n      // top instead: bottom edge on the mount line at the larder's top.\n      let standOn = null;\n      if (h.category === 'tall-units' && isWallMounted(cab) && !isWorktopDresserCab(cab)) {\n        const hostTop = (Number(h.heightOffGroundMm) || 0) + (Number(h.heightMm) || 0) - (Number(h.plinthShiftMm) || 0);\n        const lineShift = Number(h.planPlinthShiftMm) || 0;   // the lines follow the plan's plinth height\n        const level = Object.keys(WALL_MOUNT_TOPS).find(k => Math.abs(WALL_MOUNT_TOPS[k] - lineShift - hostTop) < 2);\n        if (level && wallUnitVerticalRange(cab).bottom < hostTop - 1) standOn = level;\n      }\n      return { x: mx - nx * D / 2 - W / 2, y: my - ny * D / 2 - D / 2,\n               rotationDeg: Math.round(rotationDeg * 100) / 100, standOn };\n    }\n    return null;\n  }\n\n  // Rotate 45\u00B0 (row 60): for a unit set across a corner, e.g. on top of a\n  // diagonal corner larder. A unit left at an angle no wall runs at keeps it:\n  // the rotation lock goes on, so dragging it near a wall doesn't square it\n  // back up (Unlock Rotation lets it turn to walls again).\n  function rotateCabinet(c, stepDeg = 90) {\n    c.rotationDeg = (((c.rotationDeg || 0) + stepDeg) % 360 + 360) % 360;\n    const _lockNow = stepDeg % 90 !== 0 && c.rotationDeg % 90 !== 0 && !c.rotationLocked;\n    if (_lockNow) c.rotationLocked = true;\n    // L-shape units: after rotating the cab, the L outer corner in\n    // cab-local coords stays the same but the WORLD position of the\n    // post shifts by 90\u00B0. Re-derive the desired hand against the cab's\n    // current room position so the post stays at the room-interior\n    // corner. CPV stubs use the inverted hand (= post at L outer\n    // corner = room interior; void at cutout = walls).\n    if (c.lShapeUnit) {\n      let want = lShapeUnitDesiredHand(c, c.x, c.y, room, (roomConfig && roomConfig.perimeterItems) || []);\n      if (c.lShapeUnit.cornerPostVoid && want) {\n        want = ({ NE:'SW', NW:'SE', SE:'NW', SW:'NE' })[want] || want;\n      }\n      if (want && want !== c.lShapeUnit.hand) {\n        c.lShapeUnit = { ...c.lShapeUnit, hand: want };\n      }\n    }\n    autoDetectEndPanels([c.id]);\n    autoDetectBackPanels();\n    resizeFillers();\n    rerender();\n    // The Rotate button carries the lock marker.\n    if (_lockNow && selectionPanelHandle && typeof selectionPanelHandle.refresh === 'function') selectionPanelHandle.refresh();\n  }\n\n  // Rigid 90\u00B0 CW rotation of a whole grouped assembly around the\n  // group's plan-bbox centre. Each member's rotationDeg gains 90 and\n  // its position is recomputed so the member stays in its rotated\n  // place relative to the group. Used by the right-click \"Rotate 90\u00B0\"\n  // option on a selected group (e.g. a radius-unit + backing + filler\n  // trio that needs to fit a different wall direction).\n  function rotateCabinetGroup(groupId, suppressRerender, deltaDeg = 90) {\n    if (!groupId) return;\n    const members = cabinets.filter(c => c.groupId === groupId);\n    if (!members.length) return;\n    // Group plan-bbox in VISUAL coords - for a 260\u00D7300 backing at\n    // rotation 90, the visual is 300\u00D7260 swapped around the centre,\n    // and using the unrotated bbox here would tilt the rotation\n    // pivot off-centre and slide the whole assembly when rotated.\n    let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;\n    for (const m of members) {\n      const vb = visualBbox(m);\n      minX = Math.min(minX, vb.x0); maxX = Math.max(maxX, vb.x1);\n      minY = Math.min(minY, vb.y0); maxY = Math.max(maxY, vb.y1);\n    }\n    const gCx = (minX + maxX) / 2;\n    const gCy = (minY + maxY) / 2;\n    // Generalised CW rotation in y-down screen coords:\n    //   (dx, dy) \u2192 (dx\u00B7cos \u2212 dy\u00B7sin, dx\u00B7sin + dy\u00B7cos)\n    // The CSS transform-origin is the cabinet's own centre, so we\n    // update rotationDeg and translate the centre to the new orbit\n    // position; widthMm/depthMm themselves stay unchanged.\n    const th = (deltaDeg * Math.PI) / 180;\n    const cs = Math.cos(th), sn = Math.sin(th);\n    for (const m of members) {\n      const cx = m.x + (m.widthMm || 0) / 2;\n      const cy = m.y + (m.depthMm || 0) / 2;\n      const dx = cx - gCx, dy = cy - gCy;\n      const newCx = gCx + (dx * cs - dy * sn);\n      const newCy = gCy + (dx * sn + dy * cs);\n      m.rotationDeg = (((m.rotationDeg || 0) + deltaDeg) % 360 + 360) % 360;\n      m.x = newCx - (m.widthMm || 0) / 2;\n      m.y = newCy - (m.depthMm || 0) / 2;\n    }\n    if (!suppressRerender) rerender();\n  }\n\n  // After a radius assembly has been rotated to face a wall, push it\n  // along the wall's inward normal so its back-most member-corner\n  // lands ON that wall (flush). Works for ANY wall direction - the\n  // axis-aligned shifts that used to live inline in the snap paths\n  // only covered 0/90/180/270 walls.\n  function snapRadiusGroupFlushToWall(groupId, room) {\n    if (!groupId || !room) return;\n    const members = cabinets.filter(c => c.groupId === groupId);\n    if (!members.length) return;\n    const radius = members.find(c => c.radiusUnit);\n    if (!radius) return;\n    // Back-facing direction in world coords. Cab-local +Y is the\n    // back. Applying R(rot)\u00B7(0,1) in y-down screen space gives\n    // (-sin r, cos r) - verified by the existing wall map:\n    //   rot=0    \u2192 ( 0,  1) = +Y (bottom wall)\n    //   rot=90   \u2192 (-1,  0) = -X (left wall)\n    //   rot=180  \u2192 ( 0, -1) = -Y (top wall)\n    //   rot=270  \u2192 ( 1,  0) = +X (right wall)\n    const rRad = ((radius.rotationDeg || 0) * Math.PI) / 180;\n    const bx = -Math.sin(rRad), by = Math.cos(rRad);\n    const walls = getWalls(room);\n    let best = null, bestAlign = -Infinity, bestNx = 0, bestNy = 0;\n    for (const w of walls) {\n      const dx = w.to.x - w.from.x, dy = w.to.y - w.from.y;\n      const len = Math.hypot(dx, dy);\n      if (len === 0) continue;\n      const nx = -dy / len, ny = dx / len;      // inward normal\n      // Pick the wall the group is now facing - its inward normal\n      // most opposes the group's back-outward direction.\n      const align = (-bx) * nx + (-by) * ny;\n      if (align > bestAlign) {\n        bestAlign = align; best = w; bestNx = nx; bestNy = ny;\n      }\n    }\n    if (!best || bestAlign < 0.95) return;\n    // Min signed perpendicular distance from any member-corner to\n    // the wall along the inward normal. That's the gap to close.\n    let minD = Infinity;\n    for (const m of members) {\n      const w = m.widthMm || 0, h = m.depthMm || 0;\n      const cx = (m.x || 0) + w / 2, cy = (m.y || 0) + h / 2;\n      const th = ((m.rotationDeg || 0) * Math.PI) / 180;\n      const cs = Math.cos(th), sn = Math.sin(th);\n      for (const [lx, ly] of [[-w/2,-h/2],[w/2,-h/2],[w/2,h/2],[-w/2,h/2]]) {\n        const wx = cx + lx * cs - ly * sn;\n        const wy = cy + lx * sn + ly * cs;\n        const dperp = (wx - best.from.x) * bestNx + (wy - best.from.y) * bestNy;\n        if (dperp < minD) minD = dperp;\n      }\n    }\n    if (!isFinite(minD) || Math.abs(minD) < 0.5) return;\n    const shiftX = -minD * bestNx;\n    const shiftY = -minD * bestNy;\n    for (const m of members) { m.x += shiftX; m.y += shiftY; }\n  }\n\n  // \u2500\u2500\u2500 Curved-unit hand \u2194 real-product swap \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n  // Real curved units come as left/right PAIRS: separate unit_types whose\n  // codes end in -L / -R, each with its OWN hand-correct carcase GLB and its\n  // own product / variant / price. When the plan flips a curved unit's hand\n  // (adjacency auto-detect on drag-end, or the manual flip) we must ALSO\n  // re-point the cabinet at the opposite-hand product so the 3D GLB and the\n  // basket line both match what's shown.\n  //\n  // Returns the opposite-hand unit_type for `code` at `wantHand`, or null\n  // when the code carries no -L/-R suffix (a legacy single-product curved\n  // unit - those just flip the geometry marker, no product swap).\n  function radiusCounterpartUnitType(code, wantHand) {\n    const c = String(code || '');\n    // Real codes carry the hand WITHOUT a dash and before a carcase letter -\n    // CV30LB / CV30RB (base), CV30LW / CV30RW (wall). The old /-[LR]$/ test\n    // matched none of them, so this returned null, swapRadiusHandProduct gave\n    // up, and an adjacency flip moved the unit visually while leaving the\n    // product (and therefore the basket line) on the wrong hand.\n    // [BW]? keeps CV30OPB - the open unit, no hand - out of it.\n    const m = c.match(/([LR])([BW]?)$/i);\n    if (!m) return null;\n    // Suffix names the RUN END capped, the inverse of the body-frame hand\n    // (see the seed comment in the radius-island detection block): a right-\n    // end cap (-R) presents its curve on the world right = local-front-LEFT\n    // = hand 'left'. So hand 'left' \u2192 -R, hand 'right' \u2192 -L.\n    const wantLetter  = (wantHand === 'left') ? 'R' : 'L';\n    const siblingCode = c.slice(0, m.index) + wantLetter + m[2];\n    return Catalogue.getUnitTypeByCode(siblingCode);\n  }\n\n  // Re-point a curved cabinet at its opposite-hand real product, in place.\n  // Preserves everything spatial (x / y / rotation / group) and the colour /\n  // end-panel state; swaps only the product identity (unitTypeId / variantId /\n  // code / category / price / cutoutSchema / planner2D) and the radiusUnit\n  // hand. Returns true when a real swap happened; false for legacy single-\n  // product curved units (caller then just flips the marker hand as before).\n  function swapRadiusHandProduct(cab, wantHand) {\n    if (!cab || !cab.radiusUnit) return false;\n    const sibling = radiusCounterpartUnitType(cab.code, wantHand);\n    if (!sibling || sibling.id === cab.unitTypeId) return false;\n    // Match the sibling product's variant to the cab's current dimensions\n    // (curved pairs mirror each other, so this is normally the sole variant).\n    const info = Catalogue.findVariant({\n      unitTypeId:     sibling.id,\n      kitchenStyleId: cab.kitchenStyleId,\n      widthMm:        cab.widthMm,\n      heightMm:       cab.heightMm\n    });\n    const variantId = info?.variant?.id || null;\n    const def = Catalogue.buildCabinetDefinition({\n      unitTypeId: sibling.id, variantId, kitchenStyleId: cab.kitchenStyleId\n    });\n    if (!def) return false;\n    cab.unitTypeId   = def.unitTypeId;\n    cab.variantId    = def.variantId;\n    cab.code         = def.code;\n    cab.category     = def.category || def.categoryHandle || cab.category;\n    cab.priceCents   = def.priceCents;\n    cab.compareAtCents = (typeof def.compareAtCents === 'number') ? def.compareAtCents : null;\n    cab.planner2D    = def.planner2D || cab.planner2D;\n    cab.cutoutSchema = def.cutoutSchema || null;\n    cab.radiusUnit   = { ...cab.radiusUnit, hand: wantHand };\n    return true;\n  }\n\n  // Hand of an angled end-of-run unit, or null: a splay / open angled WALL\n  // end carries it on its splayEnd marker; the Open End Base Unit - Angled\n  // only in its unit type (\u2026-left-end / \u2026-right-end, the side that is open -\n  // the same left/right as a splay's hand).\n  function angledEndHand(cab) {\n    if (!cab) return null;\n    if (cab.splayEnd) return cab.splayEnd.hand || 'left';\n    const m = /^(?:th-)?open-end-base-unit-angled-(left|right)-end$/.exec(String(cab.unitTypeId || ''));\n    return m ? m[1] : null;\n  }\n\n  // Splay ends and open angled ends finish a run with their DEEP side against\n  // it. radiusUnitDesiredHand reports which run side a neighbour sits on in\n  // the radius sense (neighbour on the run-left \u2192 'right', a curve facing away\n  // from it); a splay wants its deep side TOWARD the neighbour, and its 'left'\n  // hand has the deep side at cab-local x=0 - the run-left. So the answer is\n  // the other way round.\n  function splayEndDesiredHand(cab, allCabs) {\n    if (!angledEndHand(cab)) return null;\n    const r = radiusUnitDesiredHand(cab, allCabs);\n    return r === 'left' ? 'right' : r === 'right' ? 'left' : null;\n  }\n\n  // The opposite-hand unit type: SPLAYLW \u2194 SPLAYRW (the hand letter straight\n  // after SPLAY, either letter order), OANGWL \u2194 OANGWR / THOANGWL \u2194 THOANGWR.\n  function splayCounterpartUnitType(code, wantHand) {\n    const c = String(code || '');\n    const L = wantHand === 'right' ? 'R' : 'L';\n    let sib = null;\n    if (/^SPLAY/i.test(c)) {\n      sib = c.slice(0, 5) + c.slice(5).replace(/[LR]/i, L);\n    } else {\n      const m = c.match(/^((?:TH)?OANGW)[LR]$/i) || c.match(/^((?:TH)?OPANG)[LR](B)$/i);\n      if (m) sib = m[1] + L + (m[2] || '');\n    }\n    return (sib && sib !== c) ? Catalogue.getUnitTypeByCode(sib) : null;\n  }\n\n  // Re-point a splay / open angled end at its opposite-hand product in place,\n  // like swapRadiusHandProduct: position, rotation, colours and panels stay;\n  // the product (3D, plan shape, basket line) and its marker change.\n  function swapSplayHandProduct(cab, wantHand) {\n    if (!angledEndHand(cab)) return false;\n    const sibling = splayCounterpartUnitType(cab.code, wantHand);\n    if (!sibling || sibling.id === cab.unitTypeId) return false;\n    // Base open ends' variants carry no height (cab.heightMm adds the plinth),\n    // so fall back to the width alone.\n    const info = Catalogue.findVariant({\n      unitTypeId:     sibling.id,\n      kitchenStyleId: cab.kitchenStyleId,\n      widthMm:        cab.widthMm,\n      heightMm:       cab.heightMm\n    }) || Catalogue.findVariant({\n      unitTypeId:     sibling.id,\n      kitchenStyleId: cab.kitchenStyleId,\n      widthMm:        cab.widthMm\n    });\n    const variantId = info?.variant?.id || null;\n    if (!variantId) return false;\n    const def = Catalogue.buildCabinetDefinition({\n      unitTypeId: sibling.id, variantId, kitchenStyleId: cab.kitchenStyleId\n    });\n    if (!def) return false;\n    cab.unitTypeId      = def.unitTypeId;\n    cab.variantId       = def.variantId;\n    cab.code            = def.code;\n    cab.category        = def.category || def.categoryHandle || cab.category;\n    cab.priceCents      = def.priceCents;\n    cab.compareAtCents  = (typeof def.compareAtCents === 'number') ? def.compareAtCents : null;\n    cab.planner2D       = def.planner2D || cab.planner2D;\n    cab.cutoutSchema    = def.cutoutSchema || null;\n    cab.hingeSelectable = def.hingeSelectable;\n    cab.hingeSide       = def.hingeSide;\n    cab.splayEnd        = def.splayEnd || null;\n    return true;\n  }\n\n  // Swap a placed cabinet for one of its Swap Unit alternatives (by rule, or\n  // the unit_type's own \"Alternative Unit Types\" list), keeping its position,\n  // rotation and colours. Like for like: the alternative's variant in exactly\n  // this unit's size, or no swap at all. Corners stay corners: a blank corner\n  // keeps its corner geometry (same cabinet, door and panel side), and an\n  // L-shape and a diagonal corner hand their marker over - addCabinet gives\n  // both the same outer square, arm and cutout - each keeping its footprint.\n  function swapCabinetUnitType(cabId, newUnitTypeId) {\n    const cab = cabinets.find(x => x.id === cabId);\n    if (!cab || !newUnitTypeId || newUnitTypeId === cab.unitTypeId) return;\n    // The same-size variant the Swap Unit popup offered and priced.\n    const alt = (Catalogue.getAlternativeUnitTypes(cab.unitTypeId, cab.kitchenStyleId, cab.variantId) || [])\n      .find(a => a.id === newUnitTypeId);\n    const variantId = alt ? alt.variantId : null;\n    if (!variantId) return;\n    const def = Catalogue.buildCabinetDefinition({\n      unitTypeId: newUnitTypeId, variantId, kitchenStyleId: cab.kitchenStyleId\n    });\n    if (!def) return;\n    cab.unitTypeId          = def.unitTypeId;\n    cab.variantId           = def.variantId;\n    cab.code                = def.code;\n    cab.category            = def.category || def.categoryHandle || cab.category;\n    cab.categoryHandle      = def.categoryHandle;\n    cab.unitTypeGroupHandle = def.unitTypeGroupHandle;\n    const _newShape  = String(def.planner2D?.shape || '').trim().toLowerCase();\n    const _keepBlank = isCornerBlankShape(_newShape) && cab.cornerUnit ? cab.cornerUnit : null;\n    const _lOrDiag   = (_newShape === 'lshape' || _newShape === 'diagonal')\n      ? (cab.lShapeUnit || cab.diagonalCornerUnit || null) : null;\n    // A corner's width / depth are its FOOTPRINT (cabinet + void, or the outer\n    // square), not the variant's own - and like for like, it is unchanged.\n    if (!_keepBlank && !_lOrDiag) {\n      cab.widthMm           = def.widthMm || cab.widthMm;\n      cab.depthMm           = def.depthMm || cab.depthMm;\n    }\n    cab.heightMm            = (def.carcaseHeightMm || 720) + (def.plinthHeightMm || 0);\n    cab.planner2D           = def.planner2D || cab.planner2D;\n    cab.priceCents          = def.priceCents;\n    cab.compareAtCents      = (typeof def.compareAtCents === 'number') ? def.compareAtCents : null;\n    cab.cutoutSchema        = def.cutoutSchema || null;\n    // Chosen appliances follow the swap only into a slot the new unit has for\n    // them (the Choose Appliance slot logic, each slot taken once); the rest\n    // are dropped - a larder has no oven slot, a fridge housing no oven.\n    if (cab.appliances && Object.keys(cab.appliances).length) {\n      const _free = ((cab.cutoutSchema && cab.cutoutSchema.openings) || []).slice();\n      const _kept = {};\n      for (const _h of Object.values(cab.appliances)) {\n        const _a = _h && Catalogue.getAppliance?.(_h);\n        const _i = _a ? Catalogue.applianceSlotIndex?.({ openings: _free }, _a, cab.widthMm) : -1;\n        if (_i >= 0) { _kept[_i] = _h; _free[_i] = null; }\n      }\n      cab.appliances = Object.keys(_kept).length ? _kept : null;\n    }\n    cab.hingeSelectable     = def.hingeSelectable;\n    cab.hingeSide           = def.hingeSide;\n    cab.drawerCount         = def.drawerCount || 0;\n    // Markers reset to the NEW unit (clears stale sink / belfast / splay / corner).\n    cab.belfastSink         = def.belfastSink || null;\n    // A Sink Unit stays one when swapped to another unit type that can be one.\n    cab.sinkBase            = def.sinkBase\n      || ((cab.sinkBase && cab.sinkBase.designated && !def.belfastSink\n           && SINK_UNIT_TYPES.has(String(cab.unitTypeId || ''))) ? cab.sinkBase : null);\n    cab.splayEnd            = def.splayEnd || null;\n    cab.isMidiUnit          = def.isMidiUnit || false;\n    cab.dresserUnit         = !!def.dresserUnit;\n    cab.trueHandlelessHanded = def.trueHandlelessHanded || false;\n    cab.diagonalCornerUnit  = (_lOrDiag && _newShape === 'diagonal') ? { ..._lOrDiag } : null;\n    cab.lShapeUnit          = (_lOrDiag && _newShape === 'lshape')   ? { ..._lOrDiag } : null;\n    cab.radiusUnit          = null;\n    cab.cornerUnit          = _keepBlank;\n    // A sink chosen on the old unit only makes sense if the new one is a sink base.\n    if (!cab.sinkBase && !def.belfastSink) cab.plannerSinkHandle = null;\n    // Swapped onto a sink unit with no sink yet: it loads with its default.\n    else if (!cab.plannerSinkHandle) cab.plannerSinkHandle = defaultSinkFor(def);\n    // Refresh catalogue-derived fields (schema / category / hinge / belfast) in place.\n    Object.assign(cab, migrateCabinet(cab));\n    rerender();\n  }\n\n  // A free-placed panel's finish (Plain / T&G / Grooved - Catalogue.\n  // getPanelFinishOptions, Change Unit Size popup): the sister product at the\n  // same size. Only the product changes; the panel keeps the size it was fitted\n  // to (the unit it stands against, 870 under a worktop) and its place.\n  function swapPanelFinish(cabId, unitTypeId, variantId) {\n    const cab = cabinets.find(x => x.id === cabId);\n    if (!cab || !cab.endPanelUnit || !unitTypeId || !variantId) return;\n    const opt = (Catalogue.getPanelFinishOptions?.(cab.unitTypeId, cab.kitchenStyleId, cab.variantId) || [])\n      .find(o => o.id === unitTypeId && String(o.variantId) === String(variantId));\n    if (!opt || opt.current) return;\n    // The option's own ids, not the button's: those arrive as strings and a\n    // string variant id misses every catalogue lookup (price, basket line).\n    const def = Catalogue.buildCabinetDefinition({ unitTypeId: opt.id, variantId: opt.variantId, kitchenStyleId: cab.kitchenStyleId });\n    if (!def) return;\n    cab.unitTypeId     = def.unitTypeId;\n    cab.variantId      = def.variantId;\n    cab.code           = def.code;\n    cab.name           = def.name || cab.name;\n    cab.priceCents     = def.priceCents;\n    cab.compareAtCents = (typeof def.compareAtCents === 'number') ? def.compareAtCents : null;\n    cab.planner2D      = def.planner2D || cab.planner2D;\n    Object.assign(cab, migrateCabinet(cab));\n    rerender();\n  }\n\n  // Is there a UNIT beside this side of a cab - base, tall, wall, appliance,\n  // corner - within RAIL_END_REACH_MM? \"Add Rail to both sides\" is for the END\n  // of a run (open, a wall, an end panel): Jonathan Print's fridge housing took\n  // a second rail with a 150 pull-out base 20mm off that side, which the flush\n  // neighbour test (epFindNeighbourOnSide) does not count (Arden, 2026-10-20).\n  // Free-placed panels and fillers finish an end, so they do not count.\n  const RAIL_END_REACH_MM = 100;\n  function thSideHasUnit(cab, side) {\n    const me = epCarcaseSides(cab)[side];\n    if (!me) return false;\n    const out = epUserSideOutward(cab, side);\n    const sdx = me.p2.x - me.p1.x, sdy = me.p2.y - me.p1.y, slen = Math.hypot(sdx, sdy);\n    if (slen < 1) return false;\n    const sux = sdx / slen, suy = sdy / slen;\n    const range = epVerticalRange(cab);\n    for (const o of cabinets) {\n      if (!o || o.id === cab.id || o.endPanelUnit || o.endPanelFiller) continue;\n      if (!epRangesOverlap(range, epVerticalRange(o))) continue;\n      const sides = epCarcaseSides(o);\n      for (const k of ['front', 'back', 'left', 'right']) {\n        const f = sides[k];\n        if (!f) continue;\n        const wdx = f.p2.x - f.p1.x, wdy = f.p2.y - f.p1.y, wlen = Math.hypot(wdx, wdy);\n        if (wlen < 1 || Math.abs(sux * (wdy / wlen) - suy * (wdx / wlen)) > 0.06) continue;   // parallel faces only\n        const tA = (f.p1.x - me.p1.x) * sux + (f.p1.y - me.p1.y) * suy;\n        const tB = (f.p2.x - me.p1.x) * sux + (f.p2.y - me.p1.y) * suy;\n        if (Math.min(slen, Math.max(tA, tB)) - Math.max(0, Math.min(tA, tB)) < 50) continue;  // must face it\n        const gap = epSignedGap(me, f, out);\n        if (gap > -5 && gap < RAIL_END_REACH_MM) return true;\n      }\n    }\n    return false;\n  }\n\n  // \"Add Rail to both sides\" on a True Handleless tall unit (Arden, 2026-10-20).\n  // NO ROOM FOR A RAIL OR END PANEL (Arden, 2026-10-26, Planner Bugs 23). A\n  // True Handleless tall unit's rail, and an end panel it gains - a High tall\n  // beside a Medium keeps its panel there - take run width. Placed units are\n  // never slid along to make that room, so where the carcases stand closer\n  // than the rails, panels and fillers between them need, the Advisory says\n  // so and the user moves a unit or changes a height.\n  const TH_RAIL_ROOM_TOL_MM = 3;\n  function thSideExtMm(c, side) {\n    let mm = 0;\n    if ((c.railGripSide === side && (c.railType !== 'intermediate' || c.railOwnsShared)) || c.railSecondSide === side) mm += TH_RAIL_GAP_MM;\n    const ep = (c.endPanels || {})[side], fil = (c.fillers || {})[side];\n    if (ep && ep.active) mm += endPanelThickMm(ep);\n    else if (fil && fil.active) mm += fil.widthMm || 0;\n    return mm;\n  }\n  function thRailRoomWarnings() {\n    const out = [], seen = new Set();\n    for (const c of cabinets) {\n      if (!c || !thGripSide(c)) continue;\n      const range = epVerticalRange(c);\n      for (const side of ['left', 'right']) {\n        const me = epCarcaseSides(c)[side];\n        if (!me) continue;\n        const out_ = epUserSideOutward(c, side);\n        const sdx = me.p2.x - me.p1.x, sdy = me.p2.y - me.p1.y, slen = Math.hypot(sdx, sdy);\n        if (slen < 1) continue;\n        const sux = sdx / slen, suy = sdy / slen;\n        for (const o of cabinets) {\n          if (!o || o.id === c.id || o.endPanelUnit || o.endPanelFiller || o.cornerUnit || o.lShapeUnit || o.diagonalCornerUnit) continue;\n          if (!epRangesOverlap(range, epVerticalRange(o))) continue;\n          for (const k of ['left', 'right']) {\n            const f = epCarcaseSides(o)[k];\n            if (!f) continue;\n            const wdx = f.p2.x - f.p1.x, wdy = f.p2.y - f.p1.y, wlen = Math.hypot(wdx, wdy);\n            if (wlen < 1 || Math.abs(sux * (wdy / wlen) - suy * (wdx / wlen)) > 0.06) continue;   // parallel faces only\n            const tA = (f.p1.x - me.p1.x) * sux + (f.p1.y - me.p1.y) * suy;\n            const tB = (f.p2.x - me.p1.x) * sux + (f.p2.y - me.p1.y) * suy;\n            if (Math.min(slen, Math.max(tA, tB)) - Math.max(0, Math.min(tA, tB)) < 50) continue;  // must face it\n            const gap = epSignedGap(me, f, out_);\n            // Carcases already overlapping is the Units Overlap advisory's job.\n            if (gap < -TH_RAIL_ROOM_TOL_MM || gap > 150) continue;\n            const need = thSideExtMm(c, side) + thSideExtMm(o, k);\n            if (gap >= need - TH_RAIL_ROOM_TOL_MM) continue;\n            const pair = [c.id, o.id].sort().join('|');\n            if (seen.has(pair)) continue;\n            seen.add(pair);\n            out.push({\n              ruleId: 'th-rail-room', severity: 'warning', itemIds: [c.id, o.id],\n              message: `Units #${c.displayNumber ?? '?'} and #${o.displayNumber ?? '?'} stand ${Math.max(0, Math.round(gap))}mm apart, ` +\n                       `but the rails and end panels between them need ${Math.round(need)}mm. Move one of them along, or make them the same height.`\n            });\n          }\n        }\n      }\n    }\n    return out;\n  }\n\n  // The second rail takes 30mm of run like the first, so the panels and the\n  // neighbours are worked out again.\n  function setCabinetRailBoth(cabId, on) {\n    const idx = cabinets.findIndex(x => x.id === cabId);\n    if (idx === -1) return;\n    cabinets[idx] = { ...cabinets[idx], railBothSides: !!on };\n    autoDetectEndPanels([cabId]);\n    resizeFillers();\n    rerender();\n    scheduleBasketResync();\n  }\n\n  // ---- A free-placed panel's length and height (Arden, 2026-10-20) --------\n  // A panel's length is its depth axis (its width is the board's thickness).\n  function isBackPanelUnit(c) {\n    return !!(c && c.endPanelUnit && /back-panel/.test(String(c.unitTypeId || '')));\n  }\n  // A free-placed panel's height as its product comes - what it is dropped at.\n  function isTallPanelHeight(h) { return h > 1500; }\n  function panelOwnHeightMm(c) {\n    const def = c && Catalogue.buildCabinetDefinition?.({ unitTypeId: c.unitTypeId, variantId: c.variantId, kitchenStyleId: c.kitchenStyleId });\n    // As placed: carcase + plinth (the add path's sum).\n    if (def && def.carcaseHeightMm) return def.carcaseHeightMm + (def.plinthHeightMm || 0);\n    return (c && c.heightMm) || 0;\n  }\n  function panelBoards(c) {\n    return (c && Catalogue.getPanelBoards?.(c.unitTypeId, c.kitchenStyleId)) || [];\n  }\n  // The longest board this panel can be cut from - or, with no board known,\n  // as long as it is now.\n  function panelMaxLengthMm(c) {\n    const b = panelBoards(c);\n    return b.length ? b[b.length - 1].lengthMm : (c.depthMm || 0);\n  }\n  // The shortest board that makes this length, or the longest when none does.\n  function panelBoardFor(c, lengthMm) {\n    const b = panelBoards(c);\n    return b.find(x => x.lengthMm + 0.5 >= lengthMm) || b[b.length - 1] || null;\n  }\n  // The product fields for cutting this panel from `board` instead.\n  function panelProductFields(c, board) {\n    if (!board || board.id === c.unitTypeId) return {};\n    const def = Catalogue.buildCabinetDefinition({ unitTypeId: board.id, variantId: board.variantId, kitchenStyleId: c.kitchenStyleId });\n    if (!def) return {};\n    return {\n      unitTypeId: def.unitTypeId, variantId: def.variantId, code: def.code, name: def.name || c.name,\n      priceCents: def.priceCents,\n      compareAtCents: (typeof def.compareAtCents === 'number') ? def.compareAtCents : null,\n      planner2D: def.planner2D || c.planner2D,\n    };\n  }\n  // The inside face of every waterfall: a leg the worktop's own thickness\n  // in from the worktop's end (or back), floor to worktop.\n  function waterfallInnerFaces() {\n    let slabs = [];\n    try { slabs = buildWorktops() || []; } catch (e) { return []; }\n    const t = waterfallThicknessMm();\n    const out = [];\n    for (const s of slabs) {\n      const f = (s && (s.waterfalls || []).length) ? worktopLocalFrame(s) : null;\n      if (!f) continue;\n      for (const side of s.waterfalls) {\n        let a, b;\n        if (side === 'left')       { a = { x: f.x1 - t, y: f.y0 }; b = { x: f.x1 - t, y: f.y1 }; }\n        else if (side === 'right') { a = { x: f.x0 + t, y: f.y0 }; b = { x: f.x0 + t, y: f.y1 }; }\n        else if (side === 'back')  { a = { x: f.x0, y: f.y1 - t }; b = { x: f.x1, y: f.y1 - t }; }\n        else continue;\n        out.push({ p1: f.toWorld(a), p2: f.toWorld(b) });\n      }\n    }\n    return out;\n  }\n  // The gap a panel stands in along its length: from its middle, the nearest\n  // face square across its line at each end - a unit's side, front or back,\n  // another panel, a wall, a pillar, or `extraFaces`. Only a face its line\n  // actually passes through counts, so a panel along an island's back is not\n  // stopped by the joins between the units. An end with nothing there stays\n  // where it is. -> { lengthMm, cx, cy, lo, hi } (lo / hi: the ends' signed\n  // distance from the middle, null where nothing was found), or null when there\n  // is nothing to fit, or the gap is longer than `maxMm`.\n  function panelLengthGap(panel, { extraFaces = [], maxMm = Infinity } = {}) {\n    const th = (panel.rotationDeg || 0) * Math.PI / 180;\n    const dir = { x: -Math.sin(th), y: Math.cos(th) };\n    const c = { x: panel.x + panel.widthMm / 2, y: panel.y + panel.depthMm / 2 };\n    const half = panel.depthMm / 2;\n    const MIN = 25;\n    let lo = -Infinity, hi = Infinity;\n    const consider = (f) => {\n      const p1 = f.p1 || f.from, p2 = f.p2 || f.to;\n      if (!p1 || !p2) return;\n      const sx = p2.x - p1.x, sy = p2.y - p1.y, L = Math.hypot(sx, sy);\n      if (L < 1) return;\n      const ux = sx / L, uy = sy / L;\n      if (Math.abs(ux * dir.x + uy * dir.y) > 0.06) return;   // square across the line only\n      const den = dir.x * uy - dir.y * ux;\n      if (Math.abs(den) < 1e-9) return;\n      const qx = p1.x - c.x, qy = p1.y - c.y;\n      const s = (qx * uy - qy * ux) / den;                      // along the panel\n      const u = (qx * dir.y - qy * dir.x) / den;                // along the face\n      if (u < 1 || u > L - 1) return;\n      if (s > MIN && s < hi) hi = s;\n      if (s < -MIN && s > lo) lo = s;\n    };\n    const myRange = epVerticalRange(panel);\n    for (const o of cabinets) {\n      if (o.id === panel.id) continue;\n      if (!epRangesOverlap(myRange, epVerticalRange(o))) continue;\n      const sides = epAllSides(o);\n      for (const k of ['front', 'back', 'left', 'right']) if (sides[k]) consider(sides[k]);\n    }\n    const V = room?.vertices || [];\n    for (let k = 0; k < V.length; k++) consider({ p1: V[k], p2: V[(k + 1) % V.length] });\n    for (const w of getPillarSnapWalls(roomConfig?.perimeterItems)) consider(w);\n    for (const f of extraFaces) consider(f);\n    const hasLo = lo > -Infinity, hasHi = hi < Infinity;\n    if (!hasLo && !hasHi) return null;\n    const a = hasLo ? lo : -half, b = hasHi ? hi : half;\n    const lengthMm = b - a;\n    if (lengthMm < 50 || lengthMm > maxMm + 0.5) return null;\n    const mid = (a + b) / 2;\n    return { lengthMm, cx: c.x + dir.x * mid, cy: c.y + dir.y * mid, lo: hasLo ? lo : null, hi: hasHi ? hi : null };\n  }\n  // Every back panel fitted to its gap, on opening a plan (Arden, 2026-10-20:\n  // \"no auto sizing?\" - the fit only ran after an edit). Stable: a fitted\n  // panel measures the same again, so it does not keep moving.\n  function fitBackPanelsToGaps() {\n    let faces = null;\n    for (let i = 0; i < cabinets.length; i++) {\n      const c = cabinets[i];\n      if (!isBackPanelUnit(c) || c.lengthManual) continue;\n      if (!faces) faces = waterfallInnerFaces();\n      const fit = panelLengthGap(c, { extraFaces: faces, maxMm: panelMaxLengthMm(c) });\n      if (!fit) continue;\n      if (Math.abs(fit.lengthMm - c.depthMm) < 0.5\n          && Math.abs(fit.cx - (c.x + c.widthMm / 2)) < 0.5 && Math.abs(fit.cy - (c.y + c.depthMm / 2)) < 0.5) continue;\n      cabinets[i] = { ...c, ...panelProductFields(c, panelBoardFor(c, fit.lengthMm)),\n                      depthMm: fit.lengthMm, x: fit.cx - c.widthMm / 2, y: fit.cy - fit.lengthMm / 2 };\n    }\n  }\n  // Typed in the panel's side panel: its length (cut from the shortest board\n  // that makes it, up to the longest the range sells) and / or its height (up\n  // to the board's). `fit` hands the length back to the gap it stands in. A\n  // typed length keeps the end that butts something where it is.\n  function setPanelSize(cabId, { lengthMm, heightMm, fit, band } = {}) {\n    const idx = cabinets.findIndex(x => x.id === cabId);\n    if (idx === -1 || !cabinets[idx].endPanelUnit) return;\n    if ((Catalogue.getUnitType?.(cabinets[idx].unitTypeId) || {}).unitTypeGroupHandle !== 'end-panels') return;   // fillers size themselves\n    let c = { ...cabinets[idx] };\n    if (fit) {\n      delete c.lengthManual;\n      cabinets[idx] = c;\n      autoDetectEndPanels([cabId]);\n      rerender(); scheduleBasketResync();\n      return;\n    }\n    if (Number.isFinite(lengthMm) && lengthMm > 0) {\n      const len = Math.max(50, Math.min(panelMaxLengthMm(c), Math.round(lengthMm)));\n      const th = (c.rotationDeg || 0) * Math.PI / 180;\n      const dir = { x: -Math.sin(th), y: Math.cos(th) };\n      const half = c.depthMm / 2;\n      const gap = panelLengthGap(c, { extraFaces: waterfallInnerFaces() }) || {};\n      const cx0 = c.x + c.widthMm / 2, cy0 = c.y + c.depthMm / 2;\n      // About the middle - or, when one end butts something, from that end.\n      let mid = 0;\n      if (gap.lo != null && Math.abs(gap.lo + half) < 2) mid = gap.lo + len / 2;\n      else if (gap.hi != null && Math.abs(gap.hi - half) < 2) mid = gap.hi - len / 2;\n      const cx = cx0 + dir.x * mid, cy = cy0 + dir.y * mid;\n      c = { ...c, ...panelProductFields(c, panelBoardFor(c, len)),\n            depthMm: len, x: cx - c.widthMm / 2, y: cy - len / 2, lengthManual: true };\n    }\n    if (Number.isFinite(heightMm) && heightMm > 0) {\n      const b = panelBoardFor(c, c.depthMm);\n      const capH = (b && b.heightMm) || c.heightMm;\n      c = { ...c, heightMm: Math.max(50, Math.min(capH, Math.round(heightMm))), heightManual: true };\n      // A wall panel's typed height wins over its neighbour's; it still\n      // hangs from the line (syncWallEndPanels).\n      if (isWallEndPanelUnit(c)) { c.wallPanelHeightTyped = true; delete c.wallPanelBand; }\n    }\n    // Low / Medium / High on a wall panel: the wall units' heights.\n    if (band && wallPanelBandMm(band) && isWallEndPanelUnit(c)) {\n      const b = panelBoardFor(c, c.depthMm);\n      const capH = (b && b.heightMm) || wallPanelBandMm(band);\n      c = { ...c, heightMm: Math.min(capH, wallPanelBandMm(band)), heightManual: true, wallPanelBand: band };\n      delete c.wallPanelHeightTyped;\n    }\n    cabinets[idx] = migrateCabinet(c);\n    rerender(); scheduleBasketResync();\n  }\n\n  // The piece a filler panel is cut from - its most width and height. Stamped\n  // when placed; a plan from before then reads it from the range's product.\n  function fillerStockOf(c) {\n    if (c && c.fillerStock && c.fillerStock.widthMm && c.fillerStock.heightMm) return c.fillerStock;\n    const ut = Catalogue.getUnitType?.(c && c.unitTypeId) || {};\n    const def = (c && Catalogue.buildCabinetDefinition?.({ unitTypeId: c.unitTypeId, variantId: c.variantId, kitchenStyleId: c.kitchenStyleId })) || null;\n    return { widthMm: ut.defaultDepthMm || 147,\n             heightMm: def ? (def.carcaseHeightMm || 720) + (def.plinthHeightMm || 0) : ((c && c.heightMm) || 715) };\n  }\n\n  // Edit Filler Size popup (row 22): width and height typed in, capped at the\n  // piece it is cut from, and whether it stands on the plinth line or the\n  // floor. Width is kept about the middle; typed sizes stay put.\n  function setFillerSize(cabId, { widthMm, heightMm, onFloor } = {}) {\n    const idx = cabinets.findIndex(x => x.id === cabId);\n    if (idx === -1 || !isFillerPanelUnit(cabinets[idx])) return;\n    let c = { ...cabinets[idx] };\n    const stock = fillerStockOf(c);\n    if (Number.isFinite(widthMm) && widthMm > 0) {\n      const w = Math.max(10, Math.min(stock.widthMm, Math.round(widthMm)));\n      const cx = c.x + c.widthMm / 2;\n      c = { ...c, widthMm: w, x: cx - w / 2, widthManual: true };\n    }\n    if (Number.isFinite(heightMm) && heightMm > 0) {\n      c = { ...c, heightMm: Math.max(10, Math.min(stock.heightMm, Math.round(heightMm))), heightManual: true };\n    }\n    if (typeof onFloor === 'boolean') c = { ...c, heightOffGroundMm: onFloor ? 0 : FILLER_PANEL_PLINTH_MM };\n    cabinets[idx] = c;\n    rerender(); scheduleBasketResync();\n  }\n\n  // ---- Wall end panels placed by hand (bug sheet, Sales row 34) ----------\n  // A Wall End Panel product (WEPP / WEPPHI / WEPTG / WEPTGHI / WEPGRHI) added\n  // from Doors, Panels & Accessories hangs like a wall unit, not from the\n  // floor: Julian's two beside Jonathan Print's corner wall units stood on the\n  // floor and showed through the worktop. Kept a free-placed panel - its\n  // height off the ground is set here - so none of the wall-unit cornice,\n  // pelmet and end-panel passes start treating it as a unit.\n  //   Top:    the wall unit it stands against (its line and anchor), else the\n  //           line it last hung from, else the Medium line.\n  //   Height: Low / Medium / High picked in its popup (the wall units' 575 /\n  //           720 / 900), else a height typed there, else the wall unit's.\n  // Both capped by the board it is cut from.\n  // Functions, not consts: rerender (which runs syncWallEndPanels) can fire\n  // while the planner is still starting, before a const here is set.\n  function wallPanelBandMm(band) { return ({ low: 575, medium: 720, high: 900 })[band] || 0; }\n  function wallPanelReachMm() { return 60; }\n  function isWallEndPanelUnit(c) {\n    return !!(c && c.endPanelUnit &&\n      (/^wall-end-panel/.test(String(c.unitTypeId || '')) || /^WEP(P|TG|GR)/i.test(String(c.code || ''))));\n  }\n  // The wall unit a wall panel stands against: a big face of the panel square\n  // to one of the unit's sides, overlapping it and within reach. Plan only -\n  // the panel may still be on the floor. Nearest wins. -> the cab, or null.\n  function wallPanelHost(panel) {\n    let best = null, bestGap = Infinity;\n    for (const side of ['left', 'right']) {\n      const me = epCarcaseSides(panel)[side];\n      if (!me) continue;\n      const out = epUserSideOutward(panel, side);\n      const sdx = me.p2.x - me.p1.x, sdy = me.p2.y - me.p1.y, slen = Math.hypot(sdx, sdy);\n      if (slen < 1) continue;\n      const sux = sdx / slen, suy = sdy / slen;\n      for (const o of cabinets) {\n        if (!o || o.id === panel.id || o.endPanelUnit || o.endPanelFiller || !isWallMounted(o)) continue;\n        const sides = epCarcaseSides(o);\n        for (const k of ['front', 'back', 'left', 'right']) {\n          const f = sides[k];\n          if (!f) continue;\n          const wdx = f.p2.x - f.p1.x, wdy = f.p2.y - f.p1.y, wlen = Math.hypot(wdx, wdy);\n          if (wlen < 1 || Math.abs(sux * (wdy / wlen) - suy * (wdx / wlen)) > 0.06) continue;   // parallel faces only\n          const tA = (f.p1.x - me.p1.x) * sux + (f.p1.y - me.p1.y) * suy;\n          const tB = (f.p2.x - me.p1.x) * sux + (f.p2.y - me.p1.y) * suy;\n          if (Math.min(slen, Math.max(tA, tB)) - Math.max(0, Math.min(tA, tB)) < 50) continue;  // must face it\n          const gap = epSignedGap(me, f, out);\n          if (gap > -5 && gap < wallPanelReachMm() && Math.abs(gap) < bestGap) { best = o; bestGap = Math.abs(gap); }\n        }\n      }\n    }\n    return best;\n  }\n  // Every wall panel hung from its line, at its height. Stable: a settled panel\n  // works out the same again, so it is safe on every render.\n  function syncWallEndPanels() {\n    for (let i = 0; i < cabinets.length; i++) {\n      const c = cabinets[i];\n      if (!isWallEndPanelUnit(c)) continue;\n      const host = wallPanelHost(c);\n      const range = host ? wallUnitVerticalRange(host) : null;\n      const top = range ? range.top\n        : (Number.isFinite(c.wallPanelTopMm) ? c.wallPanelTopMm : WALL_MOUNT_TOPS.medium);\n      let h = c.heightMm || 0;\n      if (wallPanelBandMm(c.wallPanelBand)) h = wallPanelBandMm(c.wallPanelBand);\n      else if (!c.wallPanelHeightTyped && range) h = range.top - range.bottom;\n      const b = panelBoardFor(c, c.depthMm);\n      if (b && b.heightMm) h = Math.min(h, b.heightMm);\n      h = Math.max(50, Math.round(h));\n      const off = Math.max(0, Math.round(top - h));\n      if (c.heightMm === h && c.heightOffGroundMm === off && c.wallPanelTopMm === top) continue;\n      cabinets[i] = { ...c, heightMm: h, heightOffGroundMm: off, wallPanelTopMm: top };\n    }\n  }\n\n  // Manual left/right hinge / curve-side flip for radius units.\n  // Mirrors what radiusUnitDesiredHand does on drag-end but driven\n  // by the user from the context menu - useful for islands where\n  // there's no neighbour to auto-detect from, or for forcing the\n  // hand against the auto-detected choice.\n  function flipRadiusUnitHand(c) {\n    if (!c || !c.radiusUnit) return;\n    const newHand = c.radiusUnit.hand === 'left' ? 'right' : 'left';\n    // Swap to the opposite-hand real product (own GLB + basket line); legacy\n    // single-product curved units just flip the geometry marker.\n    if (!swapRadiusHandProduct(c, newHand)) {\n      c.radiusUnit = { ...c.radiusUnit, hand: newHand };\n    }\n    if (c.groupId) {\n      // Backing's TOTAL rotation = hand-rot + group-rot. See the\n      // matching note in the drag-end hand auto-flip above.\n      const groupRot = c.rotationDeg || 0;\n      const handRot  = newHand === 'left' ? -90 : 90;\n      const total    = ((handRot + groupRot) % 360 + 360) % 360;\n      for (const m of cabinets) {\n        if (m.groupId !== c.groupId) continue;\n        if (m.radiusGroup && m.radiusGroup.role === 'backing') {\n          m.rotationDeg = total;\n        }\n      }\n    }\n    rerender();\n  }\n\n  function deleteCabinetGroup(groupId) {\n    if (!groupId) return;\n    const ids = new Set(cabinets.filter(c => c.groupId === groupId).map(c => c.id));\n    if (!ids.size) return;\n    cabinets = cabinets.filter(c => !ids.has(c.id));\n    // If anything in the deleted group was selected, drop the panel.\n    if (selectedItem && ids.has(selectedItem.id)) selectItem(null);\n    selectedCabinetIds = new Set([...selectedCabinetIds].filter(id => !ids.has(id)));\n    rerender();\n  }\n\n  function groupSelectedCabinets() {\n    if (selectedCabinetIds.size < 2) return;\n    const gid = genGroupId();\n    cabinets.forEach(c => { if (selectedCabinetIds.has(c.id)) c.groupId = gid; });\n    rerender();\n  }\n  function ungroupCabinet(gid) {\n    if (!gid) return;\n    cabinets.forEach(c => { if (c.groupId === gid) delete c.groupId; });\n    rerender();\n  }\n  function removeCabinetFromGroup(c) {\n    delete c.groupId;\n    rerender();\n  }\n  function deleteSelectedCabinets() {\n    const gone = withRadiusCompanions(selectedCabinetIds);\n    cabinets = cabinets.filter(c => !gone.has(c.id));\n    selectedCabinetIds = new Set();\n    selectItem(null);\n    rerender();\n  }\n\n  // ---- Save / load ----\n\n  function applyState(state) {\n    // Restore the plan's intrinsic id so re-saving / re-adding this\n    // loaded plan updates its existing basket instead of forking a new\n    // one. A design WITHOUT one (saved before plan ids) gets none, and a\n    // fresh id on its next save. It used to keep whatever id was current -\n    // the PREVIOUS plan's - so its next save matched that plan by id and\n    // wrote this one's contents into it (2026-09-29). Every caller that\n    // means \"same plan\" (undo/redo, live-session copies) passes a design\n    // built by currentDesign(), which always carries the id.\n    plannerPlanId = state.plannerPlanId || null;\n    // The bespoke paints (F&B / RAL) the plan's door colours use, known\n    // before anything draws (Catalogue.registerBespokePaint) - this plan's\n    // only: the last plan's are forgotten first.\n    try { Catalogue.clearBespokePaints?.(); } catch (_) {}\n    for (const bp of (Array.isArray(state.bespokePaints) ? state.bespokePaints : [])) {\n      try { Catalogue.registerBespokePaint?.(bp); } catch (_) {}\n    }\n    if (state.roomConfig) {\n      roomConfig = {\n        ...DEFAULT_ROOM_CONFIG,\n        ...state.roomConfig,\n        shapeParams: { ...(state.roomConfig.shapeParams || {}) },\n        perimeterItems: [...(state.roomConfig.perimeterItems || [])],\n        wallOpenings:   [...(state.roomConfig.wallOpenings   || [])]\n      };\n    }\n    // Auto end panels/fillers preference (default ON for older saves that\n    // predate it). Restored BEFORE the post-load autoDetectEndPanels so a plan\n    // saved in manual mode keeps its hand-set panels instead of re-detecting.\n    autoEndPanels = (state.autoEndPanels !== false);\n    acceptedWarnings = new Set(Array.isArray(state.acceptedWarnings) ? state.acceptedWarnings : []);\n    try { restoreConvertStaged(Array.isArray(state.convertStaged) ? state.convertStaged : []); } catch (e) {}\n    checklistApprovals = (state.checklistApprovals && typeof state.checklistApprovals === 'object' && !Array.isArray(state.checklistApprovals))\n      ? { ...state.checklistApprovals } : {};\n    checklistElsewhere = new Set(Array.isArray(state.checklistElsewhere) ? state.checklistElsewhere : []);\n    checklistRecord = Array.isArray(state.checklistRecord) ? state.checklistRecord.slice() : [];\n    quoteExcludedLines = (state.quoteExcludedLines && typeof state.quoteExcludedLines === 'object') ? { ...state.quoteExcludedLines } : {};\n    quoteFreeLines = (state.quoteFreeLines && typeof state.quoteFreeLines === 'object') ? { ...state.quoteFreeLines } : {};\n    {\n      const wq = state.worktopQuote;\n      const next = (wq && typeof wq === 'object' && wq.ordered) ? { ...wq } : null;\n      if ((next && next.ordered) !== (worktopQuote && worktopQuote.ordered)) { worktopQuoteLink = null; worktopQuoteLinkFor = null; }\n      worktopQuote = next;\n      try { syncWorktopQuoteMode(); } catch (e) { console.warn('[BTK worktop quote] mode not set', e); }\n    }\n    if (state.cabinets) cabinets = state.cabinets.map(migrateCabinet);\n    // A corner return saved longer than the unit it meets is cut back on\n    // open, so the plan, cornice and cut list are right before anything moves.\n    // Loading doesn't run the end-panel walk, so re-decide the panels of the\n    // units it touched once the plan is up (the unit the return now meets\n    // drops the panel the post replaces).\n    try {\n      const _clamped = clampCornerReturns();\n      if (_clamped.length) setTimeout(() => {\n        try { autoDetectEndPanels(_clamped); resizeFillers(); rerender(); } catch (e) { /* cosmetic */ }\n      }, 0);\n    } catch (e) { /* keep the plan as saved */ }\n    // A plan saved with end panels behind a worktop's end waterfall (Sales row\n    // 149 - the back row of an island): re-decide just those units once the\n    // plan is up, so the panels come off. Auto mode only; a side set by hand\n    // keeps the user's choice (the walk skips it).\n    try {\n      if (autoEndPanels) {\n        const _cov = waterfallCoveredEndSides(cabinets);\n        const _ids = [...new Set([..._cov].filter(k => {\n          const i = k.lastIndexOf(':');\n          const c = cabinets.find(x => x && x.id === k.slice(0, i));\n          return !!(c && c.endPanels && c.endPanels[k.slice(i + 1)] && c.endPanels[k.slice(i + 1)].active);\n        }).map(k => k.slice(0, k.lastIndexOf(':'))))];\n        if (_ids.length) setTimeout(() => {\n          try { autoDetectEndPanels(_ids); resizeFillers(); rerender(); } catch (e) { /* cosmetic */ }\n        }, 0);\n      }\n    } catch (e) { /* keep the plan as saved */ }\n    // Heal a plan saved while a radius companion was stranded (its parent curve\n    // deleted on its own) - the filler is unselectable, so the user cannot.\n    pruneOrphanRadiusCompanions();\n    selectedCabinetIds = new Set();   // ids from a previous design are stale\n    // Worktop items (sinks + hobs) - restore with their stored ids,\n    // bumping the next-id past any incoming. Older saves fall back to\n    // an empty list.\n    worktopItems = Array.isArray(state.worktopItems) ? state.worktopItems.map(it => ({ ...it })) : [];\n    extraSinkLines = [];\n    setTimeout(refreshExtraSinks, 0);\n    furnitureItems = Array.isArray(state.furnitureItems) ? state.furnitureItems.map(it => ({ ...it })) : [];\n    nextFurnitureItemId = furnitureItems.reduce((m, f) => {\n      const n = parseInt(String(f.id).replace('fur-', ''), 10);\n      return isNaN(n) ? m : Math.max(m, n);\n    }, 0) + 1;\n    nextWorktopItemId = 1;\n    for (const it of worktopItems) {\n      const m = /(\\d+)$/.exec(it.id || '');\n      if (m) nextWorktopItemId = Math.max(nextWorktopItemId, parseInt(m[1], 10) + 1);\n    }\n\n    // Active kitchen style = the MOST FREQUENT style among the loaded plan's\n    // cabinets (the plan's own dominant style). Opening a plan therefore adopts\n    // that plan's style and DROPS whatever was active before - so the trims and\n    // the whole style context reflect the units ALREADY in the plan, not what\n    // was being browsed. Falls back to the saved style, then to the current\n    // value, for empty plans / older saves that carry no per-cabinet style.\n    const _styleFreq = {};\n    for (const c of cabinets) {\n      if (c && c.kitchenStyleId) _styleFreq[c.kitchenStyleId] = (_styleFreq[c.kitchenStyleId] || 0) + 1;\n    }\n    const _dominantStyle = Object.keys(_styleFreq)\n      .sort((a, b) => _styleFreq[b] - _styleFreq[a])[0];\n    if (_dominantStyle) {\n      kitchenStyleId = _dominantStyle;\n    } else if (state.kitchenStyleId) {\n      kitchenStyleId = state.kitchenStyleId;\n    }\n\n    // Restore globals. Pre-Phase-C1 saves don't have them - derive from\n    // the first cabinet's handles so the picker still reflects something\n    // sensible. If there are no cabinets either, globals stay null and\n    // get populated on the next kitchen-style change.\n    if (state.globalDoorColourHandle) {\n      globalDoorColourHandle = state.globalDoorColourHandle;\n    } else if (cabinets[0]?.doorColourHandle) {\n      globalDoorColourHandle = cabinets[0].doorColourHandle;\n    }\n    if (state.globalCarcaseColourHandle) {\n      globalCarcaseColourHandle = state.globalCarcaseColourHandle;\n    } else if (cabinets[0]?.carcaseColourHandle) {\n      globalCarcaseColourHandle = cabinets[0].carcaseColourHandle;\n    }\n\n    // Style Setup buying styles (up to 3). New saves carry `buyingStyles`;\n    // older saves derive a single entry from the restored globals so the panel\n    // still shows the active style. Always reset per plan (never leak the\n    // previous plan's set).\n    if (Array.isArray(state.buyingStyles) && !state.buyingStyles.length && !cabinets.length) {\n      buyingStyles = [];   // a new plan saved before its style was picked\n    } else if (Array.isArray(state.buyingStyles) && state.buyingStyles.length) {\n      buyingStyles = state.buyingStyles.slice(0, 3)\n        .map(s => ({ styleId: s.styleId || null, doorHandle: s.doorHandle || null, carcaseHandle: s.carcaseHandle || null }))\n        .filter(s => s.styleId);\n    } else if (kitchenStyleId) {\n      buyingStyles = [{ styleId: kitchenStyleId, doorHandle: globalDoorColourHandle, carcaseHandle: globalCarcaseColourHandle }];\n    } else {\n      buyingStyles = [];\n    }\n\n    // ONE ACTIVE STYLE (Arden, 2026-10-28). The active style and the active\n    // door + carcase colours are ONE choice: every way of adding a unit gives\n    // it the active style AND the active colours. They were restored apart -\n    // the style from whichever style most units use (above), the colours from\n    // the save - so a two-style plan saved with its second style active came\n    // back split. Folkestone (PLN100337): 8 Lacquered Oak units, 6 On-Trend,\n    // saved active On-Trend Porcelain, reopened as Lacquered Oak + Porcelain,\n    // and every unit added after that was a Lacquered Oak product with a\n    // Porcelain door - a front that range is not made in, ordered as oak.\n    // Settle the three together: the saved active set when it is a real one\n    // (a style that sells both colours, and part of this plan), else the first\n    // buying style (what the style bar shows as active), else the dominant\n    // style with the colours its own units carry.\n    {\n      const doorOk = (s, h) => { const l = Catalogue.getDoorColoursForStyle?.(s) || []; return !!h && (!l.length || l.some(d => d.handle === h)); };\n      const carcOk = (s, h) => { const l = Catalogue.getCarcaseColoursForStyle?.(s) || []; return !h || !l.length || l.some(c => c.handle === h); };\n      const whole  = (p) => !!(p && p.styleId && doorOk(p.styleId, p.doorHandle) && carcOk(p.styleId, p.carcaseHandle));\n      const inPlan = (s) => cabinets.some(c => c && c.kitchenStyleId === s) || buyingStyles.some(b => b.styleId === s);\n      const saved  = { styleId: state.kitchenStyleId || null, doorHandle: state.globalDoorColourHandle || null,\n                       carcaseHandle: state.globalCarcaseColourHandle || null };\n      let active = null;\n      if (whole(saved) && (!cabinets.length || inPlan(saved.styleId))) active = saved;\n      else if (whole(buyingStyles[0])) active = buyingStyles[0];\n      else if (kitchenStyleId) {\n        const own = cabinets.filter(c => c && c.kitchenStyleId === kitchenStyleId);\n        const most = (vals) => { const n = {}; for (const v of vals) n[v] = (n[v] || 0) + 1; return Object.keys(n).sort((a, b) => n[b] - n[a])[0] || null; };\n        const door = most(own.map(c => c.doorColourHandle).filter(h => h && doorOk(kitchenStyleId, h)))\n          || (Catalogue.getDoorColoursForStyle?.(kitchenStyleId) || [])[0]?.handle || null;\n        const carc = most(own.map(c => c.carcaseColourHandle).filter(h => h && carcOk(kitchenStyleId, h)))\n          || (carcOk(kitchenStyleId, globalCarcaseColourHandle) ? globalCarcaseColourHandle : null)\n          || (Catalogue.getCarcaseColoursForStyle?.(kitchenStyleId) || [])[0]?.handle || null;\n        active = { styleId: kitchenStyleId, doorHandle: door, carcaseHandle: carc };\n      }\n      if (active) {\n        kitchenStyleId            = active.styleId;\n        globalDoorColourHandle    = active.doorHandle;\n        globalCarcaseColourHandle = active.carcaseHandle;\n        // An older save's buying style was derived from the split set above.\n        if (buyingStyles[0] && buyingStyles[0].styleId === active.styleId && !whole(buyingStyles[0])) {\n          buyingStyles[0] = { styleId: active.styleId, doorHandle: active.doorHandle, carcaseHandle: active.carcaseHandle };\n        }\n      }\n    }\n\n    // Restore wall + floor colours. Pre-Phase-D saves don't have\n    // these - fall back to the palette defaults.\n    wallColourHandle  = state.wallColourHandle  || DEFAULT_WALL_COLOUR_HANDLE;\n    featureWalls      = (state.featureWalls && typeof state.featureWalls === 'object') ? { ...state.featureWalls } : {};\n    floorColourHandle = state.floorColourHandle || DEFAULT_FLOOR_HANDLE;\n    floorSettings     = state.floorSettings ? { ...state.floorSettings } : { ...DEFAULT_FLOOR_SETTINGS };\n\n    // Feature settings - older saves won't have these; fall back to\n    // defaults and only keep recognised keys.\n    featureStyles = { ...DEFAULT_FEATURE_STYLES, ...(state.featureStyles || {}) };\n    railFinishHandle = state.railFinishHandle || DEFAULT_RAIL_FINISH_HANDLE;\n\n    // Handle groups. New saves carry `handleGroups`; migrate an old\n    // single `globalHandle` onto ALL groups so a pre-groups plan keeps its\n    // handle everywhere. Older-still saves fall back to \"no handle\". A save\n    // predating the pan-drawers split simply has no pan-drawers key \u2192 empty.\n    handleGroups = emptyHandleGroups();\n    if (state.handleGroups && typeof state.handleGroups === 'object') {\n      for (const k of HANDLE_GROUP_KEYS) {\n        const g = state.handleGroups[k] || {};\n        handleGroups[k] = {\n          designId:     g.designId     ?? null,\n          finishHandle: g.finishHandle ?? null,\n          sizeMm:       g.sizeMm        ?? null,\n          orientation:  g.orientation  ?? null\n        };\n      }\n    } else if (state.globalHandle) {\n      for (const k of HANDLE_GROUP_KEYS) {\n        handleGroups[k] = {\n          designId:     state.globalHandle.designId     ?? null,\n          finishHandle: state.globalHandle.finishHandle ?? null,\n          sizeMm:       state.globalHandle.sizeMm        ?? null,\n          orientation:  null\n        };\n      }\n    }\n\n    // Per-trim-segment colour overrides - fresh empty map on older saves.\n    segmentColours = state.segmentColours ? { ...state.segmentColours } : {};\n\n    // Global worktop colour - older saves fall back to the default.\n    worktopColourHex = (typeof state.worktopColourHex === 'string' && state.worktopColourHex)\n      ? state.worktopColourHex : DEFAULT_WORKTOP_COLOUR;\n    worktopColours   = (state.worktopColours && typeof state.worktopColours === 'object')\n      ? { ...state.worktopColours } : {};\n    worktopCornerRadii = (state.worktopCornerRadii && typeof state.worktopCornerRadii === 'object')\n      ? { ...state.worktopCornerRadii } : {};\n    // Worktop material - older saves have neither; default to none.\n    worktopMaterialHandle = (typeof state.worktopMaterialHandle === 'string' && state.worktopMaterialHandle)\n      ? state.worktopMaterialHandle : null;\n    worktopsNotPriced = state.worktopsNotPriced === true;\n    worktopParts = {\n      upstand: (state.worktopParts && state.worktopParts.upstand) || null,\n      splashback: (state.worktopParts && state.worktopParts.splashback) || null,\n      edging: (state.worktopParts && state.worktopParts.edging) || null,\n    };\n    worktopMaterialsBySection = (state.worktopMaterialsBySection && typeof state.worktopMaterialsBySection === 'object')\n      ? { ...state.worktopMaterialsBySection } : {};\n    worktopBespoke = normaliseBespokeOptions(state.worktopBespoke);\n\n    // Style Setup option sets (handles / worktops / rails). New saves carry the\n    // arrays; older saves derive a single applied entry from the globals just\n    // restored above so the panel still shows one card. Always reset per plan.\n    buyingHandles = (Array.isArray(state.buyingHandles) && state.buyingHandles.length)\n      ? state.buyingHandles.slice(0, 3).filter(h => h && h.designId)\n      : ((handleGroups.base && handleGroups.base.designId)\n          ? [{ designId: handleGroups.base.designId, designName: '', finishHandle: handleGroups.base.finishHandle || null, finishName: '' }]\n          : []);\n    buyingWorktops = (Array.isArray(state.buyingWorktops) && state.buyingWorktops.length)\n      ? state.buyingWorktops.slice(0, 3).filter(w => w && w.handle)\n      : (worktopMaterialHandle ? [{ handle: worktopMaterialHandle, name: '' }] : []);\n    buyingRails = (Array.isArray(state.buyingRails) && state.buyingRails.length)\n      ? state.buyingRails.slice(0, 3).filter(r => r && r.handle)\n      : (railFinishHandle ? [{ handle: railFinishHandle, name: '' }] : []);\n\n    if (handle3D) {\n      if (handle3D.setWallColour)  handle3D.setWallColour(getWallColour(wallColourHandle).hex);\n      applyFeatureWallsTo3D();\n      applyFloorTo3D();\n    }\n\n    // Flythrough waypoints - restore the saved list, sanitising any\n    // missing-x/y entries. Older saves without the field stay empty.\n    // Optional per-waypoint look-at target carries over too.\n    flythroughWaypoints = Array.isArray(state.flythroughWaypoints)\n      ? state.flythroughWaypoints\n          .filter(w => w && typeof w.x === 'number' && typeof w.y === 'number')\n          .map(w => {\n            const out = { x: w.x, y: w.y };\n            if (w.look && typeof w.look.x === 'number' && typeof w.look.y === 'number') {\n              out.look = { x: w.look.x, y: w.look.y };\n            }\n            return out;\n          })\n      : [];\n    flythroughSpeed = (typeof state.flythroughSpeed === 'number' && state.flythroughSpeed > 0)\n      ? Math.max(0.25, Math.min(4, state.flythroughSpeed))\n      : 1;\n\n    // Lights - restore the saved list, sanitising each entry. Older\n    // saves without the field stay empty.\n    lights = Array.isArray(state.lights)\n      ? state.lights\n          .filter(l => l && typeof l.x === 'number' && typeof l.y === 'number')\n          .map(l => ({\n            id:       l.id,\n            x:        l.x,\n            y:        l.y,\n            settings: (l.settings && typeof l.settings === 'object')\n              ? {\n                  brightness: l.settings.brightness || 'medium',\n                  colour:     l.settings.colour     || 'warm',\n                  spread:     l.settings.spread     || 'medium'\n                }\n              : { brightness: 'medium', colour: 'warm', spread: 'medium' }\n          }))\n      : [];\n    nextLightId = computeNextId(lights);\n    lightsOn = (typeof state.lightsOn === 'boolean') ? state.lightsOn : true;\n\n    nextCabinetId       = computeNextId(cabinets);\n    nextPerimeterItemId = computeNextId(roomConfig.perimeterItems || []);\n    nextOpeningId       = computeNextId(roomConfig.wallOpenings   || []);\n    try { fitBackPanelsToGaps(); } catch (e) { console.warn('[BTK KP] back panel fit', e); }\n    cabinetsHandle.refresh();\n    styleColoursHandle.refresh();\n    rerender();\n  }\n\n  // \u2500\u2500 Live-session viewer apply \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n  // A full applyState() rebuilds the whole 2D + 3D scene (~1s with GLBs) - far\n  // too slow to mirror a drag streaming at many frames/sec, so the viewer falls\n  // hopelessly behind. For a PURE-TRANSLATION update (only existing cabinets'\n  // x/y changed) do a cheap update instead: rebuild 2D but SKIP the full 3D\n  // rebuild, nudging the 3D meshes by their delta; then a debounced full\n  // reconcile once the drag settles (fixes 3D worktops/splashbacks). Anything\n  // structural (add/remove/rotate/resize/colour\u2026) falls back to a full apply.\n  let _mirrorPrevDesign = null;\n  let _mirrorReconcileT = null;\n  function applyMirrorSnapshot(design) {\n    const moves = mirrorTranslationMoves(_mirrorPrevDesign, design);\n    if (moves) {\n      for (const mv of moves) {\n        const cab = cabinets.find(c => c.id === mv.id);\n        if (cab) { cab.x = mv.x; cab.y = mv.y; }\n      }\n      const nudge = () => {\n        if (handle3D && handle3D.nudgeCabinets) {\n          handle3D.nudgeCabinets(moves.map(mv => ({ id: mv.id, dxMm: mv.dx, dyMm: mv.dy })));\n        }\n      };\n      // The viewer only looks at ONE view - update just that one, live. In 3D\n      // slide the meshes and SKIP the 2D rebuild entirely (near-instant); in 2D\n      // rebuild the cheap 2D and skip the costly 3D. The other view + the\n      // worktops/splashbacks are trued up by the debounced full reconcile below.\n      if (viewMode === '3d') { nudge(); }\n      else { rerender({ skip3D: true }); nudge(); }\n      _mirrorPrevDesign = design;\n      if (_mirrorReconcileT) clearTimeout(_mirrorReconcileT);\n      _mirrorReconcileT = setTimeout(() => {             // settle \u2192 full reconcile\n        _mirrorReconcileT = null;\n        applyState(_mirrorPrevDesign); autoDetectBackPanels();\n      }, 350);\n      return;\n    }\n    if (_mirrorReconcileT) { clearTimeout(_mirrorReconcileT); _mirrorReconcileT = null; }\n    applyState(design); autoDetectBackPanels();\n    _mirrorPrevDesign = design;\n  }\n  // Returns [{id,x,y,dx,dy}] if `next` differs from `prev` ONLY by the x/y of\n  // existing cabinets (same ids + everything else byte-identical); else null.\n  function mirrorTranslationMoves(prev, next) {\n    if (!prev || !next || !Array.isArray(prev.cabinets) || !Array.isArray(next.cabinets)) return null;\n    if (prev.cabinets.length !== next.cabinets.length) return null;\n    const strip = (d) => { const c = { ...d }; delete c.cabinets; return JSON.stringify(c); };\n    if (strip(prev) !== strip(next)) return null;         // any non-cabinet change \u2192 full apply\n    const prevById = new Map(prev.cabinets.map(c => [c.id, c]));\n    const moves = [];\n    for (const b of next.cabinets) {\n      const a = prevById.get(b.id);\n      if (!a) return null;\n      if (JSON.stringify({ ...a, x: 0, y: 0 }) !== JSON.stringify({ ...b, x: 0, y: 0 })) return null;\n      if (a.x !== b.x || a.y !== b.y) moves.push({ id: b.id, x: b.x, y: b.y, dx: b.x - a.x, dy: b.y - a.y });\n    }\n    return moves;                                         // may be empty (no-op) - harmless\n  }\n\n  // Currently-active named plan. Set by handleSaveAs after a successful\n  // save and by handleLoadPlan after a successful load. Plain Save\n  // (the bottombar's first button) goes back to the same name when\n  // one is active, otherwise behaves like Save As and prompts.\n  let activePlanName = null;\n  // New Plan's room-shape card (syncRoomShapeCard): the newest saved plan's\n  // room, and a counter so an older listPlans reply cannot overwrite a newer.\n  // Up here, not beside the function: New Plan first renders during init.\n  let previousPlanRoom = null;\n  let roomShapeSyncSeq = 0;\n\n  // \"Live Quote\" labels - the top-bar quote button and the quote drawer\n  // header both reflect the active plan name: \"Live Quote: <name>\" once\n  // saved, otherwise their plain defaults. Call after any plan-name change.\n  const liveQuoteHeadingEl  = root.querySelector('[data-btk-kp-livequote-heading]');\n  const embedQuoteNameEl    = root.querySelector('[data-btk-kp-embed-quote-name]');\n  function refreshLiveQuoteLabels() {\n    if (liveQuoteHeadingEl) {\n      liveQuoteHeadingEl.textContent = activePlanName ? `Live Quote: ${activePlanName}` : 'Live Quote';\n    }\n    if (embedQuoteNameEl) {\n      // \"Quote:\" is a light-weight label; the plan name is the bold value.\n      // Build with textContent on the value span so user-typed names are safe.\n      // Always show \"Plan: <name>\"; an unsaved plan reads \"Plan: Unsaved\" so\n      // there's always a value after the label.\n      embedQuoteNameEl.textContent = '';\n      const label = document.createElement('span');\n      label.className = 'btk-kp-quotebar-name-label';\n      label.textContent = 'Plan:';\n      embedQuoteNameEl.appendChild(label);\n      embedQuoteNameEl.appendChild(document.createTextNode(' '));\n      const value = document.createElement('span');\n      value.className = 'btk-kp-quotebar-name-value';\n      value.textContent = activePlanName || 'Unsaved';\n      embedQuoteNameEl.appendChild(value);\n      // The plan's number (planner-api src/basket-refs.js), once it has one -\n      // the number the customer and the sales team quote to each other.\n      let ref = null;\n      try { ref = window.BTKBasketAPI?.basketRef?.(lastQuoteBasketId) || null; } catch (e) { ref = null; }\n      if (ref) {\n        const r = document.createElement('span');\n        r.className = 'btk-kp-quotebar-name-ref';\n        r.style.cssText = 'margin-left:8px;font-weight:400;opacity:0.75;white-space:nowrap;';\n        r.textContent = ref;\n        embedQuoteNameEl.appendChild(r);\n      }\n    }\n  }\n  window.addEventListener('btk:basket-refs', () => refreshLiveQuoteLabels());\n\n  // Stable, intrinsic id for THIS plan. It travels inside the design\n  // blob (so it survives save/load and any page navigation) and is how\n  // a saved basket is matched back to its plan - preventing duplicate\n  // baskets when the same plan is saved or added to the basket again.\n  // Generated lazily; restored by applyState; reset by handleClear.\n  let plannerPlanId = null;\n  function ensurePlanId() {\n    if (!plannerPlanId) {\n      plannerPlanId = 'plan_' + Date.now().toString(36) + '_' + Math.random().toString(36).slice(2, 9);\n    }\n    return plannerPlanId;\n  }\n\n  function currentDesign() {\n    return {\n      plannerPlanId: ensurePlanId(),\n      // The base name this plan is a version of, if any - lifted to the\n      // payload's top level by buildPayload so listings can group by it.\n      versionOf: activePlanVersionOf,\n      roomConfig,\n      autoEndPanels,\n      // Warnings the designer has signed off. Saved so the ticks survive a\n      // reload; the plan still shows them red, the tick only records review.\n      acceptedWarnings: [...acceptedWarnings],\n      // Units from a converted basket still waiting in the tray (Arden,\n      // 2026-10-11) - saved, so a refresh or a later visit keeps them.\n      convertStaged: (() => { try { return convertStagedUnits.map(u => u.line).filter(Boolean); } catch (e) { return []; } })(),\n      // Checklist approvals (the Checklist stage), each with what it approved.\n      checklistApprovals: { ...checklistApprovals },\n      checklistElsewhere: [...checklistElsewhere],\n      checklistRecord: checklistRecord.map(r => ({ ...r })),\n      quoteExcludedLines: { ...quoteExcludedLines },\n      quoteFreeLines: { ...quoteFreeLines },\n      worktopQuote: worktopQuote ? { ...worktopQuote } : null,\n      cabinets: liveDragCabs || cabinets,\n      worktopItems,\n      furnitureItems,\n      kitchenStyleId,\n      globalDoorColourHandle,\n      globalCarcaseColourHandle,\n      buyingStyles,\n      buyingHandles,\n      buyingWorktops,\n      buyingRails,\n      wallColourHandle,\n      featureWalls,\n      floorColourHandle,\n      floorSettings,\n      featureStyles,\n      railFinishHandle,\n      segmentColours,\n      worktopColourHex,\n      worktopColours,\n      worktopCornerRadii,\n      // The F&B / RAL paints chosen for the F&B ranges (applyState).\n      bespokePaints: Catalogue.getBespokePaints ? Catalogue.getBespokePaints() : [],\n      worktopMaterialHandle,\n      worktopsNotPriced,\n      worktopParts,\n      worktopMaterialsBySection,\n      worktopBespoke,\n      handleGroups,\n      flythroughWaypoints,\n      flythroughSpeed,\n      lights,\n      lightsOn\n    };\n  }\n\n  // The current plan's saved thumbnail (a 3D render). Preserved across saves so\n  // saving from 2D doesn't wipe a previously-captured 3D preview. Seeded on plan\n  // load, cleared on a new blank plan, refreshed whenever a 3D snapshot is taken.\n  let planThumb = null;\n  // Set once an off-screen capture has genuinely failed (no WebGL, a tainted\n  // canvas). Stops autosave paying the cost of rebuilding the 3D scene on every\n  // save for a device that is never going to produce a preview.\n  let thumbOffscreenFailed = false;\n\n  // Small 3D thumbnail for the saved plan card. ONLY a real 3D render counts -\n  // a 2D plan / mood board yields no thumbnail (the card shows \"No preview yet\").\n  // `allowOffscreen` builds the 3D renderer if the customer has never opened 3D,\n  // so a plan saved purely from 2D still gets a preview. That means loading every\n  // unit's GLB, which is slow on a big kitchen \u2014 so it is NEVER done on the save\n  // path itself (see capturePlanThumbDeferred), only afterwards.\n  async function capturePlanThumb({ allowOffscreen = false } = {}) {\n    try {\n      let src = null;\n      if (allowOffscreen && viewMode !== '3d') {\n        // Same lazy plumbing the Add Units popup uses for its 3D product cards.\n        try {\n          await ensure3DReady();\n          // ensure3DReady only MOUNTS the renderer \u2014 the scene stays empty until\n          // it is given the plan. Without this the snapshot finds an empty\n          // bounding box, returns null, and the save silently keeps whatever\n          // thumbnail was stored before (which looks like \"nothing changed\").\n          if (handle3D) {\n            handle3D.setActive?.(true);\n            handle3D.render({\n              room, roomConfig, cabinets, baseRoom, featureStyles, railFinishHandle,\n              segmentColours, worktops: buildWorktops(), worktopColourHex, worktopColours,\n              worktopCornerRadii, worktopItems, furnitureItems, handleGroups, lights, lightsOn,\n            });\n            handle3D.resize?.();\n            // Cabinet GLBs load asynchronously; without a pause the shot is an\n            // empty room. Two rAFs plus a short wait is enough for the room and\n            // most units \u2014 anything still missing simply isn't in this frame.\n            await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));\n            await new Promise((r) => setTimeout(r, Number(THUMB_MODEL_WAIT_MS) || 1500));\n          }\n        } catch (e) {\n          console.warn('[BTK thumb] offscreen 3D build failed', e);\n        }\n      }\n      if (handle3D && typeof handle3D.snapshot === 'function') {\n        // 'plan' looks down from ~4m over the room's clearest wall, so every\n        // saved plan reads the same way up instead of an arbitrary iso angle.\n        // 1200 x 800, kept at 1000 wide: the picture is also the plan card in\n        // the customer's emails (Odoo Customer Journeys), shown 544px wide, so\n        // 400 wide looked soft there (Arden, 2026-11-14).\n        src = handle3D.snapshot({ view: 'plan', width: 1200, height: 800 });\n      }\n      if (!src) return null;\n      return await new Promise((resolve) => {\n        const img = new Image();\n        img.onload = () => {\n          try {\n            const W = 1000;\n            const H = Math.round(W * (img.height / img.width)) || 260;\n            const c = document.createElement('canvas');\n            c.width = W; c.height = H;\n            c.getContext('2d').drawImage(img, 0, 0, W, H);\n            resolve(c.toDataURL('image/jpeg', 0.72));\n          } catch (e) { resolve(null); }\n        };\n        img.onerror = () => resolve(null);\n        img.src = src;\n      });\n    } catch (e) { console.warn('[BTK thumb] capture failed', e); return null; }\n  }\n\n  // Capture a preview AFTER a save has completed, then patch it onto the stored\n  // plan. Deferred deliberately: building 3D off-screen can take seconds on a\n  // large kitchen, and the customer must never wait on it to save. Best-effort \u2014\n  // \"no preview yet\" is already a supported state on the plan card.\n  // How long to let cabinet GLBs load before taking an off-screen snapshot.\n  // Too short and the room is empty; too long and the background capture drags.\n  const THUMB_MODEL_WAIT_MS = 1500;\n\n  // Set by currentDesignWithThumb() when it managed to capture inline (3D was\n  // already built), so the deferred pass doesn't repeat work for that save.\n  let thumbCapturedThisSave = false;\n\n  // True when `basket` holds a DIFFERENT plan from the one on screen. The\n  // working pointer moves to a plan as it opens, before its design is drawn,\n  // so anything written by the pointer in that moment went into the plan being\n  // opened: the last plan's basket lines landed in Jonathan Print's plans when\n  // they were opened from Odoo (bug sheet, Julian, 2026-10-30). A basket with\n  // no plan id yet (a new draft, a plan from before ids) is not another plan's.\n  function basketHoldsOtherPlan(basket) {\n    const theirs = basket && basket.plannerDesign && basket.plannerDesign.design\n      && basket.plannerDesign.design.plannerPlanId;\n    return !!(theirs && plannerPlanId && theirs !== plannerPlanId);\n  }\n\n  // The basket holding the plan currently open, resolved the way the planner\n  // itself tracks it. Falls back to the cart's active basket only when the\n  // planner has no id of its own yet.\n  async function plannerBasketForWrite() {\n    const api = window.BTKBasketAPI;\n    if (!api) return null;\n    try {\n      const id = (planStore && typeof planStore.getActiveBasketId === 'function')\n        ? await planStore.getActiveBasketId() : null;\n      if (id) {\n        const project = await api.getProject();\n        const hit = (project && (project.baskets || []).find(b => b && b.id === id)) || null;\n        if (hit) return basketHoldsOtherPlan(hit) ? null : hit;\n      }\n      return await api.getActiveBasket();\n    } catch (e) { return null; }\n  }\n\n  // ---- Undo / redo --------------------------------------------------------\n  //\n  // Snapshot history rather than a command log: every change already funnels\n  // through rerender(), and applyState() can restore a whole design, so a stack\n  // of designs gives correct undo for everything - units, room shape, colours,\n  // worktops - without each feature having to describe its own inverse.\n  //\n  // Snapshots are taken AFTER a change lands, and the stack starts with the\n  // state the plan opened in, so undo always has somewhere to go back to.\n  const UNDO_LIMIT = 40;\n  const undoStack = [];\n  const redoStack = [];\n  let undoApplying = false;      // suppress capture while restoring\n  let undoLast = null;           // the snapshot the plan is currently AT\n  // The purchased plan exactly as it opened in the viewer (openOrderedPlan).\n  // While set, the plan cannot move: any change is put straight back.\n  let orderedFrozen = null;\n\n  function undoSnapshot() {\n    try { return JSON.stringify(currentDesign()); } catch (e) { return null; }\n  }\n\n  function pushUndoSnapshot() {\n    if (undoApplying) return;\n    const snap = undoSnapshot();\n    // PURCHASED PLAN: every change funnels through rerender, so this is the one\n    // place that sees all of them, including any edit path the viewer's input\n    // blocking has not thought of. Put the plan back as it was bought, on the\n    // next frame so the render in progress finishes first. Never recorded, so\n    // there is no undo either.\n    if (orderedFrozen) {\n      if (snap && snap !== orderedFrozen) {\n        requestAnimationFrame(() => {\n          if (undoSnapshot() === orderedFrozen) return;\n          console.warn('[BTK planner] a change reached the purchased plan - put back');\n          applyUndoSnapshot(orderedFrozen);\n        });\n      }\n      return;\n    }\n    if (!snap || snap === undoLast) return;      // nothing actually changed\n    if (undoLast) {\n      undoStack.push(undoLast);\n      if (undoStack.length > UNDO_LIMIT) undoStack.shift();\n      // A new change abandons the redo branch, the same as any editor.\n      redoStack.length = 0;\n    }\n    undoLast = snap;\n    syncUndoButtons();\n  }\n\n  function applyUndoSnapshot(snap) {\n    let design = null;\n    try { design = JSON.parse(snap); } catch (e) { return false; }\n    undoApplying = true;\n    try {\n      applyState(design);\n      undoLast = snap;\n      rerender();\n      roomShapeHandle?.refresh?.();\n      selectionPanelHandle?.refresh?.();\n    } finally {\n      undoApplying = false;\n    }\n    syncUndoButtons();\n    scheduleAutosave();\n    return true;\n  }\n\n  function undo() {\n    if (!undoStack.length) return;\n    const prev = undoStack.pop();\n    if (undoLast) redoStack.push(undoLast);\n    applyUndoSnapshot(prev);\n  }\n\n  function redo() {\n    if (!redoStack.length) return;\n    const next = redoStack.pop();\n    if (undoLast) undoStack.push(undoLast);\n    applyUndoSnapshot(next);\n  }\n\n  function syncUndoButtons() {\n    root.querySelectorAll('[data-btk-kp-undo]').forEach(b => { b.disabled = !undoStack.length; });\n    root.querySelectorAll('[data-btk-kp-redo]').forEach(b => { b.disabled = !redoStack.length; });\n  }\n\n  // ---- Autosave ----------------------------------------------------------\n  //\n  // Saving the DATA is cheap - JSON and one basket write - so it runs on a\n  // debounce after the user stops changing things.\n  //\n  // The PREVIEW is not always cheap. With 3D already open the renderer is\n  // mounted and the scene current, so a snapshot is one extra frame; from 2D it\n  // would have to lazy-load the engine, build the scene and wait on GLBs, which\n  // is far too much to put on a timer. So autosave refreshes the preview only\n  // when the renderer is already warm, and leaving 3D takes one too - that is\n  // the moment the view is most current and the cost is nil.\n  const AUTOSAVE_KEY   = 'btk_kp_autosave_on';\n  const AUTOSAVE_IDLE_MS = 6000;\n  let autosaveOn = (() => {\n    try { return localStorage.getItem(AUTOSAVE_KEY) !== '0'; } catch (e) { return true; }\n  })();\n  let autosaveTimer = null;\n  let autosaveRunning = false;\n  let autosaveDirty = false;\n  // A plan part-way through opening (loadNamedPlan): its design is on screen\n  // but its styles are still loading. A save then went out under the name of\n  // the plan open before it and renamed this one (Jonathan Print's plans,\n  // 2026-10-29), so nothing autosaves until it has opened.\n  let planOpening = 0;\n  let namedSaveRunning = false;   // see withAutosaveHeld\n  // The website's Start Planning: the last plan is restored under the name\n  // popup, which redraws it and so marked it changed - and the new plan's\n  // reset then uploaded it again, unchanged, first (3.1s, ?btktime=1, Arden\n  // 2026-10-07). Nothing can edit it from there, so no autosave until the new\n  // plan's reset starts, or the name popup is closed and it is back in use.\n  let autosaveHeldForLinkedNewPlan = false;\n  // What the plan looked like when it was last loaded or autosaved. Redrawing\n  // marks a plan changed whether or not anything is, so a plan only opened -\n  // nothing touched - was uploaded again, whole project and all: 3.2s before\n  // Choose Room Shape could start the new plan (?btktime=1, Arden 2026-10-07).\n  // Autosave now skips a plan that is the same as this.\n  let lastSavedSig = null;\n  function designSig() {\n    try { return JSON.stringify(currentDesign()); } catch (e) { return null; }\n  }\n\n  function setAutosaveEnabled(on) {\n    autosaveOn = !!on;\n    try { localStorage.setItem(AUTOSAVE_KEY, autosaveOn ? '1' : '0'); } catch (e) {}\n    syncAutosaveToggle();\n    if (!autosaveOn && autosaveTimer) { clearTimeout(autosaveTimer); autosaveTimer = null; }\n    if (autosaveOn && autosaveDirty) scheduleAutosave();\n  }\n\n  // Ordered in another tab while this one was open: the save is refused, so\n  // move this tab onto a fresh plan rather than let it keep failing.\n  try {\n    window.addEventListener('btk:plan-locked', () => { startFreshIfOrdered(); });\n    // The server kept its own version of a basket this page saved (held for\n    // checkout, or ordered - possibly from another tab). If it is the plan on\n    // screen, handle it exactly as a load would: move off an ordered plan, ask\n    // about a held one. Another basket being kept is not this page's business.\n    // A save that failed (including one running in the background after the\n    // basket opened) is shown, and the plan is marked unsaved so the next change\n    // tries again. Nothing listened for this before, so a background failure\n    // would have been invisible.\n    window.addEventListener('btk:project-save-failed', () => {\n      if (_bootOrdered) return;\n      try { designControlsHandle.setSaveState?.('error', 'Save failed - your changes will be tried again'); } catch (_) {}\n      autosaveDirty = true;\n    });\n    window.addEventListener('btk:plan-kept', async (e) => {\n      if (_bootOrdered) return;\n      try {\n        const kept = ((e && e.detail && e.detail.kept) || []).map(k => String(k && k.basketId));\n        const id = await window.BTKBasketAPI?.getActivePlannerBasketId?.();\n        if (id && kept.includes(String(id))) startFreshIfOrdered();\n      } catch (_) {}\n    });\n  } catch (e) {}\n\n  function syncAutosaveToggle() {\n    root.querySelectorAll('[data-btk-kp-autosave-toggle]').forEach(el => {\n      el.setAttribute('aria-pressed', autosaveOn ? 'true' : 'false');\n      el.classList.toggle('is-active', autosaveOn);\n      const lbl = el.querySelector('[data-btk-kp-autosave-state]');\n      if (lbl) lbl.textContent = autosaveOn ? 'On' : 'Off';\n    });\n  }\n\n  // An ORDERED plan is not editable anywhere, so it is not left sitting in the\n  // planner: the planner starts a fresh empty plan and the bought one is read\n  // from the account's Orders page instead. Disabling the editor was not\n  // enough - the canvas still took drags, and the plan IS the record of what\n  // was bought (Arden: \"they could change it to win an argument with us\").\n  // After an order the planner opens a FRESH plan, and a fresh plan takes its\n  // style from the buying-style context the site remembers (this tab's\n  // session keys, restored in a new tab from the cart's kitchen_* attributes).\n  // Opening the bought plan had written ITS styles there, so the new plan came\n  // up in the old kitchen's style and mood board instead of empty (Arden,\n  // 2026-09-29). Forget them, so it starts on the planner's defaults.\n  async function forgetBoughtPlanStyles() {\n    ['btk_kitchen_context', 'btk_comparison_styles', 'btk_style_slots'].forEach((k) => {\n      try { sessionStorage.removeItem(k); } catch (e) {}\n    });\n    try {\n      await fetch('/cart/update.js', {\n        method: 'POST', headers: { 'Content-Type': 'application/json' },\n        body: JSON.stringify({ attributes: {\n          kitchen_style: '', kitchen_style_name: '', kitchen_colour: '',\n          kitchen_carcase_colour: '', kitchen_comparison_styles: '' } })\n      });\n    } catch (e) { /* the session keys are gone either way */ }\n  }\n\n  const heldAnswered = new Map();   // basketId -> 'edit' | 'leave', this page only\n  const heldNotBought = new Set();  // checked for an order on this page, none came\n  const FURTHER_ORDER_CHECKS = 6, ORDER_CHECK_EVERY_MS = 5000;\n  let heldAsking = false;\n  async function startFreshIfOrdered() {\n    try {\n      const api = window.BTKBasketAPI;\n      if (!api || typeof api.getBasketLock !== 'function') return;\n      const id = await api.getActivePlannerBasketId();\n      if (!id) return;\n      const lock = api.getBasketLock(id);\n      // Back through pre-checkout's Basket step: they have left checkout, so it\n      // is theirs again. (Shopify's \"Return to cart\" lands on /cart, which\n      // releases it the same way.)\n      const basketStepReturn = _bootBasketStepReturn;\n      _bootBasketStepReturn = false;\n      if (basketStepReturn && lock && lock.status === 'held') {\n        await api.releaseBasket(id);\n        return;\n      }\n      // HELD: the plan is at checkout. That used to be released on ANY load,\n      // which also undid the hold when the planner was simply opened in another\n      // tab while payment was going through - exactly when it is needed.\n      const bought = await planIsBought(api, id, lock);\n      if (lock && lock.status === 'held' && !bought) {\n        // Anything else cannot tell \"came back unpaid\" from \"paying in another\n        // tab\", so ask rather than guess. Declining leaves the hold in place;\n        // it expires on its own if that checkout is never finished.\n        // Asked ONCE per page: every refused save lands back here (see\n        // btk:plan-kept), and a question on each autosave would train people\n        // to click through it. After \"Leave It\" the status just says so.\n        if (heldAnswered.has(id) || heldAsking) {\n          if (heldAnswered.get(id) === 'leave') {\n            designControlsHandle.setSaveState?.('error', 'Not saved: this plan is at checkout');\n          }\n          return;\n        }\n        heldAsking = true;\n        let carryOn = false;\n        try {\n          carryOn = await window.BTKKPDialog.confirm(\n            'This plan is at checkout, so changes to it cannot be saved while the payment is in progress. '\n            + 'If you are not going ahead with that checkout, you can carry on editing it.',\n            { title: 'Plan At Checkout', confirmText: 'Carry On Editing', cancelText: 'Leave It' });\n        } finally { heldAsking = false; }\n        heldAnswered.set(id, carryOn ? 'edit' : 'leave');\n        if (carryOn) {\n          await api.releaseBasket(id);\n          // The edits the server put back are still here on screen: save them now.\n          autosaveDirty = true;\n          scheduleAutosave();\n        } else {\n          designControlsHandle.setSaveState?.('error', 'Not saved: this plan is at checkout');\n        }\n        return;\n      }\n      if (!bought) return;\n      // Bought while this page had it open (another tab, or the order landed\n      // after load): leave it, and reload onto the planner's Home.\n      await leaveBoughtPlan();\n      window.location.reload();\n    } catch (e) { /* never block the planner on this */ }\n  }\n\n  // Has the ACTIVE plan been bought? ORDERED says so outright. A HELD plan\n  // counts too when it was JUST paid for: the server only marks it ordered\n  // once the order webhook has imported it into Odoo, 10-20 seconds after\n  // payment, and in that gap the planner showed the bought plan and then\n  // reloaded out of nowhere on the first refused save (Arden, 2026-09-29).\n  // Shopify empties the Online cart the moment an order is placed, so a hold\n  // THIS browser took in the last 30 minutes, beside an empty cart, is a\n  // purchase. Only then: an empty cart on another device, or long after an\n  // abandoned attempt, is not evidence of an order, and wrongly treating a\n  // plan as bought moves the customer off it. Any doubt = not bought.\n  async function planIsBought(api, id, lock) {\n    if (!lock) return false;\n    if (lock.status === 'ordered') return true;\n    if (lock.status !== 'held' || !api.heldHereAt || _bootBasketStepReturn) return false;\n    if (heldNotBought.has(id)) return false;\n    const heldAt = api.heldHereAt(id);\n    if (!heldAt || (Date.now() - heldAt) >= 30 * 60 * 1000) return false;\n    let emptyCart = false;\n    try {\n      const r = await fetch('/cart.js', { headers: { Accept: 'application/json' } });\n      const cart = r.ok ? await r.json() : null;\n      emptyCart = !!cart && !(cart.item_count > 0);\n    } catch (e) { return false; }\n    if (!emptyCart) return false;\n    // An empty cart alone is not an order: a cart write cut short (a tab closed\n    // while it refills, a refused line) leaves one too, and treating that as a\n    // purchase dropped a customer's unpaid plan for a blank one (Ellie Wing,\n    // 2026-11-02). So wait for the order itself. The server marks the plan\n    // ordered once the webhook has imported it, 10-20 seconds after payment.\n    // An order later than this still lands: the next refused save moves off it.\n    try { window.BTKLoader?.show?.(); } catch (e) {}\n    try {\n      if (!api.refreshLocks) return false;\n      for (let i = 0; i < FURTHER_ORDER_CHECKS; i++) {\n        await new Promise(res => setTimeout(res, ORDER_CHECK_EVERY_MS));\n        await api.refreshLocks();\n        const now = api.getBasketLock(id);\n        if (now && now.status === 'ordered') return true;\n        if (!now) return false;\n      }\n      heldNotBought.add(id);\n      return false;\n    } catch (e) {\n      return false;\n    } finally {\n      try { window.BTKLoader?.hide?.(); } catch (e) {}\n    }\n  }\n\n  // Step off a bought plan: it is no longer the active plan, so the planner\n  // opens on its Home, exactly as a first visit does - nothing restored, no\n  // plan loaded by default, and no spare \"New Kitchen\" plan made to stand in\n  // (that is what used to pick up one of the customer's own saved plans, and\n  // what minted a dozen empty ones on 2026-09-26). The styles the bought plan\n  // left in the browsing context go too.\n  async function leaveBoughtPlan() {\n    try { await planStore.clear(); } catch (e) { /* non-fatal */ }\n    await forgetBoughtPlanStyles();\n  }\n\n  function scheduleAutosave() {\n    // A live-session viewer only mirrors the salesperson's plan. Saving it\n    // would write the same project back from a second tab on every snapshot,\n    // racing the salesperson's own saves.\n    if (_bootLive.session && _bootLive.role === 'viewer') return;\n    // A purchased plan is only ever looked at. See openOrderedPlan.\n    if (_bootOrdered) return;\n    // Nor is a plan opened view-only.\n    if (_bootViewOnly) return;\n    // Opening a linked plan: nothing is saved until it has landed. Whatever is\n    // on screen before then is not the plan being opened, and saving it wrote\n    // over the customer's plan (2026-09-29).\n    if (_bootPlanLink && !planLinkLanded) return;\n    if (autosaveHeldForLinkedNewPlan) return;\n    autosaveDirty = true;\n    if (!autosaveOn) return;\n    if (autosaveTimer) clearTimeout(autosaveTimer);\n    autosaveTimer = setTimeout(runAutosave, AUTOSAVE_IDLE_MS);\n  }\n\n  // \u2500\u2500 Time on Plan (Arden, 2026-10-20) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n  // How long people spend on a plan, for Odoo's Kitchen Plans list and the\n  // opportunity: counted in 15-second steps while the planner tab is showing\n  // AND someone has used it in the last two minutes (a press, a key, the\n  // wheel, a touch, or the pointer moving), so a tab left open or behind\n  // another counts nothing. Staff time (staff mode, which a live session's\n  // salesperson is in) is kept apart from the customer's. Not counted for a\n  // customer watching a live session, a bought plan or a view-only one, or\n  // before anything has been planned. The storage engine adds it to the plan\n  // on every save (addPlanTime / stampPlanTime there).\n  (function countTimeOnPlan() {\n    const STEP_MS = 15000, IDLE_MS = 120000;\n    let lastActive = 0, lastStep = Date.now(), lastMove = 0;\n    const active = () => { lastActive = Date.now(); };\n    ['pointerdown', 'keydown', 'wheel', 'touchstart'].forEach((ev) =>\n      window.addEventListener(ev, active, { capture: true, passive: true }));\n    window.addEventListener('pointermove', () => {\n      const now = Date.now();\n      if (now - lastMove > 5000) { lastMove = now; lastActive = now; }\n    }, { capture: true, passive: true });\n    const counting = () => !(_bootOrdered || _bootViewOnly || (_bootLive.session && _bootLive.role === 'viewer'))\n      && (!!activePlanName || (cabinets || []).length > 0);\n    setInterval(() => {\n      const now = Date.now();\n      const ms = Math.min(now - lastStep, STEP_MS * 2);\n      lastStep = now;\n      if (document.visibilityState !== 'visible' || now - lastActive > IDLE_MS || !counting()) return;\n      const staff = !!(window.BTKBasketAPI && BTKBasketAPI.isStaffMode && BTKBasketAPI.isStaffMode());\n      addPlanTime(staff ? 'staff' : 'customer', ms / 1000);\n    }, STEP_MS);\n    // Saves carry the time, but a plan looked over without being changed is\n    // not saved. So, with autosave on and nothing of the design waiting to be\n    // saved, the plan is saved for its time alone: every five minutes of\n    // counted time, and when the tab is hidden with a minute or more counted.\n    // Never with autosave off - that would save design changes the person has\n    // chosen not to - and never over a save already in the air.\n    async function saveTimeOnly(minSeconds) {\n      if (!autosaveOn || autosaveDirty || autosaveRunning || planOpening || namedSaveRunning || !activePlanName || !counting()) return;\n      if (_bootPlanLink && !planLinkLanded) return;\n      if (pendingPlanTime() < minSeconds) return;\n      autosaveRunning = true;\n      try { await planStore.saveAs(activePlanName, await currentDesignWithThumb()); }\n      catch (e) { /* the time stays counted and goes with the next save */ }\n      finally { autosaveRunning = false; }\n    }\n    setInterval(() => { saveTimeOnly(300); }, 60000);\n    document.addEventListener('visibilitychange', () => {\n      if (document.visibilityState === 'hidden') saveTimeOnly(60);\n    });\n  })();\n\n  async function runAutosave() {\n    autosaveTimer = null;\n    if (_bootPlanLink && !planLinkLanded) return;   // see scheduleAutosave\n    if (planOpening) return;   // loadNamedPlan saves again once it has opened\n    if (_bootViewOnly) return;\n    await awaitJourneySave();   // never race Start Planning's own save\n    if (!autosaveOn || autosaveRunning || !autosaveDirty || namedSaveRunning) return;\n    const sigNow = designSig();\n    if (sigNow && sigNow === lastSavedSig) { autosaveDirty = false; return; }   // nothing changed\n    // An unnamed plan has nowhere of its own to go; the draft slot below still\n    // keeps it safe across a refresh.\n    autosaveRunning = true;\n    designControlsHandle.setSaveState?.('saving');\n    try {\n      // The SAME enrichment an explicit save gets: a 3D preview when one can be\n      // taken cheaply, plus the quote totals. Autosave is the path most plans\n      // are actually saved by, so anything it left out was missing from most\n      // saved plans - which is why the back office showed \"no preview\" and no\n      // value against the majority of them.\n      const design = await currentDesignWithThumb();\n      let stamp = null;\n      if (activePlanName) {\n        const payload = await planStore.saveAs(activePlanName, design);\n        stamp = payload && payload.savedAt;\n        if (!payload) throw new Error('saveAs returned nothing');\n        if (plannerIsLoggedIn()) reportPlanSaved();\n      } else {\n        const payload = await planStore.save(design);\n        stamp = payload && payload.savedAt;\n        // planStore.save reports a failure by returning nothing, not by\n        // throwing. Unchecked, a failed save of an unnamed plan cleared the\n        // dirty flag and said \"Autosaved\", so the work was never retried and\n        // the customer was told it was safe.\n        if (!payload) throw new Error('save returned nothing');\n      }\n      autosaveDirty = false;\n      lastSavedSig = sigNow;\n      // Still no preview means the customer has never opened 3D. Build one\n      // off-screen in idle time and patch it on, exactly as an explicit save\n      // does. Guarded on planThumb so a 2D-only session pays for this once\n      // rather than on every autosave, and on the failure flag so a device that\n      // cannot render 3D at all stops trying.\n      if (!planThumb && !thumbOffscreenFailed) capturePlanThumbDeferred();\n      designControlsHandle.setSaveState?.('saved',\n        stamp ? `Autosaved ${formatTime(stamp)}` : 'Autosaved');\n    } catch (e) {\n      console.warn('[BTK Kitchen Planner] Autosave failed', e);\n      designControlsHandle.setSaveState?.('error');\n    } finally {\n      autosaveRunning = false;\n    }\n  }\n\n  function capturePlanThumbDeferred() {\n    // Runs on EVERY save, not just the first: the plan has changed, so a stale\n    // preview of an older layout is worse than none. Skipped only when the save\n    // path already captured a fresh one a moment ago.\n    if (thumbCapturedThisSave) { thumbCapturedThisSave = false; return; }\n    if (_bootOrdered) return;   // nothing is saved from the purchased-plan viewer\n    const run = async () => {\n      try {\n        const thumb = await capturePlanThumb({ allowOffscreen: true });\n        if (!thumb) { thumbOffscreenFailed = true; return; }\n        thumbOffscreenFailed = false;\n        planThumb = thumb;\n        // The PLAN's basket, not the cart's. getActiveBasket() returns whatever\n        // carries isActive, which cart flows set - so the preview could land on\n        // a samples basket (dropped by the guard below) or on a different\n        // plan's, which is why previews went missing or appeared to move.\n        const basket = await plannerBasketForWrite();\n        if (!basket || !basket.plannerDesign) return;\n        basket.plannerDesign.thumbnail = thumb;\n        if (basket.plannerDesign.design) basket.plannerDesign.design.thumbnail = thumb;\n        await BTKBasketAPI.saveBasket(basket);\n      } catch (e) {\n        console.warn('[BTK thumb] deferred capture failed', e);\n      }\n    };\n    // Was `requestIdleCallback(run, { timeout: 8000 })`, which is a deadline and\n    // so fired onto the busy basket - see whenPageFree for the whole story. A\n    // preview can wait; the basket cannot.\n    whenPageFree(run);\n  }\n\n  // The plan's last good price, { after, before, incDelivery } - the one it\n  // opened with, then each one stamped since.\n  let openedPlanPrice = null;\n  // The basket's Total Price for the plan on screen, { planId, after, before },\n  // as the basket panel last worked it out (btk-cart-advanced.js renderFooter).\n  let basketTotalPrice = null;\n  let basketPriceSaveTimer = null;\n  window.__btkSetPlannerBasketTotal = function (totalGbp, wasGbp, planId) {\n    const after = Math.round((Number(totalGbp) || 0) * 100) / 100;\n    if (!planId || planId !== plannerPlanId || !(after > 0)) return;\n    basketTotalPrice = { planId, after, before: Math.round(Math.max(Number(wasGbp) || 0, after) * 100) / 100 };\n    // The basket saves the plan BEFORE it works its total out, and autosave\n    // only saves a changed design, so a new total would wait for the next\n    // edit. Saved on its own instead, once the basket has settled, under the\n    // same guards as the time-only save.\n    if (openedPlanPrice && openedPlanPrice.incDelivery && openedPlanPrice.after === after) return;\n    if (basketPriceSaveTimer) clearTimeout(basketPriceSaveTimer);\n    basketPriceSaveTimer = setTimeout(savePlanPriceOnly, 4000);\n  };\n  async function savePlanPriceOnly() {\n    basketPriceSaveTimer = null;\n    if (!autosaveOn || autosaveDirty || autosaveRunning || planOpening || namedSaveRunning || !activePlanName) return;\n    if (_bootOrdered || _bootViewOnly || (_bootLive.session && _bootLive.role === 'viewer')) return;\n    if (_bootPlanLink && !planLinkLanded) return;\n    if (!basketTotalPrice || basketTotalPrice.planId !== plannerPlanId || planPricesPending()) return;\n    if (openedPlanPrice && openedPlanPrice.incDelivery && openedPlanPrice.after === basketTotalPrice.after) return;\n    autosaveRunning = true;\n    try { await planStore.saveAs(activePlanName, currentDesign()); }\n    catch (e) { /* the price goes with the next save */ }\n    finally { autosaveRunning = false; }\n  }\n\n  // THE PLAN'S PRICE, stamped on every save (planStore below) so the account\n  // page, Saved plans and Odoo's Kitchen Plans can show it without loading the\n  // catalogue: priceAfter = what the customer pays, priceBefore = the Was.\n  // It is the basket's Total Price, delivery and discounts in (Arden,\n  // 2026-11-06: the account page showed \u00A316,640 for a \u00A320,000.38 basket, as\n  // the figure was the planner's own units-and-parts sum, and Odoo showed\n  // nothing, as only some saves stamped it). Until the basket has worked it\n  // out this visit, the plan keeps the last one; a plan that has never had one\n  // keeps the old sum. While the plan's prices are loading that sum would be\n  // too low (planPricesPending), so the last good figure stays.\n  function stampPlanPrice(design) {\n    if (!design) return;\n    try {\n      const pending = planPricesPending();\n      let p = null;\n      if (!pending && basketTotalPrice && basketTotalPrice.planId === plannerPlanId) {\n        p = { after: basketTotalPrice.after, before: basketTotalPrice.before, incDelivery: true };\n      } else if (openedPlanPrice && (openedPlanPrice.incDelivery || pending)) {\n        p = openedPlanPrice;\n      } else if (!pending) {\n        p = { after: Math.round(computeTotal()), before: Math.round(computeCompareTotal()), incDelivery: false };\n      }\n      if (!p) return;\n      design.priceAfter = p.after;\n      design.priceBefore = p.before;\n      if (p.incDelivery) design.priceIncDelivery = true;\n      else delete design.priceIncDelivery;\n      openedPlanPrice = p;\n    } catch (e) { /* best-effort */ }\n  }\n\n  // A plan opened (or a new one started): its own saved price is the last\n  // good one, and a basket total worked out for the plan before is not its.\n  function takePlanPrice(design) {\n    openedPlanPrice = (design && typeof design.priceAfter === 'number')\n      ? { after: design.priceAfter, before: design.priceBefore, incDelivery: !!design.priceIncDelivery } : null;\n    basketTotalPrice = null;\n  }\n\n  async function currentDesignWithThumb() {\n    const design = currentDesign();\n    const thumb = await capturePlanThumb();\n    thumbCapturedThisSave = !!thumb;\n    if (thumb) planThumb = thumb;               // fresh 3D render \u2192 remember it\n    if (planThumb) design.thumbnail = planThumb; // keep the last 3D render when saving from 2D\n    return design;\n  }\n\n  // \u2500\u2500\u2500 Guest saves: login gate + design handoff \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n  // Saved plans belong to an ACCOUNT. A guest can design freely, but SAVING\n  // needs a login - matching the advanced basket, which has gated save /\n  // duplicate / multi-quote behind its own login prompt from the start.\n  //\n  // Without this the planner wrote guest plans to localStorage under a cookie\n  // id (btk_project_guest_xxx) while logged-in plans live server-side under the\n  // Shopify customer id. Two separate stores with no merge, so a guest's plans\n  // silently vanished the moment they logged in - they were never lost, just\n  // stranded somewhere the account could not see.\n  //\n  // The design is stashed BEFORE the redirect, so the prompt's promise - your\n  // work will be waiting - is actually true. localStorage rather than the URL:\n  // a design is far too big for a query string, and it has to survive Shopify's\n  // multi-hop auth redirect.\n  const PENDING_DESIGN_KEY = 'btk_kp_pending_design';\n  const PENDING_DESIGN_TTL = 7 * 24 * 60 * 60 * 1000;   // a week\n\n  // Sign in, then come back to `path` on this site. Built by the site-wide\n  // account-links script when it is on (snippets/btk-account-links.liquid); the\n  // plain Shopify form otherwise, which is what these buttons always used.\n  function accountSignInUrl(path) {\n    const links = window.BTKAccountLinks;\n    if (links && typeof links.signInUrl === 'function') return links.signInUrl(path);\n    return '/account/login?return_url=' + encodeURIComponent(path || '/');\n  }\n\n  function plannerIsLoggedIn() {\n    const api = window.BTKBasketAPI;\n    return !!(api && typeof api.isLoggedIn === 'function' && api.isLoggedIn());\n  }\n\n  async function requireLoginToSave(intendedName, wording) {\n    if (plannerIsLoggedIn()) return true;\n    try {\n      const design = await currentDesignWithThumb();\n      localStorage.setItem(PENDING_DESIGN_KEY, JSON.stringify({\n        design,\n        name: (intendedName || activePlanName || '').trim(),\n        stashedAt: Date.now(),\n      }));\n    } catch (e) {\n      console.warn('[BTK Kitchen Planner] could not stash the pending design', e);\n    }\n    const go = await window.BTKKPDialog.confirm(\n      (wording && wording.lead || 'Saved plans live on your account, so you can open them again from any device.') + '\\n\\n'\n      + 'Your design is held safely - it will be waiting for you as soon as you log in.',\n      { title: (wording && wording.title) || 'Log in to save your plan', confirmText: 'Log in or sign up', cancelText: 'Not now',\n        // Signing up is where we take their details: the UK soft opt-in needs\n        // them told here, with no tick to tick (Arden, 2026-11-07).\n        note: \"We'll occasionally send you bedroom ideas and offers by email or text. You can unsubscribe at any time.\" }\n    );\n    // Back to the planner after signing in - that is where the held design is\n    // offered back. Plain /account/login dropped the customer on Shopify's\n    // account page instead, so \"it will be waiting for you\" never came true.\n    if (go) window.location.href = accountSignInUrl(window.location.pathname);\n    return false;\n  }\n\n  // The name a held design had, offered once in Save As when it comes back.\n  let restoredPlanName = '';\n\n  // Called on boot once the customer is back from logging in.\n  async function maybeRestorePendingDesign() {\n    if (!plannerIsLoggedIn()) return;\n    let stash = null;\n    try {\n      const raw = localStorage.getItem(PENDING_DESIGN_KEY);\n      if (!raw) return;\n      stash = JSON.parse(raw);\n    } catch (e) { return; }\n    // Clear FIRST: a stash we cannot apply must not sit there offering itself\n    // on every future load.\n    try { localStorage.removeItem(PENDING_DESIGN_KEY); } catch (e) {}\n    if (!stash || !stash.design) return;\n    if (Date.now() - (stash.stashedAt || 0) > PENDING_DESIGN_TTL) return;\n    const ok = await window.BTKKPDialog.confirm(\n      'You were designing a bedroom just before you logged in. Would you like to carry on with it?',\n      { title: 'Pick up where you left off?', confirmText: 'Restore my design', cancelText: 'Start fresh' }\n    );\n    if (!ok) return;\n    // The guest's design is a NEW plan on this account, never the one the boot\n    // just restored. It used to keep that plan's name and working slot, so the\n    // first save or autosave wrote the guest kitchen over it. Same order as\n    // resetToNewPlan: the store lets go of the old plan's basket first.\n    try { await planStore.clear(); } catch (e) { /* non-fatal */ }\n    applyState(stash.design);\n    activePlanName = null;\n    activePlanVersionOf = null;\n    restoredPlanName = (stash.name || '').trim();\n    designControlsHandle.setPlanName(null);\n    refreshLiveQuoteLabels();\n    basketDrawerHandle?.refresh?.();\n    hideWelcome();\n    roomShapePrompted = true;\n    try { stepperHandle.setStep('add-units'); } catch (e) {}\n    designControlsHandle.setStatus('Restored the design you started before logging in - Save it to keep it on your account.');\n  }\n\n  // Tells Google Ads a customer saved a plan with something in it, only for\n  // visitors who accepted marketing cookies on the banner. Same approach as\n  // the enquiry form: Shopify's Google channel runs in a pixel, so the page has\n  // no Google tag of its own and loads one here. Called from the customer's own\n  // Save and Save As, and from autosave of a named plan when signed in, because\n  // autosave is how most plans get saved. Ads counts one per ad click.\n  const ADS_TAG = 'AW-1046829233';\n  const ADS_PLAN_SAVED = ADS_TAG + '/zUv2COO8ibUdELGxlfMD';   // Plan Saved conversion\n  let planSavedReported = false;\n  function reportPlanSaved() {\n    if (planSavedReported) return;\n    try {\n      const api = window.BTKBasketAPI;\n      if (api && typeof api.isStaffMode === 'function' && api.isStaffMode()) return;\n      if (!(cabinets || []).length) return;\n      const privacy = window.Shopify && window.Shopify.customerPrivacy;\n      if (!privacy || !privacy.marketingAllowed || !privacy.marketingAllowed()) return;\n      planSavedReported = true;\n      window.dataLayer = window.dataLayer || [];\n      const gtag = function () { window.dataLayer.push(arguments); };\n      gtag('consent', 'default', { ad_storage: 'granted', ad_user_data: 'granted', ad_personalization: 'granted' });\n      gtag('js', new Date());\n      gtag('config', ADS_TAG, { send_page_view: false });\n      gtag('event', 'conversion', { send_to: ADS_PLAN_SAVED });\n      const s = document.createElement('script');\n      s.async = true;\n      s.src = 'https://www.googletagmanager.com/gtag/js?id=' + ADS_TAG;\n      document.head.appendChild(s);\n    } catch (e) {}\n  }\n\n  async function handleSave() {\n    if (!(await requireLoginToSave())) return;\n    try { await awaitJourneySave(); } catch (e) {}   // a new plan's clear + first save\n    // If we already have a named active plan, overwrite that slot\n    // directly. Otherwise fall through to Save As so the user picks\n    // a name on first save.\n    if (activePlanName) {\n      const design = await currentDesignWithThumb();\n      const payload = await planStore.saveAs(activePlanName, design);\n      designControlsHandle.setStatus(\n        payload ? `Saved \"${activePlanName}\" at ${formatTime(payload.savedAt)}` : 'Save failed (see console)'\n      );\n      if (payload) reportPlanSaved();\n      // Also tag the autosave slot so a refresh restores this plan.\n      await planStore.save(design);\n      // Plans saved from 2D have no preview yet \u2014 build one in the background.\n      capturePlanThumbDeferred();\n      return;\n    }\n    handleSaveAs();\n  }\n\n  async function handleSaveAs() {\n    // Gate BEFORE the popup opens - asking someone to type a name and only then\n    // telling them they cannot save is the wrong order.\n    if (!(await requireLoginToSave())) return;\n    openSaveAsPopup();\n  }\n\n  // Saved plans (planner baskets) called `name` that belong to a DIFFERENT plan\n  // than ownPlanId. Drafts (\"Unsaved Plan\") never count.\n  async function otherPlansNamed(name, ownPlanId) {\n    const api = window.BTKBasketAPI;\n    if (!api || !name) return [];\n    try {\n      const project = await api.getProject();\n      // A bought plan is invisible here (not in Saved Plans), so it must not\n      // count as a clash: the customer would be asked to replace a plan they\n      // cannot see, and \"Replace\" would try to delete the order's record.\n      const ordered = (b) => {\n        const lock = api.getBasketLock && api.getBasketLock(b.id);\n        return !!(lock && lock.status === 'ordered');\n      };\n      return (project.baskets || []).filter(b => b && b.source === 'planner' && !b.isDraft\n        && b.name === name && !ordered(b)\n        && !(ownPlanId && b.plannerDesign && b.plannerDesign.design\n             && b.plannerDesign.design.plannerPlanId === ownPlanId));\n    } catch (e) { return []; }\n  }\n\n  // A BOUGHT plan keeps its name for good (Sales sheet line 109). It is not in\n  // Saved Plans, so otherPlansNamed leaves it out - which let a new plan be\n  // saved as \"Final\" after a plan called \"Final\" was ordered, leaving two\n  // \"Final\"s on the customer's account and orders. Any name a customer types\n  // (new plan, Save As, rename) is checked here first; there is no Replace,\n  // because a bought plan cannot be replaced. Case and spacing do not matter.\n  async function boughtPlanNamed(name) {\n    const api = window.BTKBasketAPI;\n    const want = String(name || '').trim().toLowerCase().replace(/\\s+/g, ' ');\n    if (!api || !want) return '';\n    try {\n      const project = await api.getProject();\n      const hit = (project.baskets || []).find(b => {\n        if (!b || b.source !== 'planner') return false;\n        const lock = api.getBasketLock && api.getBasketLock(b.id);\n        return !!(lock && lock.status === 'ordered')\n          && String(b.name || '').trim().toLowerCase().replace(/\\s+/g, ' ') === want;\n      });\n      return hit ? String(hit.name).trim() : '';\n    } catch (e) { return ''; }\n  }\n  // True (and the customer told) when the name belongs to a bought plan.\n  async function refuseBoughtPlanName(name) {\n    const bought = await boughtPlanNamed(name);\n    if (!bought) return false;\n    await window.BTKKPDialog.alert(\n      `You have already ordered a plan called \"${bought}\". Please choose a different name for this one, so the two are easy to tell apart.`,\n      { title: 'Name Already Ordered' });\n    return true;\n  }\n\n  // Saving under a name another saved plan already has used to TAKE OVER that\n  // plan's basket (the store matches by name): its design was overwritten and\n  // its line items stayed, so a \"new\" plan opened holding the old one's units.\n  // Replacing now removes the other plan first, so the plan being saved keeps\n  // its own (clean) basket.\n  async function removeOtherPlansNamed(name, ownPlanId) {\n    const api = window.BTKBasketAPI;\n    for (const b of await otherPlansNamed(name, ownPlanId)) {\n      try { await api.deleteBasket(b.id); }\n      catch (e) { console.warn('[BTK Kitchen Planner] could not remove the replaced plan', e); }\n    }\n  }\n\n  // A NEW plan's name (Start Planning): if another saved plan already has it,\n  // ask - Replace it, or go back and choose another name. True = go ahead.\n  async function confirmPlanNameFree(name) {\n    if (await refuseBoughtPlanName(name)) return false;\n    const clash = await otherPlansNamed(name, plannerPlanId);\n    if (!clash.length) return true;\n    const ok = await window.BTKKPDialog.confirm(\n      `A saved plan called \"${name}\" already exists.\\n\\nReplace it with this new plan, or choose another name?`,\n      { title: 'Plan name already used', confirmText: 'Replace it', cancelText: 'Choose another name', danger: true }\n    );\n    if (!ok) return false;\n    await removeOtherPlansNamed(name, plannerPlanId);\n    return true;\n  }\n\n  // Save As and Save as Version move the design to a new name in several steps.\n  // An autosave landing part way through saved under the old name: with the\n  // original already renamed \"- Version 1\", that made a stray plan with the old\n  // name (bug sheet, Julian, 2026-11-04). So none runs until they are done, and\n  // whatever it held back is saved after.\n  async function withAutosaveHeld(run) {\n    namedSaveRunning = true;\n    try {\n      for (let i = 0; autosaveRunning && i < 100; i++) await new Promise((r) => setTimeout(r, 100));\n      return await run();\n    } finally {\n      namedSaveRunning = false;\n      if (autosaveDirty && autosaveOn && !autosaveTimer) scheduleAutosave();\n    }\n  }\n\n  async function commitSaveAs(name) {\n    const trimmed = (name || '').trim();\n    if (!trimmed) return false;\n    // Backstop: the popup can be opened by paths that do not run handleSaveAs.\n    if (!(await requireLoginToSave(trimmed))) return false;\n    try { await awaitJourneySave(); } catch (e) {}   // a new plan's clear + first save\n    // Save As = a NEW plan copy. Drop the loaded plan's id so the store\n    // forks a fresh basket instead of re-targeting (overwriting) the\n    // original plan whose plannerPlanId would otherwise match. Saving As\n    // over an existing *name* still overwrites that plan (by-name rule).\n    const ownPlanId = plannerPlanId;   // the plan being copied - its own name is not a clash\n    // A plan with no name yet is being named, not copied: it keeps its id, so\n    // its own autosaved draft takes the name instead of staying behind as a\n    // second, unnamed plan. Its basket may already be saved as \"Planner Quote\",\n    // so the store is told this is the plan's name (bug sheet, Julian, 2026-11-04).\n    const naming = !activePlanName;\n    if (activePlanName) plannerPlanId = null;\n    const design = await currentDesignWithThumb();\n\n    // Every caller has already confirmed overwriting a plan of this name (or\n    // made the name unique). Overwrite means REPLACE: remove the other plan so\n    // its leftover line items cannot ride along into this one.\n    await removeOtherPlansNamed(trimmed, ownPlanId);\n    const payload = await planStore.saveAs(trimmed, design, naming ? { rename: true } : undefined);\n    if (!payload) {\n      designControlsHandle.setStatus('Save failed (see console)');\n      return false;\n    }\n    reportPlanSaved();\n    // Plans saved from 2D have no preview yet \u2014 build one in the background.\n    capturePlanThumbDeferred();\n    activePlanName = trimmed;\n    designControlsHandle.setPlanName(trimmed);\n    designControlsHandle.setSaveState?.('saved', `Saved \"${trimmed}\" at ${formatTime(payload.savedAt)}`);\n    // Plan is now saved \u2192 flip the basket button label to \"Add to Basket\"\n    // and update the Live Quote labels with the new name.\n    basketDrawerHandle?.refresh?.();\n    refreshLiveQuoteLabels();\n    // Also write the autosave slot so the named version survives a\n    // refresh without the user having to click Load.\n    await planStore.save(design);\n    return true;\n  }\n\n  async function handleLoad() {\n    openLoadPlanPopup();\n  }\n\n  // Open the plan a deep-link points at. Prefers the intrinsic plannerPlanId -\n  // stable across renames and unambiguous when two baskets share a name - and\n  // falls back to the name so links minted before planId existed still open.\n  // \"Restore as Copy\" from Odoo's Plan History (planner-api plan_history, read\n  // through GET /plan-history/:id). The version opens as a NEW plan named for\n  // when it was saved, and is saved as one straight away, so the plan it came\n  // from - or whatever replaced it - is never touched. Resolves true once the\n  // copy is drawn and saved.\n  async function openRestoredVersion(versionId) {\n    const api = window.BTKBasketAPI;\n    const version = api && api.getPlanVersion ? await api.getPlanVersion(versionId) : null;\n    const payload = version && normaliseLoadedPayload(version.payload);\n    if (!payload || !payload.design) {\n      await window.BTKKPDialog.alert('That earlier version could not be found. It may have been removed, '\n        + 'or it belongs to a different customer.', { title: 'Version Not Found' });\n      return false;\n    }\n    // A copy, not the plan: no plan id (applyState then clears it and the\n    // next save mints a fresh one) and not grouped as a version of anything.\n    const { plannerPlanId: _oldId, versionOf: _vo, ...design } = payload.design;\n    const when = new Date(version.savedAt);\n    const stamp = isNaN(when.getTime()) ? '' : when.toLocaleString('en-GB',\n      { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' });\n    const name = `${version.name || 'Bedroom'} (restored from ${stamp || 'an earlier save'})`;\n    // The version's own picture (planner-api keeps it with the version), so\n    // the copy shows its preview straight away. loadNamedPlan takes it as\n    // planThumb; the save below carries it, as an ordinary save does.\n    const thumb = (typeof version.thumbnail === 'string'\n      && /^(data:image\\/(png|jpe?g|webp);base64,|https:\\/\\/)/i.test(version.thumbnail)) ? version.thumbnail : null;\n    await loadNamedPlan(name, { ...payload, versionOf: null, thumbnail: thumb, design }, { noSlotSave: true });\n    const copy = currentDesign();\n    if (planThumb) copy.thumbnail = planThumb;\n    const saved = await planStore.saveAs(name, copy);\n    if (!saved) {\n      await window.BTKKPDialog.alert('The restored copy is open but could not be saved. '\n        + 'Press Save to try again before leaving.', { title: 'Not Saved', danger: true });\n      return true;\n    }\n    designControlsHandle.setStatus(`Restored a copy of \"${version.name || 'the plan'}\" as it was ${stamp}`);\n    return true;\n  }\n\n  // Resolves true when the plan was found and drawn.\n  async function loadLinkedPlan(planId, name, opts) {\n    if (planId && typeof planStore.loadPlanById === 'function') {\n      // Finding the plan moves the working pointer to it, while the plan open\n      // before is still on screen: nothing saves until it is drawn (see\n      // loadNamedPlan).\n      let hit = null;\n      planOpening++;\n      try { hit = await planStore.loadPlanById(planId); }\n      finally { planOpening--; }\n      if (hit && hit.payload) return loadNamedPlan(hit.name, hit.payload, opts);\n    }\n    if (!name) {\n      designControlsHandle.setStatus('Plan not found');\n      return false;\n    }\n    return loadNamedPlan(name, undefined, opts);\n  }\n\n  // opts.backgroundSave: do not wait for the autosave-slot save at the end, so\n  // an arrival can land on the plan while it goes up.\n  // opts.noSlotSave: skip that save; the caller saves the plan itself.\n  async function loadNamedPlan(name, preloaded, opts) {\n    // A change still waiting for its autosave belongs to the plan open now:\n    // save it before the next plan replaces it on screen.\n    if (autosaveTimer && autosaveDirty && !planOpening) {\n      clearTimeout(autosaveTimer);\n      try { await runAutosave(); } catch (_) { /* reported by runAutosave */ }\n    }\n    planOpening++;\n    try { return await openNamedPlan(name, preloaded, opts); }\n    finally {\n      planOpening--;\n      // A change held back while it opened goes now (an unchanged plan is\n      // not saved: runAutosave compares it with what was loaded).\n      if (!planOpening && autosaveDirty && !autosaveTimer) scheduleAutosave();\n    }\n  }\n  async function openNamedPlan(name, preloaded, opts) {\n    const payload = preloaded || await planStore.loadPlan(name);\n    if (!payload) {\n      designControlsHandle.setStatus(`Plan \"${name}\" not found`);\n      return false;\n    }\n    applyState(payload.design);\n    takePlanPrice(payload.design);\n    // The plan's name goes with its design at once, before anything below\n    // waits: any save from here is this plan's, under this plan's name.\n    activePlanName = name;\n    activePlanVersionOf = payload.versionOf\n      || (payload.design && payload.design.versionOf) || null;\n    // The plan's own (dominant) style, awaited as it always was - the\n    // Add-Units picker needs it before the list is drawn.\n    try { await ensureStyleProducts(kitchenStyleId); cabinetsHandle?.refresh?.(); } catch (_) {}\n    // Plans saved before corner variants followed the hand can carry the\n    // wrong panel side - the drawing (hand) is what the customer arranged.\n    cabinets.forEach(syncCornerHandVariant);\n    // ...and plans saved before the restyle fix carry a variant belonging to\n    // the style the unit was PLACED in, not the one it was changed to.\n    repairStyleVariants();\n          repairMissingPlinthHeights();\n\n    // \u26A0 A MIXED-STYLE PLAN'S OTHER STYLES LOAD IN THE BACKGROUND, NEVER AWAITED.\n    // Each one is a fetch of /collections/<handle>?view=catalogue, which is slow\n    // and 500s while its render cache is cold - i.e. right after a theme push.\n    // Awaiting them here put the whole plan load behind that fetch: when it hung,\n    // loadNamedPlan never resolved, so the caller never reached hideWelcome() and\n    // the planner sat on the Welcome page with the stage buttons half-wired\n    // (Arden, 2026-09-26). Nothing on the load path may wait on a network call\n    // for a style the plan does not lead with. The repair runs again when they\n    // land, so a mixed-style plan still corrects itself - just a moment later.\n    const _otherStyles = [...new Set(cabinets.map(c => c && c.kitchenStyleId).filter(Boolean))]\n      .filter(sid => sid !== kitchenStyleId && !Catalogue.hasProductsForStyle?.(sid));\n    if (_otherStyles.length) {\n      Promise.all(_otherStyles.map(sid => ensureStyleProducts(sid).catch(() => {})))\n        .then(() => {\n          repairStyleVariants();\n          repairMissingPlinthHeights();\n          try { cabinetsHandle?.refresh?.(); } catch (_) {}\n          try { rerender(); } catch (_) {}\n        })\n        .catch(() => {});\n    }\n    planThumb = payload.thumbnail || null;   // keep the plan's saved 3D preview\n    // A LOADED plan LEADS: push its full buying-style set (active + alternates)\n    // to the shared session store so the Add-Units bar, drawer, listing + detail\n    // pages all reflect the plan - not stale browsing. Fires btk:style-changed.\n    // Not for a purchased plan being looked at: that would repoint the\n    // customer's browsing, and their cart, at the old order's styles.\n    if (!_bootOrdered) syncBuyingStylesToSession();\n    // Re-evaluate the back panels after a load - saved plans may\n    // predate this feature, so we never trust a stale .backPanel\n    // flag (or absence of one) and let the auto-detect take a fresh\n    // pass over every base unit against the loaded room layout.\n    autoDetectBackPanels();\n    activePlanName = name;\n    designControlsHandle.setPlanName(name);\n    refreshLiveQuoteLabels();\n    basketDrawerHandle?.refresh?.();\n    designControlsHandle.setStatus(`Loaded \"${name}\" (saved at ${formatTime(payload.savedAt)})`);\n    lastSavedSig = designSig();   // as the server has it\n    // Sync the autosave slot to the just-loaded plan. Never for a purchased\n    // plan: that save made it the customer's ACTIVE plan, so their next visit\n    // to the planner was swapped onto an empty one (startFreshIfOrdered).\n    if (!_bootOrdered && !_bootViewOnly && !(opts && opts.noSlotSave)) {\n      if (opts && opts.backgroundSave) {\n        planStore.save(currentDesign())\n          .catch((e) => console.warn('[BTK Kitchen Planner] autosave after opening a plan failed', e));\n      } else {\n        await planStore.save(currentDesign());\n      }\n    }\n    return true;\n  }\n\n  async function deleteNamedPlan(name) {\n    await planStore.deletePlan(name);\n    if (activePlanName === name) {\n      activePlanName = null;\n      designControlsHandle.setPlanName(null);\n      refreshLiveQuoteLabels();\n      basketDrawerHandle?.refresh?.();\n    }\n    designControlsHandle.setStatus(`Deleted \"${name}\"`);\n  }\n\n  // \u2500\u2500\u2500 Live joint session (salesperson-guided co-design) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n  // A short-lived room shared by a salesperson (DRIVER) and the customer\n  // (VIEWER). The salesperson opens this customer's plan via the ?cid= staff\n  // override and drives; the customer watches their own plan change in real\n  // time. Consent-gated - nothing mirrors to the customer until they accept.\n  // Transport is polling for now (v0); the API shape is transport-agnostic so a\n  // WebSocket relay can replace the polling later with no UX change. Backend:\n  // btk-planner-api /session/* endpoints. See the joint-session design memo.\n  const LiveSession = (() => {\n    const BASE = '/apps/planner';\n    const DRIVER_KEY_STORE = 'btk-live-driver-v1';\n    let sid = null, driverKey = null, pushTimer = null, pollTimer = null;\n    let lastPushed = '', lastSeq = -1, booted = false, ended = false;\n    let ws = null, wsInfo = null, viewerPolling = false;\n    let pushCount = 0, recvCount = 0;   // TEMP diagnostics: updates sent / received\n\n    function cid() {\n      return (window.BTKBasketAPI && window.BTKBasketAPI.staffCustomerId && window.BTKBasketAPI.staffCustomerId())\n        || _bootLive.cid || (window.BTKCustomer && window.BTKCustomer.id) || '';\n    }\n    function url(path) {\n      const c = cid();\n      let u = `${BASE}${path}`;\n      if (c) u += `${u.indexOf('?') === -1 ? '?' : '&'}cid=${encodeURIComponent(c)}`;\n      // The basket API's WORKING token wins: Odoo's one-time link token is\n      // swapped for it there, and the link token itself is refused by the API.\n      // A token read from the URL is only an older, reusable staff link.\n      const t = (window.BTKBasketAPI && window.BTKBasketAPI.staffToken && window.BTKBasketAPI.staffToken())\n        || (/^L\\./.test(_bootLive.cidt) ? '' : _bootLive.cidt);\n      if (t) u += `${u.indexOf('?') === -1 ? '?' : '&'}cidt=${encodeURIComponent(t)}`;\n      return u;\n    }\n    function api(path, opts = {}) {\n      // Merge headers LAST so a caller's headers (e.g. x-driver-key) don't blow\n      // away Content-Type - otherwise the body isn't parsed server-side (400).\n      const { headers, ...rest } = opts;\n      const ready = (window.BTKBasketAPI && window.BTKBasketAPI.staffReady && window.BTKBasketAPI.staffReady())\n        || Promise.resolve();\n      return Promise.resolve(ready).then(() => fetch(url(path), {\n        credentials: 'same-origin',\n        ...rest,\n        headers: { 'Content-Type': 'application/json', ...(headers || {}) }\n      }).then(r => {\n        if (!r.ok) throw new Error(`session ${r.status}`);\n        return r.status === 204 ? {} : r.json();\n      }));\n    }\n\n    // Open the direct WebSocket (wss://<box>/ws?token=\u2026). Returns the socket, or\n    // null if the browser/URL can't. Every caller keeps HTTP polling as a\n    // fallback, so the session still works if WS is blocked/unavailable.\n    function openWS(info, handlers) {\n      if (!info || !info.wsUrl || !info.wsToken || typeof WebSocket === 'undefined') return null;\n      let sock;\n      try { sock = new WebSocket(`${info.wsUrl}?token=${encodeURIComponent(info.wsToken)}`); }\n      catch (e) { return null; }\n      sock.addEventListener('open',    () => { handlers.onOpen && handlers.onOpen(); });\n      sock.addEventListener('message', (ev) => { let m; try { m = JSON.parse(ev.data); } catch (e) { return; } handlers.onMessage(m); });\n      sock.addEventListener('close',   () => { handlers.onClose && handlers.onClose(); });\n      sock.addEventListener('error',   () => { /* a close event follows */ });\n      return sock;\n    }\n    function wsOpen() { return !!ws && ws.readyState === 1; }\n\n    // Keep the socket up for the whole session. A server restart or a network\n    // blip used to drop a page onto the slower HTTP path for good - and the\n    // pointer, the stage and the popups only travel over the socket, so the\n    // customer's screen quietly stopped following. It now reconnects itself,\n    // backing off, and fetches a fresh pass if the old one has expired.\n    let liveRole = '';                    // 'driver' | 'viewer'\n    // What the server relays (it says so when a session starts or resumes).\n    // Below 2 it only passes on a pointer over the plan, and would turn one\n    // anchored to a control into a wrong position - so none is sent.\n    let relayVersion = 1;\n    const noteRelay = (r) => { relayVersion = Number(r && r.relay) || 1; };\n    let wsHandlers = null, wsRetry = 0, wsRetryTimer = null;\n    function connectSocket(handlers) {\n      if (handlers) wsHandlers = handlers;\n      if (ended || !wsInfo || !wsHandlers || wsOpen()) return;\n      const h = wsHandlers;\n      ws = openWS(wsInfo, {\n        onOpen: () => { wsRetry = 0; if (h.onOpen) h.onOpen(); },\n        onMessage: h.onMessage,\n        onClose: () => { ws = null; if (h.onClose) h.onClose(); reconnectSocket(); }\n      });\n      if (!ws) reconnectSocket();\n    }\n    function reconnectSocket() {\n      if (ended || wsRetryTimer || typeof WebSocket === 'undefined') return;\n      const delay = Math.min(15000, 1000 * Math.pow(2, Math.min(wsRetry, 4)));\n      wsRetry++;\n      wsRetryTimer = setTimeout(async () => {\n        wsRetryTimer = null;\n        if (ended || wsOpen()) return;\n        if (wsRetry % 3 === 0) await refreshSocketPass();\n        connectSocket();\n      }, delay);\n    }\n    async function refreshSocketPass() {\n      try {\n        const r = liveRole === 'driver'\n          ? await api(`/session/${sid}/resume`, {\n              method: 'POST', headers: { 'x-driver-key': driverKey }, body: '{}'\n            })\n          // The customer already said yes; saying it again issues a new pass.\n          : await api(`/session/${sid}/consent`, { method: 'POST', body: JSON.stringify({ grant: true }) });\n        if (r && r.wsUrl && r.wsToken) wsInfo = { wsUrl: r.wsUrl, wsToken: r.wsToken };\n        if (liveRole === 'driver') noteRelay(r);\n      } catch (e) {\n        // 409: the session is over - stop trying and say so.\n        if (String(e && e.message || '').indexOf('409') !== -1) {\n          if (liveRole === 'driver') driverSessionEnded();\n          else handleSessionEnded();\n        }\n      }\n    }\n\n    // ---- DRIVER (salesperson) ----\n    // Did this tab leave a session mid-flight? (Cheap, synchronous check.)\n    function hasHeldSession() {\n      try {\n        const h = JSON.parse(sessionStorage.getItem(DRIVER_KEY_STORE) || 'null');\n        return !!(h && h.sid && h.driverKey);\n      } catch (e) { return false; }\n    }\n\n    // The SALESPERSON's pointer, drawn on the CUSTOMER's screen. (This used to\n    // run the other way round, which let a customer flick about on the\n    // salesperson's screen.) Fades on its own - a dot left sitting there would\n    // read as part of the plan.\n    //\n    // Positions arrive as a fraction of the thing being pointed at, never of\n    // the window: the two screens are different sizes with different sidebars,\n    // so a window fraction lands on the wrong thing.\n    //   grid / canvas - the 2D room grid or the 3D canvas. The grid is the same\n    //                   room on both screens, just scaled; in 3D the customer's\n    //                   camera follows the salesperson's (applyDriverView).\n    //   anchor        - any control or panel off the plan - the stage bar, the\n    //                   sidebar, a popup - found by the same attribute on both\n    //                   screens (anchorFor / resolveAnchor).\n    //   app           - the window, only when there was nothing to anchor to.\n    // A press arrives with `click` and shows as a ripple, so the customer sees\n    // what was clicked and not just where the pointer went - the point of\n    // using a session to show someone how the planner works.\n    let ptrEl = null, ptrTimer = null;\n    let driverIsAway = false;            // the salesperson's connection dropped\n    function hideStaffPointer() {\n      clearTimeout(ptrTimer);\n      if (ptrEl) ptrEl.style.opacity = '0';\n    }\n\n    // The element a pointer is hung on: the nearest one - the target or a\n    // parent - with an id or one of the planner's own data-btk-kp-* attributes.\n    // Both screens run the same planner, so the same attribute finds the same\n    // control on each; `i` picks between elements that share the value. The\n    // server accepts nothing else (btk-planner-api src/live-relay.js).\n    const ANCHOR_ATTR = /^data-btk-kp-[a-z0-9-]{1,48}$/;\n    const ANCHOR_ID = /^[A-Za-z][A-Za-z0-9_-]{0,99}$/;\n    // Planner names (stages, popups) are plain words-and-hyphens, and the\n    // server refuses anything else, so this only guards the odd character.\n    const cssq = (v) => ((window.CSS && CSS.escape) ? CSS.escape(String(v)) : String(v).replace(/[\"\\\\]/g, '\\\\$&'));\n    // Every element carrying the attribute with exactly this value, in page\n    // order. The value is compared as text rather than written into a\n    // selector, so nothing in it can change what is matched; only the\n    // attribute NAME goes into the selector, and that is checked first.\n    function anchorMatches(a, v) {\n      if (a === 'id') {\n        // An id names one element - no need to look past it.\n        const el = document.getElementById(v);\n        return el ? [el] : [];\n      }\n      if (!ANCHOR_ATTR.test(a)) return [];\n      return Array.prototype.filter.call(document.querySelectorAll(`[${a}]`),\n        (n) => n.getAttribute(a) === v);\n    }\n    function anchorFor(el) {\n      for (let n = el; n && n.nodeType === 1 && n !== document.body && n !== document.documentElement; n = n.parentElement) {\n        let a = null, v = null;\n        if (n.id && ANCHOR_ID.test(n.id)) { a = 'id'; v = n.id; }\n        else {\n          for (const at of n.attributes) {\n            if (ANCHOR_ATTR.test(at.name) && at.value.length <= 100) { a = at.name; v = at.value; break; }\n          }\n        }\n        if (!a) continue;\n        const i = anchorMatches(a, v).indexOf(n);\n        return { a, v, i: i > 0 ? i : 0, el: n };\n      }\n      return null;\n    }\n    function resolveAnchor(m) {\n      if (typeof m.a !== 'string' || typeof m.v !== 'string') return null;\n      // Over a copied popup, the pointer is named within the copy.\n      if (copyFrames.size && (m.a === 'id' || ANCHOR_ATTR.test(m.a))) {\n        const hit = anchorInCopies(m);\n        if (hit) return hit;\n      }\n      return anchorMatches(m.a, m.v)[m.i || 0] || null;\n    }\n    // ---- Clicks the customer's screen follows ----------------------------\n    // The salesperson's way round the screen - a popup's left menu and the\n    // choices in it, the Checklist's Show / Hide, the basket's sections, its\n    // lines, the Current Offers tab, the lower-left panel's cards - is clicked\n    // on the customer's screen too (Arden, 2026-10-19). Only in those places,\n    // and never a control that changes the plan or the basket for real: the\n    // plan arrives in the snapshots and the basket is re-read from the server,\n    // so the customer's screen must not act on either by itself.\n    const FOLLOW_IN = '[data-btk-kp-popup], [data-btk-kp-checklist-cards], [data-btk-kp-basket-embed]';\n    const FOLLOW_CONTROL = 'button, [role=\"button\"], [role=\"tab\"], [data-action], [data-item-id]';\n    const FOLLOW_NEVER = 'a[href], input, select, textarea, label, [type=\"submit\"], [disabled], '\n      + '.btk-ca-qty-btn, [data-btk-kp-proceed-checkout], [data-btk-kp-footer-checkout], '\n      + '[data-btk-kp-basket-embed-additems], [data-action=\"rename-basket\"], '\n      + '[data-btk-kp-check-approve], [data-btk-kp-check-unapprove], [data-btk-kp-checklist-checkout]';\n    // Buttons that do something rather than show something, by what they say.\n    const FOLLOW_NEVER_TEXT = /checkout|basket|confirm|apply|save|delete|remove|clear|empty|^add\\b|order|buy|pay|send|copy|print|download|log ?in|sign ?in/i;\n    function followableControl(t) {\n      const el = t && t.closest && t.closest(FOLLOW_CONTROL);\n      if (!el || !el.closest(FOLLOW_IN) || el.closest(FOLLOW_NEVER) || el.matches(FOLLOW_NEVER)) return null;\n      if (el.closest('#btk-live-driver, #btk-live-viewer')) return null;\n      if (el.matches('button, [role=\"button\"], [role=\"tab\"]')) {\n        const said = ((el.getAttribute('aria-label') || '') + ' ' + (el.textContent || '')).trim().replace(/\\s+/g, ' ');\n        if (said.length < 80 && FOLLOW_NEVER_TEXT.test(said)) return null;\n      }\n      return el;\n    }\n    // The attributes a followed control may be named by - the same set the\n    // server accepts (btk-planner-api src/live-relay.js relayAct).\n    const ACT_ATTR = /^(id|data-btk-[a-z0-9-]{1,48}|data-(action|qgroup|item-id|popup))$/;\n    function actMatches(a, v) {\n      if (a === 'id') { const el = document.getElementById(v); return el ? [el] : []; }\n      if (!ACT_ATTR.test(a)) return [];\n      return Array.prototype.filter.call(document.querySelectorAll(`[${a}]`), (n) => n.getAttribute(a) === v);\n    }\n    // The control's own attribute that names it most nearly uniquely, and\n    // which of the matches it is.\n    function controlKey(el) {\n      let best = null;\n      const cands = [];\n      if (el.id && ANCHOR_ID.test(el.id)) cands.push(['id', el.id]);\n      for (const at of el.attributes) {\n        if (at.name !== 'id' && ACT_ATTR.test(at.name) && at.value.length <= 100) cands.push([at.name, at.value]);\n      }\n      for (const [a, v] of cands) {\n        const all = actMatches(a, v);\n        const i = all.indexOf(el);\n        if (i === -1) continue;\n        if (!best || all.length < best.n) best = { a, v, i, n: all.length };\n        if (best.n === 1) break;\n      }\n      return best ? { a: best.a, v: best.v, i: best.i } : null;\n    }\n    // A toggle's state: open / pressed, or undefined for a plain button.\n    function controlState(el) {\n      for (const at of ['aria-expanded', 'aria-pressed', 'aria-selected']) {\n        const v = el.getAttribute(at);\n        if (v === 'true') return true;\n        if (v === 'false') return false;\n      }\n      return undefined;\n    }\n    // Customer's screen: click what the salesperson clicked, unless a toggle\n    // is already the way theirs now is.\n    function followAct(m) {\n      const el = actMatches(m.a, m.v)[m.i || 0];\n      if (!el || !el.getClientRects().length) return;\n      if (typeof m.on === 'boolean' && controlState(el) === m.on) return;\n      liveReplay(() => el.click());\n    }\n\n    // A panel that scrolls up and down: content taller than it, and set to\n    // scroll rather than clip.\n    function canScroll(el) {\n      if (!el || el.nodeType !== 1 || !(el.scrollHeight > el.clientHeight + 1)) return false;\n      const oy = getComputedStyle(el).overflowY;\n      return oy === 'auto' || oy === 'scroll' || oy === 'overlay';\n    }\n\n    function ensureLiveKeyframes() {\n      if (document.getElementById('btk-live-kf')) return;\n      const st = document.createElement('style');\n      st.id = 'btk-live-kf';\n      st.textContent = '@keyframes btkpulse{0%,100%{opacity:1}50%{opacity:.3}}'\n        + '@keyframes btkLiveRipple{from{transform:scale(.35);opacity:.9}to{transform:scale(1.9);opacity:0}}';\n      document.head.appendChild(st);\n    }\n    // Above everything the planner draws, dialogs included - the pointer has\n    // to stay visible over whatever the salesperson has opened.\n    const LIVE_POINTER_Z = 2147483000;\n    function clickRipple(x, y) {\n      ensureLiveKeyframes();\n      const d = document.createElement('div');\n      d.setAttribute('data-btk-live-pointer', '');\n      d.style.cssText = `position:fixed;left:${x}px;top:${y}px;z-index:${LIVE_POINTER_Z};pointer-events:none;`\n        + 'width:36px;height:36px;margin:-18px 0 0 -18px;border-radius:50%;border:3px solid #2d7a3a;'\n        + 'animation:btkLiveRipple .6s ease-out forwards';\n      document.body.appendChild(d);\n      setTimeout(() => d.remove(), 700);\n    }\n\n    function showStaffPointer(m) {\n      if (!m || m.hide) { hideStaffPointer(); return; }\n      if (driverIsAway) return;\n      const nx = Number(m.x), ny = Number(m.y);\n      if (!(nx >= 0 && nx <= 1 && ny >= 0 && ny <= 1)) return;\n      let r = null;\n      if (m.space === 'anchor') {\n        const el = resolveAnchor(m);\n        // Not on this screen, or not showing (a closed popup): nothing to point at.\n        if (!el || !el.getClientRects().length) { hideStaffPointer(); return; }\n        // A press on something scrolled out of sight here - further down a\n        // list, along a row - brings it into view, so the customer sees it.\n        if (m.click) { try { el.scrollIntoView({ block: 'nearest', inline: 'nearest' }); } catch (e) {} }\n        r = el.getBoundingClientRect();\n      } else if (m.space === 'app') {\n        r = { left: 0, top: 0, width: window.innerWidth, height: window.innerHeight };\n      } else {\n        const ref = m.space === 'canvas'\n          ? (handle3D && handle3D.getCanvas && handle3D.getCanvas())\n          : currentGridEl;\n        if (!ref || !ref.getBoundingClientRect) return;\n        r = ref.getBoundingClientRect();\n      }\n      if (!r || !r.width || !r.height) { hideStaffPointer(); return; }\n      if (!ptrEl) {\n        ptrEl = document.createElement('div');\n        ptrEl.setAttribute('data-btk-live-pointer', '');\n        ptrEl.style.cssText = `position:fixed;z-index:${LIVE_POINTER_Z};pointer-events:none;`\n          + 'width:18px;height:18px;margin:-9px 0 0 -9px;border-radius:50%;'\n          + 'background:rgba(45,122,58,.35);border:2px solid #2d7a3a;'\n          + 'transition:opacity .4s,left .08s linear,top .08s linear;'\n          + 'box-shadow:0 0 0 4px rgba(45,122,58,.15)';\n        const tag = document.createElement('div');\n        tag.textContent = 'Better Bedrooms';\n        tag.style.cssText = 'position:absolute;top:20px;left:-6px;white-space:nowrap;'\n          + 'background:#2d7a3a;color:#fff;font:600 11px/1 system-ui,sans-serif;'\n          + 'padding:3px 6px;border-radius:3px';\n        ptrEl.appendChild(tag);\n        document.body.appendChild(ptrEl);\n      }\n      const px = r.left + nx * r.width, py = r.top + ny * r.height;\n      ptrEl.style.left = px + 'px';\n      ptrEl.style.top = py + 'px';\n      ptrEl.style.opacity = '1';\n      if (m.click) clickRipple(px, py);\n      clearTimeout(ptrTimer);\n      ptrTimer = setTimeout(hideStaffPointer, 4000);\n    }\n\n    // Make the customer's screen match the salesperson's: the stage, the Home\n    // panel or Style Setup step showing, the popups open, 2D or 3D and how it\n    // is framed, and what is selected. Without it the pointer is meaningless -\n    // it would point at something the customer isn't looking at - and a\n    // customer being shown the planner never sees the stages it is used in.\n    //\n    // Order matters: changing stage resets the 2D/3D mode and clears the\n    // selection, so the stage goes first and those are applied after it.\n    let driverSel, driverIds;            // the selection the salesperson last sent\n    function applyDriverView(v) {\n      if (!v) return;\n      // The basket closes BEFORE a stage change and opens after it: closing it\n      // puts back the canvas for whatever stage is showing.\n      if (v.basket === false) followBasket(false, v.basketRev);\n      try {\n        if (typeof v.stage === 'string' && v.stage !== currentStep\n            && root.querySelector(`[data-btk-kp-step=\"${cssq(v.stage)}\"]`)) {\n          stepperHandle.setStep(v.stage);\n        }\n      } catch (e) { /* a stage we cannot show is not worth breaking the mirror */ }\n      try { if (typeof v.hp === 'string') followHomePanel(v.hp); } catch (e) {}\n      try { if (typeof v.js === 'string') followJourneyStep(v.js); } catch (e) {}\n      try { if (Array.isArray(v.popups)) followPopups(v.popups); } catch (e) {}\n      if (v.basket === true) followBasket(true, v.basketRev);\n      applyDriverFraming(v);\n      if ('sel' in v) driverSel = v.sel;\n      if (Array.isArray(v.ids)) driverIds = v.ids;\n      followSelection();\n      try { if (Array.isArray(v.scroll)) followScroll(v.scroll); } catch (e) {}\n    }\n\n    // The planner basket, open when the salesperson has it open, so they can\n    // take the customer round it (Arden, 2026-10-19). It is the customer's own\n    // saved basket - the one the salesperson's screen is filling - re-read from\n    // the server first: this page loaded it once at the start, before the\n    // salesperson changed anything. basketRev moves on each time their basket\n    // redraws, and the copy here is re-read to match (a moment later, so their\n    // save has landed). Opened directly, never through openLiveQuote, which\n    // builds and saves the basket - the salesperson's job, not this page's.\n    let basketWant = false, basketRev = null, basketBusy = false, basketTimer = null;\n    function refreshViewerBasket() {\n      const api = window.BTKBasketAPI;\n      return Promise.resolve(api && api.refreshProject ? api.refreshProject() : null).catch(() => {});\n    }\n    function followBasket(open, rev) {\n      if (!basketEmbedPanel) return;\n      basketWant = open;\n      const showing = !basketEmbedPanel.hidden;\n      if (!open) {\n        clearTimeout(basketTimer);\n        if (showing) closeBasketEmbed();\n        return;\n      }\n      if (!showing) {\n        if (basketBusy) return;\n        basketBusy = true;\n        basketRev = rev;\n        refreshViewerBasket().then(() => {\n          basketBusy = false;\n          if (basketWant && !ended && basketEmbedPanel.hidden) openBasketEmbed();\n        });\n        return;\n      }\n      if (rev === undefined || rev === basketRev) return;\n      basketRev = rev;\n      clearTimeout(basketTimer);\n      basketTimer = setTimeout(() => {\n        refreshViewerBasket().then(() => {\n          const CA = window.BTKCartAdvanced;\n          if (basketWant && !ended && !basketEmbedPanel.hidden && CA && CA.reload) CA.reload();\n        });\n      }, 1200);\n    }\n\n    // How far down the salesperson has scrolled each panel - the Checklist,\n    // the basket, a long popup - so the customer is not left at the top while\n    // they are talking about the bottom (Arden, 2026-10-19). Each arrives as\n    // the anchor of the scrolled panel (anchorFor, the pointer's own naming)\n    // and a fraction of how far it can scroll, so it lands at the same place\n    // on a taller or shorter screen.\n    function scrollerIn(el) {\n      if (!el) return null;\n      if (canScroll(el)) return el;\n      // The anchor was the nearest named parent of the panel that scrolls:\n      // the first scrolling panel inside it, as on the salesperson's screen.\n      const all = el.querySelectorAll('*');\n      for (let i = 0; i < all.length && i < 4000; i++) if (canScroll(all[i])) return all[i];\n      return null;\n    }\n    function followScroll(list) {\n      for (const p of list) {\n        const el = p.a === 'page' ? document.scrollingElement : scrollerIn(resolveAnchor(p));\n        if (!el) continue;\n        const max = el.scrollHeight - el.clientHeight;\n        if (!(max > 0)) continue;\n        const want = Math.round((Number(p.f) || 0) * max);\n        if (Math.abs(el.scrollTop - want) > 2) el.scrollTop = want;\n      }\n    }\n\n    // A click the mirror makes for itself, so the viewer's input shield lets\n    // it through (see the shield near the top of this file).\n    function liveReplay(fn) {\n      window.__btkLiveReplay = true;\n      try { fn(); } finally { window.__btkLiveReplay = false; }\n    }\n\n    // Planner Home's right-hand panel (the start cards, saved plans, guides).\n    // Switched directly rather than by replaying the tile: the \"Start\" tile\n    // begins a new guided journey, which the customer's screen must not do -\n    // it follows the stage the salesperson's journey is on instead.\n    function followHomePanel(name) {\n      if (currentStep !== 'planner-home' && currentStep !== 'style-setup') return;\n      const panels = [...root.querySelectorAll('[data-btk-kp-home-panel]')];\n      if (!panels.some(p => p.dataset.btkKpHomePanel === name)) return;\n      const showing = panels.find(p => !p.hidden);\n      if (showing && showing.dataset.btkKpHomePanel === name) return;\n      panels.forEach(p => { p.hidden = p.dataset.btkKpHomePanel !== name; });\n      if (name === 'open-saved-plan') Promise.resolve(renderHomeSavedPlans()).catch(() => {});\n      if (name !== 'start') setHeaderActive(name);\n    }\n\n    // Which step of the Style Setup journey is showing (style, colours,\n    // worktops, handles...).\n    function followJourneyStep(name) {\n      if (currentStep !== 'style-setup') return;\n      const steps = [...root.querySelectorAll('[data-btk-kp-journey-step]')];\n      if (!steps.some(s => s.dataset.btkKpJourneyStep === name)) return;\n      const showing = steps.find(s => !s.hidden);\n      if (showing && showing.dataset.btkKpJourneyStep === name) return;\n      showJourneyStep(name);\n    }\n\n    // Open what the salesperson has open, close what they have closed. A popup\n    // is opened by clicking its own opener, the way the salesperson did, so its\n    // contents are built by the same code; one with no opener (opened by the\n    // planner itself) is simply shown.\n    function followPopups(names) {\n      const want = new Set(names);\n      document.querySelectorAll('[data-btk-kp-popup]').forEach((p) => {\n        const name = p.dataset.btkKpPopup;\n        if (want.has(name)) { if (p.hidden) openPopupAsViewer(name); }\n        else if (!p.hidden) p.hidden = true;\n      });\n      // Popups the planner only builds when they are first opened.\n      for (const name of want) {\n        if (!document.querySelector(`[data-btk-kp-popup=\"${cssq(name)}\"]`)) openPopupAsViewer(name);\n      }\n    }\n    function openPopupAsViewer(name) {\n      const openers = [...root.querySelectorAll(`[data-btk-kp-open-popup=\"${cssq(name)}\"]`)];\n      const opener = openers.find(b => b.getClientRects().length) || openers[0];\n      if (opener) liveReplay(() => opener.click());\n      const el = document.querySelector(`[data-btk-kp-popup=\"${cssq(name)}\"]`);\n      if (el && el.hidden) el.hidden = false;\n    }\n\n    // ---- COPIES: popups the customer's screen cannot build itself --------\n    // (Bug sheet, Sales row 35.) A popup followed by name (followPopups) is\n    // opened on the customer's screen by pressing its own opener, so the same\n    // code builds the same contents. That only works for popups with an\n    // opener. The rest reached the customer empty or not at all:\n    //   - popups the planner fills for one unit or slot from code - the unit's\n    //     own popup, Choose Appliance / Housing, Product Details, the sink,\n    //     Paint, Worktop Corners / Waterfall, Cut List, Add Other Items,\n    //     Save As, Load Plan - shown with whatever was last left in them;\n    //   - overlays the session never named - the planner's message boxes,\n    //     Help, Magic Layout, Planning Styles, Raise a Support Ticket, the\n    //     Style Setup popups, the style list, the restyle prompt.\n    // For those the salesperson's screen sends a COPY: the popup's markup\n    // with what is typed in it and its pictures, sent again when it changes,\n    // with how far its panel is scrolled, and a close when it goes. The\n    // customer's screen shows it in a full-window frame with scripts and\n    // clicking switched off (sandbox, pointer-events none), in the planner's\n    // own stylesheets, so it looks the same and cannot do anything. Which\n    // way a popup goes is decided as it shows - by name when it has an\n    // opener, else a copy - so a new popup needs nothing here.\n    // Server: btk-planner-api src/live-relay.js relayOverlay (relay 5).\n    const COPY_SELECTOR = '.btk-kp-popup, .btk-kp-dialog-overlay, .btk-kp-help-overlay, '\n      + '.btk-kp-styles-modal, #btk-kp-restyle-confirm';\n    const COPY_MAX = 4;\n    const COPY_HTML_MAX = 880000;   // the server's cap is 900000\n    function hasOwnOpener(name) {\n      return !!root.querySelector(`[data-btk-kp-open-popup=\"${cssq(name)}\"]`);\n    }\n    // Followed by name (followPopups) rather than copied. An older server\n    // relays no copies, so there every popup still goes by name.\n    function followedByName(name) {\n      return relayVersion < 5 || hasOwnOpener(name);\n    }\n    function showingNow(el) {\n      if (!el || !el.isConnected || el.hidden || (el.parentElement && el.parentElement.closest('[hidden]'))) return false;\n      if (el.closest('#btk-live-driver, #btk-live-viewer, [data-btk-live-copies]')) return false;\n      const cs = getComputedStyle(el);\n      return cs.display !== 'none' && cs.visibility !== 'hidden';\n    }\n    // The overlays to copy, outermost only (a popup inside a copied one is\n    // already in its copy).\n    function copyTargets() {\n      const out = [];\n      document.querySelectorAll(COPY_SELECTOR).forEach((el) => {\n        if (out.length >= COPY_MAX || !showingNow(el)) return;\n        const name = el.dataset && el.dataset.btkKpPopup;\n        if (name && followedByName(name)) return;\n        if (el.parentElement && el.parentElement.closest(COPY_SELECTOR)) return;\n        out.push(el);\n      });\n      return out;\n    }\n    // A planner-style name for a copy (the server only takes those): its\n    // popup name, else its own data-btk-kp-* attribute, id or class.\n    function copyKeyOf(el) {\n      const clean = (s) => String(s || '').toLowerCase().replace(/[^a-z0-9-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 44);\n      if (el.dataset && el.dataset.btkKpPopup) return clean(el.dataset.btkKpPopup) || 'popup';\n      for (const at of el.attributes) {\n        if (/^data-btk-kp-[a-z0-9-]+$/.test(at.name)) return clean(at.name.slice(12)) || 'popup';\n      }\n      if (el.id) return clean(el.id) || 'popup';\n      for (const c of el.classList) {\n        if (c !== 'btk-kp-popup' && /^btk-kp-[a-z0-9-]+$/.test(c) && c.indexOf('--') === -1) return clean(c.slice(7)) || 'popup';\n      }\n      return 'overlay';\n    }\n    // The copy's markup: the overlay as it looks now - what is typed in its\n    // boxes, its ticks and choices, its drawn pictures - inside plain copies\n    // of the elements around it, so the planner's styles still match it.\n    function copyHtml(el) {\n      const clone = el.cloneNode(true);\n      const src = el.querySelectorAll('input, textarea, select');\n      const dst = clone.querySelectorAll('input, textarea, select');\n      src.forEach((s, i) => {\n        const d = dst[i];\n        if (!d) return;\n        if (s.tagName === 'TEXTAREA') d.textContent = s.value;\n        else if (s.tagName === 'SELECT') {\n          Array.prototype.forEach.call(d.options, (o, j) => {\n            if (s.options[j] && s.options[j].selected) o.setAttribute('selected', ''); else o.removeAttribute('selected');\n          });\n        } else if (s.type === 'checkbox' || s.type === 'radio') {\n          if (s.checked) d.setAttribute('checked', ''); else d.removeAttribute('checked');\n        } else if (s.type !== 'password' && s.type !== 'file') d.setAttribute('value', s.value);\n      });\n      const sc = el.querySelectorAll('canvas'), dc = clone.querySelectorAll('canvas');\n      sc.forEach((c, i) => {\n        const d = dc[i];\n        if (!d) return;\n        let url = '';\n        try { url = c.toDataURL('image/jpeg', 0.75); } catch (e) { /* a tainted canvas stays blank */ }\n        const img = document.createElement('img');\n        if (url) img.setAttribute('src', url);\n        img.className = c.className;\n        img.setAttribute('style', `${c.getAttribute('style') || ''};width:${c.clientWidth}px;height:${c.clientHeight}px`);\n        d.replaceWith(img);\n      });\n      clone.querySelectorAll('script, iframe, object, embed').forEach((n) => n.remove());\n      clone.removeAttribute('hidden');\n      let html = clone.outerHTML;\n      for (let a = el.parentElement; a && a !== document.body && a !== document.documentElement; a = a.parentElement) {\n        const shell = a.cloneNode(false);\n        shell.removeAttribute('hidden');\n        shell.innerHTML = html;\n        html = shell.outerHTML;\n      }\n      // Too big to send (several drawn unit pictures): send it without the\n      // pictures rather than not at all.\n      if (html.length > COPY_HTML_MAX) html = html.replace(/(\\ssrc=\")data:[^\"]*\"/g, '$1\"');\n      return html.length > COPY_HTML_MAX ? '' : html;\n    }\n    // How far down the copy's own panel is scrolled, 0-1.\n    function copyScrollOf(el) {\n      const s = scrollerIn(el);\n      if (!s) return undefined;\n      const max = s.scrollHeight - s.clientHeight;\n      return max > 0 ? Math.round(Math.min(1, Math.max(0, s.scrollTop / max)) * 10000) / 10000 : 0;\n    }\n\n    // Salesperson: send the copies showing, what has changed in them, and a\n    // close for each that has gone. Every few seconds each is sent whole\n    // again, so a customer who joins mid-way, or reconnects, gets them.\n    const copiesSent = new Map();    // key -> { html, f }\n    let copyElByKey = new Map();     // key -> the element copied, for the pointer\n    let copiesFullAt = 0;\n    function sendCopies(send) {\n      if (relayVersion < 5) return;\n      const now = Date.now();\n      const full = now - copiesFullAt > 4000;\n      if (full) copiesFullAt = now;\n      const seen = new Map();\n      for (const el of copyTargets()) {\n        const base = copyKeyOf(el);\n        let key = base, n = 2;\n        while (seen.has(key)) key = `${base}-${n++}`;\n        const html = copyHtml(el);\n        if (!html) continue;\n        seen.set(key, el);\n        const f = copyScrollOf(el);\n        const prev = copiesSent.get(key);\n        if (full || !prev || prev.html !== html) {\n          send({ type: 'overlay', key, html, ...(f !== undefined ? { f } : {}) });\n          copiesSent.set(key, { html, f });\n        } else if (f !== undefined && prev.f !== f) {\n          send({ type: 'overlay', key, f });\n          prev.f = f;\n        }\n      }\n      for (const key of [...copiesSent.keys()]) {\n        if (!seen.has(key)) { send({ type: 'overlay', key, close: true }); copiesSent.delete(key); }\n      }\n      copyElByKey = seen;\n    }\n    // The pointer over a copied popup is named within that popup, so the\n    // customer's screen finds it in the copy (resolveAnchor) rather than in\n    // its own unbuilt one.\n    function anchorInCopy(an) {\n      if (!an) return an;\n      for (const el of copyElByKey.values()) {\n        if (!el.contains(an.el)) continue;\n        const all = [el, ...el.querySelectorAll(an.a === 'id' ? '[id]' : `[${an.a}]`)]\n          .filter((n) => (an.a === 'id' ? n.id : n.getAttribute(an.a)) === an.v);\n        const i = all.indexOf(an.el);\n        return { ...an, i: i > 0 ? i : 0 };\n      }\n      return an;\n    }\n\n    // Customer: show the copies, in frames that cannot run or be clicked.\n    let copiesEl = null, copyHead = null;\n    const copyFrames = new Map();    // key -> iframe\n    const escAttr = (s) => String(s || '').replace(/&/g, '&amp;').replace(/\"/g, '&quot;').replace(/</g, '&lt;');\n    function copyHeadHtml() {\n      if (copyHead !== null) return copyHead;\n      const parts = [];\n      document.querySelectorAll('link[rel=\"stylesheet\"], style').forEach((n) => {\n        if (!n.closest('[data-btk-live-copies]')) parts.push(n.outerHTML);\n      });\n      copyHead = parts.join('');\n      return copyHead;\n    }\n    function applyCopyScroll(fr) {\n      const f = Number(fr.dataset.f);\n      const d = fr.contentDocument;\n      if (!Number.isFinite(f) || !d || !d.body) return;\n      const s = scrollerIn(d.body.firstElementChild ? d.body : null);\n      if (!s) return;\n      const max = s.scrollHeight - s.clientHeight;\n      if (max > 0) s.scrollTop = Math.round(f * max);\n    }\n    function clearCopies() {\n      copyFrames.forEach((fr) => fr.remove());\n      copyFrames.clear();\n    }\n    function showCopy(m) {\n      if (!m) return;\n      if (m.close && !m.key) { clearCopies(); return; }\n      if (typeof m.key !== 'string') return;\n      if (m.close) {\n        const fr = copyFrames.get(m.key);\n        if (fr) fr.remove();\n        copyFrames.delete(m.key);\n        return;\n      }\n      let fr = copyFrames.get(m.key);\n      if (typeof m.html === 'string') {\n        if (!copiesEl || !copiesEl.isConnected) {\n          copiesEl = document.createElement('div');\n          copiesEl.setAttribute('data-btk-live-copies', '');\n          copiesEl.style.cssText = `position:fixed;inset:0;z-index:${LIVE_POINTER_Z - 10};pointer-events:none;`;\n          document.body.appendChild(copiesEl);\n        }\n        if (!fr) {\n          fr = document.createElement('iframe');\n          // No allow-scripts: nothing in the copy can run. Same origin only so\n          // this page can follow its scroll and find the pointer in it.\n          fr.setAttribute('sandbox', 'allow-same-origin');\n          fr.setAttribute('aria-hidden', 'true');\n          fr.setAttribute('tabindex', '-1');\n          fr.setAttribute('title', 'What your Better Bedrooms adviser has open');\n          fr.style.cssText = 'position:absolute;inset:0;width:100%;height:100%;border:0;'\n            + 'background:transparent;pointer-events:none;';\n          fr.srcdoc = '<!doctype html><html class=\"' + escAttr(document.documentElement.className) + '\"><head>'\n            + '<meta charset=\"utf-8\"><base href=\"' + escAttr(location.origin) + '/\">' + copyHeadHtml()\n            // A blur behind a popup cannot see through the frame to the plan\n            // and paints solid instead, so copies are dimmed without it.\n            + '<style>html,body{background:transparent!important;margin:0;overflow:hidden}'\n            + '*{backdrop-filter:none!important;-webkit-backdrop-filter:none!important}</style></head>'\n            + '<body class=\"' + escAttr(document.body.className) + '\">' + m.html + '</body></html>';\n          fr.addEventListener('load', () => applyCopyScroll(fr));\n          copyFrames.set(m.key, fr);\n          copiesEl.appendChild(fr);\n        } else {\n          const d = fr.contentDocument;\n          if (d && d.body) d.body.innerHTML = m.html;\n        }\n      }\n      if (fr && m.f !== undefined) { fr.dataset.f = String(m.f); applyCopyScroll(fr); }\n    }\n    // A pointer anchor: in a copy first (the newest copy on top), else here.\n    function anchorInCopies(m) {\n      const frames = [...copyFrames.values()].reverse();\n      for (const fr of frames) {\n        const d = fr.contentDocument;\n        if (!d) continue;\n        const all = m.a === 'id' ? [d.getElementById(m.v)].filter(Boolean)\n          : Array.prototype.filter.call(d.querySelectorAll(`[${m.a}]`), (n) => n.getAttribute(m.a) === m.v);\n        const hit = all[m.i || 0] || null;\n        if (hit && hit.getClientRects().length) return hit;\n      }\n      return null;\n    }\n\n    // Select what the salesperson has selected: the item behind the side\n    // panel, and the highlighted units. Re-applied after every plan update,\n    // because loading a new copy of the plan clears the highlight.\n    function followSelection() {\n      if (driverSel === undefined && driverIds === undefined) return;\n      try {\n        if (driverSel !== undefined) {\n          const want = driverSel ? JSON.stringify(driverSel) : '';\n          const have = selectedItem ? JSON.stringify(selectedItem) : '';\n          if (want !== have) selectItem(driverSel ? { ...driverSel } : null);\n        }\n        if (Array.isArray(driverIds)) {\n          const same = driverIds.length === selectedCabinetIds.size\n            && driverIds.every(id => selectedCabinetIds.has(id));\n          if (!same) { selectedCabinetIds = new Set(driverIds); applySelectionVisual(); }\n        }\n      } catch (e) {\n        // Usually a unit the next plan update hasn't delivered yet. Forget the\n        // half-applied selection so the next attempt starts clean.\n        selectedItem = null;\n      }\n    }\n\n    // 2D or 3D, the 2D zoom and pan, the 3D camera.\n    function applyDriverFraming(v) {\n      try {\n        const want3D = v.mode === '3d';\n        if (want3D !== (viewMode === '3d')) setViewMode(want3D ? '3d' : '2d');\n        if (!want3D && Number.isFinite(v.zoom)) {\n          // Pan arrives as a fraction of the salesperson's viewport, so it frames\n          // the same part of the room on a differently sized screen.\n          const main = document.getElementById('btk-kp-main');\n          const mr = main ? main.getBoundingClientRect() : { width: 0, height: 0 };\n          view2d.zoom = v.zoom;\n          view2d.panX = (Number(v.panX) || 0) * (mr.width || 0);\n          view2d.panY = (Number(v.panY) || 0) * (mr.height || 0);\n          applyView2dTransform();\n        }\n        // The 3D renderer is built lazily on the first switch to 3D, so the\n        // camera may not be settable yet; the next view message applies it.\n        if (want3D && v.cam && handle3D && handle3D.setCameraState) handle3D.setCameraState(v.cam);\n      } catch (e) { /* a view we cannot apply is not worth breaking the mirror */ }\n    }\n\n    // ---- DRIVER: send the pointer and the view to the customer ----------\n    let stopDriverSharing = () => {};\n    function startDriverSharing() {\n      let lastPtrAt = 0, ptrShown = false;\n      const sendPtr = (msg) => {\n        if (ended || !wsOpen()) return;\n        try { ws.send(JSON.stringify(Object.assign({ type: 'pointer' }, msg))); } catch (_) {}\n      };\n      // Where the pointer is, in the terms the customer's screen needs (see\n      // showStaffPointer): over the plan, a fraction of the room grid or 3D\n      // canvas; anywhere else, a fraction of the control or panel under it.\n      const clamp01 = (n) => Math.min(1, Math.max(0, n));\n      const pointerAt = (cx, cy) => {\n        const under = document.elementFromPoint(cx, cy);\n        if (!under) return null;\n        const in3D = viewMode === '3d';\n        const planEl = in3D ? (handle3D && handle3D.getCanvas && handle3D.getCanvas()) : currentGridEl;\n        if (planEl && (under === planEl || planEl.contains(under))) {\n          const r = planEl.getBoundingClientRect();\n          if (r.width && r.height) {\n            return { x: clamp01((cx - r.left) / r.width), y: clamp01((cy - r.top) / r.height),\n                     space: in3D ? 'canvas' : 'grid' };\n          }\n        }\n        if (relayVersion < 2) return null;          // an older server: plan only\n        const an = anchorInCopy(anchorFor(under));\n        if (an) {\n          const r = an.el.getBoundingClientRect();\n          if (r.width && r.height) {\n            return { space: 'anchor', a: an.a, v: an.v, i: an.i,\n                     x: clamp01((cx - r.left) / r.width), y: clamp01((cy - r.top) / r.height) };\n          }\n        }\n        if (!window.innerWidth || !window.innerHeight) return null;\n        return { space: 'app', x: clamp01(cx / window.innerWidth), y: clamp01(cy / window.innerHeight) };\n      };\n      const onMove = (e) => {\n        const now = Date.now();\n        if (now - lastPtrAt < 60) return;           // ~16 a second is smooth enough\n        lastPtrAt = now;\n        const p = pointerAt(e.clientX, e.clientY);\n        if (!p) {\n          if (ptrShown) { sendPtr({ hide: true }); ptrShown = false; }\n          return;\n        }\n        ptrShown = true;\n        sendPtr(p);\n      };\n      // A press goes at once, and in the capture phase - before the click has\n      // changed anything here - so it is anchored to what was actually pressed.\n      const onDown = (e) => {\n        const p = pointerAt(e.clientX, e.clientY);\n        if (!p) return;\n        p.click = true;\n        ptrShown = true;\n        lastPtrAt = Date.now();\n        sendPtr(p);\n      };\n      // Off the page altogether (another window, the taskbar): hide it.\n      const onLeave = (e) => {\n        if (e.relatedTarget) return;\n        if (ptrShown) { sendPtr({ hide: true }); ptrShown = false; }\n      };\n      document.addEventListener('pointermove', onMove, { passive: true });\n      document.addEventListener('pointerdown', onDown, { capture: true, passive: true });\n      document.addEventListener('mouseout', onLeave, { passive: true });\n\n      // The panels scrolled lately (most recent last, a few at most), sent\n      // with the view - see followScroll. Scroll events do not bubble, so this\n      // listens in the capture phase.\n      const scrolled = new Set();\n      const onScroll = (e) => {\n        const el = (e.target === document || e.target === document.documentElement)\n          ? document.scrollingElement : e.target;\n        if (!el || el.nodeType !== 1) return;\n        if (el.closest && el.closest('#btk-live-driver')) return;\n        scrolled.delete(el); scrolled.add(el);\n        if (scrolled.size > 6) scrolled.delete(scrolled.values().next().value);\n      };\n      document.addEventListener('scroll', onScroll, { capture: true, passive: true });\n      const scrollPositions = () => {\n        const out = [];\n        for (const el of scrolled) {\n          if (!el.isConnected) { scrolled.delete(el); continue; }\n          const max = el.scrollHeight - el.clientHeight;\n          const f = max > 0 ? round(Math.min(1, Math.max(0, el.scrollTop / max)), 4) : 0;\n          if (el === document.scrollingElement) { out.push({ a: 'page', v: '', i: 0, f }); continue; }\n          const an = anchorFor(el);\n          // Only when the customer's screen can find this same panel again:\n          // the anchor itself, or the first scrolling panel inside it.\n          if (!an || scrollerIn(an.el) !== el) continue;\n          out.push({ a: an.a, v: an.v, i: an.i, f });\n        }\n        return out;\n      };\n      // A followed click: named before the click changes anything (capture\n      // phase), sent once it has (a tick later), with a toggle's new state.\n      const onAct = (e) => {\n        if (ended || !wsOpen() || relayVersion < 4) return;\n        const el = followableControl(e.target);\n        if (!el) return;\n        const k = controlKey(el);\n        if (!k) return;\n        setTimeout(() => {\n          if (ended || !wsOpen()) return;\n          const now = el.isConnected ? el : actMatches(k.a, k.v)[k.i];\n          const on = now ? controlState(now) : undefined;\n          const msg = { type: 'act', a: k.a, v: k.v, i: k.i };\n          if (typeof on === 'boolean') msg.on = on;\n          try { ws.send(JSON.stringify(msg)); } catch (_) {}\n        }, 0);\n      };\n      document.addEventListener('click', onAct, { capture: true, passive: true });\n\n      // The basket moves on each time it redraws here; the customer's copy is\n      // re-read to match (followBasket).\n      let basketRevSent = 0;\n      const onBasketDrawn = () => { basketRevSent++; };\n      window.addEventListener('btk:basket-drawn', onBasketDrawn);\n\n      // The view: sent when it changes, and every couple of seconds regardless\n      // so a customer who joins mid-session catches up without waiting for the\n      // salesperson to move.\n      let lastView = '', lastViewAt = 0;\n      const round = (n, dp) => { const f = Math.pow(10, dp); return Math.round(n * f) / f; };\n      const viewTimer = setInterval(() => {\n        if (ended || !wsOpen()) return;\n        const main = document.getElementById('btk-kp-main');\n        const mr = main ? main.getBoundingClientRect() : null;\n        const v = { type: 'view', mode: viewMode === '3d' ? '3d' : '2d' };\n        if (v.mode === '2d') {\n          v.zoom = round(view2d.zoom, 3);\n          v.panX = mr && mr.width ? round(view2d.panX / mr.width, 4) : 0;\n          v.panY = mr && mr.height ? round(view2d.panY / mr.height, 4) : 0;\n        } else if (handle3D && handle3D.getCameraState) {\n          const c = handle3D.getCameraState();\n          if (c) v.cam = { pos: c.pos.map(n => round(n, 0)), target: c.target.map(n => round(n, 0)) };\n        }\n        // Where in the planner they are, so the customer's screen follows\n        // them through every stage and popup (applyDriverView).\n        v.stage = currentStep;\n        v.popups = openPopupNames();\n        const hp = root.querySelector('[data-btk-kp-home-panel]:not([hidden])');\n        if (hp) v.hp = hp.dataset.btkKpHomePanel;\n        const js = root.querySelector('[data-btk-kp-journey-step]:not([hidden])');\n        if (js) v.js = js.dataset.btkKpJourneyStep;\n        v.sel = selectedItem ? flatRef(selectedItem) : null;\n        v.ids = [...selectedCabinetIds].slice(0, 60);\n        if (relayVersion >= 3) {\n          v.basket = !!(basketEmbedPanel && !basketEmbedPanel.hidden);\n          v.basketRev = basketRevSent;\n          v.scroll = scrollPositions();\n        }\n        // Copies of the popups the customer's screen cannot build itself.\n        try { sendCopies((msg) => { try { ws.send(JSON.stringify(msg)); } catch (_) {} }); }\n        catch (e) { /* a popup we cannot copy is not worth breaking the view */ }\n        const json = JSON.stringify(v);\n        const now = Date.now();\n        if (json === lastView && now - lastViewAt < 2000) return;\n        lastView = json; lastViewAt = now;\n        try { ws.send(json); } catch (_) {}\n      }, 150);\n\n      stopDriverSharing = () => {\n        document.removeEventListener('pointermove', onMove);\n        document.removeEventListener('pointerdown', onDown, { capture: true });\n        document.removeEventListener('mouseout', onLeave);\n        document.removeEventListener('scroll', onScroll, { capture: true });\n        document.removeEventListener('click', onAct, { capture: true });\n        window.removeEventListener('btk:basket-drawn', onBasketDrawn);\n        clearInterval(viewTimer);\n        if (ptrShown) sendPtr({ hide: true });\n        if (copiesSent.size && wsOpen()) {\n          try { ws.send(JSON.stringify({ type: 'overlay', close: true })); } catch (_) {}\n        }\n        copiesSent.clear();\n      };\n    }\n\n    // The popups showing on this screen. \"Showing\" is judged from the DOM\n    // alone - not hidden, and not inside anything hidden - rather than from\n    // layout, which would force a reflow several times a second mid-drag.\n    function openPopupNames() {\n      const out = [];\n      document.querySelectorAll('[data-btk-kp-popup]').forEach((p) => {\n        const name = p.dataset.btkKpPopup;\n        // One with no opener goes as a copy (sendCopies), not by name.\n        if (!p.hidden && !p.parentElement?.closest('[hidden]') && out.indexOf(name) === -1\n            && followedByName(name)) out.push(name);\n      });\n      return out.slice(0, 20);\n    }\n    // A selection reference with only its plain values - it is sent as-is.\n    function flatRef(ref) {\n      const out = {};\n      for (const k of Object.keys(ref)) {\n        const val = ref[k];\n        if (typeof val === 'string' || typeof val === 'boolean'\n            || (typeof val === 'number' && Number.isFinite(val))) out[k] = val;\n      }\n      return out;\n    }\n\n    // Take back a session this tab was already driving. Returns true if we did.\n    async function resumeAsDriver() {\n      let held = null;\n      try { held = JSON.parse(sessionStorage.getItem(DRIVER_KEY_STORE) || 'null'); } catch (e) {}\n      if (!held || !held.sid || !held.driverKey) return false;\n      try {\n        const r = await api(`/session/${held.sid}/resume`, {\n          method: 'POST', headers: { 'x-driver-key': held.driverKey }, body: '{}'\n        });\n        sid = held.sid; driverKey = held.driverKey;\n        wsInfo = (r && r.wsUrl && r.wsToken) ? { wsUrl: r.wsUrl, wsToken: r.wsToken } : null;\n        noteRelay(r);\n        booted = true;          // so a deep-link cannot start a second session\n        ended = false;\n        attachAsDriver();       // panel + socket + push loop, same as a fresh start\n        return true;\n      } catch (e) {\n        // Ended, expired, or not ours any more - forget it rather than\n        // retrying a session that cannot come back.\n        try { sessionStorage.removeItem(DRIVER_KEY_STORE); } catch (_) {}\n        return false;\n      }\n    }\n\n    async function startAsDriver() {\n      if (booted) return; booted = true;\n      try {\n        const r = await api('/session/start', {\n          method: 'POST',\n          body: JSON.stringify({ planName: activePlanName || 'Bedroom plan' })\n        });\n        sid = r.sid; driverKey = r.driverKey;\n        // Keep the keys for this tab only: a refresh or a crash can then pick\n        // the SAME session back up instead of stranding the customer in an\n        // abandoned one and needing a fresh link sent mid-call.\n        try {\n          sessionStorage.setItem(DRIVER_KEY_STORE, JSON.stringify({ sid: r.sid, driverKey: r.driverKey }));\n        } catch (e) {}\n        wsInfo = (r.wsUrl && r.wsToken) ? { wsUrl: r.wsUrl, wsToken: r.wsToken } : null;\n        noteRelay(r);\n      } catch (e) {\n        console.warn('[LiveSession] start failed', e);\n        window.BTKKPDialog.alert('Could not start the live session. Please try again.', { title: 'Session error', danger: true });\n        return;\n      }\n      attachAsDriver();\n    }\n\n    // Everything that makes this tab actually DRIVE: the panel, the socket, the\n    // push loop. Shared by start and resume - resume used to set the ids and\n    // stop there, so a reclaimed session reconnected nothing and the customer\n    // watched a frozen plan, which is the failure resume exists to prevent.\n    function attachAsDriver() {\n      // NO cid and NO cidt. This link goes to the CUSTOMER. Carrying the staff\n      // pass put their own browser into staff mode - the green bar and an Exit\n      // button - and made every request from their tab authenticate as the\n      // salesperson, so their saves were audited as staff actions. The customer\n      // joins as themselves: signed in, the session matches their account.\n      const viewerUrl = `${window.location.origin}${window.location.pathname}`\n        + `?session=${encodeURIComponent(sid)}&role=viewer&view3d=1`\n        + (_bootLive.preview ? `&preview_theme_id=${encodeURIComponent(_bootLive.preview)}` : '');\n      showDriverPanel(viewerUrl);\n      liveRole = 'driver';\n      // Prefer WS (instant). Presence messages update the status line; while\n      // the socket is down, pushOnce routes over HTTP and it reconnects itself.\n      connectSocket({\n        onMessage: (m) => {\n          if (m.type === 'presence') {\n            setDriverStatus(m.viewers > 0\n              ? '\u25CF Customer connected - they can see your changes live.'\n              : '\u25CB Waiting for the customer to accept\u2026', m.viewers > 0);\n          } else if (m.type === 'end') {\n            driverSessionEnded();\n          }\n        }\n      });\n      pushOnce();\n      startPushLoop();\n      startDriverSharing();                            // pointer + view, over the socket\n      pollTimer = setInterval(driverStatusPoll, 2500); // presence fallback when WS is down\n    }\n    // Drive pushes from requestAnimationFrame, NOT setInterval. During a drag the\n    // planner's mousemove + re-render saturates the event loop and starves a\n    // timer - so nothing was sent until mouse-up (\"only changes after release\").\n    // rAF fires per paint, aligned with the driver's own view, so the viewer\n    // tracks the drag live. Throttled + diffed so identical frames aren't spammed.\n    let rafPush = null, lastPushAt = 0;\n    function startPushLoop() {\n      const throttle = wsInfo ? 100 : 500;   // HTTP fallback is heavier \u2192 slower\n      const tick = () => {\n        if (ended) return;\n        const now = (typeof performance !== 'undefined' && performance.now) ? performance.now() : Date.now();\n        if (now - lastPushAt >= throttle) { lastPushAt = now; pushOnce(); }\n        rafPush = requestAnimationFrame(tick);\n      };\n      rafPush = requestAnimationFrame(tick);\n    }\n    function stopPushLoop() { if (rafPush) { cancelAnimationFrame(rafPush); rafPush = null; } }\n    async function pushOnce() {\n      if (!sid || ended) return;\n      let design;\n      try { design = currentDesign(); } catch (e) { return; }\n      const json = JSON.stringify(design);\n      if (json === lastPushed) return;                 // nothing changed \u2192 skip\n      lastPushed = json;\n      if (wsOpen()) {                                  // instant path\n        try { ws.send(JSON.stringify({ type: 'snapshot', snapshot: design })); pushCount++; setDriverDbg('ws'); }\n        catch (e) { lastPushed = ''; }\n        return;\n      }\n      try {                                            // HTTP fallback\n        await api(`/session/${sid}/state`, {\n          method: 'POST',                              // POST forwards cleanly through the App Proxy\n          headers: { 'x-driver-key': driverKey },\n          body: JSON.stringify({ snapshot: design })\n        });\n        pushCount++; setDriverDbg('http');\n      } catch (e) { lastPushed = ''; }                 // force a retry next tick\n    }\n    async function driverStatusPoll() {\n      if (!sid || ended) return;\n      try {\n        // With the driver key, this check-in also tells the server the\n        // salesperson is still here, socket or no socket.\n        const s = await api(`/session/${sid}`, { headers: { 'x-driver-key': driverKey } });\n        if (s.status === 'ended') { driverSessionEnded(); return; }\n        setDriverStatus(\n          s.consent === 'granted'  ? '\u25CF Customer connected - they can see your changes live.'\n          : s.consent === 'declined' ? '\u25CB Customer declined to join.'\n          : '\u25CB Waiting for the customer to accept\u2026',\n          s.consent === 'granted'\n        );\n      } catch (e) { /* transient */ }\n    }\n    // The server ended the session under this page: it lost its connection for\n    // longer than the grace period (a laptop lid shut, a dropped network) and\n    // the customer has already been told. Say so here too, rather than leaving\n    // a \"live\" panel up over a session that is over.\n    function driverSessionEnded() {\n      if (ended) return;\n      stopDriverSharing();\n      ended = true;\n      stopPushLoop(); clearInterval(pollTimer); clearTimeout(wsRetryTimer);\n      try { if (ws) ws.close(); } catch (e) {}\n      try { sessionStorage.removeItem(DRIVER_KEY_STORE); } catch (e) {}\n      try {\n        if (window.BTKBasketAPI && window.BTKBasketAPI.setStaffBannerActions) {\n          window.BTKBasketAPI.setStaffBannerActions([]);\n        }\n      } catch (e) {}\n      removeDriverPanel();\n      window.BTKKPDialog.alert(\n        'This live session has ended - the page lost its connection for too long. '\n        + 'Start a new session to carry on with the customer.',\n        { title: 'Live session ended' }\n      );\n    }\n\n    async function endSession() {\n      stopDriverSharing();                  // before `ended`, so the hide gets sent\n      ended = true;\n      stopPushLoop(); clearInterval(pollTimer); clearTimeout(wsRetryTimer);\n      try { if (wsOpen()) ws.send(JSON.stringify({ type: 'end' })); } catch (e) {}\n      try { if (ws) ws.close(); } catch (e) {}\n      try {\n        if (sid) await api(`/session/${sid}/end`, {\n          method: 'POST', headers: { 'x-driver-key': driverKey }, body: '{}'\n        });\n      } catch (e) { /* best effort */ }\n      // Deliberately ended - so this tab must NOT try to reclaim it on reload.\n      try { sessionStorage.removeItem(DRIVER_KEY_STORE); } catch (e) {}\n      try {\n        if (window.BTKBasketAPI && window.BTKBasketAPI.setStaffBannerActions) {\n          window.BTKBasketAPI.setStaffBannerActions([]);   // no session, no buttons\n        }\n      } catch (e) {}\n      removeDriverPanel();\n    }\n\n    // ---- VIEWER (customer) ----\n    async function joinAsViewer(sessionId) {\n      if (booted) return; booted = true;\n      sid = sessionId;\n      // Drop the boot loader (\"Rebuilding your 3D plan\u2026\") so it can't sit on\n      // top of the consent dialog (which otherwise looks like a stuck load).\n      if (window.BTKLoader && window.BTKLoader.hide) window.BTKLoader.hide();\n      const ok = await window.BTKKPDialog.confirm(\n        'Better Bedrooms would like to guide this bedroom plan with you live during your call - '\n        + 'you will see changes appear on screen in real time. You can close the page to leave at any point.',\n        { title: 'Join live session?', confirmText: 'Allow', cancelText: 'Not now' }\n      );\n      try {\n        const cr = await api(`/session/${sid}/consent`, { method: 'POST', body: JSON.stringify({ grant: !!ok }) });\n        wsInfo = (ok && cr && cr.wsUrl && cr.wsToken) ? { wsUrl: cr.wsUrl, wsToken: cr.wsToken } : null;\n      } catch (e) {\n        // A session belongs to ONE customer account, so a viewer who isn't\n        // signed in cannot be matched to it. That is a login problem, not a\n        // fault - and \"please refresh and try again\" is advice that cannot\n        // work, which is the worst thing to say to someone on a phone call.\n        if (String(e && e.message || '').indexOf('401') !== -1) {\n          const back = window.location.pathname + window.location.search;\n          const go = await window.BTKKPDialog.confirm(\n            'Please sign in to your Better Bedrooms account to join this session - '\n            + 'it opens on your own saved plan, so we need to know it is you. '\n            + 'You will come straight back here afterwards.',\n            { title: 'Sign in to join', confirmText: 'Sign in', cancelText: 'Not now' }\n          );\n          if (go) {\n            window.location.href = accountSignInUrl(back);\n          }\n          return;\n        }\n        window.BTKKPDialog.alert('Could not join the live session. Please refresh and try again.', { title: 'Session error', danger: true });\n        return;\n      }\n      if (!ok) return;\n      showViewerBanner();\n      liveRole = 'viewer';\n      // Prefer WS (instant mirror). If it opens, stop polling; if it can't open\n      // (or drops), poll instead so the plan keeps updating either way, while\n      // the socket reconnects itself.\n      connectSocket({\n        onOpen: () => { stopViewerPolling(); },\n        onMessage: (m) => {\n          if (m.type === 'snapshot' && m.snapshot && m.driverSeq !== lastSeq) {\n            queueMirror(m.snapshot, m.driverSeq);\n          } else if (m.type === 'pointer') {\n            showStaffPointer(m);\n          } else if (m.type === 'view') {\n            applyDriverView(m);\n          } else if (m.type === 'act') {\n            try { followAct(m); } catch (e) { /* a click we cannot follow is not worth breaking the mirror */ }\n          } else if (m.type === 'overlay') {\n            try { showCopy(m); } catch (e) { /* a copy we cannot show is not worth breaking the mirror */ }\n          } else if (m.type === 'driver') {\n            setDriverAway(m.state === 'away');\n          } else if (m.type === 'end') { handleSessionEnded(); }\n        },\n        onClose: () => { if (!ended) startViewerPolling(); }\n      });\n      setTimeout(() => { if (!ended && !wsOpen()) startViewerPolling(); }, 3000);\n      if (!wsInfo) startViewerPolling();\n    }\n    // Coalesce incoming snapshots: applyState() does a full 2D+3D rebuild, so\n    // when updates arrive faster than we can render, keep only the LATEST and\n    // apply one per animation frame. This prevents a backlog (which shows up as\n    // \"lags a second then snaps\") - the viewer always tracks the newest state.\n    let pendingSnap = null, pendingSeq = -1, applyScheduled = false;\n    function queueMirror(snapshot, seq) {\n      recvCount++;\n      const vt = document.getElementById('btk-live-viewer-text');\n      if (vt && !driverIsAway) vt.textContent = `Live - updates received: ${recvCount}`;\n      pendingSnap = snapshot; pendingSeq = seq;\n      if (applyScheduled) return;\n      applyScheduled = true;\n      const run = () => {\n        applyScheduled = false;\n        if (pendingSnap != null && pendingSeq !== lastSeq) {\n          lastSeq = pendingSeq;\n          const snap = pendingSnap; pendingSnap = null;\n          applyMirror(snap);\n        }\n      };\n      (typeof requestAnimationFrame === 'function' ? requestAnimationFrame : (fn) => setTimeout(fn, 16))(run);\n    }\n    function applyMirror(snapshot) {\n      try { applyMirrorSnapshot(snapshot); }\n      catch (e) { console.warn('[LiveSession] apply failed', e); }\n      // A new copy of the plan clears the highlight; put the salesperson's\n      // selection back on it.\n      followSelection();\n    }\n    function handleSessionEnded() {\n      if (ended) return;               // the socket and a poll can both say so\n      ended = true; stopViewerPolling(); clearTimeout(wsRetryTimer);\n      driverIsAway = false;\n      hideStaffPointer();              // nobody is pointing any more\n      clearCopies();                   // nor showing anything\n      try { if (ws) ws.close(); } catch (e) {}\n      setViewerBanner('The live session has ended.');\n      setTimeout(removeViewerBanner, 4000);\n    }\n    // The salesperson's connection dropped (a refresh, a closed tab, a lost\n    // network) or came back. Say so, rather than leave the customer looking at\n    // a plan that has silently stopped moving. If they don't come back, the\n    // server ends the session and handleSessionEnded takes over.\n    function setDriverAway(away) {\n      if (ended || away === driverIsAway) return;\n      driverIsAway = away;\n      if (away) hideStaffPointer();\n      setViewerBanner(away\n        ? 'Your Better Bedrooms adviser has disconnected - reconnecting\u2026'\n        : 'Live - Better Bedrooms is guiding your plan');\n    }\n    function startViewerPolling() {\n      if (viewerPolling || ended) return;\n      viewerPolling = true;\n      pollTimer = setInterval(viewerPoll, 1500);\n      viewerPoll();\n    }\n    function stopViewerPolling() {\n      viewerPolling = false;\n      if (pollTimer) { clearInterval(pollTimer); pollTimer = null; }\n    }\n    async function viewerPoll() {\n      if (!sid || ended) return;\n      let s;\n      try { s = await api(`/session/${sid}`); } catch (e) { return; }\n      if (s.status === 'ended') { handleSessionEnded(); return; }\n      if (typeof s.driverAway === 'boolean') setDriverAway(s.driverAway);\n      if (typeof s.driverSeq === 'number' && s.driverSeq !== lastSeq && s.snapshot) {\n        queueMirror(s.snapshot, s.driverSeq);\n      }\n    }\n\n    // ---- Minimal, self-contained UI (inline-styled; text set via textContent) ----\n    // Whether the panel is collapsed. Kept for the tab so a refresh - or a\n    // resumed session - comes back the way the salesperson left it.\n    const DRIVER_MIN_KEY = 'btk-live-driver-min';\n    function driverMinimised() {\n      try { return sessionStorage.getItem(DRIVER_MIN_KEY) === '1'; } catch (e) { return false; }\n    }\n    function setDriverMinimised(on) {\n      try { sessionStorage.setItem(DRIVER_MIN_KEY, on ? '1' : '0'); } catch (e) {}\n    }\n\n    function showDriverPanel(viewerUrl) {\n      removeDriverPanel();\n      const box = document.createElement('div');\n      box.id = 'btk-live-driver';\n      const EXPANDED = 'position:fixed;top:12px;left:50%;transform:translateX(-50%);z-index:100000;'\n        + 'background:#1f2d3d;color:#fff;border-radius:10px;padding:12px 14px;max-width:460px;width:calc(100% - 24px);'\n        + 'box-shadow:0 8px 30px rgba(0,0,0,.35);font:13px/1.4 system-ui,sans-serif;';\n      // Collapsed, it also moves OUT of the centre. The planner's stage bar runs\n      // across the middle of the top bar, so a small pill left at top-centre\n      // would still sit on top of it - the reason for minimising in the first\n      // place. Top-right is clear.\n      const COLLAPSED = 'position:fixed;top:12px;right:12px;left:auto;transform:none;z-index:100000;'\n        + 'background:#1f2d3d;color:#fff;border-radius:999px;padding:6px 12px;max-width:none;width:auto;'\n        + 'box-shadow:0 6px 20px rgba(0,0,0,.3);font:13px/1.4 system-ui,sans-serif;cursor:pointer;';\n      box.style.cssText = EXPANDED;\n\n      // Header: title on the left, collapse control on the right.\n      const head = document.createElement('div');\n      head.style.cssText = 'display:flex;align-items:center;gap:8px;';\n      const title = document.createElement('div');\n      title.textContent = 'Live session active';\n      title.style.cssText = 'font-weight:600;flex:1;min-width:0;';\n      const toggle = document.createElement('button');\n      toggle.type = 'button';\n      toggle.style.cssText = 'border:0;background:rgba(255,255,255,.15);color:#fff;border-radius:6px;'\n        + 'width:26px;height:26px;line-height:1;cursor:pointer;font-size:16px;flex:0 0 auto;';\n      head.append(title, toggle);\n\n      // Everything except the header hides when collapsed.\n      const body = document.createElement('div');\n\n      // Minimised, the panel goes away completely and its controls move into\n      // the green staff bar already across the top - one strip of controls\n      // instead of a second box sitting over the planner's own menu.\n      // If that bar isn't there to move them to (no staff mode, or an older\n      // cached script), fall back to collapsing to a pill in the corner.\n      const bannerAvailable = () => !!(window.BTKBasketAPI\n        && typeof window.BTKBasketAPI.setStaffBannerActions === 'function'\n        && window.BTKBasketAPI.isStaffMode && window.BTKBasketAPI.isStaffMode());\n      const applyMin = (min) => {\n        const toBar = min && bannerAvailable();\n        box.style.cssText = toBar ? 'display:none;' : (min ? COLLAPSED : EXPANDED);\n        body.hidden = min;\n        title.textContent = min ? 'Live session' : 'Live session active';\n        title.style.marginBottom = min ? '0' : '4px';\n        toggle.textContent = min ? '+' : '\\u2013';               // \u2013 / +\n        toggle.title = min ? 'Show the session panel' : 'Minimise';\n        toggle.setAttribute('aria-label', toggle.title);\n        setDriverMinimised(min);\n        if (!bannerAvailable()) return;\n        window.BTKBasketAPI.setStaffBannerActions(toBar ? [\n          // The link stays reachable - minimising must not strand a salesperson\n          // who has not sent it to the customer yet.\n          { label: 'Session link', onClick: () => applyMin(false) },\n          { label: 'End session', danger: true, onClick: endSession },\n        ] : []);\n      };\n      toggle.addEventListener('click', (e) => { e.stopPropagation(); applyMin(!body.hidden); });\n      // Collapsed to a pill (no staff bar), the whole pill is the target.\n      box.addEventListener('click', () => { if (body.hidden) applyMin(false); });\n\n      const status = document.createElement('div');\n      status.id = 'btk-live-driver-status';\n      status.textContent = '\u25CB Waiting for the customer to accept\u2026';\n      status.style.cssText = 'opacity:.85;margin-bottom:8px;';\n      const label = document.createElement('div');\n      label.textContent = 'Send the customer this link to join:';\n      label.style.cssText = 'font-size:12px;opacity:.8;margin-bottom:4px;';\n      const row = document.createElement('div');\n      row.style.cssText = 'display:flex;gap:6px;';\n      const input = document.createElement('input');\n      input.readOnly = true; input.value = viewerUrl;\n      input.style.cssText = 'flex:1;min-width:0;border:0;border-radius:6px;padding:6px 8px;font:12px monospace;color:#111;';\n      const copy = document.createElement('button');\n      copy.type = 'button'; copy.textContent = 'Copy';\n      copy.style.cssText = 'border:0;border-radius:6px;padding:6px 12px;background:#2e7d32;color:#fff;cursor:pointer;font-weight:600;';\n      copy.addEventListener('click', () => {\n        input.select();\n        (navigator.clipboard ? navigator.clipboard.writeText(viewerUrl) : Promise.reject())\n          .then(() => { copy.textContent = 'Copied'; setTimeout(() => (copy.textContent = 'Copy'), 1500); })\n          .catch(() => { try { document.execCommand('copy'); } catch (e) {} });\n      });\n      const end = document.createElement('button');\n      end.type = 'button'; end.textContent = 'End session';\n      end.style.cssText = 'margin-top:8px;border:0;border-radius:6px;padding:6px 12px;background:#b3261e;color:#fff;cursor:pointer;';\n      end.addEventListener('click', endSession);\n      const dbg = document.createElement('div');\n      dbg.id = 'btk-live-driver-dbg';\n      dbg.textContent = 'updates sent: 0';\n      dbg.style.cssText = 'margin-top:6px;font-size:11px;opacity:.6;';\n      row.append(input, copy);\n      body.append(status, label, row, end, dbg);\n      box.append(head, body);\n      document.body.appendChild(box);\n      applyMin(driverMinimised());\n    }\n    function setDriverStatus(text, connected) {\n      const el = document.getElementById('btk-live-driver-status');\n      if (el) { el.textContent = text; el.style.color = connected ? '#7fdd8a' : ''; }\n    }\n    function setDriverDbg(via) {\n      const el = document.getElementById('btk-live-driver-dbg');\n      if (el) el.textContent = `updates sent: ${pushCount} (${via})`;\n    }\n    function removeDriverPanel() {\n      const el = document.getElementById('btk-live-driver');\n      if (el) el.remove();\n    }\n    function showViewerBanner() {\n      removeViewerBanner();\n      const b = document.createElement('div');\n      b.id = 'btk-live-viewer';\n      b.style.cssText = 'position:fixed;top:12px;left:50%;transform:translateX(-50%);z-index:100000;'\n        + 'background:#2e7d32;color:#fff;border-radius:20px;padding:8px 16px;'\n        + 'box-shadow:0 6px 20px rgba(0,0,0,.3);font:600 13px/1 system-ui,sans-serif;display:flex;align-items:center;gap:8px;';\n      const dot = document.createElement('span');\n      dot.textContent = '\u25CF'; dot.style.cssText = 'color:#ff5a5a;animation:btkpulse 1.4s infinite;';\n      const txt = document.createElement('span');\n      txt.id = 'btk-live-viewer-text';\n      txt.textContent = 'Live - Better Bedrooms is guiding your plan';\n      ensureLiveKeyframes();\n      b.append(dot, txt);\n      document.body.appendChild(b);\n    }\n    function setViewerBanner(text) {\n      const el = document.getElementById('btk-live-viewer-text');\n      if (el) el.textContent = text;\n    }\n    function removeViewerBanner() {\n      const el = document.getElementById('btk-live-viewer');\n      if (el) el.remove();\n    }\n\n    // \"Back to Odoo\" while driving: the customer is told it has ended, rather\n    // than left watching a plan nobody is working on.\n    async function endIfDriving() {\n      if (sid && driverKey && !ended) await endSession();\n    }\n\n    return { startAsDriver, joinAsViewer, resumeAsDriver, hasHeldSession, endIfDriving };\n  })();\n\n  // \"Back to Odoo\" (the staff bar, btk-basket-api.js) saves before it leaves:\n  // the salesperson is done with this customer's plan, so it is saved now\n  // rather than on the autosave timer - even if they switched autosave off.\n  // False = not saved, and they are asked before the tab closes.\n  async function saveBeforeStaffExit() {\n    // Ending a live session comes first, whatever plan is open: the customer\n    // is told it is over rather than left watching a plan nobody is on.\n    try { await LiveSession.endIfDriving(); } catch (e) { /* best effort */ }\n    if (_bootOrdered) return true;\n    if (autosaveTimer) { clearTimeout(autosaveTimer); autosaveTimer = null; }\n    try { await awaitJourneySave(); } catch (e) {}   // Start Planning's own save\n    // A save already under way finishes first; it may be all that was needed.\n    for (let i = 0; autosaveRunning && i < 100; i++) await new Promise((r) => setTimeout(r, 100));\n    if (!autosaveDirty) return true;\n    const wasOn = autosaveOn;\n    autosaveOn = true;\n    try { await runAutosave(); } finally { autosaveOn = wasOn; }\n    return !autosaveDirty;\n  }\n  // The boot can fall back to starting before btk-basket-api.js has run; the\n  // hook is then registered once the page has loaded instead.\n  const registerStaffExit = () => {\n    const api = window.BTKBasketAPI;\n    if (!api || typeof api.onStaffExit !== 'function') return false;\n    api.onStaffExit(saveBeforeStaffExit);\n    return true;\n  };\n  try {\n    if (!registerStaffExit()) window.addEventListener('load', registerStaffExit, { once: true });\n  } catch (e) {}\n\n  async function handleClear() {\n    if (!(await window.BTKKPDialog.confirm('This wipes the canvas back to an empty 5000\u00D73500 room. Any named saves stay in the Load list.', { title: 'Reset the whole plan?', confirmText: 'Reset', danger: true }))) return;\n    await planStore.clear();\n    // Fresh canvas = a fresh plan: drop the id so the next save starts\n    // a brand-new basket rather than overwriting the one just cleared.\n    plannerPlanId = null;\n    applyState({\n      roomConfig: freshRoomConfig(),\n      cabinets: []\n    });\n    activePlanName = null;\n    designControlsHandle.setPlanName(null);\n    refreshLiveQuoteLabels();\n    basketDrawerHandle?.refresh?.();\n    designControlsHandle.setStatus('Reset');\n    stepperHandle.setStep('room-setup');\n  }\n\n  // ---- Wire UI ----\n\n  pricingHandle = initPricingDisplay(root, { currency: context.currency || 'GBP' });\n  // The embedded advanced cart calls this with its upgrade add-on total (GBP).\n  // The top-bar price is units-only so upgrades no longer move it, but the\n  // total still feeds computeTotal (PDF report + saved-plan price).\n  window.__btkSetPlannerAddonTotal = function (gbp) {\n    const v = Number(gbp) || 0;\n    if (v === plannerAddonTotalGbp) return;\n    plannerAddonTotalGbp = v;\n    try {\n      pricingHandle.update(headPriceState());\n    } catch (e) {}\n  };\n\n  rerender();\n\n  roomShapeHandle = initRoomShapeUI(sidebar, {\n    getRoomConfig,\n    onShapeChange:           handleShapeChange,\n    onParamsApply:           handleParamsApply,\n    onCeilingChange:         handleCeilingChange,\n    // A new shape is in: ask for the room's height next. Two frames so the\n    // new room is drawn behind the dialog before it asks.\n    onShapeCommitted:        () => requestAnimationFrame(() => requestAnimationFrame(askRoomHeight)),\n    onAddColumn:             handleAddColumn,\n    onRemovePerimeterItem:   handleRemovePerimeterItem,\n    onAddCornerCut:          handleAddCornerCut,\n    onRemoveCornerCut:       handleRemovePerimeterItem,\n    onAddPillar:             handleAddPillar,\n    onRemovePillar:          handleRemovePerimeterItem,\n    onAddWall:               handleAddWall,\n    onAddPillarFeature:      handleAddPillarFeature,\n    onAddStepBlock:          handleAddStepBlock,\n    onAddCookerAlcove:       handleAddCookerAlcove,\n    onAddBeam:               handleAddBeam,\n    onAddSlopedCeiling:      handleAddSlopedCeiling,\n    onAddCeilingWedgeFull:   handleAddCeilingWedgeFull,\n    onAddFreeBlock:          handleAddFreeBlock,\n    onAddFloorBlock:         handleAddFloorBlock,\n    onAddRoomFeature:        handleAddRoomFeature,\n    // Authored tiles for the room-features picker (planner_room_feature).\n    getRoomFeatureTiles:     () => (Catalogue.getRoomFeatureTiles?.() || []),\n    // A vaulted ceiling's roof lights are the catalogue's fixed window, so the\n    // colours they offer are that window's own.\n    getOpeningColours:       () => (Catalogue.getOpeningColours?.() || []),\n    // The picker previews what it is about to add, with the same builders the\n    // room itself uses.\n    renderRoomFeatureThumbnail: async (item, o) => {\n      await ensure3DReady();\n      if (!handle3D || typeof handle3D.renderRoomFeatureThumbnail !== 'function') return null;\n      return handle3D.renderRoomFeatureThumbnail(item, o);\n    },\n    onUpdateFeature:         handleUpdateFeature,\n    onToggleRoomLock:        handleToggleRoomLock,\n    onResetRoom:             handleResetRoom,\n    onUseExistingRoom:       () => openPreviousRoomPicker('apply'),\n    // Walls & Floor swatches live under Room Setup now.\n    WallColours:             WALL_COLOURS,\n    FloorColours:            floorColourList,\n    FlooringTypes:           (Catalogue.getFlooringTypes && Catalogue.getFlooringTypes()) || [],\n    getWallColourHandle:     () => wallColourHandle,\n    getFloorColourHandle:    () => floorColourHandle,\n    getFloorSettings:        getFloorSettings,\n    onSetWallColour:         handleSetWallColour,\n    onSetFloorColour:        handleSetFloorColour,\n    onRotateFloor:           handleRotateFloor,\n    onSetFloorZoom:          handleSetFloorZoom\n  });\n\n  doorsWindowsHandle = initDoorsWindowsUI(sidebar, {\n    Catalogue,\n    getRoomConfig,\n    getRoom:         () => room,\n    getWorktopColourHex: () => worktopColourHex,\n    renderOpeningThumbnail,\n    onAddOpening:    handleAddOpening,\n    onRemoveOpening: handleRemoveOpening\n  });\n\n  cabinetsHandle = initCabinetsUI(sidebar, styleGated({\n    Catalogue,\n    getAutoEndPanels:  () => autoEndPanels,\n    onSetAutoEndPanels: handleSetAutoEndPanels,\n    getKitchenStyleId:            () => kitchenStyleId,\n    onKitchenStyleChange:         handleKitchenStyleChange,\n    getGlobalDoorColourHandle:    () => globalDoorColourHandle,\n    onSetGlobalDoorColour:        handleSetGlobalDoorColour,\n    getGlobalCarcaseColourHandle: () => globalCarcaseColourHandle,\n    onSetGlobalCarcaseColour:     handleSetGlobalCarcaseColour,\n    onAddCabinet:      addCabinet,\n    onAddIsland:       addIsland,\n    getIslandPlinth:   islandPlinthInfo,\n    onIsland3D:        renderIslandPreview,\n    getIslandWaterfall: islandWaterfallInfo,\n    onHideIsland3D:    hideIslandPreview,\n    getWorktopItemCatalogue,\n    onAddWorktopItem:  addWorktopItem,\n    getRadiusUnitCatalogue,\n    onAddRadiusUnit:   addRadiusUnit,\n    getLShapeUnitCatalogue,\n    onAddLShapeUnit:   addLShapeUnit,\n    getDiagonalCornerUnitCatalogue,\n    onAddDiagonalCornerUnit: addDiagonalCornerUnit,\n    getLShapeWallUnitCatalogue,\n    onAddLShapeWallUnit: addLShapeWallUnit,\n    getDiagonalCornerWallUnitCatalogue,\n    onAddDiagonalCornerWallUnit: addDiagonalCornerWallUnit,\n    getWalkInCornerLarderUnitCatalogue,\n    onAddWalkInCornerLarderUnit: addWalkInCornerLarderUnit,\n    getDiagonalCornerLarderUnitCatalogue,\n    onAddDiagonalCornerLarderUnit: addDiagonalCornerLarderUnit,\n    getOpenBaseUnitCatalogue,\n    onAddOpenBaseUnit: addOpenBaseUnit,\n    getCornerWallUnitCatalogue,\n    onAddCornerWallUnit: addCornerWallUnit,\n    getBelfastSinkUnitCatalogue,\n    onAddBelfastSinkUnit: addBelfastSinkUnit,\n    getOvenHousingUnitCatalogue,\n    onAddOvenHousingUnit: addOvenHousingUnit,\n    getTallOvenHousingUnitCatalogue,\n    onAddTallOvenHousingUnit: addTallOvenHousingUnit,\n    getSinkBaseUnitCatalogue,\n    onAddSinkBaseUnit: addSinkBaseUnit,\n    getEndPanelsFillersCatalogue,\n    onAddEndPanelFiller: addEndPanelFiller,\n    getCornerPostVoidCatalogue,\n    onAddCornerPostVoid: addCornerPostVoid,\n    // Choose Sink popup needs the cabinet list (to find sink-base\n    // cabs with no Planner Sink yet) + a way to commit the chosen\n    // sink onto a specific cab. The sink panel's \"Choose Sink\"\n    // button also drives this popup via the same handle.\n    getCabinets:               () => cabinets,\n    onSetCabinetPlannerSink:   handleSetCabinetPlannerSink,\n    // Why a sink of this install type cannot go on this plan, or null.\n    sinkWorktopBlock:          (installType, cabId) => sinkWorktopBlock(installType, false, cabId ? (cabinets || []).find(c => c && c.id === cabId) : null),\n    // Why this sink cannot go on this sink unit (an appliance beside it), or null.\n    sinkApplianceBlock:        sinkApplianceBlock,\n    // A sink in the basket offered to this unit (refreshSpareSinks), or undefined.\n    getSpareSink:              (cabinetId) => spareSinkByCab.get(cabinetId),\n    onAddTapToCabinet:         addTapForCabinet,\n    getTapTargetCabinetId:     tapTargetCabinetId,\n    onSetCabinetAppliance:     handleSetCabinetAppliance,\n    // Freestanding appliance (Add Appliances \u2192 \"Add to Plan\") \u2192 placed on the\n    // plan as a draggable footprint box (+ GLB in 3D when it has one).\n    onAddFreestandingAppliance: handleAddFreestandingAppliance,\n    onAddPlanAppliance:         handleAddPlanAppliance,\n    // Inline restyle panel inside Add Units (under the kitchen-style\n    // card). Mirrors the Customise \"Change Colours\" group cards so\n    // existing-unit restyle and Customise share the same handler.\n    getSelectedCabinetIds:     () => [...selectedCabinetIds],\n    onApplyStyleToIds:         handleApplyStyleToIds,\n    // Off-screen 3D thumbnails for the Add Units popup product cards, from\n    // the HEADLESS renderer (renderCabinetThumbHeadless) - never the live 3D\n    // view, which froze the list while it built the whole kitchen.\n    renderCabinetThumbnail: (cab, opts) => renderCabinetThumbHeadless(cab, opts),\n    // A Pastry Bench card's price is its whole set's.\n    getUnitSetPriceCents: (unitTypeId, styleId, variantId) => pastrySetPriceCents(unitTypeId, styleId, variantId),\n    // Add Units owns the retry for the style-product load. The boot fetch\n    // (below) can fail on a cold / just-pushed theme; without these the popup\n    // had no way back and read \"No matching cabinets\" all session.\n    hasStyleProducts:    (styleId) => Catalogue.hasProductsForStyle(styleId),\n    // On a late-arriving load, re-render the plan too: cabinets placed before\n    // the products landed can now resolve their variant + price.\n    ensureStyleProducts: (styleId) => ensureStyleProducts(styleId)\n      .then(() => { try { rerender(); } catch (_) {} })\n  }));\n\n  // Ensure the initial buying style's products are indexed. The inline\n  // catalogue is scoped to the buying style so this is usually a no-op; it\n  // covers the case where the inline scope missed (no cart attribute at render,\n  // or the JS-seeded style differs from the rendered one) by fetching before\n  // the first Add Units open.\n  // A failure here is no longer terminal - the Add Units popup retries the\n  // load when it opens (see ensureProductsForActiveStyle in ui-cabinets), so\n  // an intermittent 500 on this fetch costs a spinner, not the session.\n  ensureStyleProducts(kitchenStyleId)\n    .then(() => cabinetsHandle.refresh())\n    .catch((e) => console.warn('[BTK Kitchen Planner] style products load failed; Add Units will retry on open:', e));\n\n  // The planner UI is built and interactive from here, so drop the boot loader\n  // (the copy the planner document ships inline, plus the one btk-loader.js put\n  // up on the page we navigated FROM). Deliberately NOT on DOMContentLoaded:\n  // that fires while the UI is still assembling, and lifting the veil onto a\n  // half-built planner reads as more broken than the loader does.\n  //\n  // Two rAFs so the first painted frame of the real UI is already on screen\n  // before the overlay goes - one alone still lets a blank frame through.\n  requestAnimationFrame(() => requestAnimationFrame(() => {\n    try { planNavStep('loader', 'planner UI built, boot loader down'); } catch (_) {}\n    if (!window.BTKLoader) return;\n    // Opening one saved plan: keep covering until it has landed (the plan-link\n    // path drops it). show() also arms the loader's 25s safety hide.\n    if (_bootPlanLink && !planLinkLanded) window.BTKLoader.show({ message: 'Opening your plan\u2026' });\n    else if (_bootJourneyLink && !journeyLinkLanded) window.BTKLoader.show({ message: 'Setting up your new plan\u2026' });\n    else window.BTKLoader.hide();\n  }));\n\n  // Warm the style/colour preview images once the browser is idle. They are no\n  // longer inlined into the page (see ensurePreviews), and every consumer\n  // degrades to \"no photo\" until they land - so this is a prefetch, not a\n  // dependency. requestIdleCallback keeps it off the boot critical path; the\n  // setTimeout fallback covers Safari, which still lacks it.\n  const _warmPreviews = () => { ensurePreviews(); };\n  if (typeof requestIdleCallback === 'function') {\n    requestIdleCallback(_warmPreviews, { timeout: 4000 });\n  } else {\n    setTimeout(_warmPreviews, 1200);\n  }\n\n  // If the style step was already on screen when the previews landed, its cards\n  // drew without photos - repaint just that step. Guarded on the step actually\n  // being visible so this never redraws (and resets scroll on) a panel the user\n  // isn't looking at.\n  document.addEventListener('btk:previews-ready', () => {\n    try {\n      const stepEl = journeyEl && journeyEl.querySelector('[data-btk-kp-journey-step=\"style\"]');\n      if (stepEl && !stepEl.hidden) renderJourneyStyles();\n    } catch (e) {\n      console.warn('[BTK Kitchen Planner] preview repaint skipped:', e);\n    }\n  });\n\n  // ---- Buying-style drawer bridge -----------------------------------\n  // The Active Buying Style bar in the Add Units sidebar opens the\n  // shared drawer (rendered by snippets/btk-buying-style-drawer.liquid).\n  // The drawer normally reloads the page when the user picks a new\n  // style - fine on the listing page, terrible here because it would\n  // lose any in-progress plan state. Register a hook so the drawer\n  // applies the switch in-place instead.\n  function applyBuyingContextToPlanner(ctx) {\n    if (!ctx) return;\n    if (ctx.style && ctx.style !== kitchenStyleId) {\n      handleKitchenStyleChange(ctx.style);\n    }\n    // Door + carcase are not part of handleKitchenStyleChange (it\n    // resets them to the new style's first colour). Apply the\n    // explicit ones from the buying context AFTER so they win.\n    if (ctx.colour && ctx.colour !== globalDoorColourHandle) {\n      handleSetGlobalDoorColour(ctx.colour);\n    }\n    if (ctx.carcase && ctx.carcase !== globalCarcaseColourHandle) {\n      handleSetGlobalCarcaseColour(ctx.carcase);\n    }\n    // The cabinets handle re-renders the style preview + restyle\n    // panel so they reflect the new buying-style pick instantly.\n    cabinetsHandle?.refresh?.();\n  }\n  window.__btkBuyingStyleHooks = {\n    onSwitchToStyle: (newCtx) => {\n      applyBuyingContextToPlanner(newCtx);\n      return true;   // claim the switch - drawer skips the reload\n    },\n    onActiveCleared: () => {\n      // No clean \"no style picked\" state inside the planner today\n      // (kitchenStyleId always points at something). Leave the\n      // current style alone and just claim the action.\n      return true;\n    },\n    // Drawer's \"Add Buying Style N\" placeholder click. We capture\n    // the current ctx at click-time (via closure on `oldCtx`) and\n    // open the planner's style modal with a CUSTOM onApply so we\n    // can deterministically push the old ctx to alts after the\n    // standard handlers have written the new active ctx to\n    // sessionStorage. Avoids the flag-based path which was sensitive\n    // to multi-sync ordering during a single modal commit.\n    onAddBuyingStyleRequested: () => {\n      let oldCtx = null;\n      try { oldCtx = JSON.parse(sessionStorage.getItem('btk_kitchen_context') || 'null'); }\n      catch (_) { oldCtx = null; }\n      cabinetsHandle?.openStyleModal?.({\n        title: 'Add Buying Style',\n        onApply: (styleId, doorHandle) => {\n          // Standard planner-state update path - same as the\n          // default modal ctx. Writes the new active to\n          // sessionStorage via syncBuyingStyleToSession.\n          if (styleId && styleId !== kitchenStyleId) handleKitchenStyleChange(styleId);\n          if (doorHandle) handleSetGlobalDoorColour(doorHandle);\n          cabinetsHandle?.refresh?.();\n          // Now the new active ctx is in sessionStorage. Push the\n          // OLD ctx (captured at click-time) as an alt and reconcile\n          // slots so the drawer sees both styles on next open.\n          let newCtx = null;\n          try { newCtx = JSON.parse(sessionStorage.getItem('btk_kitchen_context') || 'null'); }\n          catch (_) {}\n          if (oldCtx && newCtx && (oldCtx.style !== newCtx.style || oldCtx.colour !== newCtx.colour)) {\n            pushBuyingStyleAlt(oldCtx, newCtx);\n            reconcileBuyingStyleSlots();\n            try { document.dispatchEvent(new CustomEvent('btk:style-changed', { detail: newCtx })); } catch (_) {}\n          }\n        },\n        onApplyCarcase: (carcaseHandle) => {\n          handleSetGlobalCarcaseColour(carcaseHandle);\n          cabinetsHandle?.refresh?.();\n        }\n      });\n    }\n  };\n\n  function handleSetFeatureStyle(key, value) {\n    if (!(key in DEFAULT_FEATURE_STYLES)) return;\n    featureStyles = { ...featureStyles, [key]: value };\n    // Re-render so the 3D trim moldings + basket Trim totals reflect\n    // the new style choice (or \"None\" hides them).\n    rerender();\n    scheduleBasketResync();\n  }\n  // One colour for a whole trim TYPE (plinth / cornice / pelmet), chosen in\n  // Customise > Cornice, Pelmet & Plinth; null = match the units each run is\n  // fitted to. Kept in featureStyles beside the profile ('plinthColour' ...)\n  // so it saves and reaches the 3D with it (Arden, 2026-10-06).\n  // The Cornice, Pelmet & Plinth popup's preview (Arden, 2026-10-06): a 500mm\n  // unit in the plan's kitchen style and colours - a WALL unit for cornice and\n  // pelmet, a BASE unit for plinth - wearing that one trim as chosen. A plain\n  // single-door unit is preferred so the trim, not the unit, is what reads.\n  // The range the plan's trims come from (Arden, 2026-10-13): Customise >\n  // Cornice, Pelmet & Plinth offers what can be fitted to the units ALREADY\n  // on the plan, not the active planning style - which is only what the next\n  // unit added will be, and can be another range entirely. So: the range most\n  // of the plan's units are in, with the door and carcase colour most of those\n  // units carry. Free-standing appliances and free-place panels have no trims\n  // of their own and don't count. An empty plan falls back to the active style.\n  function planTrimStyle() {\n    const tally = (arr) => {\n      const n = new Map();\n      for (const v of arr) if (v) n.set(v, (n.get(v) || 0) + 1);\n      let best = null, top = 0;\n      for (const [v, k] of n) if (k > top) { best = v; top = k; }\n      return best;\n    };\n    const units = cabinets.filter(c => c && c.kitchenStyleId && !c.freestandingAppliance\n      && !c.endPanelUnit && !c.endPanelFiller);\n    const styleId = tally(units.map(c => c.kitchenStyleId));\n    if (!styleId) return { styleId: kitchenStyleId, doorHandle: globalDoorColourHandle, carcaseHandle: globalCarcaseColourHandle };\n    const mine = units.filter(c => c.kitchenStyleId === styleId);\n    return {\n      styleId,\n      doorHandle:    tally(mine.map(c => c.doorColourHandle))    || globalDoorColourHandle,\n      carcaseHandle: tally(mine.map(c => c.carcaseColourHandle)) || globalCarcaseColourHandle\n    };\n  }\n  function trimPreviewCab(feature) {\n    const plan = planTrimStyle();\n    const styleId = plan.styleId;\n    if (!styleId || !Catalogue.getUnitTypes) return null;\n    const wall = feature !== 'plinth';\n    const prefer = wall ? ['SDW', 'SW', 'DDW'] : ['SB', 'SDB', 'DB'];\n    const rank = (u) => { const i = prefer.indexOf(String(u.code || '').toUpperCase()); return i < 0 ? 99 : i; };\n    const types = Catalogue.getUnitTypes()\n      .filter(u => u && u.isActive !== false && u.carcaseModelGlbUrl\n        && (wall ? /^wall/i : /^base/i).test(u.categoryHandle || ''))\n      .sort((a, b) => (rank(a) - rank(b)) || ((a.sortOrder ?? 999) - (b.sortOrder ?? 999)));\n    for (const ut of types) {\n      const info = Catalogue.findVariant?.({ unitTypeId: ut.id, kitchenStyleId: styleId, widthMm: 500 });\n      if (!info || info.widthMm !== 500 || !info.variant) continue;\n      const cab = cabinetsHandle?.unitThumbCab?.({ unitTypeId: ut.id, variantId: info.variant.id,\n        kitchenStyleId: styleId, doorColourHandle: plan.doorHandle, carcaseColourHandle: plan.carcaseHandle });\n      if (cab) return cab;\n    }\n    return null;\n  }\n  async function renderTrimPreview(feature, styles) {\n    if (!['plinth', 'cornice', 'pelmet'].includes(feature)) return null;\n    const cab = trimPreviewCab(feature);\n    if (!cab) return null;\n    try {\n      const h = await openingThumbnailRenderer();\n      if (!h || typeof h.renderTrimThumbnail !== 'function') return null;\n      // The trim being chosen - and on the wall unit BOTH the cornice and the\n      // pelmet, so the picture is the finished unit (Arden, 2026-10-07). A\n      // trim never chosen passes through unset, so the preview shows the\n      // range's default exactly as the plan does; only 'none' leaves it off.\n      const st = styles || {};\n      const fs = { cornice: 'none', pelmet: 'none', plinth: 'none' };\n      const shown = (feature === 'plinth') ? ['plinth'] : ['cornice', 'pelmet'];\n      for (const f of shown) {\n        fs[f] = (st[f] == null || st[f] === '') ? undefined : st[f];\n        fs[f + 'Colour'] = st[f + 'Colour'] || null;\n      }\n      if (feature === 'plinth') fs.plinthPosition = st.plinthPosition || 'proud';\n      return await h.renderTrimThumbnail(cab, fs, { width: 640, height: 640 });\n    } catch (e) {\n      console.warn('[BTK Planner] trim preview failed', e);\n      return null;\n    }\n  }\n\n  function handleSetTrimColour(feature, handle) {\n    if (!['plinth', 'cornice', 'pelmet'].includes(feature)) return;\n    featureStyles = { ...featureStyles, [feature + 'Colour']: handle || null };\n    rerender();\n    scheduleBasketResync();\n  }\n\n  // Handle hardware ---------------------------------------------------------\n  // Global default (Style & Colours) + per-cab override (selection\n  // panel). A patch of { designId?, finishHandle?, sizeMm? } merges\n  // into the target; the 3D renderer reads the RESOLVED handle per cab\n  // via effectiveHandle().\n  // Splashback / upstand settings: a `slotPatch` of the form\n  //   { upstand: { heightMm: 50 } }\n  // gets merged into the matching slot on roomConfig.splashbacks.\n  // The renderers (2D + 3D) pick the new value up on the next rerender.\n  function handleUpdateSplashbacks(slotPatch) {\n    const current = roomConfig.splashbacks || {};\n    const next = { ...current };\n    for (const key of Object.keys(slotPatch || {})) {\n      const val = slotPatch[key];\n      // Special-case the `overrides` slot - it's a MAP of per-section\n      // overrides keyed by slabId:wallIndex, not a single settings\n      // object. Passing `{ overrides: {} }` (or `null`) should\n      // REPLACE the whole map so callers can reset every section\n      // back to the kitchen-wide defaults in one go. Other slots\n      // (upstand / splashback / hobSplashback) keep merge semantics\n      // so partial patches don't drop unrelated fields.\n      if (key === 'overrides') {\n        next.overrides = val == null ? {} : val;\n      } else {\n        next[key] = { ...(current[key] || {}), ...val };\n      }\n    }\n    roomConfig = { ...roomConfig, splashbacks: next };\n    rerender();\n    // Glass & Metal Splashbacks shows these same settings, so it is redrawn\n    // whoever changed them - the Worktops popup takes a glass one off, and\n    // its tick box has to say so.\n    try { finishesHandle?.refresh?.(); } catch (e) {}\n  }\n\n  // Snap a group's finish/size onto ones the chosen design actually offers,\n  // so we never store an invalid combo. Mutates + returns the group object.\n  function snapHandleGroup(group) {\n    if (!group || !group.designId) return group;\n    const d = Catalogue.getHandleDesign(group.designId);\n    if (!d) return group;\n    const finishes = Catalogue.getHandleFinishesForDesign(group.designId);\n    const sizes    = Catalogue.getHandleSizesForDesign(group.designId);\n    if (!finishes.some(f => f.handle === group.finishHandle)) {\n      group.finishHandle = finishes[0]?.handle || null;\n    }\n    if (!sizes.includes(group.sizeMm)) {\n      group.sizeMm = sizes[0] ?? d.referenceSizeMm ?? null;\n    }\n    return group;\n  }\n\n  // Set one position group's handle (Base / Wall / Tall / Drawers). Choosing\n  // a group handle is the source of truth for every cab in that group, so it\n  // ALSO clears any per-cabinet overrides on those cabs - a later group pick\n  // overwrites individual tweaks by design (confirmed behaviour).\n  function handleSetGroupHandle(groupKey, patch) {\n    if (!HANDLE_GROUP_KEYS.includes(groupKey)) return;\n    handleGroups[groupKey] = snapHandleGroup({ ...handleGroups[groupKey], ...(patch || {}) });\n    let cleared = 0;\n    cabinets = cabinets.map(c => {\n      if (c.handle && Catalogue.handleGroupKey(c) === groupKey) { cleared++; return { ...c, handle: null }; }\n      return c;\n    });\n    rerender();\n    // The Style Setup stage shows these same groups, and the mood board shows\n    // one of them - so a pick made in the popup (from either stage) is\n    // reflected without the user having to leave and come back.\n    try { syncJourneyHandleFromGroups(); renderJourneyHandleGroups(); } catch (e) {}\n  }\n\n  // Back-compat shim: the OLD single-handle popup calls this. Apply the same\n  // handle to ALL four groups so its behaviour is unchanged until the new\n  // per-group popup lands (Stage 2).\n  function handleSetGlobalHandle(patch) {\n    for (const k of HANDLE_GROUP_KEYS) handleSetGroupHandle(k, patch);\n  }\n  // Supplying my own handles (row 79): this unit's handles stay on the plan\n  // but are left out of the basket's Handles line.\n  function handleSetCabinetOwnHandles(cabId, on) {\n    const idx = cabinets.findIndex(c => c.id === cabId);\n    if (idx === -1) return;\n    const next = { ...cabinets[idx] };\n    if (on) next.ownHandles = true; else delete next.ownHandles;\n    cabinets[idx] = next;\n    rerender();\n  }\n  function handleSetCabinetHandle(cabId, patch) {\n    const idx = cabinets.findIndex(c => c.id === cabId);\n    if (idx === -1) return;\n    const cab  = cabinets[idx];\n    const next = { ...(cab.handle || { designId: null, finishHandle: null, sizeMm: null }), ...(patch || {}) };\n    cabinets[idx] = { ...cab, handle: next };\n    rerender();\n  }\n  // Resolve a front's final handle spec: per-cab field wins, else the\n  // front's position-group default (frontType 'door'|'drawer'|'pan', or\n  // omitted for the whole-cab heuristic). Returns { design, finish, sizeMm,\n  // product } with resolved catalogue records, or null when no design is set.\n  function effectiveHandle(cab, frontType) {\n    const h = cab && cab.handle ? cab.handle : {};\n    const grp = handleGroups[Catalogue.handleGroupKey(cab, frontType)] || {};\n    const designId     = h.designId     || grp.designId;\n    if (!designId) return null;\n    const design = Catalogue.getHandleDesign(designId);\n    if (!design) return null;\n    const finishes = Catalogue.getHandleFinishesForDesign(designId);\n    const sizes    = Catalogue.getHandleSizesForDesign(designId);\n    const finishHandle = h.finishHandle || grp.finishHandle;\n    const finish = Catalogue.getHandleFinish(finishHandle)\n      || finishes[0] || null;\n    let sizeMm = (h.sizeMm != null) ? h.sizeMm : grp.sizeMm;\n    if (!sizes.includes(sizeMm)) {\n      sizeMm = sizes[0] ?? design.referenceSizeMm ?? null;\n    }\n    // The sellable product for this exact pick - carries variantId +\n    // price for the cart (future). null if the combo isn't stocked.\n    const product = (finish)\n      ? Catalogue.getHandleProduct(designId, finish.handle, sizeMm)\n      : null;\n    return { design, finish, sizeMm, product };\n  }\n\n  styleColoursHandle = initStyleColoursUI(sidebar, {\n    Catalogue,\n    getCabinets:            () => cabinets,\n    getSelectedCabinetIds:  () => [...selectedCabinetIds],\n    onApplyStyleToIds:      handleApplyStyleToIds,\n    // Door colour for picked PARTS (ends, back panels) - see handleSetPartColours.\n    onSetPartColours:       handleSetPartColours,\n    // The plan's item numbers for parts, to label them on the popup's plan.\n    getEndPanelLayout:      () => endPanelLayout,\n    // Re-use the cabinets-module modal for the row-scoped Change\n    // action; the restyle module passes overrides in so Select +\n    // carcase pick apply to the row's cabinet IDs, not the global\n    // default for next-added units.\n    openStyleModal:         (opts) => cabinetsHandle.openStyleModal(opts),\n    // Worktop material picker - plan-wide material, chosen from the\n    // Customise stage's Worktops popup.\n    getWorktopMaterialOptions: () => rangeWorktopMaterials(),\n    getWorktopMaterialHandle:  () => worktopMaterialForSlab(),\n    onSetWorktopMaterial:      handleSetWorktopMaterial,\n    // Which handle buttons Customise shows while no unit is placed yet.\n    getKitchenStyleId:         () => kitchenStyleId,\n    // The room outline for the Door & Carcase unit selector.\n    getRoomVertices:           () => (room && room.vertices) || [],\n    // The shared kitchen-style cards, for that popup's Change Kitchen Style.\n    renderStyleCards:          (el, opts) => renderStyleCardsInto(el, opts)\n  });\n\n  // The Worktops popup (Customise > Worktops): material + every feature it\n  // allows, a plan / cut list view, and the bespoke job options. It owns\n  // nothing - state and pricing stay here.\n  worktopsPopupHandle = initWorktopsPopup(root.querySelector('[data-btk-kp-popup=\"worktop\"]'), {\n    Catalogue,\n    getMaterialOptions: () => rangeWorktopMaterials(),\n    getMaterialHandle:  () => worktopTargetHandle() || worktopMaterialForSlab(),\n    setMaterial:        (h) => ((worktopTarget && worktopPopupOpen())\n      ? handleSetUnitsWorktop(worktopTarget.cabIds, h) : handleSetWorktopMaterial(h, 'all')),\n    // Choosing for part of the plan: what for, and the plan's own worktop.\n    getTarget:          () => ((worktopTarget && worktopPopupOpen()) ? { label: worktopTarget.label,\n      own: (cabinets || []).some(c => c && worktopTarget.cabIds.includes(c.id) && c.worktopMaterialHandle) } : null),\n    getSlabs:           () => {\n      // Stitched, so \"N worktops\" matches the sections on the drawing.\n      try { return mergeCornerRuns(buildWorktops() || []); } catch (e) { return []; }\n    },\n    getBespokeJob:      () => bespokeJob(),\n    getCharges:         () => computeWorktopCharges(),\n    getEdgingNeed:      (handle) => worktopEdgingNeed(handle),\n    // Sections no stock board is wide enough for: missing from the drawing,\n    // the Cutting Plan and the price, so the popup has to say so.\n    getUnpriced:        () => {\n      computeWorktopCharges();                  // refreshes lastUnpriced\n      const h = worktopMaterialForSlab();\n      return (lastUnpriced && lastUnpriced.handle === h) ? lastUnpriced : null;\n    },\n    getCutList:         () => worktopCutList().filter(b => !b.kind),\n    getPlanCounts:      (slabs) => worktopPlanCounts(slabs),\n    getBespokeOptions:  () => worktopBespoke,\n    setBespokeOptions:  (patch) => {\n      worktopBespoke = normaliseBespokeOptions({ ...worktopBespoke, ...(patch || {}) });\n      rerender();\n    },\n    drawPiece:          cutListPieceSVG,\n    edgeKey:            CUTLIST_EDGE,\n    curveWarning:       () => (isPostformedMaterial(worktopMaterialForSlab()) && planHasCurvedWorktop())\n                               ? { title: BULLNOSE_CURVE_TITLE, text: BULLNOSE_CURVE_TEXT } : null,\n    // Extras & Accessories: into the plan's Extras, totalled with the worktops.\n    addAccessory:       (item) => addExtraToBasket(item, 'Worktops'),\n    // Upstands & splashbacks - the same kitchen-wide settings the plan draws\n    // from (roomConfig.splashbacks), so choosing one here draws it.\n    getSplashbackSettings: () => roomConfig.splashbacks || {},\n    isWorktopHeatSafe: () => planWorktopHeatSafe(),\n    setSplashbacks:     (patch) => handleUpdateSplashbacks(patch),\n    getSplashbackStrips: (settings) => splashbackStripsFor(null, settings),\n    // The room outline, for the Worktop Plan drawing: the worktops read as a\n    // kitchen rather than blocks on a page.\n    getRoomVertices:    () => (room && room.vertices) || [],\n    // The worktops as the pieces they are cut into, for that same drawing.\n    getWorktopPieces:   () => worktopPlanPieces(),\n    getWaterfalls:      () => worktopWaterfallList(),\n    // And the joint between each pair of them, so the drawing shows how they\n    // meet: a mason's mitre where the material takes one, otherwise a butt.\n    getWorktopJoints:   () => worktopPlanJoints(),\n    // Window boards set to \"Match Worktop\": [{ id, n, lengthMm, depthMm }].\n    getWindowCills:     () => windowCills(),\n    // Windows the worktop itself runs into (Worktop in to Window): [{ id, n }],\n    // numbered the way the cills are.\n    getWorktopWindows:  () => {\n      const into = new Set();\n      for (const s of (buildWorktops() || [])) for (const t of (s.windowTabs || [])) into.add(t.openingId);\n      const out = [];\n      let n = 0;\n      for (const op of (roomConfig.wallOpenings || [])) {\n        if (!op || op.type !== 'window') continue;\n        n++;\n        if (into.has(op.id)) out.push({ id: op.id, n });\n      }\n      return out;\n    },\n    // Every window on the plan, so the popup can tell \"none set to match the\n    // worktop\" from \"there are no windows\".\n    getWindowCount:     () => (roomConfig.wallOpenings || []).filter(o => o && o.type === 'window').length,\n    // A board's matching upstand / splashback: the product it is bought as,\n    // kept with the plan and priced with the worktops.\n    getWorktopParts:    () => worktopParts,\n    setWorktopPart:     (part, info) => {\n      if (part !== 'upstand' && part !== 'splashback' && part !== 'edging') return;\n      // Idempotent, so it is safe to call while rendering. Edging is not\n      // chosen by anyone - it is required - so the popup registers its product\n      // as soon as the accessories are known, which is on a render path. An\n      // unconditional rerender() there would recurse for ever.\n      const cur = worktopParts[part] || null;\n      const next = info || null;\n      if (!cur && !next) return;\n      if (cur && next && cur.variantId === next.variantId\n          && cur.priceCents === next.priceCents && cur.lengthMm === next.lengthMm) return;\n      worktopParts = { ...worktopParts, [part]: next };\n      rerender();\n    },\n    // \"I am buying my worktops elsewhere\": drawn on the plan, never charged.\n    getWorktopsNotPriced: () => worktopsNotPriced,\n    setWorktopsNotPriced: (on) => { worktopsNotPriced = !!on; rerender(); },\n    // Why a worktop cannot go on this plan (a faced laminate with an undermount\n    // or Belfast sink), or null - the picker greys it out.\n    worktopSinkBlock: (handle) => worktopSinkBlock(handle, (worktopTarget && worktopPopupOpen()) ? worktopTarget.cabIds : undefined),\n  });\n\n  // The project's postcode picks a bespoke worktop's templating zone - or makes\n  // the job Price on Request when its area is in no zone. The page was rendered\n  // for whoever is signed in to the shop (for staff, the salesperson or\n  // nobody), so its customerPostcode is not to be trusted: the basket API asks\n  // the planner API for the customer's own (typed in the basket, else their\n  // Shopify address, else their Odoo contact) and announces every change\n  // typed into the basket's delivery card (Arden, 2026-10-12: a customer in\n  // Edinburgh was quoted at the cheapest zone).\n  function applyCustomerPostcode(postcode) {\n    const raw = window.BTKKitchenCatalogue;\n    if (!raw) return;\n    const next = postcode || null;\n    if (raw.customerPostcode === next) return;\n    raw.customerPostcode = next;\n    rerender();\n    if (worktopsPopupHandle) worktopsPopupHandle.refreshIfOpen();\n    refreshQuoteLocally();\n  }\n  // The basket's Request a Price went to our team: keep it with the plan, so\n  // the basket says so after every rebuild and reload (worktopBespoke.requested).\n  window.__btkPlannerWorktopPriceRequested = (key, at, ticket) => {\n    worktopBespoke = normaliseBespokeOptions({ ...worktopBespoke, requested: { key: String(key || ''), at: String(at || ''), ticket: String(ticket || '') } });\n    rerender();\n    refreshQuoteLocally();\n  };\n  // ...and Order Kitchen Now, Worktop to Follow (key '' = back to waiting for\n  // the price before checkout).\n  window.__btkPlannerWorktopDeferred = (key, at) => {\n    worktopBespoke = normaliseBespokeOptions({ ...worktopBespoke,\n      deferred: key ? { key: String(key), at: String(at || '') } : null });\n    rerender();\n    refreshQuoteLocally();\n  };\n  function loadCustomerPostcode() {\n    window.addEventListener('btk:postcode:changed', (e) => applyCustomerPostcode(e && e.detail && e.detail.postcode));\n    const api = window.BTKBasketAPI;\n    if (!api || typeof api.getPostcode !== 'function') return;\n    // Never the salesperson's own, even before the customer's arrives.\n    if (typeof api.isStaffMode === 'function' && api.isStaffMode() && window.BTKKitchenCatalogue) {\n      window.BTKKitchenCatalogue.customerPostcode = null;\n    }\n    api.getPostcode().then(found => { if (found && found.postcode) applyCustomerPostcode(found.postcode); })\n      .catch(() => {});\n  }\n  loadCustomerPostcode();\n\n  // LEG PACK for Make Base Unit: the 150mm Cabinet Leg Pack - Screw On - Set\n  // of 4, one per converted unit. Read once, then the plan is priced again.\n  const LEG_PACK_HANDLE = '150mm-cabinet-leg-pack-screw-on-set-of-4';\n  (async function loadLegPack() {\n    try {\n      const p = await (await fetch('/products/' + LEG_PACK_HANDLE + '.js')).json();\n      const v = (p.variants || []).find(x => x.available !== false) || (p.variants || [])[0];\n      if (!v) return;\n      window.BTKLegPack = { variantId: v.id, title: p.title, variantTitle: v.title, priceCents: v.price,\n        compareAtCents: v.compare_at_price || null, handle: p.handle };\n      if ((cabinets || []).some(c => c && c.asBase)) { rerender(); refreshQuoteLocally(); }\n    } catch (e) { /* no leg pack offered */ }\n  })();\n\n  // FITTERS PANEL for the Worktop Pantry Unit (row 142): the 2400 x 610\n  // variant of the store's Fitters Panel, as many as the unit's parts need.\n  (async function loadFittersPanel() {\n    try {\n      const p = await (await fetch('/products/' + FITTERS_PANEL.handle + '.js')).json();\n      const v = (p.variants || []).find(x => String(x.title || '').replace(/\\s+/g, '') === FITTERS_PANEL.variantTitle.replace(/\\s+/g, ''));\n      if (!v) return;\n      window.BTKFittersPanel = { variantId: v.id, title: p.title, variantTitle: v.title, priceCents: v.price,\n        compareAtCents: v.compare_at_price || null, handle: p.handle };\n      if ((cabinets || []).some(isPantryCab)) { rerender(); refreshQuoteLocally(); }\n    } catch (e) { /* no fitters panel offered */ }\n  })();\n\n  // ACOUSTIC PANELLING (Arden, 2026-10-21): the finishes on offer for a\n  // breakfast bar back are the Slatted Acoustic Wall Panels on the store - one\n  // product per finish (Oak, Walnut), each with a \"Single Panel\" and a \"2 x\n  // Panels\" variant. Read once, then the plan is priced again.\n  (async function loadAcousticPanels() {\n    try {\n      const r = await fetch('/search/suggest.json?q=' + encodeURIComponent('Slatted Acoustic Wall Panels')\n        + '&resources[type]=product&resources[limit]=10');\n      const j = await r.json();\n      const found = ((j.resources && j.resources.results && j.resources.results.products) || [])\n        .filter(p => /acoustic/i.test(p.title || '') && /slat/i.test(p.title || ''));\n      const out = [];\n      for (const f of found) {\n        const p = await (await fetch('/products/' + f.handle + '.js')).json();\n        const v = (p.variants || []).filter(x => x.available !== false);\n        const pick = (re) => v.find(x => re.test(x.title || '')) || null;\n        const asV = (x) => x ? { id: x.id, title: x.title, priceCents: x.price, compareAtCents: x.compare_at_price || null } : null;\n        const finish = String(p.title || '').split(' - ').slice(1).join(' - ') || p.title;\n        const wood = /walnut/i.test(finish) ? 'Walnut' : /oak/i.test(finish) ? 'Oak' : finish;\n        out.push({ handle: p.handle, title: p.title, finish, label: wood,\n                   hex: /walnut/i.test(finish) ? '#5E4330' : '#C49A6C',\n                   image: p.featured_image ? (String(p.featured_image).replace(/^\\/\\//, 'https://')) : null,\n                   single: asV(pick(/single/i) || v.find(x => !/2\\s*x/i.test(x.title || ''))),\n                   pair: asV(pick(/2\\s*x/i)) });\n      }\n      window.BTKAcousticPanels = out;\n      if (out.length && (cabinets || []).some(c => c && c.breakfastBarBack && c.breakfastBarBack.finish === 'acoustic')) {\n        rerender();\n        refreshQuoteLocally();\n      }\n    } catch (e) { /* no acoustic finish offered */ }\n  })();\n\n  // Freestanding appliance (wine cooler, USA fridge, freestanding fridge /\n  // dishwasher / washer\u2026) \u2192 placed on the plan as a draggable footprint box\n  // for manual placing. Reuses the furniture-item machinery: 2D draws a\n  // labelled box from widthMm/depthMm; 3D renders the GLB when present and\n  // safely skips it otherwise (renderer guards a missing glbUrl).\n  function handleAddFreestandingAppliance(appliance) {\n    if (!appliance) return;\n    if (isCanopyExtractor(appliance)) { handleAddCanopy(appliance); return; }\n    if (isFreestandingWineCooler(appliance)) { handleAddWineCooler(appliance); return; }\n    if (isSoldFreestandingCooker(appliance)) { handleAddFreestandingCooker(appliance); return; }\n    if (isWallExtractor(appliance)) { handleAddExtractor(appliance); return; }\n    const fp = appliance.footprint;\n    if (!fp || !fp.wMm) {\n      designControlsHandle.setStatus(`\u201C${appliance.title || 'Appliance'}\u201D has no footprint size set (appliance_footprint)`);\n      return;\n    }\n    const w = fp.wMm, d = fp.dMm || 600;\n    const bbox = getBoundingBox(room);\n    const spot = findFreeSpotForFurniture(\n      w, d,\n      bbox.minX + bbox.widthMm  / 2,\n      bbox.minY + bbox.heightMm / 2,\n      null\n    );\n    furnitureItems.push({\n      id:          `fur-${nextFurnitureItemId++}`,\n      name:        appliance.title || appliance.handle,\n      applianceHandle: appliance.handle,\n      glbUrl:      appliance.glbUrl || null,\n      widthMm:     w,\n      depthMm:     d,\n      heightMm:    fp.hMm || null,\n      x:           spot.x,\n      y:           spot.y,\n      rotationDeg: 0\n    });\n    // Keep the user on the canvas so they can drag it into place. Stay in 2D\n    // if that's the view (footprint box); only rerender in 3D if already there.\n    if (viewMode === '2d' || viewMode === '3d') rerender();\n    else setViewMode('2d');\n    designControlsHandle.setStatus(`Added ${appliance.title || 'appliance'} - drag it into place`);\n    const popup = root.querySelector('[data-btk-kp-popup=\"add-appliances\"]');\n    if (popup) popup.hidden = true;\n  }\n\n  // ---- Wine coolers (freestanding appliances we sell) --------------------\n  // A wine cooler stands in the base run like a built-under freestanding\n  // appliance - an end panel each side with the 5mm fitting gap, the worktop\n  // over it at 870 (Arden, 2026-10-12) - so it IS a freestanding-appliance cab\n  // (code \"wine-cooler\", kind built-under), but backed by its product\n  // (freestandingAppliance.productHandle): it takes a plan number and a priced\n  // basket line, and counts in the totals through its own priceCents. Width is\n  // the product's nominal size less 5 (a \"600mm\" cooler is 595 wide). One fitted\n  // INTO a housing (an appliance_aperture, e.g. the 45cm-high built-in) is not\n  // this - it goes through Choose Housing like an oven.\n  // 600 deep: a built-under appliance is planned at a carcase's depth PLUS a\n  // door (it has no door of ours), which is how the worktop engine reads it -\n  // at 570 the worktop stepped back 30mm over the cooler (Arden, 2026-10-12).\n  const WINE_COOLER_HEIGHT_MM = 870, WINE_COOLER_DEPTH_MM = 600;\n  function isFreestandingWineCooler(a) {\n    return !!a && /wine-cooler/i.test(String(a.category || '')) && a.apertureHMm == null;\n  }\n  function handleAddWineCooler(appliance) {\n    const sizeText = [].concat((appliance.facets && appliance.facets.size) || []).join(' ') + ' ' + (appliance.title || '');\n    const mmM = /(\\d+)\\s*mm/i.exec(sizeText), cmM = /(\\d+)\\s*cm(?!\\s*high)/i.exec(sizeText);\n    const nominal = mmM ? Number(mmM[1]) : (cmM ? Number(cmM[1]) * 10 : 600);\n    const w = Math.max(100, nominal - 5), d = WINE_COOLER_DEPTH_MM, h = WINE_COOLER_HEIGHT_MM;\n    const title = String(appliance.title || '');\n    const finish = /black/i.test(title) ? 'black' : /stainless|steel|silver/i.test(title) ? 'stainless' : 'black';\n    const bbox = getBoundingBox(room);\n    const stagger = (cabinets.length % CABINET_STAGGER_WRAP) * CABINET_STAGGER_MM;\n    const cab = {\n      id:             `cab-wc-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 5)}`,\n      unitTypeId:     'FSA-wine-cooler',\n      variantId:      null,\n      kitchenStyleId: null,\n      code:           title || 'Wine cooler',\n      name:           title || 'Wine cooler',\n      priceCents:     (typeof appliance.priceCents === 'number') ? appliance.priceCents : 0,\n      widthMm: w, depthMm: d, heightMm: h,\n      plinthHeightMm: 0,\n      category:       'base-units',\n      x: bbox.minX + bbox.widthMm / 2 - w / 2 + stagger,\n      y: bbox.minY + bbox.heightMm / 2 - d / 2 + stagger,\n      rotationDeg:    0,\n      excludeFromQuote: false,\n      stackOn:        null,\n      freestandingAppliance: {\n        code: 'wine-cooler', kind: 'built-under', stackable: false,\n        colour: finish, hinge: null,\n        productHandle: appliance.handle || null,\n        twinDoor: /twin door/i.test(title)\n      },\n      stackTrim: { plinth: true, worktop: true, cornice: false },\n      endPanelGapMm: FSA_END_PANEL_GAP_MM,\n      endPanels: { left:  { active: false, style: 'flat', inline: false, pelmetExt: 'modern' },\n                   right: { active: false, style: 'flat', inline: false, pelmetExt: 'modern' } },\n      fillers:   { left:  { active: false, widthMm: 20, setBackMm: 0 },\n                   right: { active: false, widthMm: 20, setBackMm: 0 } }\n    };\n    cabinets.push(cab);\n    renumberAllCabinets();\n    designControlsHandle.setStatus(`Added ${title || 'wine cooler'} - drag it into the run`);\n  }\n\n  // ---- Freestanding cookers we sell (CDA CFD600MB / CFC6100MB) ------------\n  // Drawn as the planning-only RANGE COOKER block at the cooker's own size\n  // (Arden, 2026-10-12): the gas or electric block (from \"Gas Hob\" in the\n  // name), its front scaled to 600 and its own hob top, between end panels\n  // with the fitting gap and no worktop over it. Backed by its product like a\n  // wine cooler (freestandingAppliance.productHandle), so it is numbered,\n  // priced and on the basket.\n  function isSoldFreestandingCooker(a) {\n    return !!a && a.placement === 'freestanding' && /cooker/i.test(String(a.title || ''))\n      && /oven/i.test(String(a.category || ''));\n  }\n  function handleAddFreestandingCooker(appliance) {\n    const title = String(appliance.title || '');\n    const gas = /gas/i.test(title);\n    const cm = /(\\d{2,3})\\s*cm\\b/i.exec(title);\n    const w = cm ? Number(cm[1]) * 10 : 600, d = 600, h = 900;\n    const bbox = getBoundingBox(room);\n    const stagger = (cabinets.length % CABINET_STAGGER_WRAP) * CABINET_STAGGER_MM;\n    const cab = {\n      id:             `cab-ck-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 5)}`,\n      unitTypeId:     gas ? 'FSA-range-cooker-gas' : 'FSA-range-cooker-electric',\n      variantId:      null,\n      kitchenStyleId: null,\n      code:           title || 'Cooker',\n      name:           title || 'Cooker',\n      priceCents:     (typeof appliance.priceCents === 'number') ? appliance.priceCents : 0,\n      widthMm: w, depthMm: d, heightMm: h,\n      plinthHeightMm: 0,\n      category:       'base-units',\n      x: bbox.minX + bbox.widthMm / 2 - w / 2 + stagger,\n      y: bbox.minY + bbox.heightMm / 2 - d / 2 + stagger,\n      rotationDeg:    0,\n      excludeFromQuote: false,\n      stackOn:        null,\n      freestandingAppliance: {\n        code: gas ? 'range-cooker-gas' : 'range-cooker-electric', kind: 'range', stackable: false,\n        colour: /black|mb\\b/i.test(title) ? 'black' : 'stainless', hinge: null,\n        productHandle: appliance.handle || null\n      },\n      stackTrim: { plinth: true, worktop: false, cornice: false },\n      endPanelGapMm: FSA_END_PANEL_GAP_MM,\n      endPanels: { left:  { active: false, style: 'flat', inline: false, pelmetExt: 'modern' },\n                   right: { active: false, style: 'flat', inline: false, pelmetExt: 'modern' } },\n      fillers:   { left:  { active: false, widthMm: 20, setBackMm: 0 },\n                   right: { active: false, widthMm: 20, setBackMm: 0 } }\n    };\n    cabinets.push(cab);\n    renumberAllCabinets();\n    designControlsHandle.setStatus(`Added ${title || 'cooker'} - drag it into the run`);\n  }\n\n  // ---- Built-under double oven (CDA DC741BL) ------------------------------\n  // It has no housing (Arden, 2026-10-12): it stands in the base run between\n  // the units either side, 600 wide and 720 tall ON the plinth, under the\n  // worktop - fixed to a pair of Under Counter Oven Fitting Panels screwed to\n  // those units' sides (MFCUC, 715 x 100 x 18mm, one shared product). So it is\n  // a sold freestanding-appliance cab with a 570 footprint like a base unit -\n  // the plinth (trim: onPlinth) and the worktop run straight across it - its\n  // front on the door line, no end panels of its own, and the fitting panels\n  // billed as a second line at the next plan number.\n  const FITTING_PANELS_UNIT_TYPE = 'under-counter-oven-fitting-panels';\n  function isSoldBuiltUnderDouble(a) {\n    return !!a && /oven/i.test(String(a.category || ''))\n      && typeof a.apertureHMm === 'number' && a.apertureHMm >= 700 && a.apertureHMm <= 760;\n  }\n  // The fitting-panel pair for a cab that needs one: { variantId, title, priceCents, compareAtCents }.\n  function fittingKitFor(c) {\n    if (!(c && c.freestandingAppliance && c.freestandingAppliance.fittingPanels)) return null;\n    if (c.excludeFromQuote) return null;\n    const style = c.kitchenStyleId || kitchenStyleId || null;\n    const product = Catalogue.getProductForUnitInStyle ? Catalogue.getProductForUnitInStyle(FITTING_PANELS_UNIT_TYPE, style) : null;\n    const v = product && product.variants && product.variants[0];\n    if (!v) return null;\n    const info = Catalogue.getVariantInfo ? Catalogue.getVariantInfo(v.id) : null;\n    const priceCents = (info && typeof info.priceCents === 'number') ? info.priceCents : (typeof v.price === 'number' ? v.price : 0);\n    const compareAtCents = (info && typeof info.compareAtCents === 'number') ? info.compareAtCents : null;\n    return { variantId: v.id, title: product.title || 'Under Counter Oven Fitting Panels', handle: product.handle || null, priceCents, compareAtCents };\n  }\n  function handleAddBuiltUnderDouble(appliance) {\n    const title = String(appliance.title || '');\n    const w = 600, d = 570, h = 870;\n    const bbox = getBoundingBox(room);\n    const stagger = (cabinets.length % CABINET_STAGGER_WRAP) * CABINET_STAGGER_MM;\n    const cab = {\n      id:             `cab-bdo-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 5)}`,\n      unitTypeId:     'FSA-built-under-double-oven',\n      variantId:      null,\n      kitchenStyleId: kitchenStyleId || null,\n      code:           title || 'Built-under double oven',\n      name:           title || 'Built-under double oven',\n      priceCents:     (typeof appliance.priceCents === 'number') ? appliance.priceCents : 0,\n      widthMm: w, depthMm: d, heightMm: h,\n      plinthHeightMm: 150,\n      category:       'base-units',\n      x: bbox.minX + bbox.widthMm / 2 - w / 2 + stagger,\n      y: bbox.minY + bbox.heightMm / 2 - d / 2 + stagger,\n      rotationDeg:    0,\n      excludeFromQuote: false,\n      stackOn:        null,\n      freestandingAppliance: {\n        code: 'built-under-double-oven', kind: 'built-under-oven', stackable: false,\n        colour: 'black', hinge: null,\n        productHandle: appliance.handle || null,\n        onPlinth: true, fillsOpening: true, fittingPanels: true, panelsCleared: true\n      },\n      stackTrim: { plinth: true, worktop: true, cornice: false },\n      endPanelGapMm: 0,\n      endPanels: { left:  { active: false, style: 'flat', inline: false, pelmetExt: 'modern' },\n                   right: { active: false, style: 'flat', inline: false, pelmetExt: 'modern' } },\n      fillers:   { left:  { active: false, widthMm: 20, setBackMm: 0 },\n                   right: { active: false, widthMm: 20, setBackMm: 0 } }\n    };\n    cabinets.push(cab);\n    renumberAllCabinets();\n    designControlsHandle.setStatus(`Added ${title || 'built-under double oven'} with its fitting panels - drag it into the base run`);\n  }\n\n  // ---- Free-standing appliances (planning only) ------------------------\n  // Appliances we don't sell but a customer has to plan round - American\n  // fridge, tall fridge / freezer, and the built-under washer, dryer and\n  // dishwasher. Each is a PRODUCT-LESS UNIT, so it snaps to walls and runs,\n  // collides, rotates and stacks like any unit, and a built-under one sits in\n  // a run with the worktop running over it. What it never gets: plinth,\n  // cornice, end panels, fillers, door fronts, a number, or a basket line\n  // (excludeFromQuote - there is nothing to buy). Size limits, stackability\n  // and the GLB are read from the catalogue by code at use, so editing the\n  // metaobject reaches plans already saved.\n  // The gap a freestanding appliance stands off its end panels, as fitted.\n  const FSA_END_PANEL_GAP_MM = 5;\n\n  function planApplianceEntry(cab) {\n    const code = cab && cab.freestandingAppliance && cab.freestandingAppliance.code;\n    return code ? (Catalogue.getFreestandingAppliance?.(code) || null) : null;\n  }\n\n  // `cfg` is what the popup was set to before placing - size, colour and\n  // whether it goes straight onto another appliance. Sizes are clamped to the\n  // entry's ranges here too, so a stale popup can never place an impossible\n  // appliance.\n  function handleAddPlanAppliance(entry, cfg = {}) {\n    const cab = planApplianceCab(entry, cfg);\n    if (!cab) return;\n    cabinets.push(cab);\n    rerender();\n    designControlsHandle.setStatus(`Added ${entry.name} - drag it into place`);\n    const popup = root.querySelector('[data-btk-kp-popup=\"add-appliances\"]');\n    if (popup) popup.hidden = true;\n  }\n\n  // The product-less unit a free standing appliance places as (the popup, and\n  // the Island Designer's Free Standing units).\n  function planApplianceCab(entry, cfg = {}) {\n    if (!entry || !entry.code) return null;\n    const lim = entry.limits || {};\n    const sized = (key) => {\n      const r = lim[key], v = Number(cfg[key]);\n      if (!r || !Number.isFinite(v)) return entry[key];\n      return Math.max(r.min, Math.min(r.max, Math.round(v)));\n    };\n    const w = sized('widthMm'), d = sized('depthMm'), h = sized('heightMm');\n    // Built-under sits under the worktop; a range cooker stands in the same\n    // band but carries its own top, and a tall appliance stands on its own.\n    const builtUnder = entry.kind === 'built-under';\n    const tall       = entry.kind === 'tall';\n    const stacked    = !!cfg.stacked && !!entry.stackable;\n    const colour     = cfg.colour || entry.defaultColour || 'white';\n    // No end panels when placed: the user adds them in End Panels & Fillers,\n    // and the auto walk leaves them alone. Any panel added stands a gap off it\n    // so it can be pulled out (5mm as fitted, set in the popup).\n    const gapMm = Math.max(0, Math.min(50, Math.round(Number(cfg.gapMm ?? FSA_END_PANEL_GAP_MM))));\n    const bbox = getBoundingBox(room);\n    const stagger = (cabinets.length % CABINET_STAGGER_WRAP) * CABINET_STAGGER_MM;\n    const cab = {\n      id:             `cab-fsa-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 5)}`,\n      unitTypeId:     `FSA-${entry.code}`,\n      variantId:      null,\n      kitchenStyleId: null,\n      code:           entry.name,     // the plan label's first line\n      name:           entry.name,\n      priceCents:     0,\n      widthMm:        w,\n      depthMm:        d,\n      heightMm:       h,\n      plinthHeightMm: 0,\n      // Tall stands in the tall band; built-under and range in the base band,\n      // so they line up in a run - only built-under takes the worktop.\n      category:       tall ? 'tall-units' : 'base-units',\n      x:              bbox.minX + bbox.widthMm  / 2 - w / 2 + stagger,\n      y:              bbox.minY + bbox.heightMm / 2 - d / 2 + stagger,\n      rotationDeg:    0,\n      excludeFromQuote: true,\n      stackOn:        stacked ? 'appliance' : null,\n      freestandingAppliance: {\n        code:      entry.code,\n        kind:      entry.kind,\n        stackable: !!entry.stackable,\n        colour,\n        // Left / right hinged, as seen from in front - only where offered.\n        hinge:     entry.hingeSelectable ? (cfg.hinge === 'left' ? 'left' : 'right') : null\n      },\n      stackTrim: { plinth: true, worktop: builtUnder && !stacked, cornice: false },\n      endPanelGapMm: gapMm,\n      endPanels: { left:  { active: false, style: 'flat', inline: false, pelmetExt: 'modern' },\n                   right: { active: false, style: 'flat', inline: false, pelmetExt: 'modern' } },\n      fillers:   { left:  { active: false, widthMm: 20, setBackMm: 0 },\n                   right: { active: false, widthMm: 20, setBackMm: 0 } }\n    };\n    return cab;\n  }\n\n  // Finish - one of the planner_appliance_colour codes.\n  function handleSetPlanApplianceColour(cabId, colourCode) {\n    const idx = cabinets.findIndex(c => c.id === cabId);\n    if (idx === -1 || !cabinets[idx].freestandingAppliance) return;\n    const cab = cabinets[idx];\n    cabinets[idx] = { ...cab, freestandingAppliance: { ...cab.freestandingAppliance, colour: colourCode } };\n    rerender();\n    if (selectionPanelHandle && typeof selectionPanelHandle.refresh === 'function') {\n      selectionPanelHandle.refresh();\n    }\n  }\n\n  // Left / right hinged doors, for the appliances that offer the choice.\n  function handleSetPlanApplianceHinge(cabId, side) {\n    const idx = cabinets.findIndex(c => c.id === cabId);\n    if (idx === -1 || !cabinets[idx].freestandingAppliance) return;\n    if (side !== 'left' && side !== 'right') return;\n    const cab = cabinets[idx];\n    cabinets[idx] = { ...cab, freestandingAppliance: { ...cab.freestandingAppliance, hinge: side } };\n    rerender();\n    if (selectionPanelHandle && typeof selectionPanelHandle.refresh === 'function') {\n      selectionPanelHandle.refresh();\n    }\n  }\n\n  // What a stackable appliance stands on: the floor (null), another stackable\n  // appliance ('appliance'), or a half-height base unit ('half-base' - bug\n  // sheet, Planner row 62: a washing machine raised on a pan drawer unit).\n  // `mode` true is 'appliance', for older callers. A stacked appliance carries\n  // no worktop - there is no slab at the top of a washer-dryer tower - and\n  // gets it back when taken down.\n  function handleSetPlanApplianceStacked(cabId, mode) {\n    const idx = cabinets.findIndex(c => c.id === cabId);\n    if (idx === -1) return;\n    const cab = cabinets[idx];\n    const fa = cab.freestandingAppliance;\n    if (!fa || !fa.stackable) return;\n    const next = mode === true ? 'appliance' : (isApplianceStackMode(mode) ? mode : null);\n    const builtUnder = fa.kind === 'built-under';\n    cabinets[idx] = {\n      ...cab,\n      stackOn: next,\n      stackTrim: { ...(cab.stackTrim || {}), plinth: true, worktop: builtUnder && !next }\n    };\n    rerender();\n    if (selectionPanelHandle && typeof selectionPanelHandle.refresh === 'function') {\n      selectionPanelHandle.refresh();\n    }\n  }\n\n  // Add Furniture picker (Customise \u2192 Add Furniture popup). Phase 1 is\n  // the picker only; onAddFurniture is a placeholder until placement\n  // (Phase 2) is wired.\n  function handleAddFurniture(item, choice = {}) {\n    if (!item) return;\n    if (!item.glbUrl && !item.kind) {\n      designControlsHandle.setStatus(`\u201C${item.name}\u201D has no 3D model (furniture_glb) yet`);\n      return;\n    }\n    const bbox = getBoundingBox(room);\n    const sz   = furnitureSizeCache[item.id] || {};\n    const sized = choice.size ? { w: choice.size.w, d: choice.size.d, h: choice.size.h } : null;\n    const w = (sized && sized.w) || sz.w || 500, h = (sized && sized.d) || sz.d || 500;     // footprint (cached if seen before)\n    const onSurface = item.placement === 'surface' ? worktopSpotForFurniture() : null;\n    // A shelf starts on a wall: behind the longest worktop, else the one nearest the room's middle.\n    const onWall = (item.placement === 'wall' || item.kind === 'bed')\n      ? wallSpotForFurniture(w, h, choice.size && choice.size.f, worktopSpotForFurniture() || { x: bbox.minX + bbox.widthMm / 2, y: bbox.minY + bbox.heightMm / 2 })\n      : null;\n    const spot = onSurface || onWall || findFreeSpotForFurniture(   // avoid landing inside other items\n      w, h,\n      bbox.minX + bbox.widthMm  / 2,            // prefer the room centre\n      bbox.minY + bbox.heightMm / 2,\n      null\n    );\n    furnitureItems.push({\n      id:          `fur-${nextFurnitureItemId++}`,\n      furnitureId: item.id,\n      name:        item.name,\n      glbUrl:      item.glbUrl,\n      // Size learned from this model's GLB earlier, so the 2D box is right\n      // straight away; otherwise 500 x 500 until the 3D loader reports it.\n      widthMm:     (sized && sized.w) || sz.w || undefined,\n      depthMm:     (sized && sized.d) || sz.d || undefined,\n      heightMm:    sz.h || undefined,\n      sizedMm:     sized || undefined,\n      // A table built to size in 3D (3d-tables.js), and any parts with a colour\n      // of their own: a table's top and legs, a sofa's legs, a lamp's base.\n      tableKind:   item.kind || undefined,\n      partColours: choice.parts || undefined,\n      fitHeightMm: item.modelHeightMm || undefined,\n      // What makes this piece a priced basket line. Set here only, on adding it:\n      // a stool already on a saved plan (even Velluto Blue, the same id as the\n      // product) has none and stays free (Arden, 2026-11-02).\n      productHandle: item.variantId ? item.id : undefined,\n      wallHeightMm: (choice.size && choice.size.f) || undefined,\n      colourHex:   (choice.colour && choice.colour.hex) || undefined,\n      colourName:  (choice.colour && choice.colour.name) || undefined,\n      x:           spot.x,\n      y:           spot.y,\n      rotationDeg: (onWall && onWall.rotationDeg) || 0\n    });\n    // Always land on the 2D plan, where it can be dragged into place. It\n    // used to switch to 3D to show the model.\n    if (viewMode === '2d') rerender();\n    else setViewMode('2d');\n    designControlsHandle.setStatus(`Added ${item.name}`);\n    const popup = root.querySelector('[data-btk-kp-popup=\"add-furniture\"]');\n    if (popup) popup.hidden = true;             // close the picker\n  }\n  // The Delete key removes the selected furniture (Backspace is that key on a Mac).\n  // Not while typing, or while a popup is open over the plan.\n  document.addEventListener('keydown', (e) => {\n    if (e.key !== 'Delete' && e.key !== 'Backspace') return;\n    if (selectedItem?.kind !== 'furniture' || window.__btkKpDragLocked) return;\n    if (e.target && e.target.closest && e.target.closest('input, textarea, select, [contenteditable=\"true\"]')) return;\n    if (root.querySelector('.btk-kp-popup:not([hidden])')) return;\n    e.preventDefault();\n    deleteFurniture(selectedItem.id);\n  });\n  const furnitureHandle = initFurnitureUI(root, {\n    Furniture:        (Catalogue.getFurniture && Catalogue.getFurniture())         || [],\n    FurnitureTypes:   (Catalogue.getFurnitureTypes && Catalogue.getFurnitureTypes()) || [],\n    OpeningColours:   (Catalogue.getOpeningColours && Catalogue.getOpeningColours()) || [],\n    onAddFurniture:   handleAddFurniture\n  });\n\n  // The Handle Selector toggle on the Handles popup's first screen. The Style\n  // Setup page's listener is scoped to that page, so the popup's copy needs its\n  // own; both copies are redrawn so they never disagree.\n  document.addEventListener('click', (e) => {\n    const hMode = e.target.closest('[data-btk-kp-popup=\"handles\"] [data-btk-kp-journey-handle-mode]');\n    if (!hMode) return;\n    journeyHandleMode = hMode.dataset.btkKpJourneyHandleMode;\n    renderJourneyHandleGroups();\n  });\n  finishesHandle = initFinishesUI(sidebar, {\n    Catalogue,\n    renderHandleSelector,\n    // The plan's own range, not the active planning style - see planTrimStyle.\n    getKitchenStyleId:            () => planTrimStyle().styleId,\n    getFeatureStyles:             () => featureStyles,\n    onSetFeatureStyle:            handleSetFeatureStyle,\n    onSetTrimColour:              handleSetTrimColour,\n    renderTrimPreview:            (feature, styles) => renderTrimPreview(feature, styles),\n    getDefaultTrimColour:         () => planTrimStyle().doorHandle,\n    // A cornice profile is only usable when the range also sells the curved\n    // BLOCK that caps a radius end - so the picker can grey out a profile the\n    // plan can't actually be built in.\n    getRadiusEndCount:            () => radiusBlockEndCount(),\n    getProfiledPlinthBlockers:    () => profiledPlinthBlockers(),\n    hasRadiusCorniceBlock:        (profileName) =>\n                                    !!radiusCorniceBlockProduct(profileName, planTrimStyle().styleId),\n    getGlobalHandle:              () => handleGroups.base,   // back-compat (old popup)\n    onSetGlobalHandle:            handleSetGlobalHandle,      // back-compat (writes all groups)\n    getHandleGroups:              () => handleGroups,\n    onSetGroupHandle:             handleSetGroupHandle,\n    getRailFinishHandle:          () => railFinishHandle,\n    onSetRailFinish:              handleSetRailFinish,\n    getSplashbacks:               () => roomConfig.splashbacks,\n    onUpdateSplashbacks:          handleUpdateSplashbacks,\n    // Stone worktop? Then a splashback cut from it is heat-safe behind a hob.\n    isWorktopHeatSafe:            () => planWorktopHeatSafe(),\n    // A bought panel goes on the wall behind a hob, so the picker says how\n    // many there are to go behind.\n    getHobCount:                  () => (worktopItems || []).filter(it => it && it.kind === 'hob').length,\n    // The stock splashback panels are bought, not drawn: they go into the\n    // plan's Extras like anything else from a picker.\n    addExtra:                     (item) => addExtraToBasket(item, 'Splashbacks')\n  });\n\n  // Popup open / close wiring - listens at root level so any panel\n  // section can carry [data-btk-kp-open-popup] buttons, and any\n  // [data-btk-kp-popup-close] inside a popup dismisses it. Popups\n  // themselves live wherever in the DOM (a `data-btk-kp-popup=\"...\"`\n  // attribute is the only contract). Room-shape special-cases its\n  // 2D preview refresh after the popup becomes visible.\n  const roomSetupPanel = root.querySelector('[data-btk-kp-panel=\"room-setup\"]');\n  // Ceiling-height accent card: pulse its green border when the Room Shape\n  // popup opens, so it's the first thing the eye lands on (it always got\n  // missed). Restart the animation each open; stop once the user engages.\n  const ceilingCardEl  = root.querySelector('[data-btk-kp-ceiling-card]');\n  const ceilingInputEl = root.querySelector('[data-btk-kp-ceiling-height]');\n  const ceilingApplyEl = root.querySelector('[data-btk-kp-ceiling-apply]');\n  function pulseCeilingCard() {\n    if (!ceilingCardEl) return;\n    ceilingCardEl.classList.remove('is-pulsing');\n    void ceilingCardEl.offsetWidth;   // reflow so the animation restarts\n    ceilingCardEl.classList.add('is-pulsing');\n  }\n  if (ceilingInputEl) {\n    ceilingInputEl.addEventListener('focus', () => ceilingCardEl && ceilingCardEl.classList.remove('is-pulsing'));\n  }\n  // Apply button: empty falls back to the 2400 default; commit via the input's\n  // change handler (validation + onCeilingChange \u2192 records below the box).\n  if (ceilingApplyEl && ceilingInputEl) {\n    ceilingApplyEl.addEventListener('click', () => {\n      if (String(ceilingInputEl.value).trim() === '') ceilingInputEl.value = '2400';\n      ceilingInputEl.dispatchEvent(new Event('change', { bubbles: true }));\n    });\n  }\n\n  // Asked straight after a new room shape goes in (Room Shape's\n  // onShapeCommitted), since the height is the next thing to measure. The\n  // planner's own prompt dialog; Save commits through the Room Height box in\n  // the Edit Room Size menu - the same path as its Update button - so there\n  // is one way a height gets set. Skip keeps whatever height the room has.\n  async function askRoomHeight() {\n    const dlg = window.BTKKPDialog;\n    if (!dlg || !dlg.prompt || !ceilingInputEl) return;\n    if (document.querySelector('.btk-kp-dialog-overlay')) return;   // never stack two dialogs\n    const intro = 'Measure from the floor to the ceiling, in mm. It sets how tall the walls and ceiling are in the 3D view.';\n    let message = intro;\n    for (;;) {\n      const current = (roomConfig && roomConfig.ceilingHeightMm) || 2400;\n      const raw = await dlg.prompt(message, {\n        title: 'Room Height', type: 'number', defaultValue: String(current), placeholder: '2400',\n        confirmText: 'Save Room Height', cancelText: 'Skip for now'\n      });\n      if (raw == null) return;                       // skipped\n      const mm = parseInt(String(raw).trim() || '2400', 10);\n      // The same range the Room Height box accepts.\n      if (isNaN(mm) || mm < 0 || mm > 4000) {\n        message = 'Enter a height between 0 and 4000 mm.\\n\\n' + intro;\n        continue;\n      }\n      ceilingInputEl.value = String(mm);\n      ceilingInputEl.dispatchEvent(new Event('change', { bubbles: true }));\n      return;\n    }\n  }\n  // Popups are AUTHORED inside the sidebar panels (easier to read next to the\n  // button that opens them), but .btk-kp-sidebar is position:sticky with\n  // z-index:5 - a stacking context. Anything nested inside it is capped at that\n  // layer, so a popup could never paint above the Home (2000) / Welcome (2001)\n  // overlays however high its own z-index went: opening Room Shape from the\n  // Start panel put the popup BEHIND the Welcome page, with its viewport-fixed\n  // header poking out over the top bar. Re-parenting to the planner root\n  // escapes the sidebar's context while staying inside #btk-kp-root, so every\n  // root.querySelector('[data-btk-kp-popup=\"...\"]') elsewhere still resolves.\n  // \u26A0 ROOM SHAPE ONLY - do not widen this without reading the next paragraph.\n  //\n  // initCabinetsUI is mounted on the SIDEBAR element, so the cabinets UI\n  // delegates its popup-close clicks to `.btk-kp-sidebar` itself. Any popup\n  // lifted out of the sidebar therefore loses its close handler: it still\n  // opens, still adds the unit, but the close button and backdrop do nothing.\n  // Hoisting all popups broke Add Units that way, and scoping the selector to\n  // `.btk-kp-sidebar [data-btk-kp-popup]` did NOT fix it - the cabinets popups\n  // live inside the sidebar, so that selector still matched every one of them.\n  //\n  // Room Shape is the only popup that actually needed to escape: the sidebar is\n  // position:sticky with z-index 5, which makes it a stacking context its\n  // children can never paint above, so the popup rendered BEHIND the Welcome\n  // overlay (z 2001). Its close is handled by the planner-root delegation\n  // below, which still receives the click after the move.\n  function hoistPopupsToRoot() {\n    // Room Edit joins it: that one is opened from the wall selection panel, so\n    // by the time it is wanted its own home - the Room Setup panel - is hidden,\n    // and a popup inside a hidden section stays hidden however un-hidden it is.\n    for (const name of ['room-shape', 'room-edit']) {\n      const el = root.querySelector(`[data-btk-kp-popup=\"${name}\"]`);\n      if (el && el.parentElement !== root) root.appendChild(el);\n    }\n  }\n  hoistPopupsToRoot();\n\n  root.addEventListener('click', (e) => {\n    const opener = e.target.closest('[data-btk-kp-open-popup]');\n    if (opener) {\n      const action = opener.dataset.btkKpOpenPopup;\n      // \u26A0 CUSTOMISE WORKS ON THE UNITS THAT ARE THERE. Every button on its\n      // left menu changes something about the plan's units - their doors,\n      // their worktops, their handles - so with an empty plan they open onto\n      // nothing. Worktops was the worst of them: it opened and half worked,\n      // because there are no runs to price (Arden, 2026-10-01).\n      //\n      // Gated on the STAGE rather than a list of popup names, so a button\n      // added to this menu later is covered without anyone remembering to.\n      // ...except the way OUT of the problem. Telling someone to add units and\n      // then blocking the button that adds them would be a trap, however it\n      // came to be clicked.\n      // Wall and floor colours are the room's, not the units', so they open\n      // on an empty plan too.\n      const ALWAYS_OPEN = action === 'add-units' || action === 'wall-floor';\n      if (!ALWAYS_OPEN && currentStep === 'style-colours' && !(cabinets && cabinets.length)) {\n        e.preventDefault();\n        e.stopPropagation();\n        if (window.BTKKPDialog && window.BTKKPDialog.alert) {\n          window.BTKKPDialog.alert(\n            'There are no units on your plan yet, so there is nothing to customise.'\n            + String.fromCharCode(10) + String.fromCharCode(10)\n            + 'Add some units first, then come back here to choose your doors, worktops and handles.',\n            { eyebrow: 'Customise', title: 'Add Your Units First', okText: 'OK' }\n          );\n        }\n        return;\n      }\n      const popup  = root.querySelector(`[data-btk-kp-popup=\"${action}\"]`);\n      if (popup) {\n        // Room Shape only, for the reasons on hoistPopupsToRoot above: moving\n        // any other popup out of the sidebar severs the cabinets UI's close\n        // delegation, which is mounted on the sidebar element.\n        if (action === 'room-shape' && popup.parentElement !== root) {\n          root.appendChild(popup);\n        }\n        popup.hidden = false;\n        if (action === 'room-edit') openRoomEditor(popup);\n        // From Style Setup the worktop is only being chosen - the material\n        // and its colour - so the popup opens as the picker and closes on the\n        // pick (Arden, 2026-09-24). Everywhere else it opens in full.\n        if (action === 'worktop') {\n          worktopTarget = null;\n          worktopsPopupHandle?.open?.({ pickOnly: opener.hasAttribute('data-btk-kp-worktop-pick') });\n        }\n        if (action === 'wall-floor') renderWallFloorPopup(popup);\n        if (action === 'room-shape' && roomShapeHandle) {\n          snapshotRoomShape();             // so Cancel has something to go back to\n          roomShapeHandle.resetView?.();   // open fitted, whatever last session's zoom was\n          requestAnimationFrame(() =>\n            requestAnimationFrame(() => roomShapeHandle.refresh())\n          );\n          pulseCeilingCard();\n        }\n      }\n      return;\n    }\n    // Cancel: put the plan back exactly as it was when the popup opened,\n    // then close. Checked BEFORE the generic close so it can restore.\n    if (e.target.closest('[data-btk-kp-rs-cancel]')) {\n      restoreRoomShape();\n      const popup = e.target.closest('.btk-kp-popup');\n      if (popup) popup.hidden = true;\n      return;\n    }\n    if (e.target.closest('[data-btk-kp-popup-close]')) {\n      const popup = e.target.closest('.btk-kp-popup');\n      if (popup && popup.classList.contains('is-loading')) return;   // new plan still setting up\n      if (popup) popup.hidden = true;\n      // Closing any other way KEEPS the edits, so drop the snapshot -\n      // it must never be able to revert a later, unrelated session.\n      if (popup && popup.dataset.btkKpPopup === 'room-shape') roomShapeSnapshot = null;\n    }\n  });\n\n  // Edit Custom Room. Mounted fresh on every open so it always starts from the\n  // room as it is now, and torn down on close so a stale polygon can never be\n  // applied over a later edit.\n  // A polygon out of the room editor is pinned to its FIRST vertex, so a wall\n  // that swings can put part of the shape above or left of the origin. The 2D\n  // grid draws from (0, 0), not from the polygon's bounding box, so a negative\n  // coordinate slides the room off its own floor and every unit with it. Bring\n  // it back to the origin, and hand back the shift so whatever stands on the\n  // floor can be carried the same distance - nothing should move relative to\n  // the walls just because the walls moved relative to the origin.\n  //\n  // Doubled vertices go at the same time: a zero-length wall has no meaningful\n  // inward normal, and the clamp turns one into a barrier nothing can get past.\n  function rebaseRoomVertices(verts) {\n    const clean = [];\n    for (const v of (verts || [])) {\n      const last = clean[clean.length - 1];\n      if (last && Math.hypot(v.x - last.x, v.y - last.y) < 1) continue;\n      clean.push({ x: v.x, y: v.y });\n    }\n    while (clean.length > 3 &&\n           Math.hypot(clean[0].x - clean[clean.length - 1].x,\n                      clean[0].y - clean[clean.length - 1].y) < 1) clean.pop();\n    if (clean.length < 3) return { vertices: verts || [], dx: 0, dy: 0 };\n    const dx = -Math.min(...clean.map(v => v.x));\n    const dy = -Math.min(...clean.map(v => v.y));\n    return {\n      vertices: clean.map(v => ({ x: Math.round(v.x + dx), y: Math.round(v.y + dy) })),\n      dx, dy\n    };\n  }\n\n  let roomEditorHandle = null;\n  function openRoomEditor(popup) {\n    const host = popup.querySelector('[data-btk-kp-room-edit-host]');\n    if (!host) return;\n    if (roomEditorHandle) { try { roomEditorHandle.destroy(); } catch (_) {} }\n    const close = () => {\n      popup.hidden = true;\n      if (roomEditorHandle) { try { roomEditorHandle.destroy(); } catch (_) {} }\n      roomEditorHandle = null;\n    };\n    roomEditorHandle = mountRoomEditor(host, {\n      vertices: (room && room.vertices) || [],\n      // The numbers the plan prints on the walls, so the editor's rows and the\n      // wall list in the left menu read the same as the drawing.\n      labels: deriveWallLabels(getWalls(room)),\n      onApply: ({ vertices }) => {\n        // Straight into shapeParams, the same place the builder commits to -\n        // an edited room is still just a polygon. Nothing has reached the plan\n        // before this point: every wall is settled on the editor's own preview\n        // first, so Cancel has nothing to put back.\n        const based = rebaseRoomVertices(vertices);\n        if (based.dx || based.dy) {\n          // The room moved relative to the origin, so everything standing in\n          // it moves with it and ends up exactly where it was on the floor.\n          cabinets = cabinets.map(c => ({ ...c, x: c.x + based.dx, y: c.y + based.dy }));\n          furnitureItems = furnitureItems.map(f => ({ ...f, x: f.x + based.dx, y: f.y + based.dy }));\n          roomConfig = {\n            ...roomConfig,\n            perimeterItems: (roomConfig.perimeterItems || [])\n              .map(it => ({ ...it, x: (it.x || 0) + based.dx, y: (it.y || 0) + based.dy }))\n          };\n        }\n        handleParamsApply({ vertices: based.vertices });\n        close();\n      },\n      onCancel: close\n    });\n  }\n\n  // Reflect each OPEN popup as .is-open on its [data-btk-kp-open-popup] trigger,\n  // so the button shows the active-black state while its popup is open (Room\n  // Shape, Add Units, Customise, etc.). A MutationObserver keeps it in sync\n  // across EVERY open/close path - clicks, backdrop and programmatic hides (e.g.\n  // Add Units closing itself after a unit lands).\n  (function () {\n    function syncPopupOpeners() {\n      root.querySelectorAll('[data-btk-kp-open-popup]').forEach((btn) => {\n        const action = btn.dataset.btkKpOpenPopup;\n        const popup  = action && root.querySelector(`[data-btk-kp-popup=\"${action}\"]`);\n        btn.classList.toggle('is-open', !!(popup && !popup.hidden));\n      });\n    }\n    try {\n      const mo = new MutationObserver((muts) => {\n        for (const m of muts) {\n          if (m.target && m.target.getAttribute && m.target.getAttribute('data-btk-kp-popup') != null) {\n            syncPopupOpeners();\n            return;\n          }\n        }\n      });\n      mo.observe(root, { subtree: true, attributes: true, attributeFilter: ['hidden'] });\n    } catch (e) { /* MutationObserver unavailable - non-fatal */ }\n    syncPopupOpeners();\n  })();\n\n  \n\n  designControlsHandle = initDesignControls(root, {\n    // Split Save button: the main face saves the current plan (overwrites the\n    // active plan, or opens the name popup on a brand-new unsaved plan). The\n    // caret menu's \"Save As\" always opens the name popup for a NEW entry.\n    onSave:   () => handleSave(),\n    onSaveAs: () => openSaveAsPopup(),\n    onLoad:   handleLoad,\n    onClear:  handleClear\n  });\n\n  // Save split-button caret \u2192 toggle the little Save-options menu.\n  const saveSplit     = root.querySelector('[data-btk-kp-save-split]');\n  const saveMenu      = root.querySelector('[data-btk-kp-save-menu]');\n  const saveMenuToggle = root.querySelector('[data-btk-kp-save-menu-toggle]');\n  function closeSaveMenu() {\n    if (saveMenu) saveMenu.hidden = true;\n    if (saveMenuToggle) saveMenuToggle.setAttribute('aria-expanded', 'false');\n  }\n  if (saveMenuToggle && saveMenu) {\n    saveMenuToggle.addEventListener('click', (e) => {\n      e.stopPropagation();\n      const open = saveMenu.hidden;\n      saveMenu.hidden = !open;\n      saveMenuToggle.setAttribute('aria-expanded', open ? 'true' : 'false');\n    });\n    root.querySelectorAll('[data-btk-kp-autosave-toggle]').forEach(btn => {\n      btn.addEventListener('click', (e) => {\n        e.stopPropagation();                      // the toggle must not close the menu\n        setAutosaveEnabled(!autosaveOn);\n      });\n    });\n    const saveVersionBtn = root.querySelector('[data-btk-kp-save-version]');\n    if (saveVersionBtn) {\n      saveVersionBtn.addEventListener('click', () => openSaveAsPopup(null, 'version'));\n    }\n    // Clicking the Save As item (or anywhere outside) closes the menu.\n    saveMenu.addEventListener('click', () => closeSaveMenu());\n    document.addEventListener('click', (e) => {\n      if (saveSplit && !saveSplit.contains(e.target)) closeSaveMenu();\n    });\n  }\n\n  // ---- Save As + Load Plan popups -------------------------------\n  const saveAsPopup    = root.querySelector('[data-btk-kp-popup=\"save-as\"]');\n  const saveAsInput    = root.querySelector('[data-btk-kp-saveas-input]');\n  const saveAsConfirm  = root.querySelector('[data-btk-kp-saveas-confirm]');\n  const saveAsError    = root.querySelector('[data-btk-kp-saveas-error]');\n  const saveAsListWrap = root.querySelector('[data-btk-kp-saveas-existing-wrap]');\n  const saveAsList     = root.querySelector('[data-btk-kp-saveas-list]');\n  const loadPlanPopup  = root.querySelector('[data-btk-kp-popup=\"load-plan\"]');\n  const loadPlanList   = root.querySelector('[data-btk-kp-loadplan-list]');\n  const loadPlanEmpty  = root.querySelector('[data-btk-kp-loadplan-empty]');\n\n  // ---- Plan versions ----\n  //\n  // A version is a separate saved plan that shares a BASE NAME with its\n  // siblings: \"Kitchen - Version 1\", \"Kitchen - Version 2\". The base is stored\n  // on the payload as versionOf rather than parsed back out of the name, so a\n  // plan the user calls \"Kitchen - Blue\" is never mistaken for a version of\n  // \"Kitchen\", and a version can be called anything the user likes: a typed\n  // name is used as given, with no base in front (bug sheet, Julian, 2026-11-04).\n  //\n  // The first Save as Version also renames the ORIGINAL to \"- Version 1\", so a\n  // plan never sits alongside its own versions looking unrelated.\n  let activePlanVersionOf = null;\n\n  // Highest version number already used under this base, so the default suffix\n  // continues the sequence instead of colliding.\n  function nextVersionNumber(plans, base) {\n    let top = 1;\n    for (const p of plans) {\n      if ((p.versionOf || null) !== base) continue;\n      const m = /-\\s*Version\\s+(\\d+)\\s*$/i.exec(p.name || '');\n      if (m) top = Math.max(top, parseInt(m[1], 10));\n    }\n    return top + 1;\n  }\n\n  // Optional callback run after a successful save from the Save As\n  // popup - lets \"Create New Basket\" name the plan, then transfer it.\n  let saveAsOnSaved = null;\n\n  // Render the list of existing saved plans inside the Save As popup so\n  // the user can overwrite one by clicking it (fills the name box),\n  // instead of only typing a brand-new name.\n  async function renderSaveAsExisting() {\n    if (!saveAsList) return;\n    const plans = await planStore.listPlans();\n    saveAsList.replaceChildren();\n    if (saveAsListWrap) saveAsListWrap.hidden = plans.length === 0;\n    for (const p of plans) {\n      const li = document.createElement('li');\n      li.className = 'btk-kp-loadplan-row';\n      li.innerHTML = `\n        <button type=\"button\" class=\"btk-kp-header-button btk-kp-saveas-existing-btn\" style=\"width:100%;text-align:left;justify-content:space-between;display:flex;gap:10px;\">\n          <span class=\"btk-kp-loadplan-name\"></span>\n          <span class=\"btk-kp-loadplan-time\" style=\"opacity:.6;\"></span>\n        </button>`;\n      li.querySelector('.btk-kp-loadplan-name').textContent = p.name;\n      li.querySelector('.btk-kp-loadplan-time').textContent = p.savedAt ? formatTime(p.savedAt) : '';\n      li.querySelector('button').addEventListener('click', async () => {\n        // Clicking an existing plan overwrites it with the current design.\n        if (!(await window.BTKKPDialog.confirm(\n          `Overwrite \"${p.name}\" with your current design?`,\n          { title: 'Overwrite plan?', confirmText: 'Overwrite', danger: true }\n        ))) return;\n        if (saveAsBusy) return;\n        setSaveAsBusy(true);\n        try {\n          const ok = await withAutosaveHeld(() => commitSaveAs(p.name));\n          if (ok) {\n            closeSaveAsPopup();\n            const cb = saveAsOnSaved;\n            saveAsOnSaved = null;\n            if (cb) cb();\n          }\n        } finally {\n          setSaveAsBusy(false);\n        }\n      });\n      saveAsList.appendChild(li);\n    }\n  }\n\n  const saveAsTitleEl = root.querySelector('[data-btk-kp-saveas-title]');\n  const saveAsLabelEl = root.querySelector('[data-btk-kp-saveas-label]');\n  const saveAsCtaEl   = root.querySelector('[data-btk-kp-saveas-cta]');\n  let saveAsMode = 'as';        // 'as' | 'version'\n\n  // A save takes a few seconds (preview picture, server, autosave slot) and the\n  // popup only closes once it has landed. With nothing on screen in between,\n  // people clicked again - and the second save found the first one's name and\n  // asked to overwrite it. So the button says it is saving and takes no more\n  // clicks (or Enter) until the save has finished one way or the other.\n  let saveAsBusy = false;\n  function setSaveAsBusy(on) {\n    saveAsBusy = !!on;\n    if (saveAsConfirm) {\n      saveAsConfirm.disabled = saveAsBusy;\n      saveAsConfirm.classList.toggle('is-saving', saveAsBusy);   // tick \u2192 spinner\n      saveAsConfirm.setAttribute('aria-busy', saveAsBusy ? 'true' : 'false');\n    }\n    if (saveAsCtaEl) saveAsCtaEl.textContent = saveAsBusy ? 'Saving\u2026' : 'Confirm';\n  }\n\n  function openSaveAsPopup(onSaved, mode) {\n    if (!saveAsPopup) return;\n    saveAsOnSaved = (typeof onSaved === 'function') ? onSaved : null;\n    saveAsMode = (mode === 'version') ? 'version' : 'as';\n    const isVersion = saveAsMode === 'version';\n    // Same popup, different job: Save As names a new plan outright, Save as\n    // Version adds a suffix to the name this plan already has.\n    if (saveAsTitleEl) saveAsTitleEl.textContent = isVersion ? 'Save as a version\u2026' : 'Save plan as\u2026';\n    if (saveAsLabelEl) saveAsLabelEl.textContent = isVersion\n      ? `Version of \"${versionBaseName()}\" - give it a name, or leave blank`\n      : 'Save as a new plan';\n    if (!saveAsBusy) setSaveAsBusy(false);   // resets the button to Confirm\n    if (saveAsInput) {\n      // Empty by default - the name box is for saving a NEW plan (\"Save As\").\n      // To re-save an existing plan, the user clicks it in the list below.\n      saveAsInput.value = isVersion ? '' : restoredPlanName;\n      if (!isVersion) restoredPlanName = '';\n      saveAsInput.placeholder = isVersion ? 'e.g. Oak doors  (blank = next version number)'\n                                          : 'e.g. Bedroom - Smith, Jane';\n      saveAsInput.focus();\n    }\n    // The overwrite-an-existing-plan list is a Save As affordance; a version\n    // is always a new plan, so it would only invite the wrong thing.\n    if (saveAsListWrap) saveAsListWrap.hidden = isVersion;\n    if (saveAsError) saveAsError.hidden = true;\n    saveAsPopup.hidden = false;\n  }\n\n  // The name a version hangs off: the plan's stored base if it already has\n  // one, otherwise its own name with any trailing \"- Version n\" removed.\n  function versionBaseName() {\n    if (activePlanVersionOf) return activePlanVersionOf;\n    return String(activePlanName || '').replace(/\\s*-\\s*Version\\s+\\d+\\s*$/i, '').trim()\n        || String(activePlanName || '').trim();\n  }\n  function closeSaveAsPopup() {\n    if (saveAsPopup) saveAsPopup.hidden = true;\n    saveAsOnSaved = null;\n  }\n  async function confirmSaveAs() {\n    if (saveAsBusy) return;\n    setSaveAsBusy(true);\n    try {\n      await withAutosaveHeld(() => (saveAsMode === 'version' ? confirmSaveVersion() : confirmSaveAsNamed()));\n    } finally {\n      setSaveAsBusy(false);\n    }\n  }\n  async function confirmSaveAsNamed() {\n    // Save As names a plan outright, so it leaves any version set behind and\n    // starts one of its own. confirmSaveVersion sets the base before calling\n    // commitSaveAs, which is what keeps a version tied to its siblings.\n    activePlanVersionOf = null;\n    const raw = saveAsInput ? saveAsInput.value : '';\n    const trimmed = String(raw || '').trim();\n    if (!trimmed) {\n      if (saveAsError) {\n        saveAsError.textContent = 'Type a name to save your plan under.';\n        saveAsError.hidden = false;\n      }\n      return;\n    }\n    if (await refuseBoughtPlanName(trimmed)) return;\n    const existing = await planStore.listPlans();\n    const clash = existing.some(p => p.name === trimmed && trimmed !== activePlanName);\n    if (clash && !(await window.BTKKPDialog.confirm(`A plan called \"${trimmed}\" already exists. Overwrite it?`, { title: 'Overwrite plan?', confirmText: 'Overwrite', danger: true }))) return;\n    const ok = await commitSaveAs(trimmed);\n    if (ok) {\n      closeSaveAsPopup();\n      // Run any \"after save\" hook (e.g. continue into add-to-basket).\n      const cb = saveAsOnSaved;\n      saveAsOnSaved = null;\n      if (cb) cb();\n    }\n  }\n\n  // Save the current design as a NEW plan alongside the one it came from.\n  //\n  // A blank name continues the numbering (\"Kitchen - Version 3\"); a typed one\n  // is used as given (\"Oak doors\"). Either way the two are tied together by\n  // versionOf, and the first time this runs the ORIGINAL is renamed to\n  // \"- Version 1\" so the pair reads as a pair rather than a plan and a stray.\n  async function confirmSaveVersion() {\n    const base = versionBaseName();\n    if (!base) {\n      if (saveAsError) {\n        saveAsError.textContent = 'Save this plan first, then you can version it.';\n        saveAsError.hidden = false;\n      }\n      return;\n    }\n    const typed = String((saveAsInput ? saveAsInput.value : '') || '').trim();\n    const plans = await planStore.listPlans();\n    const name  = typed || `${base} - Version ${nextVersionNumber(plans, base)}`;\n\n    if (plans.some(p => p.name === name)) {\n      if (saveAsError) {\n        saveAsError.textContent = `A plan called \"${name}\" already exists. Use a different name.`;\n        saveAsError.hidden = false;\n      }\n      return;\n    }\n\n    // First version of this plan: adopt the original into the set.\n    if (!activePlanVersionOf && activePlanName && typeof planStore.renamePlan === 'function') {\n      const firstName = `${base} - Version 1`;\n      if (!plans.some(p => p.name === firstName)) {\n        await planStore.renamePlan(activePlanName, firstName, { versionOf: base });\n      }\n    }\n\n    activePlanVersionOf = base;\n    const ok = await commitSaveAs(name);\n    if (!ok) { activePlanVersionOf = null; return; }\n    closeSaveAsPopup();\n    const cb = saveAsOnSaved;\n    saveAsOnSaved = null;\n    if (cb) cb();\n  }\n\n  async function openLoadPlanPopup() {\n    if (!loadPlanPopup || !loadPlanList) return;\n    const plans = await planStore.listPlans();\n    loadPlanList.replaceChildren();\n    if (plans.length === 0) {\n      if (loadPlanEmpty) loadPlanEmpty.hidden = false;\n    } else {\n      if (loadPlanEmpty) loadPlanEmpty.hidden = true;\n      const rows = groupPlanVersions(plans).flatMap(set => set.plans);\n      for (const p of rows) {\n        const li = document.createElement('li');\n        li.className = 'btk-kp-loadplan-row';\n        li.innerHTML = `\n          <div class=\"btk-kp-loadplan-meta\">\n            <div class=\"btk-kp-loadplan-name\"></div>\n            <div class=\"btk-kp-loadplan-time\"></div>\n          </div>\n          <div class=\"btk-kp-loadplan-actions\">\n            <button type=\"button\" class=\"btk-kp-header-button\" data-action=\"load\">Load</button>\n            <button type=\"button\" class=\"btk-kp-header-button btk-kp-header-button-danger\" data-action=\"delete\" title=\"Delete plan\">\u00D7</button>\n          </div>`;\n        li.querySelector('.btk-kp-loadplan-name').textContent = p.name;\n        if (p.versionOf) li.classList.add('btk-kp-loadplan-row--version');\n        li.querySelector('.btk-kp-loadplan-time').textContent = p.savedAt\n          ? `Saved ${formatTime(p.savedAt)}`\n          : '';\n        li.querySelector('[data-action=\"load\"]').addEventListener('click', async () => {\n          await loadNamedPlan(p.name);\n          loadPlanPopup.hidden = true;\n          roomShapePrompted = true;\n          stepperHandle.setStep('add-units');\n        });\n        li.querySelector('[data-action=\"delete\"]').addEventListener('click', async () => {\n          if (!(await window.BTKKPDialog.confirm(`Delete \"${p.name}\"? This can\u2019t be undone.`, { title: 'Delete plan?', confirmText: 'Delete', danger: true }))) return;\n          await deleteNamedPlan(p.name);\n          openLoadPlanPopup();   // refresh list in place\n        });\n        loadPlanList.appendChild(li);\n      }\n    }\n    loadPlanPopup.hidden = false;\n  }\n\n  if (saveAsConfirm) saveAsConfirm.addEventListener('click', confirmSaveAs);\n  if (saveAsInput) {\n    saveAsInput.addEventListener('keydown', e => {\n      if (e.key === 'Enter') { e.preventDefault(); confirmSaveAs(); }\n    });\n  }\n  // Backdrop / \u00D7 close machinery for both popups - uses the same\n  // [data-btk-kp-popup-close] convention as every other planner popup.\n  [saveAsPopup, loadPlanPopup].forEach(popup => {\n    if (!popup) return;\n    popup.addEventListener('click', e => {\n      if (e.target.closest('[data-btk-kp-popup-close]')) {\n        popup.hidden = true;\n        // Dismissing the Save As popup cancels any pending \"after save\"\n        // hook (e.g. the user backed out of naming before adding).\n        if (popup === saveAsPopup) saveAsOnSaved = null;\n      }\n    });\n  });\n\n  // ---- Planning Styles popup ------------------------------------------\n  // What the Add Units \"Active Planning Style\" bar opens, in place of the\n  // shared side drawer (Arden, 2026-10-07). A standard planner popup with no\n  // left menu: the three style slots across the top, as Style Setup's cards.\n  // Clicking a slot - a style to change it, an empty one to add one - turns\n  // the whole popup into the kitchen-style list, filter pills along the top,\n  // the same list as Customise > Door & Carcase's Choose new style. Picking a\n  // style there fills that slot and comes back to the slots. The first slot is\n  // the active planning style: what new units are drawn and priced in.\n  const psPopup = document.createElement('div');\n  psPopup.className = 'btk-kp-popup btk-kp-popup--wide btk-kp-ps-popup';\n  psPopup.hidden = true;\n  psPopup.innerHTML = `\n    <div class=\"btk-kp-popup-backdrop\" data-btk-kp-ps-close></div>\n    <div class=\"btk-kp-popup-panel btk-kp-ps-panel\" role=\"dialog\" aria-labelledby=\"btk-kp-ps-title\">\n      <header class=\"btk-kp-popup-head\">\n        <h2 id=\"btk-kp-ps-title\" data-btk-kp-ps-title>Your Planning Styles</h2>\n        <div class=\"btk-kp-popup-search\" data-btk-kp-ps-searchbar hidden>\n          <svg class=\"btk-kp-popup-search-icon\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\"><circle cx=\"11\" cy=\"11\" r=\"7\"/><path d=\"M21 21l-4.35-4.35\"/></svg>\n          <input type=\"search\" class=\"btk-kp-popup-search-input\" data-btk-kp-ps-search\n                 placeholder=\"Search styles - name, type or door colour...\" aria-label=\"Search bedroom styles\"\n                 autocomplete=\"off\" spellcheck=\"false\">\n          <button type=\"button\" class=\"btk-kp-popup-search-clear\" data-btk-kp-ps-search-clear aria-label=\"Clear search\" hidden>\u00D7</button>\n        </div>\n        <button type=\"button\" class=\"btk-kp-popup-close\" data-btk-kp-ps-close aria-label=\"Close\">&times;</button>\n      </header>\n      <div class=\"btk-kp-popup-body\" data-btk-kp-ps-body></div>\n    </div>`;\n  (saveAsPopup && saveAsPopup.parentNode ? saveAsPopup.parentNode : root).appendChild(psPopup);\n  const psTitleEl = psPopup.querySelector('[data-btk-kp-ps-title]');\n  const psBodyEl  = psPopup.querySelector('[data-btk-kp-ps-body]');\n  // The top bar search (Arden, 2026-10-12): on the style list only, the same\n  // field as Add Units', filtering the cards as it is typed.\n  const psSearchBar   = psPopup.querySelector('[data-btk-kp-ps-searchbar]');\n  const psSearchEl    = psPopup.querySelector('[data-btk-kp-ps-search]');\n  const psSearchClear = psPopup.querySelector('[data-btk-kp-ps-search-clear]');\n  function psApplySearch() {\n    const host = psBodyEl.querySelector('[data-btk-kp-ps-stylecards]');\n    if (psSearchClear) psSearchClear.hidden = !psSearchEl.value;\n    if (!host) return;\n    host._btkStyleQuery = psSearchEl.value;\n    applyStyleCardFilters(host);\n  }\n  psSearchEl.addEventListener('input', psApplySearch);\n  psSearchClear.addEventListener('click', () => { psSearchEl.value = ''; psApplySearch(); psSearchEl.focus(); });\n  let psSlot = null;   // null: the slots. A number: choosing the style for that slot.\n\n  const PS_BACK_BTN = `<button type=\"button\" class=\"btk-kp-action-btn btk-kp-action-btn--green btk-kp-action-btn--sm\" data-btk-kp-ps-back>\n      <span class=\"btk-kp-action-btn-arrow\" aria-hidden=\"true\"><svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M15 18l-6-6 6-6\"/></svg></span>\n      <span class=\"btk-kp-action-btn-label\">Back</span>\n    </button>`;\n\n  // NO STYLE, NO UNITS. A new plan has no planning style (Arden, 2026-10-07),\n  // and units are drawn and priced in one, so every way of adding a unit -\n  // the Add Units lists, drag and drop, appliances - asks for one first:\n  // Planning Styles opens at its style list (\"Choose Your Active Planning\n  // Style\") and the unit is not added. Arriving at Add Items asks too.\n  // A style chosen on the kitchen pages before coming in (the shared store -\n  // a new plan clears it) is a choice already made: it becomes the active one.\n  let psAskedForStyle = false;\n  let psOpenAddUnitsAfter = false;   // asked from Start Adding Units: Add Units follows the pick\n  function needsPlanningStyle() {\n    if (buyingStyles.length) return false;\n    let ctx = null;\n    try { ctx = JSON.parse(sessionStorage.getItem('btk_kitchen_context') || 'null'); } catch (_) {}\n    if (ctx && ctx.style && ctx.colour && Catalogue.getKitchenStyle && Catalogue.getKitchenStyle(ctx.style)) {\n      buyingStyles = [{ styleId: ctx.style, doorHandle: ctx.colour, carcaseHandle: ctx.carcase || null }];\n      applyBuyingContextToPlanner(ctx);\n      syncJourneyFromOptions();\n      return false;\n    }\n    return true;\n  }\n  function askForPlanningStyle() {\n    if (!psPopup.hidden && psSlot != null) return;   // already asking\n    psAskedForStyle = true;\n    psSlot = 0;\n    renderPlanningStylesPopup();\n    psPopup.hidden = false;\n  }\n  function styleGated(opts) {\n    for (const k of Object.keys(opts)) {\n      if (!/^onAdd/.test(k) || typeof opts[k] !== 'function') continue;\n      const add = opts[k];\n      opts[k] = (...args) => {\n        if (needsPlanningStyle()) { askForPlanningStyle(); return null; }\n        // Whatever this add puts on the plan is shown (revealNewItems) - but\n        // not a unit added from the + on a unit already on the plan: it goes\n        // beside the one clicked, where the customer is already looking.\n        const before = new Set(cabinets.map(c => c.id));\n        const r = add(...args);\n        const fromRun = !!(args[1] && args[1].runAnchor);\n        if (!fromRun) {\n          Promise.resolve(r).then(() => {\n            revealNewItems(cabinets.filter(c => !before.has(c.id)).map(c => c.id));\n          }, () => {});\n        }\n        return r;\n      };\n    }\n    return opts;\n  }\n  // A newly added or duplicated item is SHOWN (Arden, 2026-10-12): the plan\n  // goes to 2D and fully zoomed out, so the whole room is in view, and the\n  // new item's outline pulses blue a few times. Added into a busy layout -\n  // a filler above all - it was otherwise hard to find. The pulse waits for\n  // any open popup (Add Units) to close, or it would play unseen behind it,\n  // and is drawn over the plan rather than on the unit, so a redraw of the\n  // plan mid-pulse does not cut it short.\n  function revealNewItems(ids) {\n    if (!ids || !ids.length) return;\n    if (viewMode !== '2d') { setViewMode('2d'); rerender(); }\n    if (view2d.zoom !== 1 || view2d.panX || view2d.panY) {\n      view2d.zoom = 1; view2d.panX = 0; view2d.panY = 0;\n      embedPrev2dView = null;\n      applyView2dTransform();\n    }\n    const started = Date.now();\n    const whenClear = () => {\n      // getClientRects, not offsetParent: a popup is position: fixed, and a\n      // fixed element has no offsetParent even while it is on screen.\n      const popupOpen = [...root.querySelectorAll('.btk-kp-popup')].some(p => !p.hidden && p.getClientRects().length > 0);\n      if (popupOpen && Date.now() - started < 60000) { setTimeout(whenClear, 250); return; }\n      requestAnimationFrame(() => ids.forEach(pulseItem));\n    };\n    whenClear();\n  }\n  // The ring follows the unit every frame (Planner Bugs row 353): it was\n  // placed once, so moving the unit (or panning/zooming) mid-pulse left it\n  // behind on the old spot. Re-found by id each frame, since a redraw\n  // replaces the unit's element; gone (deleted, or left 2D) = ring goes.\n  function pulseItem(cabId) {\n    if (!currentGridEl || viewMode !== '2d') return;\n    const esc = (window.CSS && CSS.escape) ? CSS.escape(String(cabId)) : String(cabId);\n    const find = () => currentGridEl && viewMode === '2d' ? currentGridEl.querySelector(`[data-cabinet-id=\"${esc}\"]`) : null;\n    const el = find();\n    if (!el) return;\n    const r0 = el.getBoundingClientRect();\n    if (!r0.width && !r0.height) return;\n    const ring = document.createElement('div');\n    ring.className = 'btk-kp-new-pulse';\n    // Clear of the unit's own outline, and at least 36px across, so a 50mm\n    // filler still gets a ring you can see.\n    const MIN = 36, PAD = 10;\n    const place = (r) => {\n      const w = Math.max(MIN, r.width + PAD * 2), h = Math.max(MIN, r.height + PAD * 2);\n      ring.style.left = (r.left + r.width / 2 - w / 2) + 'px';\n      ring.style.top = (r.top + r.height / 2 - h / 2) + 'px';\n      ring.style.width = w + 'px';\n      ring.style.height = h + 'px';\n    };\n    place(r0);\n    document.body.appendChild(ring);\n    let done = false;\n    const end = () => { done = true; ring.remove(); };\n    const follow = () => {\n      if (done) return;\n      const cur = find();\n      const r = cur && cur.getBoundingClientRect();\n      if (!r || (!r.width && !r.height)) { end(); return; }\n      place(r);\n      requestAnimationFrame(follow);\n    };\n    requestAnimationFrame(follow);\n    ring.addEventListener('animationend', end);\n    setTimeout(end, 4000);   // safety: never left behind\n  }\n  function openPlanningStylesPopup() {\n    psSlot = null;\n    renderPlanningStylesPopup();\n    psPopup.hidden = false;\n  }\n  function closePlanningStylesPopup() {\n    psPopup.hidden = true;\n    psSlot = null;\n    psAskedForStyle = false;\n    psOpenAddUnitsAfter = false;\n  }\n\n  // A slot's card is the Door & Carcase popup's style card (Arden,\n  // 2026-10-07): a black head band with the palette chip, the style name and\n  // the count circle, then the door-on-carcase picture with the door and\n  // carcase stacked beside it. The count is the units on the plan in this\n  // exact style, door and carcase - what the circle counts there too. A card\n  // with a style on it is not a button (no chevron): only an empty slot opens\n  // the style list. Under it, the active style's green Active, or a black Set\n  // Active on the others, and Remove.\n  const PS_ICON_STYLE   = '<svg width=\"20\" height=\"20\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><circle cx=\"13.5\" cy=\"6.5\" r=\"1.5\"/><circle cx=\"17.5\" cy=\"10.5\" r=\"1.5\"/><circle cx=\"8.5\" cy=\"7.5\" r=\"1.5\"/><circle cx=\"6.5\" cy=\"12.5\" r=\"1.5\"/><path d=\"M12 2a10 10 0 0 0 0 20c.5 0 1-.4 1-1 0-.3-.1-.6-.2-.8a2 2 0 0 1 1.6-3.2H17a5 5 0 0 0 5-5c0-5.5-4.5-10-10-10z\"/></svg>';\n  function psStyleCardHTML(bs, i) {\n    const ks      = Catalogue.getKitchenStyle && Catalogue.getKitchenStyle(bs.styleId);\n    const name    = (ks && ks.name) || bs.styleId || '';\n    const family  = ks && ks.carcaseFamilyHandle;\n    const door    = ((Catalogue.getDoorColoursForStyle && Catalogue.getDoorColoursForStyle(bs.styleId)) || []).find(c => c.handle === bs.doorHandle) || null;\n    const carcase = ((Catalogue.getCarcaseColoursForStyle && Catalogue.getCarcaseColoursForStyle(bs.styleId)) || []).find(c => c.handle === bs.carcaseHandle) || null;\n    const { doorImg, carcaseImg } = unitPicture(bs.styleId, bs.doorHandle, bs.carcaseHandle,\n      (bs.doorHandle && Catalogue.getDoorPreviewUrl) ? (Catalogue.getDoorPreviewUrl(bs.styleId, bs.doorHandle) || '') : '',\n      (family && bs.carcaseHandle && Catalogue.getCarcasePreviewUrl) ? (Catalogue.getCarcasePreviewUrl(family, bs.carcaseHandle) || '') : '');\n    const n = cabinets.filter(c => c && !c.freestandingAppliance && c.kitchenStyleId === bs.styleId\n      && (c.doorColourHandle || null) === (bs.doorHandle || null)\n      && (c.carcaseColourHandle || null) === (bs.carcaseHandle || null)).length;\n    const isActive = i === 0;\n    const setBtn = isActive\n      ? `<span class=\"btk-kp-action-btn btk-kp-action-btn--green btk-kp-action-btn--sm btk-kp-ps-state is-current\" aria-current=\"true\">\n            <span class=\"btk-kp-action-btn-icon\" aria-hidden=\"true\"><svg viewBox=\"0 0 24 24\" width=\"18\" height=\"18\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2.4\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><polyline points=\"4 11 9 16 20 5\"/></svg></span>\n            <span class=\"btk-kp-action-btn-label\">Active</span>\n          </span>`\n      : `<button type=\"button\" class=\"btk-kp-action-btn btk-kp-action-btn--sm btk-kp-ps-state\" data-btk-kp-journey-style-makefirst=\"${i}\">\n            <span class=\"btk-kp-action-btn-label\">Set Active</span>\n          </button>`;\n    return `\n      <div class=\"btk-kp-ps-slot\">\n      <div class=\"btk-kp-dc-group btk-kp-ps-card is-static${isActive ? ' is-active' : ''}\" role=\"group\"\n           aria-label=\"${jEsc(`${isActive ? 'Active planning style' : 'Planning style'}: ${name}, door ${door ? door.name : 'not set'}, carcase ${carcase ? carcase.name : 'not set'}`)}\">\n        <span class=\"btk-kp-dc-group-head\">\n          <span class=\"btk-kp-action-btn-icon\" aria-hidden=\"true\">${PS_ICON_STYLE}</span>\n          <span class=\"btk-kp-action-btn-label\">${jEsc(name)}</span>\n          ${n ? `<span class=\"btk-kp-jnav-count\" title=\"${n} unit${n === 1 ? '' : 's'} on your plan\">${n}</span>` : ''}\n        </span>\n        <span class=\"btk-kp-dc-group-body\">\n          <span class=\"btk-kp-restyle-card-img btk-kp-dc-group-img\">\n            ${carcaseImg ? `<img class=\"btk-kp-restyle-tile-carcase\" src=\"${jEsc(carcaseImg)}\" alt=\"\">` : ''}\n            ${doorImg ? `<img class=\"btk-kp-restyle-tile-door\" src=\"${jEsc(doorImg)}\" alt=\"\">` : ''}\n          </span>\n          <span class=\"btk-kp-restyle-card-colours btk-kp-dc-group-colours\">\n            <span class=\"btk-kp-restyle-card-colour\">\n              <span class=\"btk-kp-restyle-card-colour-label\">Door</span>\n              <span class=\"btk-kp-restyle-card-colour-val\">${jEsc(door ? (door.name || bs.doorHandle) : 'Not set')}</span>\n            </span>\n            <span class=\"btk-kp-restyle-card-colour\">\n              <span class=\"btk-kp-restyle-card-colour-label\">Carcase</span>\n              <span class=\"btk-kp-restyle-card-colour-val\">${jEsc(carcase ? (carcase.name || bs.carcaseHandle) : 'Not set')}</span>\n            </span>\n          </span>\n        </span>\n      </div>\n      ${setBtn}\n      ${buyingStyles.length > 1 ? `<button type=\"button\" class=\"btk-kp-ps-remove\" data-btk-kp-journey-style-remove=\"${i}\">Remove</button>` : ''}\n      </div>`;\n  }\n\n  // WHERE each style sits in the popup. The active style is always first in\n  // buyingStyles (the rest of the planner reads it from there), so the order\n  // on screen comes from the slot positions the buying-style store already\n  // keeps (btk_style_slots, style:door keys, kept in place by\n  // reconcileBuyingStyleSlots). Setting a style active, or removing one, then\n  // leaves every card where it was (Arden, 2026-10-07). Returns one entry per\n  // position: the style's index in buyingStyles, or -1 for an empty slot.\n  const psKey = (bs) => bs.styleId + ':' + (bs.doorHandle || '');\n  function psReadSlots() {\n    let slots = [];\n    try { slots = JSON.parse(sessionStorage.getItem('btk_style_slots') || '[]'); } catch (_) {}\n    slots = (Array.isArray(slots) ? slots : []).slice(0, J_STYLE_MAX);\n    while (slots.length < J_STYLE_MAX) slots.push('');\n    return slots;\n  }\n  function psWriteSlots(slots) {\n    try { sessionStorage.setItem('btk_style_slots', JSON.stringify(slots)); } catch (_) {}\n  }\n  function psPositions() {\n    const used = new Set();\n    const pos = psReadSlots().map(key => {\n      if (!key) return -1;\n      const i = buyingStyles.findIndex((bs, j) => j < J_STYLE_MAX && !used.has(j) && psKey(bs) === key);\n      if (i > -1) used.add(i);\n      return i;\n    });\n    // A style the store has not placed yet takes the first free position.\n    buyingStyles.slice(0, J_STYLE_MAX).forEach((bs, i) => {\n      if (used.has(i)) return;\n      const free = pos.indexOf(-1);\n      if (free > -1) { pos[free] = i; used.add(i); }\n    });\n    psWriteSlots(pos.map(i => (i > -1 ? psKey(buyingStyles[i]) : '')));\n    return pos;\n  }\n\n  function renderPlanningStylesPopup() {\n    // The search is for the style list; a fresh list starts unsearched.\n    if (psSearchBar) psSearchBar.hidden = psSlot == null;\n    if (psSearchEl) psSearchEl.value = '';\n    if (psSearchClear) psSearchClear.hidden = true;\n    if (psSlot == null) {\n      psTitleEl.textContent = 'Your Planning Styles';\n      const cards = psPositions().map((i, p) => (i > -1 ? psStyleCardHTML(buyingStyles[i], i) : `\n          <button type=\"button\" class=\"btk-kp-ps-add\" data-btk-kp-ps-slot=\"${p}\">\n            <span class=\"btk-kp-ps-add-plus\" aria-hidden=\"true\">+</span>\n            <span class=\"btk-kp-ps-add-label\">Add Planning Style</span>\n          </button>`)).join('');\n      psBodyEl.innerHTML = `\n        <p class=\"btk-kp-home-lead btk-kp-ps-lead\">Your <strong>Active</strong> style is the one new units are drawn and priced in - <strong>Set Active</strong> switches to another. Click an empty slot to add a style; you can plan in up to ${J_STYLE_MAX}.</p>\n        <div class=\"btk-kp-dc-cards btk-kp-ps-slots\">${cards}</div>`;\n      psBodyEl.scrollTop = 0;\n      return;\n    }\n    const first = buyingStyles.length === 0;\n    psTitleEl.textContent = first ? 'Choose Your Active Planning Style' : 'Add a Planning Style';\n    psBodyEl.innerHTML = `\n      <div class=\"btk-kp-ps-choose-head\">${PS_BACK_BTN}</div>\n      <div class=\"btk-kp-ps-stylecards\" data-btk-kp-ps-stylecards></div>`;\n    renderStyleCardsInto(psBodyEl.querySelector('[data-btk-kp-ps-stylecards]'), {\n      selectLabel: first ? 'Use as Active Style' : 'Add This Style',\n      onSelect: pickPlanningStyle\n    });\n    psBodyEl.scrollTop = 0;\n  }\n\n  // The set has changed: when the active style moved, the planner takes it up\n  // (what the drawer's switch did), then everything that shows the set -\n  // Style Setup, the mood board, the Add Units bar, the kitchen pages - follows.\n  function planningStylesChanged(activeChanged) {\n    if (activeChanged && buyingStyles[0]) applyBuyingContextToPlanner(buyingStyleCtx(buyingStyles[0]));\n    syncJourneyFromOptions();\n    syncBuyingStylesToSession();\n    renderJourneyStyleSlots();\n    // Refresh the Style stage's tick and count without moving the menu's\n    // highlight - this popup is opened from Add Units, not from Style Setup.\n    const curStage = journeyNav && journeyNav.querySelector('[data-btk-kp-jnav].is-active');\n    updateJourneyNav(curStage ? curStage.dataset.btkKpJnav : null);\n    psSlot = null;\n    renderPlanningStylesPopup();\n  }\n\n  // A style picked for an empty slot joins the set IN that slot. The first one\n  // ever is the active style; after that a new one waits for Set Active.\n  function pickPlanningStyle(styleId, doorHandle, carcaseHandle, card) {\n    if (card) card.dataset.face = 'door';\n    if (psSlot == null || !styleId) return;\n    const same = s => s && s.styleId === styleId && s.doorHandle === doorHandle && s.carcaseHandle === carcaseHandle;\n    if (buyingStyles.some(same) || buyingStyles.length >= J_STYLE_MAX) {\n      psSlot = null;            // already in the set (or no room): nothing to add\n      renderPlanningStylesPopup();\n      return;\n    }\n    const combo = { styleId, doorHandle, carcaseHandle };\n    const slots = psReadSlots();\n    slots[Math.max(0, Math.min(J_STYLE_MAX - 1, psSlot))] = psKey(combo);\n    psWriteSlots(slots);\n    buyingStyles.push(combo);\n    planningStylesChanged(buyingStyles.length === 1);\n    // Asked for because there was none: picked, so out of the way - they were\n    // in the middle of adding a unit. From Start Adding Units, Add Units opens.\n    const openAddUnits = psAskedForStyle && psOpenAddUnitsAfter;\n    if (psAskedForStyle) closePlanningStylesPopup();\n    if (openAddUnits) requestAnimationFrame(() => { try { openAddUnitsPopup(); } catch (_) {} });\n  }\n\n  psPopup.addEventListener('click', (e) => {\n    if (e.target.closest('[data-btk-kp-ps-close]')) { closePlanningStylesPopup(); return; }\n    if (e.target.closest('[data-btk-kp-ps-back]')) { psSlot = null; renderPlanningStylesPopup(); return; }\n    // Set Active: that style becomes the one to plan in, and the popup closes.\n    const mk = e.target.closest('[data-btk-kp-journey-style-makefirst]');\n    if (mk) {\n      const i = parseInt(mk.dataset.btkKpJourneyStyleMakefirst, 10);\n      if (i > 0 && i < buyingStyles.length) {\n        const [s] = buyingStyles.splice(i, 1);\n        buyingStyles.unshift(s);\n        planningStylesChanged(true);\n        closePlanningStylesPopup();\n      }\n      return;\n    }\n    const rm = e.target.closest('[data-btk-kp-journey-style-remove]');\n    if (rm) {\n      const i = parseInt(rm.dataset.btkKpJourneyStyleRemove, 10);\n      if (buyingStyles.length > 1 && i >= 0 && i < buyingStyles.length) {\n        buyingStyles.splice(i, 1);\n        planningStylesChanged(i === 0);\n      }\n      return;\n    }\n    // Only an empty slot opens the style list.\n    const slot = e.target.closest('[data-btk-kp-ps-slot]');\n    if (slot) {\n      const p = parseInt(slot.dataset.btkKpPsSlot, 10);\n      if (p >= 0 && p < J_STYLE_MAX) { psSlot = p; renderPlanningStylesPopup(); }\n    }\n  });\n  document.addEventListener('keydown', (e) => {\n    if (e.key === 'Escape' && !psPopup.hidden) closePlanningStylesPopup();\n  });\n  // The Add Units bar's Switch opens this rather than the shared drawer.\n  if (window.__btkBuyingStyleHooks) window.__btkBuyingStyleHooks.openPlanningStyles = openPlanningStylesPopup;\n\n  // ---- Checklist stage ------------------------------------------------\n  // The approvals to give before checking out (Arden, 2026-10-07): the\n  // planner's version of the Smart Checklist from the old Odoo checkout (the\n  // smart.checklist records on Odoo v15 staging - their wording is used here).\n  // A check only appears when the plan or basket has something for it to look\n  // at - no wall units, no Wall Unit Heights or Decor. Most count how many\n  // different things there are (door colours, carcase colours, heights) and\n  // say so: one is usual, two is worth a second look, three or more rarely\n  // meant. The customer approves each with the check's own confirmation line.\n  // An approval records WHAT it approved (its signature), so changing that\n  // part of the plan asks for it again. Advisory Points and Walkways are the\n  // Advisory panel's accepted points: accepting them there approves these,\n  // and approving these accepts them there. Cards are Planner Home cards; the\n  // picture, and optionally the title and advice, come from the\n  // planner_checklist_item metaobject by check key.\n  const CHECK_TICK = '<svg viewBox=\"0 0 24 24\" width=\"18\" height=\"18\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2.4\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><polyline points=\"4 11 9 16 20 5\"/></svg>';\n  // Each check's icon chip, and its second button's.\n  const CK_ICONS = {\n    // Worktop Pantry Units (row 142): a unit with folding doors on a worktop.\n    // Units Reduced On Site: a unit with its cut line.\n    'reduced-on-site': '<svg viewBox=\"0 0 24 24\" width=\"18\" height=\"18\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><rect x=\"3\" y=\"5\" width=\"18\" height=\"14\" rx=\"1\"/><path d=\"M14 3v18\" stroke-dasharray=\"2 2\"/></svg>',\n    'pantry': '<svg viewBox=\"0 0 24 24\" width=\"18\" height=\"18\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M2 20h20\"/><rect x=\"5\" y=\"4\" width=\"14\" height=\"16\" rx=\"1\"/><path d=\"M12 4v16\"/><path d=\"M5 12h14\" stroke-dasharray=\"2 2\"/></svg>',\n    // Room Sizes: a tape measure.\n    'room-sizes': '<svg viewBox=\"0 0 24 24\" width=\"18\" height=\"18\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><circle cx=\"9\" cy=\"12\" r=\"6\"/><circle cx=\"9\" cy=\"12\" r=\"1.5\"/><path d=\"M9 18h12v-3\"/><path d=\"M15 18v-2\"/><path d=\"M18 18v-2\"/></svg>',\n    'advisory': '<svg viewBox=\"0 0 24 24\" width=\"18\" height=\"18\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M12 3 2 21h20L12 3z\"/><path d=\"M12 10v5\"/><path d=\"M12 18h.01\"/></svg>',\n    'belfast-worktop': '<svg viewBox=\"0 0 24 24\" width=\"18\" height=\"18\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M2 7h5v6h10V7h5\"/><rect x=\"7\" y=\"7\" width=\"10\" height=\"9\" rx=\"1\"/></svg>',\n    'walkways': '<svg viewBox=\"0 0 24 24\" width=\"18\" height=\"18\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M4 12h16\"/><path d=\"M8 8l-4 4 4 4\"/><path d=\"M16 8l4 4-4 4\"/></svg>',\n    'panel-joins': '<svg viewBox=\"0 0 24 24\" width=\"18\" height=\"18\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><rect x=\"2\" y=\"6\" width=\"20\" height=\"12\" rx=\"1\"/><path d=\"M13 6v12\" stroke-dasharray=\"2 2\"/></svg>',\n    'slab-fronts': '<svg viewBox=\"0 0 24 24\" width=\"18\" height=\"18\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><rect x=\"2\" y=\"3\" width=\"13\" height=\"18\" rx=\"1\"/><rect x=\"5.5\" y=\"6.5\" width=\"6\" height=\"11\"/><rect x=\"18\" y=\"3\" width=\"4\" height=\"18\" rx=\"1\"/></svg>',\n    'door-colours': '<svg viewBox=\"0 0 24 24\" width=\"18\" height=\"18\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><rect x=\"5\" y=\"3\" width=\"14\" height=\"18\" rx=\"1\"/><circle cx=\"15\" cy=\"12\" r=\"0.8\" fill=\"currentColor\"/></svg>',\n    'door-carcase': '<svg viewBox=\"0 0 24 24\" width=\"18\" height=\"18\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><rect x=\"5\" y=\"3\" width=\"14\" height=\"18\" rx=\"1\"/><circle cx=\"15\" cy=\"12\" r=\"0.8\" fill=\"currentColor\"/></svg>',\n    'carcase-colours': '<svg viewBox=\"0 0 24 24\" width=\"18\" height=\"18\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><rect x=\"3\" y=\"4\" width=\"18\" height=\"16\" rx=\"1\"/><path d=\"M3 9h18\"/><path d=\"M12 9v11\"/></svg>',\n    'wall-heights': '<svg viewBox=\"0 0 24 24\" width=\"18\" height=\"18\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M12 3v18\"/><path d=\"M8 7l4-4 4 4\"/><path d=\"M8 17l4 4 4-4\"/></svg>',\n    'cornice': '<svg viewBox=\"0 0 24 24\" width=\"18\" height=\"18\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M3 6h18\"/><path d=\"M5 6v3h14V6\"/><rect x=\"6\" y=\"9\" width=\"12\" height=\"11\" rx=\"1\"/></svg>',\n    'pelmet': '<svg viewBox=\"0 0 24 24\" width=\"18\" height=\"18\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><rect x=\"6\" y=\"4\" width=\"12\" height=\"11\" rx=\"1\"/><path d=\"M5 15v3h14v-3\"/><path d=\"M3 18h18\"/></svg>',\n    'plinth': '<svg viewBox=\"0 0 24 24\" width=\"18\" height=\"18\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><rect x=\"5\" y=\"4\" width=\"14\" height=\"12\" rx=\"1\"/><path d=\"M5 16h14v4H5z\"/></svg>',\n    'end-panels': '<svg viewBox=\"0 0 24 24\" width=\"18\" height=\"18\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><rect x=\"7\" y=\"5\" width=\"13\" height=\"15\" rx=\"1\"/><path d=\"M4 4h3v17H4z\"/></svg>',\n    'profile': '<svg viewBox=\"0 0 24 24\" width=\"18\" height=\"18\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M3 8h18\"/><path d=\"M3 12h18\"/><rect x=\"3\" y=\"15\" width=\"18\" height=\"5\" rx=\"1\"/></svg>',\n    'inventory': '<svg viewBox=\"0 0 24 24\" width=\"18\" height=\"18\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M9 6h12\"/><path d=\"M9 12h12\"/><path d=\"M9 18h12\"/><path d=\"M4 6h.01\"/><path d=\"M4 12h.01\"/><path d=\"M4 18h.01\"/></svg>',\n    'assembly': '<svg viewBox=\"0 0 24 24\" width=\"18\" height=\"18\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M14.7 6.3a4 4 0 0 0-5.4 5.4L3 18l3 3 6.3-6.3a4 4 0 0 0 5.4-5.4l-2.6 2.6-2.4-.6-.6-2.4z\"/></svg>',\n    'recommend': '<svg viewBox=\"0 0 24 24\" width=\"18\" height=\"18\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><polygon points=\"12 2 15.1 8.3 22 9.3 17 14.1 18.2 21 12 17.8 5.8 21 7 14.1 2 9.3 8.9 8.3 12 2\"/></svg>',\n    'view': '<svg viewBox=\"0 0 24 24\" width=\"18\" height=\"18\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M1 12s4-7 11-7 11 7 11 7-4 7-11 7S1 12 1 12z\"/><circle cx=\"12\" cy=\"12\" r=\"3\"/></svg>',\n    'basket': '<svg viewBox=\"0 0 24 24\" width=\"18\" height=\"18\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><circle cx=\"9\" cy=\"20\" r=\"1.5\"/><circle cx=\"18\" cy=\"20\" r=\"1.5\"/><path d=\"M2 3h3l2.7 12.5a1 1 0 0 0 1 .8h9.6a1 1 0 0 0 1-.8L21 7H6\"/></svg>',\n  };\n  // A check's own drawing for its picture tile, until the planner_checklist_item\n  // metaobject has a picture. Joins in End Panels: an island's back, worktop\n  // over it, made from two panels with the join called out.\n  const CK_PICTURES = {\n    // Plinth Height (row 95): a base unit from the front on its legs, the\n    // plinth in front with its height marked, and the worktop above.\n    'plinth-height': `<svg viewBox=\"0 0 320 240\" width=\"100%\" height=\"100%\" role=\"img\" aria-label=\"A base unit on its legs with the plinth height marked: lower or higher than the standard 150mm\" font-family=\"inherit\">\n      <text x=\"160\" y=\"22\" text-anchor=\"middle\" font-size=\"15\" font-weight=\"700\" fill=\"#2d7a3a\">Your plinth height</text>\n      <line x1=\"30\" y1=\"214\" x2=\"290\" y2=\"214\" stroke=\"#555\" stroke-width=\"2\"/>\n      <rect x=\"70\" y=\"58\" width=\"170\" height=\"12\" fill=\"#c9b79c\" stroke=\"#555\"/>\n      <rect x=\"76\" y=\"70\" width=\"158\" height=\"104\" fill=\"#f3f3f1\" stroke=\"#555\"/>\n      <rect x=\"84\" y=\"78\" width=\"142\" height=\"88\" fill=\"#e2e6e9\" stroke=\"#777\"/>\n      <rect x=\"90\" y=\"174\" width=\"8\" height=\"40\" fill=\"#999\"/><rect x=\"212\" y=\"174\" width=\"8\" height=\"40\" fill=\"#999\"/>\n      <rect x=\"76\" y=\"176\" width=\"158\" height=\"38\" fill=\"#d7d3cc\" stroke=\"#555\"/>\n      <line x1=\"262\" y1=\"176\" x2=\"262\" y2=\"214\" stroke=\"#2d7a3a\" stroke-width=\"2\"/>\n      <path d=\"M257 182 L262 176 L267 182 M257 208 L262 214 L267 208\" fill=\"none\" stroke=\"#2d7a3a\" stroke-width=\"2\"/>\n      <text x=\"270\" y=\"199\" font-size=\"13\" font-weight=\"700\" fill=\"#2d7a3a\">70-200</text>\n      <text x=\"155\" y=\"232\" text-anchor=\"middle\" font-size=\"12\" fill=\"#555\">Standard plinth: 100mm</text>\n    </svg>`,\n    // Supports for Units With No Plinth: a unit from the side, hung on the wall\n    // with a clear floor under it, a worktop and a TV above - the brackets\n    // and wall fixings drawn dashed in amber, as the part you provide.\n    // Worktop Pantry Units (row 142): Frontal Kit + Fitters Panels = the unit\n    // your fitter builds, standing on the worktop with no base.\n    // Units Reduced On Site: a base unit from the side, the part cut away\n    // behind the plan's depth dashed in amber.\n    'reduced-on-site': `<svg viewBox=\"0 0 320 240\" width=\"100%\" height=\"100%\" role=\"img\" aria-label=\"A base unit from the side, cut down on site to the depth on your plan\" font-family=\"inherit\">\n      <text x=\"160\" y=\"22\" text-anchor=\"middle\" font-size=\"15\" font-weight=\"700\" fill=\"#2d7a3a\">Cut to depth on site</text>\n      <line x1=\"20\" y1=\"204\" x2=\"300\" y2=\"204\" stroke=\"#9a9a9a\" stroke-width=\"3\" stroke-linecap=\"round\"/>\n      <rect x=\"34\" y=\"52\" width=\"170\" height=\"10\" fill=\"#d8d2c8\" stroke=\"#8c867c\" stroke-width=\"1.2\"/>\n      <rect x=\"34\" y=\"64\" width=\"7\" height=\"108\" fill=\"#ffffff\" stroke=\"#4a4a4a\" stroke-width=\"1.5\"/>\n      <rect x=\"41\" y=\"62\" width=\"163\" height=\"112\" fill=\"#f8f4ec\" stroke=\"#4a4a4a\" stroke-width=\"1.5\"/>\n      <rect x=\"204\" y=\"62\" width=\"76\" height=\"112\" fill=\"#c26a00\" fill-opacity=\"0.12\" stroke=\"#c26a00\" stroke-width=\"2\" stroke-dasharray=\"5 3\"/>\n      <line x1=\"204\" y1=\"44\" x2=\"204\" y2=\"186\" stroke=\"#c26a00\" stroke-width=\"2.5\" stroke-dasharray=\"6 3\"/>\n      <text x=\"242\" y=\"114\" text-anchor=\"middle\" font-size=\"13\" font-weight=\"700\" fill=\"#c26a00\">Cut</text>\n      <text x=\"242\" y=\"131\" text-anchor=\"middle\" font-size=\"13\" font-weight=\"700\" fill=\"#c26a00\">away</text>\n      <rect x=\"48\" y=\"174\" width=\"150\" height=\"30\" fill=\"#d7d3cc\" stroke=\"#8c867c\" stroke-width=\"1.2\"/>\n      <line x1=\"34\" y1=\"220\" x2=\"204\" y2=\"220\" stroke=\"#2d7a3a\" stroke-width=\"2\"/>\n      <path d=\"M40 215 L34 220 L40 225 M198 215 L204 220 L198 225\" fill=\"none\" stroke=\"#2d7a3a\" stroke-width=\"2\"/>\n      <text x=\"119\" y=\"236\" text-anchor=\"middle\" font-size=\"12\" font-weight=\"700\" fill=\"#2d7a3a\">Depth on your plan</text>\n      <text x=\"96\" y=\"122\" text-anchor=\"middle\" font-size=\"11\" fill=\"#666\">Door at the front</text>\n    </svg>`,\n    'pantry': `<svg viewBox=\"0 0 320 240\" width=\"100%\" height=\"100%\" role=\"img\" aria-label=\"A Frontal Kit and Fitters Panels, built on site into a Worktop Pantry Unit that stands on the worktop\" font-family=\"inherit\">\n      <text x=\"160\" y=\"22\" text-anchor=\"middle\" font-size=\"15\" font-weight=\"700\" fill=\"#2d7a3a\">Built on site by your fitter</text>\n      <rect x=\"14\" y=\"62\" width=\"26\" height=\"74\" rx=\"1.5\" fill=\"#ffffff\" stroke=\"#4a4a4a\" stroke-width=\"1.5\"/>\n      <rect x=\"42\" y=\"62\" width=\"26\" height=\"74\" rx=\"1.5\" fill=\"#ffffff\" stroke=\"#4a4a4a\" stroke-width=\"1.5\"/>\n      <circle cx=\"58\" cy=\"99\" r=\"2\" fill=\"#4a4a4a\"/>\n      <text x=\"41\" y=\"156\" text-anchor=\"middle\" font-size=\"12\" font-weight=\"700\" fill=\"#333\">Frontal Kit</text>\n      <text x=\"41\" y=\"171\" text-anchor=\"middle\" font-size=\"10.5\" fill=\"#777\">doors &amp; fittings</text>\n      <text x=\"85\" y=\"104\" text-anchor=\"middle\" font-size=\"20\" font-weight=\"700\" fill=\"#777\">+</text>\n      <rect x=\"112\" y=\"58\" width=\"44\" height=\"80\" fill=\"#efe9df\" stroke=\"#8c867c\" stroke-width=\"1.3\"/>\n      <rect x=\"106\" y=\"62\" width=\"44\" height=\"80\" fill=\"#f4efe6\" stroke=\"#8c867c\" stroke-width=\"1.3\"/>\n      <rect x=\"100\" y=\"66\" width=\"44\" height=\"80\" fill=\"#f8f4ec\" stroke=\"#8c867c\" stroke-width=\"1.3\"/>\n      <text x=\"125\" y=\"160\" text-anchor=\"middle\" font-size=\"12\" font-weight=\"700\" fill=\"#333\">Fitters Panels</text>\n      <text x=\"125\" y=\"175\" text-anchor=\"middle\" font-size=\"10.5\" fill=\"#777\">full sheets</text>\n      <text x=\"179\" y=\"104\" text-anchor=\"middle\" font-size=\"20\" font-weight=\"700\" fill=\"#777\">=</text>\n      <rect x=\"200\" y=\"186\" width=\"112\" height=\"9\" fill=\"#d8d2c8\" stroke=\"#8c867c\" stroke-width=\"1.2\"/>\n      <rect x=\"202\" y=\"44\" width=\"106\" height=\"8\" fill=\"#e4e0d8\" stroke=\"#8c867c\" stroke-width=\"1\"/>\n      <rect x=\"206\" y=\"52\" width=\"98\" height=\"134\" fill=\"#f8f4ec\" stroke=\"#4a4a4a\" stroke-width=\"1.5\"/>\n      <line x1=\"210\" y1=\"108\" x2=\"300\" y2=\"108\" stroke=\"#8c867c\" stroke-width=\"1.5\"/>\n      <line x1=\"232\" y1=\"56\" x2=\"232\" y2=\"108\" stroke=\"#8c867c\" stroke-width=\"1\"/>\n      <line x1=\"255\" y1=\"56\" x2=\"255\" y2=\"108\" stroke=\"#8c867c\" stroke-width=\"1\"/>\n      <line x1=\"278\" y1=\"56\" x2=\"278\" y2=\"108\" stroke=\"#8c867c\" stroke-width=\"1\"/>\n      <rect x=\"208\" y=\"54\" width=\"22\" height=\"130\" fill=\"#ffffff\" fill-opacity=\"0.92\" stroke=\"#4a4a4a\" stroke-width=\"1.2\"/>\n      <rect x=\"282\" y=\"54\" width=\"20\" height=\"130\" fill=\"#ffffff\" fill-opacity=\"0.92\" stroke=\"#4a4a4a\" stroke-width=\"1.2\"/>\n      <text x=\"256\" y=\"152\" text-anchor=\"middle\" font-size=\"10\" fill=\"#777\">no base</text>\n      <text x=\"256\" y=\"212\" text-anchor=\"middle\" font-size=\"11\" fill=\"#c26a00\">stands on your worktop</text>\n      <text x=\"160\" y=\"232\" text-anchor=\"middle\" font-size=\"13\" fill=\"#777\">Worktop Pantry Unit, doors open</text>\n    </svg>`,\n    'floating': `<svg viewBox=\"0 0 320 240\" width=\"100%\" height=\"100%\" role=\"img\" aria-label=\"A unit with no plinth, from the side: it needs supports and wall fixings to suit your wall, which are not provided\" font-family=\"inherit\">\n      <text x=\"160\" y=\"22\" text-anchor=\"middle\" font-size=\"15\" font-weight=\"700\" fill=\"#2d7a3a\">Hung on the wall, no plinth</text>\n      <rect x=\"20\" y=\"34\" width=\"16\" height=\"170\" fill=\"#e4e0d8\" stroke=\"#8c867c\" stroke-width=\"1.5\"/>\n      <line x1=\"20\" y1=\"204\" x2=\"300\" y2=\"204\" stroke=\"#9a9a9a\" stroke-width=\"3\" stroke-linecap=\"round\"/>\n      <rect x=\"37\" y=\"50\" width=\"10\" height=\"56\" rx=\"1.5\" fill=\"#17181b\"/>\n      <text x=\"58\" y=\"72\" font-size=\"11\" fill=\"#666\">TV</text>\n      <rect x=\"37\" y=\"114\" width=\"122\" height=\"8\" fill=\"#d8d2c8\" stroke=\"#8c867c\" stroke-width=\"1.2\"/>\n      <rect x=\"37\" y=\"122\" width=\"116\" height=\"36\" fill=\"#ffffff\" stroke=\"#4a4a4a\" stroke-width=\"1.5\"/>\n      <line x1=\"150\" y1=\"126\" x2=\"150\" y2=\"154\" stroke=\"#4a4a4a\" stroke-width=\"1\"/>\n      <text x=\"95\" y=\"145\" text-anchor=\"middle\" font-size=\"11\" fill=\"#666\">Unit</text>\n      <path d=\"M37 160 H86 L37 190 Z\" fill=\"#c26a00\" fill-opacity=\"0.12\" stroke=\"#c26a00\" stroke-width=\"2\" stroke-dasharray=\"5 3\" stroke-linejoin=\"round\"/>\n      <line x1=\"26\" y1=\"130\" x2=\"44\" y2=\"130\" stroke=\"#c26a00\" stroke-width=\"2.5\" stroke-dasharray=\"3 2\"/>\n      <line x1=\"26\" y1=\"176\" x2=\"44\" y2=\"176\" stroke=\"#c26a00\" stroke-width=\"2.5\" stroke-dasharray=\"3 2\"/>\n      <line x1=\"120\" y1=\"162\" x2=\"120\" y2=\"201\" stroke=\"#777\" stroke-width=\"1\"/>\n      <path d=\"M116 166 L120 160 L124 166 M116 196 L120 202 L124 196\" fill=\"none\" stroke=\"#777\" stroke-width=\"1\"/>\n      <text x=\"128\" y=\"186\" font-size=\"11\" fill=\"#777\">Height from floor</text>\n      <text x=\"236\" y=\"124\" text-anchor=\"middle\" font-size=\"14\" font-weight=\"700\" fill=\"#c26a00\">Supports and</text>\n      <text x=\"236\" y=\"141\" text-anchor=\"middle\" font-size=\"14\" font-weight=\"700\" fill=\"#c26a00\">wall fixings</text>\n      <text x=\"236\" y=\"158\" text-anchor=\"middle\" font-size=\"12\" fill=\"#c26a00\">not provided</text>\n      <path d=\"M190 150 Q150 168 92 172\" fill=\"none\" stroke=\"#c26a00\" stroke-width=\"1.2\" marker-end=\"url(#btkCkArrow)\"/>\n      <defs><marker id=\"btkCkArrow\" markerWidth=\"8\" markerHeight=\"8\" refX=\"6\" refY=\"4\" orient=\"auto\"><path d=\"M0 0 L8 4 L0 8 Z\" fill=\"#c26a00\"/></marker></defs>\n      <text x=\"236\" y=\"58\" text-anchor=\"middle\" font-size=\"12\" fill=\"#666\">Chosen to suit your wall</text>\n      <text x=\"236\" y=\"74\" text-anchor=\"middle\" font-size=\"12\" fill=\"#666\">and the weight they carry</text>\n      <text x=\"160\" y=\"230\" text-anchor=\"middle\" font-size=\"13\" fill=\"#777\">Unit with no plinth, from the side</text>\n    </svg>`,\n    // Room Sizes: a room from above with its two sizes, a window, a door and\n    // a radiator - the things worth checking - and a tick in the middle\n    // (bug sheet, Sales row 50).\n    'room-sizes': `<svg viewBox=\"0 0 320 240\" width=\"100%\" height=\"100%\" role=\"img\" aria-label=\"A room from above with its wall sizes, a window, a door and a radiator to check\" font-family=\"inherit\">\n      <line x1=\"60\" y1=\"30\" x2=\"260\" y2=\"30\" stroke=\"#2d7a3a\" stroke-width=\"1.5\"/>\n      <line x1=\"60\" y1=\"24\" x2=\"60\" y2=\"36\" stroke=\"#2d7a3a\" stroke-width=\"1.5\"/>\n      <line x1=\"260\" y1=\"24\" x2=\"260\" y2=\"36\" stroke=\"#2d7a3a\" stroke-width=\"1.5\"/>\n      <text x=\"160\" y=\"22\" text-anchor=\"middle\" font-size=\"13\" font-weight=\"700\" fill=\"#2d7a3a\">4200mm</text>\n      <line x1=\"280\" y1=\"44\" x2=\"280\" y2=\"184\" stroke=\"#2d7a3a\" stroke-width=\"1.5\"/>\n      <line x1=\"274\" y1=\"44\" x2=\"286\" y2=\"44\" stroke=\"#2d7a3a\" stroke-width=\"1.5\"/>\n      <line x1=\"274\" y1=\"184\" x2=\"286\" y2=\"184\" stroke=\"#2d7a3a\" stroke-width=\"1.5\"/>\n      <text x=\"300\" y=\"114\" text-anchor=\"middle\" font-size=\"13\" font-weight=\"700\" fill=\"#2d7a3a\" transform=\"rotate(90 300 114)\">3500mm</text>\n      <rect x=\"60\" y=\"44\" width=\"200\" height=\"140\" fill=\"#f5f3ef\"/>\n      <path d=\"M120 44 H60 V184 H190 M235 184 H260 V44 H190\" fill=\"none\" stroke=\"#9a9a9a\" stroke-width=\"6\" stroke-linecap=\"square\"/>\n      <line x1=\"120\" y1=\"41\" x2=\"190\" y2=\"41\" stroke=\"#7fb3d5\" stroke-width=\"2\"/>\n      <line x1=\"120\" y1=\"47\" x2=\"190\" y2=\"47\" stroke=\"#7fb3d5\" stroke-width=\"2\"/>\n      <text x=\"155\" y=\"62\" text-anchor=\"middle\" font-size=\"11\" fill=\"#666\">Window</text>\n      <line x1=\"190\" y1=\"184\" x2=\"190\" y2=\"141\" stroke=\"#4a4a4a\" stroke-width=\"2\"/>\n      <path d=\"M190 141 A43 43 0 0 1 233 184\" fill=\"none\" stroke=\"#8c867c\" stroke-width=\"1.2\" stroke-dasharray=\"3 3\"/>\n      <text x=\"214\" y=\"176\" text-anchor=\"middle\" font-size=\"11\" fill=\"#666\">Door</text>\n      <rect x=\"64\" y=\"90\" width=\"9\" height=\"50\" fill=\"#ffffff\" stroke=\"#8c867c\" stroke-width=\"1.2\"/>\n      <line x1=\"64\" y1=\"100\" x2=\"73\" y2=\"100\" stroke=\"#8c867c\"/>\n      <line x1=\"64\" y1=\"110\" x2=\"73\" y2=\"110\" stroke=\"#8c867c\"/>\n      <line x1=\"64\" y1=\"120\" x2=\"73\" y2=\"120\" stroke=\"#8c867c\"/>\n      <line x1=\"64\" y1=\"130\" x2=\"73\" y2=\"130\" stroke=\"#8c867c\"/>\n      <text x=\"80\" y=\"119\" font-size=\"11\" fill=\"#666\">Radiator</text>\n      <circle cx=\"160\" cy=\"118\" r=\"20\" fill=\"#2d7a3a\"/>\n      <polyline points=\"150 118 157 125 171 111\" fill=\"none\" stroke=\"#ffffff\" stroke-width=\"3.2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>\n      <text x=\"160\" y=\"212\" text-anchor=\"middle\" font-size=\"14\" font-weight=\"700\" fill=\"#2d7a3a\">Every wall, window and door</text>\n      <text x=\"160\" y=\"232\" text-anchor=\"middle\" font-size=\"13\" fill=\"#777\">Your room, from above</text>\n    </svg>`,\n    // Belfast Sink Worktop: the sink and worktop from above. Left, base units\n    // both sides - the worktop wraps the sink. Right, a tall unit beside it -\n    // only a sliver of worktop is left on that edge, too thin to fit\n    // (Arden, 2026-10-26).\n    'belfast-worktop': `<svg viewBox=\"0 0 320 240\" width=\"100%\" height=\"100%\" role=\"img\" aria-label=\"The worktop wraps both sides of a Belfast sink; beside a tall unit the strip on that side is too thin\" font-family=\"inherit\">\n      <text x=\"160\" y=\"22\" text-anchor=\"middle\" font-size=\"15\" font-weight=\"700\" fill=\"#2d7a3a\">Worktop round both sides</text>\n      <line x1=\"12\" y1=\"44\" x2=\"148\" y2=\"44\" stroke=\"#9a9a9a\" stroke-width=\"5\" stroke-linecap=\"round\"/>\n      <rect x=\"60\" y=\"56\" width=\"46\" height=\"62\" rx=\"4\" fill=\"#ffffff\" stroke=\"#4a4a4a\" stroke-width=\"1.5\"/>\n      <rect x=\"66\" y=\"64\" width=\"34\" height=\"48\" rx=\"3\" fill=\"#eef1f3\" stroke=\"#8c867c\" stroke-width=\"1\"/>\n      <path d=\"M16 47 H146 V112 H102 V60 H64 V112 H16 Z\" fill=\"#d8d2c8\" stroke=\"#8c867c\" stroke-width=\"1.5\"/>\n      <line x1=\"16\" y1=\"112\" x2=\"64\" y2=\"112\" stroke=\"#2d7a3a\" stroke-width=\"3\"/>\n      <line x1=\"102\" y1=\"112\" x2=\"146\" y2=\"112\" stroke=\"#2d7a3a\" stroke-width=\"3\"/>\n      <text x=\"40\" y=\"88\" text-anchor=\"middle\" font-size=\"11\" fill=\"#666\">Base</text>\n      <text x=\"124\" y=\"88\" text-anchor=\"middle\" font-size=\"11\" fill=\"#666\">Base</text>\n      <text x=\"81\" y=\"140\" text-anchor=\"middle\" font-size=\"14\" font-weight=\"700\" fill=\"#2d7a3a\">Base units</text>\n      <text x=\"81\" y=\"157\" text-anchor=\"middle\" font-size=\"14\" font-weight=\"700\" fill=\"#2d7a3a\">both sides</text>\n      <line x1=\"172\" y1=\"44\" x2=\"308\" y2=\"44\" stroke=\"#9a9a9a\" stroke-width=\"5\" stroke-linecap=\"round\"/>\n      <rect x=\"174\" y=\"47\" width=\"40\" height=\"72\" fill=\"#f5f3ef\" stroke=\"#4a4a4a\" stroke-width=\"1.5\"/>\n      <text x=\"192\" y=\"66\" text-anchor=\"middle\" font-size=\"11\" fill=\"#666\">Tall</text>\n      <rect x=\"215\" y=\"56\" width=\"46\" height=\"62\" rx=\"4\" fill=\"#ffffff\" stroke=\"#4a4a4a\" stroke-width=\"1.5\"/>\n      <rect x=\"221\" y=\"64\" width=\"34\" height=\"48\" rx=\"3\" fill=\"#eef1f3\" stroke=\"#8c867c\" stroke-width=\"1\"/>\n      <path d=\"M214 47 H306 V112 H257 V60 H219 V112 H214 Z\" fill=\"#d8d2c8\" stroke=\"#8c867c\" stroke-width=\"1.5\"/>\n      <rect x=\"214\" y=\"60\" width=\"5\" height=\"52\" fill=\"#c26a00\" fill-opacity=\"0.35\"/>\n      <circle cx=\"217\" cy=\"92\" r=\"13\" fill=\"none\" stroke=\"#c26a00\" stroke-width=\"2\" stroke-dasharray=\"4 3\"/>\n      <text x=\"284\" y=\"88\" text-anchor=\"middle\" font-size=\"11\" fill=\"#666\">Base</text>\n      <text x=\"240\" y=\"140\" text-anchor=\"middle\" font-size=\"14\" font-weight=\"700\" fill=\"#c26a00\">Too thin beside</text>\n      <text x=\"240\" y=\"157\" text-anchor=\"middle\" font-size=\"14\" font-weight=\"700\" fill=\"#c26a00\">a tall unit</text>\n      <text x=\"240\" y=\"174\" text-anchor=\"middle\" font-size=\"12\" fill=\"#c26a00\">no worktop that side</text>\n      <text x=\"160\" y=\"210\" text-anchor=\"middle\" font-size=\"12\" fill=\"#777\">Also at the end of a run, or against a wall</text>\n      <text x=\"160\" y=\"230\" text-anchor=\"middle\" font-size=\"13\" fill=\"#777\">Belfast sink and worktop, from above</text>\n    </svg>`,\n    // Round Edge Worktop on a Curve: the worktop from above, against the wall,\n    // with a radius front corner - the rounded edge runs neatly along the\n    // straight front but cannot follow the curve; the ring marks where the\n    // two meet (Arden, 2026-10-14).\n    'bullnose': `<svg viewBox=\"0 0 320 220\" width=\"100%\" height=\"100%\" role=\"img\" aria-label=\"A round edge worktop: neat along the straight front, not as neat on the curve\" font-family=\"inherit\">\n      <path d=\"M24 26 h44 a8 8 0 0 1 0 16 h-44 z\" fill=\"#d8d2c8\" stroke=\"#8c867c\" stroke-width=\"1.5\"/>\n      <text x=\"88\" y=\"38\" font-size=\"13\" fill=\"#777\">Round edge worktop, from the side</text>\n      <line x1=\"14\" y1=\"70\" x2=\"290\" y2=\"70\" stroke=\"#9a9a9a\" stroke-width=\"5\" stroke-linecap=\"round\"/>\n      <path d=\"M20 72 H280 A88 88 0 0 1 192 160 H20 Z\" fill=\"#e7e2da\" stroke=\"#8c867c\" stroke-width=\"1.5\"/>\n      <rect x=\"20\" y=\"150\" width=\"172\" height=\"10\" fill=\"#d2ccc1\"/>\n      <line x1=\"20\" y1=\"154\" x2=\"192\" y2=\"154\" stroke=\"#f4f1ec\" stroke-width=\"2\"/>\n      <line x1=\"20\" y1=\"160\" x2=\"192\" y2=\"160\" stroke=\"#2d7a3a\" stroke-width=\"3\"/>\n      <path d=\"M280 72 A88 88 0 0 1 192 160\" fill=\"none\" stroke=\"#c26a00\" stroke-width=\"3\"/>\n      <circle cx=\"192\" cy=\"160\" r=\"16\" fill=\"none\" stroke=\"#c26a00\" stroke-width=\"2\" stroke-dasharray=\"4 3\"/>\n      <text x=\"100\" y=\"186\" text-anchor=\"middle\" font-size=\"14\" font-weight=\"700\" fill=\"#2d7a3a\">Neat on the straight</text>\n      <text x=\"258\" y=\"104\" text-anchor=\"end\" font-size=\"14\" font-weight=\"700\" fill=\"#c26a00\">Not as neat</text>\n      <text x=\"258\" y=\"121\" text-anchor=\"end\" font-size=\"14\" font-weight=\"700\" fill=\"#c26a00\">on the curve</text>\n      <text x=\"160\" y=\"210\" text-anchor=\"middle\" font-size=\"13\" fill=\"#777\">Worktop from above, against the wall</text>\n    </svg>`,\n    // Walkways: a run of units along the wall and an island, from above, with\n    // the 900mm walkway between them and a drawer pulled out into it.\n    // Plain Narrow Doors & Top Drawers: a standard framed door, a 146mm door\n    // and a drawerline unit's 140mm top drawer, drawn to one scale (0.18px per\n    // mm). The 80mm frames each would need are dashed in red over the narrow\n    // ones - they meet past the middle, so there is no panel and the front is\n    // a plain slab (Arden, 2026-10-25).\n    'slab-fronts': `<svg viewBox=\"0 0 320 240\" width=\"100%\" height=\"100%\" role=\"img\" aria-label=\"An 80mm frame does not fit on a 146mm door or a 140mm top drawer, so they are plain slab fronts\" font-family=\"inherit\">\n      <text x=\"160\" y=\"20\" text-anchor=\"middle\" font-size=\"15\" font-weight=\"700\" fill=\"#2d7a3a\">Too small for a frame</text>\n      <rect x=\"18\" y=\"44\" width=\"90\" height=\"130\" fill=\"#f5f3ef\" stroke=\"#4a4a4a\" stroke-width=\"1.5\"/>\n      <rect x=\"32\" y=\"58\" width=\"62\" height=\"102\" fill=\"#ebe6de\" stroke=\"#8c867c\" stroke-width=\"1.2\"/>\n      <line x1=\"18\" y1=\"36\" x2=\"32\" y2=\"36\" stroke=\"#2d7a3a\" stroke-width=\"1.5\"/>\n      <text x=\"25\" y=\"32\" text-anchor=\"middle\" font-size=\"11\" fill=\"#2d7a3a\">80</text>\n      <text x=\"63\" y=\"192\" text-anchor=\"middle\" font-size=\"13\" font-weight=\"700\" fill=\"#333\">Framed door</text>\n      <text x=\"63\" y=\"208\" text-anchor=\"middle\" font-size=\"12\" fill=\"#777\">frame + panel</text>\n      <rect x=\"134\" y=\"44\" width=\"26\" height=\"130\" fill=\"#f5f3ef\" stroke=\"#4a4a4a\" stroke-width=\"1.5\"/>\n      <rect x=\"134\" y=\"44\" width=\"14\" height=\"130\" fill=\"#c26a00\" fill-opacity=\"0.12\" stroke=\"#CE0402\" stroke-width=\"1\" stroke-dasharray=\"3 2\"/>\n      <rect x=\"146\" y=\"44\" width=\"14\" height=\"130\" fill=\"#c26a00\" fill-opacity=\"0.12\" stroke=\"#CE0402\" stroke-width=\"1\" stroke-dasharray=\"3 2\"/>\n      <line x1=\"134\" y1=\"36\" x2=\"160\" y2=\"36\" stroke=\"#c26a00\" stroke-width=\"1.5\"/>\n      <text x=\"147\" y=\"32\" text-anchor=\"middle\" font-size=\"11\" fill=\"#c26a00\">146</text>\n      <text x=\"147\" y=\"192\" text-anchor=\"middle\" font-size=\"13\" font-weight=\"700\" fill=\"#c26a00\">Plain</text>\n      <text x=\"147\" y=\"208\" text-anchor=\"middle\" font-size=\"12\" fill=\"#777\">narrow door</text>\n      <rect x=\"190\" y=\"44\" width=\"110\" height=\"25\" fill=\"#f5f3ef\" stroke=\"#4a4a4a\" stroke-width=\"1.5\"/>\n      <rect x=\"190\" y=\"44\" width=\"110\" height=\"14\" fill=\"#c26a00\" fill-opacity=\"0.12\" stroke=\"#CE0402\" stroke-width=\"1\" stroke-dasharray=\"3 2\"/>\n      <rect x=\"190\" y=\"55\" width=\"110\" height=\"14\" fill=\"#c26a00\" fill-opacity=\"0.12\" stroke=\"#CE0402\" stroke-width=\"1\" stroke-dasharray=\"3 2\"/>\n      <line x1=\"306\" y1=\"44\" x2=\"306\" y2=\"69\" stroke=\"#c26a00\" stroke-width=\"1.5\"/>\n      <text x=\"304\" y=\"40\" text-anchor=\"end\" font-size=\"11\" fill=\"#c26a00\">140</text>\n      <rect x=\"190\" y=\"72\" width=\"110\" height=\"102\" fill=\"#f5f3ef\" stroke=\"#4a4a4a\" stroke-width=\"1.5\"/>\n      <rect x=\"204\" y=\"86\" width=\"82\" height=\"74\" fill=\"#ebe6de\" stroke=\"#8c867c\" stroke-width=\"1.2\"/>\n      <text x=\"245\" y=\"192\" text-anchor=\"middle\" font-size=\"13\" font-weight=\"700\" fill=\"#c26a00\">Plain top drawer</text>\n      <text x=\"245\" y=\"208\" text-anchor=\"middle\" font-size=\"12\" fill=\"#777\">framed door below</text>\n      <text x=\"160\" y=\"232\" text-anchor=\"middle\" font-size=\"12\" fill=\"#CE0402\">80mm + 80mm frame = 160mm: more than the front</text>\n    </svg>`,\n    'walkways': `<svg viewBox=\"0 0 320 240\" width=\"100%\" height=\"100%\" role=\"img\" aria-label=\"Leave at least 900mm between the units and the island\" font-family=\"inherit\">\n      <text x=\"160\" y=\"22\" text-anchor=\"middle\" font-size=\"15\" font-weight=\"700\" fill=\"#2d7a3a\">Room to walk and open doors</text>\n      <line x1=\"14\" y1=\"38\" x2=\"306\" y2=\"38\" stroke=\"#9a9a9a\" stroke-width=\"5\" stroke-linecap=\"round\"/>\n      <rect x=\"20\" y=\"40\" width=\"280\" height=\"50\" fill=\"#f5f3ef\" stroke=\"#4a4a4a\" stroke-width=\"1.5\"/>\n      <line x1=\"76\" y1=\"40\" x2=\"76\" y2=\"90\" stroke=\"#4a4a4a\" stroke-width=\"1\"/>\n      <line x1=\"132\" y1=\"40\" x2=\"132\" y2=\"90\" stroke=\"#4a4a4a\" stroke-width=\"1\"/>\n      <line x1=\"188\" y1=\"40\" x2=\"188\" y2=\"90\" stroke=\"#4a4a4a\" stroke-width=\"1\"/>\n      <line x1=\"244\" y1=\"40\" x2=\"244\" y2=\"90\" stroke=\"#4a4a4a\" stroke-width=\"1\"/>\n      <rect x=\"22\" y=\"90\" width=\"52\" height=\"30\" fill=\"none\" stroke=\"#8c867c\" stroke-width=\"1.5\" stroke-dasharray=\"4 3\"/>\n      <rect x=\"60\" y=\"165\" width=\"200\" height=\"48\" fill=\"#f5f3ef\" stroke=\"#4a4a4a\" stroke-width=\"1.5\"/>\n      <line x1=\"126\" y1=\"165\" x2=\"126\" y2=\"213\" stroke=\"#4a4a4a\" stroke-width=\"1\"/>\n      <line x1=\"194\" y1=\"165\" x2=\"194\" y2=\"213\" stroke=\"#4a4a4a\" stroke-width=\"1\"/>\n      <line x1=\"160\" y1=\"94\" x2=\"160\" y2=\"161\" stroke=\"#2d7a3a\" stroke-width=\"2\"/>\n      <path d=\"M154 101 L160 93 L166 101\" fill=\"none\" stroke=\"#2d7a3a\" stroke-width=\"2\"/>\n      <path d=\"M154 154 L160 162 L166 154\" fill=\"none\" stroke=\"#2d7a3a\" stroke-width=\"2\"/>\n      <text x=\"172\" y=\"125\" font-size=\"15\" font-weight=\"700\" fill=\"#2d7a3a\">900mm</text>\n      <text x=\"172\" y=\"142\" font-size=\"13\" fill=\"#666\">or more</text>\n      <text x=\"160\" y=\"234\" text-anchor=\"middle\" font-size=\"13\" fill=\"#777\">Units and island, from above</text>\n    </svg>`,\n    'panel-joins': `<svg viewBox=\"0 0 320 220\" width=\"100%\" height=\"100%\" role=\"img\" aria-label=\"Two panels butted together with a neat join\" font-family=\"inherit\">\n      <rect x=\"14\" y=\"44\" width=\"292\" height=\"14\" rx=\"2\" fill=\"#d8d2c8\" stroke=\"#8c867c\"/>\n      <rect x=\"22\" y=\"58\" width=\"176\" height=\"120\" fill=\"#f5f3ef\" stroke=\"#4a4a4a\" stroke-width=\"1.5\"/>\n      <rect x=\"198\" y=\"58\" width=\"100\" height=\"120\" fill=\"#f5f3ef\" stroke=\"#4a4a4a\" stroke-width=\"1.5\"/>\n      <line x1=\"10\" y1=\"186\" x2=\"310\" y2=\"186\" stroke=\"#b9b9b9\" stroke-width=\"2\"/>\n      <text x=\"110\" y=\"124\" text-anchor=\"middle\" font-size=\"15\" fill=\"#666\">Panel 1</text>\n      <text x=\"248\" y=\"124\" text-anchor=\"middle\" font-size=\"15\" fill=\"#666\">Panel 2</text>\n      <line x1=\"198\" y1=\"58\" x2=\"198\" y2=\"178\" stroke=\"#2d7a3a\" stroke-width=\"3\"/>\n      <circle cx=\"198\" cy=\"118\" r=\"18\" fill=\"none\" stroke=\"#2d7a3a\" stroke-width=\"2\" stroke-dasharray=\"4 3\"/>\n      <line x1=\"198\" y1=\"36\" x2=\"198\" y2=\"22\" stroke=\"#2d7a3a\" stroke-width=\"2\"/>\n      <text x=\"198\" y=\"16\" text-anchor=\"middle\" font-size=\"15\" font-weight=\"700\" fill=\"#2d7a3a\">Neat, flush join</text>\n      <text x=\"160\" y=\"210\" text-anchor=\"middle\" font-size=\"13\" fill=\"#777\">Back of island or breakfast bar</text>\n    </svg>`,\n    // Wall Unit Heights: the three heights a wall unit is sold in, drawn to\n    // scale (575 / 720 / 900). Wall units hang with their BOTTOMS level above\n    // the worktop, so their tops step up with the height; tops only line up\n    // with tall units of the same height (Arden, 2026-10-13).\n    'wall-heights': `<svg viewBox=\"0 0 320 230\" width=\"100%\" height=\"100%\" role=\"img\" aria-label=\"Wall units in High, Medium and Low heights - taller units reach higher\" font-family=\"inherit\">\n      <text x=\"160\" y=\"28\" text-anchor=\"middle\" font-size=\"15\" font-weight=\"700\" fill=\"#2d7a3a\">Taller units reach higher</text>\n      <rect x=\"30\" y=\"42\" width=\"80\" height=\"108\" fill=\"#f5f3ef\" stroke=\"#4a4a4a\" stroke-width=\"1.5\"/>\n      <rect x=\"120\" y=\"64\" width=\"80\" height=\"86\" fill=\"#f5f3ef\" stroke=\"#4a4a4a\" stroke-width=\"1.5\"/>\n      <rect x=\"210\" y=\"81\" width=\"80\" height=\"69\" fill=\"#f5f3ef\" stroke=\"#4a4a4a\" stroke-width=\"1.5\"/>\n      <line x1=\"100\" y1=\"130\" x2=\"100\" y2=\"142\" stroke=\"#4a4a4a\" stroke-width=\"3\" stroke-linecap=\"round\"/>\n      <line x1=\"190\" y1=\"130\" x2=\"190\" y2=\"142\" stroke=\"#4a4a4a\" stroke-width=\"3\" stroke-linecap=\"round\"/>\n      <line x1=\"280\" y1=\"130\" x2=\"280\" y2=\"142\" stroke=\"#4a4a4a\" stroke-width=\"3\" stroke-linecap=\"round\"/>\n      <text x=\"70\" y=\"90\" text-anchor=\"middle\" font-size=\"15\" font-weight=\"700\" fill=\"#333\">High</text>\n      <text x=\"70\" y=\"108\" text-anchor=\"middle\" font-size=\"13\" fill=\"#666\">900mm</text>\n      <text x=\"160\" y=\"100\" text-anchor=\"middle\" font-size=\"15\" font-weight=\"700\" fill=\"#333\">Medium</text>\n      <text x=\"160\" y=\"118\" text-anchor=\"middle\" font-size=\"13\" fill=\"#666\">720mm</text>\n      <text x=\"250\" y=\"108\" text-anchor=\"middle\" font-size=\"15\" font-weight=\"700\" fill=\"#333\">Low</text>\n      <text x=\"250\" y=\"125\" text-anchor=\"middle\" font-size=\"13\" fill=\"#666\">575mm</text>\n      <rect x=\"14\" y=\"192\" width=\"292\" height=\"12\" rx=\"2\" fill=\"#d8d2c8\" stroke=\"#8c867c\"/>\n      <text x=\"160\" y=\"224\" text-anchor=\"middle\" font-size=\"13\" fill=\"#777\">Wall units above the worktop</text>\n    </svg>`,\n    // Wall Unit Heights, MIXED heights (bug sheet, Planner row 59): a shorter\n    // unit in a run - a Low over the sink between Mediums - lined up with the\n    // tops of its neighbours (Position > Mount line), which leaves more room\n    // under it. Shown only when the plan mixes heights, so a plan of all Low\n    // units isn't read as having to hang at a taller unit's top line (Arden,\n    // 2026-10-28). Same scale as 'wall-heights'.\n    'wall-heights-mixed': `<svg viewBox=\"0 0 320 230\" width=\"100%\" height=\"100%\" role=\"img\" aria-label=\"A Low wall unit over the sink lined up with the tops of the Medium units beside it\" font-family=\"inherit\">\n      <text x=\"160\" y=\"28\" text-anchor=\"middle\" font-size=\"15\" font-weight=\"700\" fill=\"#2d7a3a\">Tops can line up in a run</text>\n      <line x1=\"22\" y1=\"64\" x2=\"298\" y2=\"64\" stroke=\"#2d7a3a\" stroke-width=\"2.5\" stroke-dasharray=\"6 4\"/>\n      <rect x=\"30\" y=\"64\" width=\"80\" height=\"86\" fill=\"#f5f3ef\" stroke=\"#4a4a4a\" stroke-width=\"1.5\"/>\n      <rect x=\"120\" y=\"64\" width=\"80\" height=\"69\" fill=\"#f5f3ef\" stroke=\"#4a4a4a\" stroke-width=\"1.5\"/>\n      <rect x=\"210\" y=\"64\" width=\"80\" height=\"86\" fill=\"#f5f3ef\" stroke=\"#4a4a4a\" stroke-width=\"1.5\"/>\n      <line x1=\"100\" y1=\"130\" x2=\"100\" y2=\"142\" stroke=\"#4a4a4a\" stroke-width=\"3\" stroke-linecap=\"round\"/>\n      <line x1=\"190\" y1=\"113\" x2=\"190\" y2=\"125\" stroke=\"#4a4a4a\" stroke-width=\"3\" stroke-linecap=\"round\"/>\n      <line x1=\"280\" y1=\"130\" x2=\"280\" y2=\"142\" stroke=\"#4a4a4a\" stroke-width=\"3\" stroke-linecap=\"round\"/>\n      <text x=\"70\" y=\"100\" text-anchor=\"middle\" font-size=\"15\" font-weight=\"700\" fill=\"#333\">Medium</text>\n      <text x=\"70\" y=\"118\" text-anchor=\"middle\" font-size=\"13\" fill=\"#666\">720mm</text>\n      <text x=\"160\" y=\"93\" text-anchor=\"middle\" font-size=\"15\" font-weight=\"700\" fill=\"#333\">Low</text>\n      <text x=\"160\" y=\"110\" text-anchor=\"middle\" font-size=\"13\" fill=\"#666\">575mm</text>\n      <text x=\"250\" y=\"100\" text-anchor=\"middle\" font-size=\"15\" font-weight=\"700\" fill=\"#333\">Medium</text>\n      <text x=\"250\" y=\"118\" text-anchor=\"middle\" font-size=\"13\" fill=\"#666\">720mm</text>\n      <line x1=\"160\" y1=\"138\" x2=\"160\" y2=\"166\" stroke=\"#2d7a3a\" stroke-width=\"2\" stroke-dasharray=\"3 3\"/>\n      <text x=\"160\" y=\"160\" text-anchor=\"middle\" font-size=\"12\" font-weight=\"700\" fill=\"#2d7a3a\" stroke=\"#fff\" stroke-width=\"4\" paint-order=\"stroke\">More room</text>\n      <rect x=\"128\" y=\"186\" width=\"64\" height=\"6\" rx=\"2\" fill=\"#b9b9b9\" stroke=\"#8c867c\"/>\n      <path d=\"M168 186v-12h-8\" fill=\"none\" stroke=\"#8c867c\" stroke-width=\"2.5\" stroke-linecap=\"round\"/>\n      <rect x=\"14\" y=\"192\" width=\"292\" height=\"12\" rx=\"2\" fill=\"#d8d2c8\" stroke=\"#8c867c\"/>\n      <text x=\"160\" y=\"224\" text-anchor=\"middle\" font-size=\"13\" fill=\"#777\">A Low unit over the sink, tops in line</text>\n    </svg>`,\n    // Tall Units: Low / Medium / High tall units, each beside the wall unit of\n    // the same height over a base unit - the tops of a matching pair line up.\n    // To scale: wall units hang from 1400mm, tall units stand on 150mm legs.\n    'tall-heights': `<svg viewBox=\"0 0 320 240\" width=\"100%\" height=\"100%\" role=\"img\" aria-label=\"Low, Medium and High tall units, each lining up with the wall unit of the same height\" font-family=\"inherit\">\n      <rect x=\"16\" y=\"26\" width=\"38\" height=\"167\" fill=\"#f5f3ef\" stroke=\"#4a4a4a\" stroke-width=\"1.5\"/>\n      <rect x=\"56\" y=\"26\" width=\"50\" height=\"70\" fill=\"#f5f3ef\" stroke=\"#4a4a4a\" stroke-width=\"1.5\"/>\n      <rect x=\"56\" y=\"137\" width=\"50\" height=\"56\" fill=\"#f5f3ef\" stroke=\"#4a4a4a\" stroke-width=\"1.5\"/>\n      <rect x=\"56\" y=\"133\" width=\"50\" height=\"4\" fill=\"#d8d2c8\" stroke=\"#8c867c\" stroke-width=\"0.8\"/>\n      <rect x=\"118\" y=\"40\" width=\"38\" height=\"153\" fill=\"#f5f3ef\" stroke=\"#4a4a4a\" stroke-width=\"1.5\"/>\n      <rect x=\"158\" y=\"40\" width=\"50\" height=\"56\" fill=\"#f5f3ef\" stroke=\"#4a4a4a\" stroke-width=\"1.5\"/>\n      <rect x=\"158\" y=\"137\" width=\"50\" height=\"56\" fill=\"#f5f3ef\" stroke=\"#4a4a4a\" stroke-width=\"1.5\"/>\n      <rect x=\"158\" y=\"133\" width=\"50\" height=\"4\" fill=\"#d8d2c8\" stroke=\"#8c867c\" stroke-width=\"0.8\"/>\n      <rect x=\"220\" y=\"51\" width=\"38\" height=\"142\" fill=\"#f5f3ef\" stroke=\"#4a4a4a\" stroke-width=\"1.5\"/>\n      <rect x=\"260\" y=\"51\" width=\"50\" height=\"45\" fill=\"#f5f3ef\" stroke=\"#4a4a4a\" stroke-width=\"1.5\"/>\n      <rect x=\"260\" y=\"137\" width=\"50\" height=\"56\" fill=\"#f5f3ef\" stroke=\"#4a4a4a\" stroke-width=\"1.5\"/>\n      <rect x=\"260\" y=\"133\" width=\"50\" height=\"4\" fill=\"#d8d2c8\" stroke=\"#8c867c\" stroke-width=\"0.8\"/>\n      <line x1=\"12\" y1=\"26\" x2=\"110\" y2=\"26\" stroke=\"#2d7a3a\" stroke-width=\"2.5\" stroke-dasharray=\"6 4\"/>\n      <line x1=\"124\" y1=\"40\" x2=\"212\" y2=\"40\" stroke=\"#2d7a3a\" stroke-width=\"2.5\" stroke-dasharray=\"6 4\"/>\n      <line x1=\"216\" y1=\"51\" x2=\"314\" y2=\"51\" stroke=\"#2d7a3a\" stroke-width=\"2.5\" stroke-dasharray=\"6 4\"/>\n      <rect x=\"14\" y=\"193\" width=\"298\" height=\"12\" fill=\"#e6e3de\" stroke=\"#b9b9b9\"/>\n      <line x1=\"8\" y1=\"205\" x2=\"314\" y2=\"205\" stroke=\"#b9b9b9\" stroke-width=\"2\"/>\n      <text x=\"61\" y=\"222\" text-anchor=\"middle\" font-size=\"14\" font-weight=\"700\" fill=\"#333\">High</text>\n      <text x=\"163\" y=\"222\" text-anchor=\"middle\" font-size=\"14\" font-weight=\"700\" fill=\"#333\">Medium</text>\n      <text x=\"265\" y=\"222\" text-anchor=\"middle\" font-size=\"14\" font-weight=\"700\" fill=\"#333\">Low</text>\n      <text x=\"160\" y=\"238\" text-anchor=\"middle\" font-size=\"12\" fill=\"#2d7a3a\" font-weight=\"700\">Tops line up with units of the same height</text>\n    </svg>`\n  };\n  const CK_CHEVRON = '<svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M9 18l6-6-6-6\"/></svg>';\n  const ckEsc = (s) => String(s == null ? '' : s).replace(/[&<>\"]/g, ch => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '\"': '&quot;' }[ch]));\n  const ckUnits = (n) => `${n} unit${n === 1 ? '' : 's'}`;\n  const ckPretty = (h) => String(h || '').replace(/[-_]+/g, ' ').replace(/\\b\\w/g, ch => ch.toUpperCase());\n  // \"A (3 units), B (2 units) and C (1 unit)\" - or without counts.\n  function ckList(groups, counts = true) {\n    const parts = groups.map(g => (counts ? `${g.label} (${ckUnits(g.n)})` : g.label));\n    return parts.length > 1 ? parts.slice(0, -1).join(', ') + ' and ' + parts[parts.length - 1] : (parts[0] || '');\n  }\n  // Units that carry a door and carcase of their own: not a free-standing\n  // appliance, not a loose panel.\n  function ckUnitsOnPlan() {\n    return cabinets.filter(c => c && c.kitchenStyleId && !c.freestandingAppliance && !c.endPanelUnit);\n  }\n  // Group units by a key, keeping a label and a count, biggest group first.\n  function ckGroup(units, keyOf, labelOf) {\n    const map = new Map();\n    for (const c of units) {\n      const k = keyOf(c);\n      if (k == null) continue;\n      const g = map.get(k) || { key: k, label: labelOf(c), n: 0 };\n      g.n++;\n      map.set(k, g);\n    }\n    return [...map.values()].sort((a, b) => b.n - a.n || String(a.label).localeCompare(String(b.label)));\n  }\n  // One, two, or three-or-more of something: the Odoo checklist's primary /\n  // secondary / tertiary messages, and its zero message.\n  const ckByCount = (n, m) => (n <= 0 ? m.zero : n === 1 ? m.one : n === 2 ? m.two : m.many);\n  // A unit's door-on-carcase picture, for the colour checks' cards.\n  function ckPic(c) {\n    if (!c) return null;\n    const ks = Catalogue.getKitchenStyle && Catalogue.getKitchenStyle(c.kitchenStyleId);\n    const family = ks && ks.carcaseFamilyHandle;\n    return unitPicture(c.kitchenStyleId, c.doorColourHandle, c.carcaseColourHandle,\n      (c.doorColourHandle && Catalogue.getDoorPreviewUrl) ? (Catalogue.getDoorPreviewUrl(c.kitchenStyleId, c.doorColourHandle) || '') : '',\n      (family && c.carcaseColourHandle && Catalogue.getCarcasePreviewUrl) ? (Catalogue.getCarcasePreviewUrl(family, c.carcaseColourHandle) || '') : '');\n  }\n\n  // The plan's basket, for the checks about what is in the ORDER (item types,\n  // assembly). The open basket's own copy when it is showing, so its edits\n  // count; otherwise the saved one. null until the plan has a basket.\n  let ckBasket = null;\n  async function ckLoadBasket() {\n    const live = window.BTKCartAdvanced && window.BTKCartAdvanced.getBasket && window.BTKCartAdvanced.getBasket();\n    if (live && Array.isArray(live.sections)) return live;\n    const api = window.BTKBasketAPI;\n    if (!api) return null;\n    try {\n      const id = lastQuoteBasketId || (api.getActivePlannerBasketId && await api.getActivePlannerBasketId());\n      if (!id) return null;\n      const baskets = await api.getBaskets();\n      return (baskets || []).find(b => b && b.id === id) || null;\n    } catch (e) { return null; }\n  }\n  // Has a salesperson worked on this plan? The planner server marks a plan\n  // (staffWorked) when a staff-mode save changes it, and keeps the mark; a\n  // salesperson in staff mode now counts too. Read with the basket.\n  let ckStaffWorked = false;\n  async function ckLoadStaffWorked() {\n    const api = window.BTKBasketAPI;\n    if (!api) return false;\n    if (typeof api.isStaffMode === 'function' && api.isStaffMode()) return true;\n    try {\n      const id = lastQuoteBasketId || (api.getActivePlannerBasketId && await api.getActivePlannerBasketId());\n      if (!id) return false;\n      const baskets = await api.getBaskets();\n      const b = (baskets || []).find(x => x && x.id === id);\n      return !!(b && b.staffWorked);\n    } catch (e) { return false; }\n  }\n  const ckBasketItems = (b) => (b && Array.isArray(b.sections))\n    ? b.sections.flatMap(s => (s && Array.isArray(s.items)) ? s.items : []) : [];\n\n  const CK = {\n    // Room Sizes (bug sheet, Sales row 50): the customer agrees the room on\n    // the plan is their room. Kind, not small print (Arden, 2026-10-28).\n    roomsizes: {\n      title: 'Room Sizes',\n      advice: 'Your bedroom is designed around these room sizes, so it\\'s worth one last look before you order. They\\'re the measurements you gave us - and, if one of our designers helped, how we understood them. Rooms often change along the way, too: a wall moves, a window is swapped, a radiator goes somewhere new. We plan hundreds of kitchens every week and take real care to keep every number up to date, but now and then one can slip through. You know your room best, so please use Check My Room to look over each wall, the ceiling height, and where the doors, windows, radiators and other features sit. If anything doesn\\'t look right, just let us know - we\\'ll gladly update your plan before anything is made.',\n      confirm: 'I\\'ve checked the room sizes and features on my plan, and I\\'m happy for my bedroom to be designed around them.'\n    },\n    advisory: {\n      title: 'Advisory Points',\n      advice: 'These are points the planner noticed while you were designing. Many are deliberate, so have a look at each one on the plan and accept it there if you\\'re happy with it. This card disappears once they\\'ve all been looked at.',\n      confirm: 'I have read the advisory points and I am happy with my plan.'\n    },\n    bullnose: {\n      title: 'Round Edge Worktop on a Curve',\n      advice: 'Your worktop is a round edge (bullnose) laminate, and it runs over a curved unit or a radius end post. It can be cut to the curve, but the rounded front edge cannot follow it cleanly, so that end will not look as neat as a straight one. Square edge laminate, or a solid worktop such as quartz, gives a much better curved finish - you can change it in Customise > Worktops. If you are happy with how it will look, approve it here.',\n      confirm: 'I understand how a round edge worktop looks on a curve, and I am happy to keep it.'\n    },\n    paneljoins: {\n      title: 'Joins in End Panels',\n      advice: 'Island and breakfast bar panels come in set lengths, so a longer run - or one planned with shorter panels to keep the cost down - is made from more than one panel, butted together. This is very common, and your installer will line the panels up and fit the join as neatly as possible, but it will still be visible up close. If you are happy with that, approve it here.',\n      confirm: 'I understand there will be a visible join in my end panels, and I am happy with it.'\n    },\n    slabfronts: {\n      title: 'Plain Narrow Doors & Top Drawers',\n      advice: 'Your doors are framed: a frame runs round a centre panel. A very narrow door or a shallow top drawer has no room for both - an 80mm frame on each side of a 146mm wide door, or above and below a 140mm high drawer, would meet in the middle with no panel left. So these fronts are made as plain slab fronts, in the same colour and finish as the rest of your bedroom, and that is how they show on your plan.',\n      confirm: 'I understand my narrow doors and top drawers are plain slab fronts, and I am happy with this.'\n    },\n    belfastworktop: {\n      title: 'Belfast Sink Worktop',\n      advice: 'The worktop wraps round both sides of a Belfast sink, so the sink needs a base unit on each side for the worktop to carry on over. At the end of a run, or beside a tall unit, a tall end panel or a wall, the strip of worktop left on that edge is too thin to fit - so that side of the sink would have no worktop. You can put a base unit beside the sink, or move the sink unit along the run. If you want it that way, you can approve it here.',\n      confirm: 'I understand one side of my Belfast sink will have no worktop, and I am happy with my plan.'\n    },\n    // Units With No Plinth (Arden, 2026-10-29; not \"Wall-Hung\" - that reads as every wall unit): a unit whose plinth is set to None\n    // has no plinth or legs, so it hangs on the wall - on supports we don't\n    // supply, chosen to suit the wall and the load.\n    floating: {\n      title: 'Supports for Units With No Plinth',\n      advice: 'With the plinth set to None, these units have no plinth or legs, so they hang on the wall at the height you\\'ve chosen. Bedroom units aren\\'t made to carry themselves off a wall, so they need suitable supports to suit your installation - for example heavy-duty concealed brackets, a timber or steel frame, or a french cleat - with fixings to suit your wall, whether that\\'s masonry, stud or plasterboard. Supports and wall fixings aren\\'t provided with your order. The right ones depend on your wall and on the weight they carry: the unit, what you keep in it, the worktop, and anything standing on it such as a TV. Please plan them with your installer before fitting.',\n      confirm: 'I understand supports and wall fixings for my units with no plinth are not provided, and I will arrange suitable ones for my installation.'\n    },\n    // Worktop Pantry Unit (Sales sheet row 142, Arden 2026-11-19): planned as\n    // one unit, but bought as its parts - a Frontal Kit and Fitters Panels -\n    // and built on site. The customer agrees to that before checkout.\n    // Units Reduced On Site (Arden, 2026-11-19): the Island Designer's\n    // cut-down units, bought at their own depth and cut by the fitter.\n    reducedOnSite: {\n      title: 'Units Reduced On Site',\n      advice: 'To fit your island together just as you\\'ve planned it, some of its units come at their standard depth and are cut down to the depth on your plan when they are fitted - for example to make room behind an appliance, or to suit the depth of your island. From the outside they look just like the rest of your bedroom, with the doors and worktop lining up as planned. Cutting them to depth is part of fitting, so please check your fitter is happy to do it. These units are marked Reduced On Site on your plan and in your basket.',\n      confirm: 'I understand these units are cut down in depth on site by my fitter, and I am happy with this.'\n    },\n    pantry: {\n      title: 'Worktop Pantry Units',\n      advice: 'A Worktop Pantry Unit is built on site by your fitter, rather than arriving as a ready-made cabinet. You plan it here as one unit, and in your basket it comes as its parts: a Worktop Pantry Frontal Kit - the bi-fold doors, hinges and folding fittings - and the Fitters Panels that its sides, top, shelves and pigeon holes are cut from, at the depth and internals you chose. Panels come in full sheets, so there will be some offcut left over. There is no base panel: the unit stands on your worktop and the worktop runs inside it, so its top sits higher than the wall or tall units beside it by the thickness of your worktop. Your fitter measures and checks it on site, then cuts, assembles and fits it - please check they are happy to build it.',\n      confirm: 'I understand my Worktop Pantry Unit is built on site by my fitter from the Frontal Kit and Fitters Panels in my basket.'\n    },\n    plinthHeight: {\n      title: 'Plinth Height',\n      advice: 'Our units are made to stand on a 150mm plinth. Your plan uses a different plinth height, so your base and tall units, worktop and wall units are lower or higher than standard. A plinth lower than 150mm is cut down to height when it is fitted, and the legs are adjusted down to suit; for the lowest heights the legs may need trimming or replacing with shorter ones, which are not provided. Plinths are made 150mm high, so a plinth taller than that is cut from end panels, which are in your basket in its place, and the legs need to reach the extra height. Please check with your fitter that your legs suit the height, and that any integrated appliances under the worktop still fit the space.',\n      confirm: 'I understand my units stand on a plinth that is not the standard 150mm, and what this means for my legs, worktop height and appliances.'\n    },\n    walkways: {\n      title: 'Walkways',\n      advice: 'Walkways under 900mm can feel tight to move around in, and can make doors and drawers harder to open. If it\\'s planned that way, that\\'s fine - you can approve it here.',\n      confirm: 'I am happy with the walkways in my plan.'\n    },\n    doorcarcase: {\n      title: 'Door & Carcase',\n      one: 'You have one door and carcase combination, which is what most of our customers choose. Have a quick look to check it\\'s the look you\\'re expecting.',\n      two: 'You have two door and carcase combinations. Around 15% of our customers choose two door colours for a two-tone look, and two carcase colours is a little rarer. Have a quick look to check it\\'s what you planned.',\n      many: 'You have more than two door and carcase combinations, which is unusual. It may well be what you want - it\\'s worth a quick look to check.',\n      confirm: 'I am happy with my door and carcase colour choices.'\n    },\n    height: {\n      title: 'Wall Unit Heights',\n      one: 'All your wall units are the same height, which gives a neat, level run. Have a quick look to check it\\'s the height you\\'d like.',\n      two: 'Your wall units come in two heights - often a shorter unit over the sink or cooker. A shorter unit can line up with the tops of the units beside it (Position > Mount line), leaving more room underneath. It\\'s worth a quick look to check it\\'s what you planned.',\n      many: 'Your wall units come in three or more heights, which gives a staggered look. If you\\'d rather a run lined up along the top, a shorter unit can be moved up to its neighbours\\' line (Position > Mount line). It\\'s worth a quick look to check.',\n      confirm: 'I confirm I am happy with this configuration of units.'\n    },\n    tall: {\n      title: 'Tall Units',\n      one: 'All your tall units are the same height, so they\\'ll line up neatly. Have a quick look to check it\\'s the height you\\'d like.',\n      two: 'Your tall units come in two heights - for example a larder beside an oven housing. It\\'s worth a quick look to check it\\'s what you planned.',\n      many: 'Your tall units come in three heights, which gives a staggered look. If that\\'s the effect you\\'re after, that\\'s fine - it\\'s worth a quick look to check.',\n      confirm: 'I confirm I am happy with the heights of my tall units.'\n    },\n    cornice: {\n      title: 'Cornice',\n      chosen: 'Cornice runs along the top of your wall and tall units to give them a finished look. Here\\'s the one you\\'ve chosen - have a quick look to check it\\'s the style you want. You can change it in Customise.',\n      none: 'You haven\\'t chosen a cornice. Plenty of bedrooms look great without one - you can add one in Customise if you\\'d like.',\n      // Ceiling Filler chosen in place of a cornice (bug sheet, Sales row 32:\n      // the card said \"No cornice\").\n      filler: 'Instead of a cornice, filler panels run from the top of your wall and tall units up to the ceiling, flush with the doors, and the end panels go up to the ceiling too. Have a quick look to check it\\'s the finish you want. You can change it in Customise.',\n      confirm: 'I am happy with my cornice choice.'\n    },\n    pelmet: {\n      title: 'Pelmet',\n      chosen: 'Pelmet runs along the underside of your wall units, giving them a neat edge and hiding any under-cabinet lighting. Here\\'s the one you\\'ve chosen - have a quick look to check it\\'s the style you want. You can change it in Customise.',\n      differs: 'Your pelmet is a different style to your cornice. Most bedrooms use one style for both, so it\\'s worth a quick look - you can change either in Customise, or keep them as they are if that\\'s the look you want.',\n      none: 'You haven\\'t chosen a pelmet. Many bedrooms look great without one - you can add one in Customise if you\\'d like.',\n      confirm: 'I am happy with my pelmet choice.'\n    },\n    plinth: {\n      title: 'Plinth',\n      chosen: 'Plinth runs along the bottom of your base and tall units, covering the legs. Here\\'s the one you\\'ve chosen - have a quick look to check it\\'s the style you want. You can change it in Customise.',\n      none: 'You haven\\'t chosen a plinth, so the legs under your units will be on show. Most bedrooms have one - you can add it in Customise.',\n      confirm: 'I am happy with my plinth choice.'\n    },\n    endpanels: {\n      title: 'End Panels',\n      advice: 'End panels finish the exposed sides of your units. Here are the types on your plan - have a quick look to check they\\'re what you expected. You can change any of them by selecting the unit and opening End Panels & Fillers.',\n      confirm: 'I am happy with the end panels on my plan.'\n    },\n    profile: {\n      title: 'Profile',\n      zero: 'No profile colour is chosen yet. True Handleless units usually need one - you can choose it in Customise, or our team can help.',\n      one: 'You have one profile colour throughout, which keeps the look consistent.',\n      two: 'You have two profile colours. If that\\'s what you planned, that\\'s fine - it\\'s worth a quick look to check.',\n      many: 'You have more than two profile colours, which is unusual. It may well be what you want - it\\'s worth a quick look to check.',\n      confirm: 'I am happy with my Profile colour choice.'\n    },\n    inventory: {\n      title: 'Inventory',\n      advice: 'This isn\\'t a hard sell. We just want you to know exactly what\\'s included in your order, and to point out anything you might have overlooked. If you already have something covered, or you\\'re buying it elsewhere, just let us know with Buy Elsewhere.',\n      confirm: 'I am happy with the types of item in my order.'\n    },\n    assembly: {\n      title: 'Assembly',\n      advice: 'Most of our units come either Fully Assembled, ready to fit, or Flat Packed to build yourself. If this mix suits you, you can approve it here.',\n      confirm: 'I\\'m happy with the number of Assembled & Flat Pack units on my order.'\n    },\n    recommend: {\n      title: 'Recommendations',\n      advice: 'These are items we\\'d usually suggest for a bedroom like yours. Have a look in your basket to add any you need - or leave them if you\\'ve got it covered.',\n      confirm: 'I am happy with my choices.'\n    }\n  };\n  // The basket's groups, by the quoteGroup each line carries.\n  const CK_INVENTORY = [\n    ['units', 'Units'], ['panels', 'End Panels & Fillers'], ['worktops', 'Worktops'], ['handles', 'Handles'],\n    ['appliances', 'Appliances, Sinks & Taps'], ['trims', 'Plinth, Cornice & Pelmet'], ['extras', 'Extras']\n  ];\n  // The core groups an order is expected to have, and where each is chosen -\n  // Choose Now goes to that stage and opens it, the same as its menu button.\n  const CK_CORE = {\n    worktops:   { stage: 'style-colours', popup: 'worktop' },\n    handles:    { stage: 'style-colours', popup: 'handles' },\n    appliances: { stage: 'add-units',     popup: 'add-appliances' },\n    trims:      { stage: 'style-colours', popup: 'trims' }\n  };\n  // A wall or tall unit's height as it is sold: Low / Medium / High. Read\n  // from the variant's own Height option; failing that, matched on the\n  // catalogue's heights for its kind (HEIGHT_LABELS_BY_CATEGORY in\n  // engine-catalogue.js) - for a tall unit also on its 150mm legs, which is\n  // what the plan carries (a High is 2300mm on the plan). Else given in mm.\n  const CK_TALL_HEIGHTS = [[1825, 'Low'], [1970, 'Medium'], [2150, 'High']];\n  const CK_WALL_HEIGHTS = [[575, 'Low'], [720, 'Medium'], [900, 'High']];\n  function ckTallHeight(c) { return ckSizeLabel(c, CK_TALL_HEIGHTS, 150); }\n  function ckWallHeight(c) { return ckSizeLabel(c, CK_WALL_HEIGHTS, 0); }\n  function ckSizeLabel(c, table, legsMm) {\n    const info = c.variantId && Catalogue.getVariantInfo ? Catalogue.getVariantInfo(c.variantId) : null;\n    if (info && info.product && info.variant) {\n      const names = info.product.optionNames || [];\n      const values = info.variant.options || [];\n      for (let i = 0; i < names.length; i++) {\n        const n = String(names[i] || '').toLowerCase().replace(/\\[[^\\]]*\\]|\\([^)]*\\)/g, '').trim();\n        if (n !== 'height' && !n.startsWith('height ')) continue;\n        const m = /\\b(low|med(?:ium)?|high)\\b/i.exec(String(values[i] || ''));\n        if (m) return /^med/i.test(m[1]) ? 'Medium' : m[1][0].toUpperCase() + m[1].slice(1).toLowerCase();\n      }\n    }\n    const mm = Number(c.heightMm) || 0;\n    for (const [h, label] of table) {\n      if (Math.abs(mm - h) <= 30 || (legsMm && Math.abs(mm - (h + legsMm)) <= 30)) return label;\n    }\n    return `${Math.round(mm)}mm`;\n  }\n\n  function computeChecklist() {\n    const units = ckUnitsOnPlan();\n    const items = [];\n    const add = (it) => items.push(it);\n\n    // Room Sizes - the room the whole design is built around (bug sheet, Sales\n    // row 50). Shown on a plan with units that a salesperson has worked on\n    // (ckStaffWorked - Arden, 2026-10-28). No sizes on the card: Check My\n    // Room takes them to Room Setup to check them there (Arden, 2026-10-28).\n    // The approval is of the room as it is, so changing a wall, the ceiling,\n    // or moving a door, window or feature asks for it again.\n    {\n      const ceil = Math.round((roomConfig && roomConfig.ceilingHeightMm) || 2400);\n      // Every number in the room, rounded to the mm (its splashback\n      // settings are not the room).\n      const round = (k, v) => (typeof v === 'number' ? Math.round(v) : v);\n      const rc = roomConfig || {};\n      add({\n        key: 'room-sizes', ...CK.roomsizes, applies: units.length > 0 && ckStaffWorked,\n        detail: '',\n        extra: { attr: 'data-btk-kp-check-room', label: 'Check My Room', icon: 'view' },\n        signature: JSON.stringify([rc.shapeId, rc.shapeParams, ceil, rc.wallOpenings || [], rc.perimeterItems || []], round)\n      });\n    }\n\n    // Advisory Points - the Advisory panel's points still to be decided. No\n    // Approve of its own: each point is accepted on the plan, in the panel, and\n    // the card goes once none are left (Arden, 2026-10-07). While any are\n    // left it is outstanding, so checkout still waits for them.\n    {\n      const open = warnsInListOrder(designWarnings.filter(w => !acceptedWarnings.has(warnKey(w))));\n      add({\n        key: 'advisory', ...CK.advisory, applies: open.length > 0, derived: true, noApprove: true,\n        approved: false,\n        detail: `${open.length} still to decide, numbered on your plan:`,\n        points: open.map(wn => ({ title: warnTitle(wn), message: wn.message })),\n        pictureSvg: open.length ? advisoryPlanSVG(open) : '',\n        extra: { attr: 'data-btk-kp-check-advisory', label: 'View on Plan', icon: 'view' }\n      });\n    }\n    // Round Edge Worktop on a Curve - a bullnose laminate over a curved unit or\n    // a radius end post (bullnoseCurveWarning). Approved here; the approval\n    // holds while the worktop and those units stay the same.\n    {\n      const bw = bullnoseCurveWarning();\n      const b = bw ? bullnoseCurveUnits() : null;\n      add({\n        key: 'bullnose', ...CK.bullnose, applies: !!bw, flagged: !!bw,\n        detail: !b ? '' : b.cabs.length\n          ? `${b.cabs.length === 1 ? 'Unit' : 'Units'} ${b.cabs.map(c => '#' + (c.displayNumber ?? '?')).join(', ')} ${b.cabs.length === 1 ? 'is' : 'are'} curved or ${b.cabs.length === 1 ? 'has' : 'have'} a radius end, under a round edge laminate worktop.`\n          : 'A worktop corner is rounded on a round edge laminate worktop.',\n        advice: CK.bullnose.advice,\n        signature: bw ? bw._signature : ''\n      });\n    }\n    // Joins in End Panels - an island or breakfast bar back covered by more\n    // than one panel (Arden, 2026-10-13): the run is longer than the longest\n    // panel the range sells, or is made up from shorter, cheaper ones\n    // (planBackPanelRun). Read from the layout's faces: a split run's pieces\n    // are `<cab>:back#0`, `back#1`..., each carrying the length of the\n    // stretch it covers - so pieces of one run share that and their cab.\n    {\n      const faces = (endPanelLayout && endPanelLayout.faces) || [];\n      const nums = (endPanelLayout && endPanelLayout.faceToNumber) || {};\n      const runs = new Map();\n      for (const f of faces) {\n        if (!f || f.role !== 'breakfast-bar' || !(f.segCount > 1)) continue;\n        const k = String(f.id).split(':')[0] + '|' + Math.round(f.runTotalMm || 0);\n        const r = runs.get(k) || { runMm: f.runTotalMm || 0, pieces: [] };\n        r.pieces.push(f);\n        runs.set(k, r);\n      }\n      const joined = [...runs.values()].filter(r => r.pieces.length > 1);\n      const joins = joined.reduce((t, r) => t + r.pieces.length - 1, 0);\n      const itemNos = [...new Set(joined.flatMap(r => r.pieces.map(p => nums[p.id]).filter(n => n != null)))].sort((a, b) => a - b);\n      add({\n        key: 'panel-joins', ...CK.paneljoins, applies: joins > 0, flagged: joins > 0,\n        detail: joined.length === 1\n          ? `Your ${Math.round(joined[0].runMm)}mm panel run is made from ${joined[0].pieces.length} panels, so it has ${joins === 1 ? 'one join' : joins + ' joins'}`\n            + (itemNos.length ? ` (items ${itemNos.map(n => '#' + n).join(', ')}).` : '.')\n          : `${joined.length} panel runs are made from more than one panel, with ${joins} joins in all`\n            + (itemNos.length ? ` (items ${itemNos.map(n => '#' + n).join(', ')}).` : '.'),\n        // Each run's length and how it is split, so changing it asks again.\n        signature: joined.map(r => Math.round(r.runMm) + ':' + r.pieces.map(p => Math.round(p.runMm || 0)).join('+')).sort().join(',')\n      });\n    }\n    // Plain Narrow Doors & Top Drawers (Arden, 2026-10-25) - in a framed range\n    // (one with a slab door cut-off: door_geometry slab_door_max_width_mm +\n    // slab_door_glb), a door narrower than the cut-off has no room for its\n    // frame and is made as a plain slab, as is a top drawer. Lists the units\n    // with either; approved while that list stays the same.\n    {\n      const norm = (t) => String(t || '').toLowerCase().replace(/[\\s_-]/g, '');\n      const narrowNos = [], topNos = [];\n      for (const c of units) {\n        const dg = ((Catalogue.getKitchenStyle && Catalogue.getKitchenStyle(c.kitchenStyleId)) || {}).doorGeometry || {};\n        const cutoff = Number(dg.slabDoorMaxWidthMm) || 0;\n        if (!(cutoff > 0 && dg.slabDoorGlbUrl)) continue;\n        const ops = ((c.cutoutSchema && c.cutoutSchema.openings) || [])\n          .filter(o => o && o.fixed !== true && o.dummy !== true);\n        // A door's width: its own when the schema gives one, a corner unit's\n        // door width, or its share of the unit with the doors beside it.\n        const band = o => (o.y || 0) + '|' + (o.height || 0);\n        const perBand = {};\n        for (const o of ops) if (norm(o.type) === 'door') perBand[band(o)] = (perBand[band(o)] || 0) + 1;\n        const narrow = ops.some(o => {\n          if (norm(o.type) !== 'door') return false;\n          const w = (typeof o.width === 'number') ? o.width\n            : (typeof o.widthMm === 'number') ? o.widthMm\n            : (c.doorMm || ((c.widthMm || 0) - 4) / (perBand[band(o)] || 1));\n          return w > 0 && w < cutoff;\n        });\n        const top = ops.some(o => norm(o.type) === 'topdrawer');\n        if (narrow) narrowNos.push(c.displayNumber);\n        if (top) topNos.push(c.displayNumber);\n      }\n      const list = (nos) => nos.filter(n => n != null).sort((a, b) => a - b).map(n => '#' + n).join(', ');\n      const parts = [];\n      if (narrowNos.length) parts.push(`${narrowNos.length === 1 ? 'a narrow door on item' : 'narrow doors on items'} ${list(narrowNos)}`);\n      if (topNos.length) parts.push(`${topNos.length === 1 ? 'a top drawer on item' : 'top drawers on items'} ${list(topNos)}`);\n      add({\n        key: 'slab-fronts', ...CK.slabfronts, applies: parts.length > 0,\n        detail: parts.length ? `Plain slab fronts: ${parts.join(', and ')}.` : '',\n        signature: 'n:' + list(narrowNos) + '|t:' + list(topNos)\n      });\n    }\n    // Supports for Units With No Plinth - every unit with its plinth set to None\n    // (engine-stack isFloatingUnit), with its height from the floor. Approved\n    // while that list stays the same.\n    {\n      const hung = units.filter(c => isFloatingUnit(c) && !isUnderWorktopUnit(c) && !isHungBetweenUnit(c))\n        .map(c => {\n          const ut = c.unitTypeId && Catalogue.getUnitType ? Catalogue.getUnitType(c.unitTypeId) : null;\n          return { n: c.displayNumber, h: Math.round(floatHeightMmOf(c, (ut && ut.plinthHeightMm) || 150)) };\n        })\n        .sort((a, b) => (a.n ?? 1e9) - (b.n ?? 1e9));\n      // Just the item numbers (Arden, 2026-10-29): \"Items #17, #19 and #20\".\n      const nos = hung.map(u => u.n).filter(n => n != null).map(n => '#' + n);\n      const list = nos.length > 1 ? nos.slice(0, -1).join(', ') + ' and ' + nos[nos.length - 1] : (nos[0] || '');\n      add({\n        key: 'floating', ...CK.floating, applies: hung.length > 0, flagged: hung.length > 0,\n        detail: nos.length > 1 ? `Items ${list} have no plinth.` : nos.length ? `Item ${list} has no plinth.` : 'A unit on your plan has no plinth.',\n        signature: hung.map(u => u.n + '@' + u.h).join(',')\n      });\n    }\n    // Units Reduced On Site: approved while the same units are cut to the same depths.\n    {\n      const cut = units.map(c => ({ n: c.displayNumber, d: reducedOnSiteMm(c), from: siteCutFromMm(c) }))\n        .filter(u => u.d)\n        .sort((a, b) => (a.n ?? 1e9) - (b.n ?? 1e9));\n      const one = (u) => `${u.n != null ? `Item #${u.n}: ` : ''}cut ${u.from ? `from ${u.from}mm ` : ''}to ${u.d}mm deep.`;\n      add({\n        key: 'reduced-on-site', ...CK.reducedOnSite, applies: cut.length > 0, flagged: cut.length > 0,\n        detail: cut.map(one).join(' '),\n        signature: cut.map(u => u.n + '@' + u.d).join(',')\n      });\n    }\n    // Worktop Pantry Units (row 142): approved while each one's size, depth,\n    // internals and panel count stay the same.\n    {\n      const pp = units.filter(isPantryCab)\n        .map(c => ({ n: c.displayNumber, w: Math.round(c.widthMm || 0), d: pantryDepthMm(c), k: pantryInternalsKey(c), b: pantryCutSummary(c).boards }))\n        .sort((a, b) => (a.n ?? 1e9) - (b.n ?? 1e9));\n      const one = (u) => `${u.n != null ? `Item #${u.n}: ` : ''}${u.w}mm wide, ${u.d}mm deep, ${PANTRY_INTERNALS.find(p => p.key === u.k)?.label || ''} - a Frontal Kit and ${u.b} Fitters Panel${u.b === 1 ? '' : 's'}.`;\n      add({\n        key: 'pantry', ...CK.pantry, applies: pp.length > 0, flagged: pp.length > 0,\n        detail: pp.map(one).join(' '),\n        signature: pp.map(u => [u.n, u.w, u.d, u.k, u.b].join('@')).join(',')\n      });\n    }\n    // Plinth Height (Non-urgent sheet row 95): any unit on a plinth that isn't\n    // the standard 150mm. Approved while the heights stay the same.\n    {\n      const planH = clampPlinthMm((featureStyles || {}).plinthHeightMm) || PLINTH_STD_MM;\n      const odd = units.filter(c => hasPlinthBand(c) && Math.round(plinthHeightOf(c)) !== PLINTH_STD_MM)\n        .map(c => ({ n: c.displayNumber, h: Math.round(plinthHeightOf(c)) }))\n        .sort((a, b) => (a.n ?? 1e9) - (b.n ?? 1e9));\n      const own = odd.filter(u => u.h !== planH && u.n != null);\n      const byH = new Map();\n      for (const u of own) { if (!byH.has(u.h)) byH.set(u.h, []); byH.get(u.h).push('#' + u.n); }\n      const say = (arr) => arr.length > 1 ? arr.slice(0, -1).join(', ') + ' and ' + arr[arr.length - 1] : arr[0];\n      const ownText = [...byH].map(([h, nos]) => `${nos.length > 1 ? 'Items' : 'Item'} ${say(nos)} ${nos.length > 1 ? 'are' : 'is'} on ${h}mm.`).join(' ');\n      add({\n        key: 'plinth-height', ...CK.plinthHeight, applies: odd.length > 0, flagged: odd.length > 0,\n        detail: (planH !== PLINTH_STD_MM ? `Your plinth is ${planH}mm high (standard is ${PLINTH_STD_MM}mm).${ownText ? ' ' + ownText : ''}` : ownText) || 'A unit on your plan has its own plinth height.',\n        signature: planH + '|' + odd.map(u => u.n + '@' + u.h).join(',')\n      });\n    }\n    // Walkways - the Advisory panel's narrow walkways.\n    {\n      const ways = designWarnings.filter(w => w.ruleId === 'walkway-too-small');\n      const gaps = ways.map(w => (w.region && w.region.label) || '').filter(Boolean);\n      add({\n        key: 'walkways', ...CK.walkways, applies: ways.length > 0, derived: true,\n        approved: ways.length > 0 && ways.every(w => acceptedWarnings.has(warnKey(w))),\n        detail: ways.length === 1 ? `One is under 900mm (${gaps[0] || ''}).`\n                                  : `${ways.length} walkways are narrower than 900mm (${gaps.join(', ')}).`\n      });\n    }\n\n    // Belfast Sink Worktop - the Advisory's \"Worktop Too Thin by the Belfast\n    // Sink\" points (belfastWorktopWarnings). Like Walkways, approving here\n    // accepts them there and the other way round (Arden, 2026-10-26).\n    {\n      const bw = designWarnings.filter(w => w.ruleId === 'belfast-worktop-edge');\n      const byUnit = new Map();\n      for (const w of bw) {\n        const k = String(w._unit);\n        byUnit.set(k, (byUnit.get(k) || []).concat(w._side));\n      }\n      const where = [...byUnit].map(([n, sides]) => `unit #${n} (${sides.length > 1 ? 'both sides' : sides[0] + ' side'})`);\n      add({\n        key: 'belfast-worktop', ...CK.belfastworktop, applies: bw.length > 0, derived: true,\n        approved: bw.length > 0 && bw.every(w => acceptedWarnings.has(warnKey(w))),\n        detail: where.length ? `The worktop would be too thin beside the Belfast sink on ${where.join(', ')}.` : ''\n      });\n    }\n\n    // Door & Carcase - each combination of range, door colour and carcase\n    // colour on the plan, pictured as the door on its carcase (the overlay the\n    // Door & Carcase popup uses). Door and carcase are judged together because\n    // they go together (Arden, 2026-10-07).\n    {\n      const styleCount = new Set(units.map(c => c.kitchenStyleId)).size;\n      const nameOf = (list, h, none) => {\n        const x = (list || []).find(o => o.handle === h);\n        return x ? (x.name || h) : (h ? ckPretty(h) : none);\n      };\n      // A unit with no carcase colour of its own (no_carcase_colour) is not a\n      // combination of its own: it goes with the units of the same door, on\n      // their carcase - whatever stale handle it carries (Arden, 2026-10-17).\n      const noCarc = c => !!(Catalogue.getUnitType && (Catalogue.getUnitType(c.unitTypeId) || {}).noCarcaseColour);\n      const carcOfDoor = new Map();\n      for (const u of units) {\n        if (noCarc(u) || !u.carcaseColourHandle) continue;\n        const k = u.kitchenStyleId + '|' + (u.doorColourHandle || '');\n        if (!carcOfDoor.has(k)) carcOfDoor.set(k, u.carcaseColourHandle);\n      }\n      const carcOf = c => noCarc(c)\n        ? (carcOfDoor.get(c.kitchenStyleId + '|' + (c.doorColourHandle || '')) || '')\n        : (c.carcaseColourHandle || '');\n      const comboKey = c => c.kitchenStyleId + '|' + (c.doorColourHandle || '') + '|' + carcOf(c);\n      const groups = ckGroup(units, comboKey, c => {\n        const door = nameOf(Catalogue.getDoorColoursForStyle && Catalogue.getDoorColoursForStyle(c.kitchenStyleId), c.doorColourHandle, 'no door colour');\n        const carcase = nameOf(Catalogue.getCarcaseColoursForStyle && Catalogue.getCarcaseColoursForStyle(c.kitchenStyleId), carcOf(c), 'no carcase colour');\n        const ks = Catalogue.getKitchenStyle && Catalogue.getKitchenStyle(c.kitchenStyleId);\n        return `${door} on ${carcase}` + (styleCount > 1 && ks && ks.name ? ` (${ks.name})` : '');\n      });\n      const swatches = groups.map(g => {\n        // Pictured by a unit that HAS the carcase, where the group has one.\n        const c = units.find(u => comboKey(u) === g.key && !noCarc(u)) || units.find(u => comboKey(u) === g.key);\n        const ks = Catalogue.getKitchenStyle && Catalogue.getKitchenStyle(c.kitchenStyleId);\n        // Pictured as the planner draws it (Sales row 145, Arden 2026-11-20):\n        // one of the combination's own units, rendered in its range, door\n        // colour and carcase colour as the Add Units cards draw a unit. The\n        // door overlay photos were missing for many range colours, which left\n        // the tile showing the carcase alone. A plain door / drawer unit\n        // first - base, then wall, then tall - so the picture shows the door,\n        // not an appliance, sink, bin, corner or bridging front.\n        const inGroup = units.filter(u => comboKey(u) === g.key && !noCarc(u));\n        const fronts = u => ((u.cutoutSchema && u.cutoutSchema.openings) || []).map(o => o && o.type);\n        const plain = u => { const f = fronts(u); return f.length > 0 && f.every(t => t === 'door' || t === 'drawer' || t === 'topdrawer')\n          && !/dishwasher|washer|fridge|freezer|appliance|integrated|sink|bin|corner|curved|radius|bridging/i.test(String(u.unitTypeId || '')); };\n        const rank = u => (plain(u) ? 0 : fronts(u).includes('door') ? 10 : 20)\n          + ({ 'base-units': 0, 'wall-units': 1, 'tall-units': 2 }[u.category] ?? 3);\n        const thumbs = inGroup.map((u, i) => ({ u, i })).sort((a, b) => (rank(a.u) - rank(b.u)) || (a.i - b.i)).map(x => x.u)\n          .map(u => ({ unitTypeId: u.unitTypeId, variantId: u.variantId, kitchenStyleId: u.kitchenStyleId,\n                       doorColourHandle: u.doorColourHandle || null, carcaseColourHandle: carcOf(u) || null }));\n        return {\n          label: g.label, n: g.n, overlay: ckPic(c), thumbs,\n          door: nameOf(Catalogue.getDoorColoursForStyle && Catalogue.getDoorColoursForStyle(c.kitchenStyleId), c.doorColourHandle, 'No door colour'),\n          carcase: nameOf(Catalogue.getCarcaseColoursForStyle && Catalogue.getCarcaseColoursForStyle(c.kitchenStyleId), carcOf(c), 'no carcase colour'),\n          range: (ks && ks.name) || ''\n        };\n      });\n      add({\n        key: 'door-carcase', ...CK.doorcarcase, applies: groups.length > 0, flagged: groups.length > 1,\n        // The door style leads: it is the biggest choice, the colours come with it.\n        detail: groups.length === 1 ? `One door style and colour across all ${ckUnits(groups[0].n)}.`\n          : styleCount > 1 ? `${styleCount} door styles, in ${groups.length} combinations.`\n          : `One door style, in ${groups.length} colour combinations.`,\n        advice: ckByCount(groups.length, CK.doorcarcase),\n        swatches,\n        signature: groups.map(g => g.key).sort().join(',')\n      });\n    }\n\n    // Wall Unit Heights - the height each wall unit is sold in, Low / Medium /\n    // High (Arden, 2026-10-07: words, not mm). Only with wall units on the\n    // plan; bridging units are their own sizes and are left out.\n    {\n      const wall = units.filter(c => epCategoryGroup(c) === 'wall' && c.heightMm);\n      const groups = ckGroup(wall, c => ckWallHeight(c), c => ckWallHeight(c));\n      add({\n        key: 'wall-heights', ...CK.height, applies: groups.length > 0, flagged: groups.length > 1,\n        // Mixed heights get the tops-lined-up picture (Planner row 59).\n        picture: groups.length > 1 ? 'wall-heights-mixed' : null,\n        detail: groups.length > 1 ? `${ckList(groups)}.`\n                                  : `All ${groups.length ? groups[0].n : 0} are ${groups.length ? groups[0].label : ''}.`,\n        advice: ckByCount(groups.length, CK.height),\n        signature: groups.map(g => g.key).sort().join(',')\n      });\n    }\n\n    // Tall Units - the same check for tall units, by the height they are sold\n    // in (Low / Medium / High) rather than in mm. Only with tall units on the\n    // plan; a stack of carcases counts with its host, not as a tall unit.\n    {\n      const tall = units.filter(c => /^tall/i.test(c.category || '') && !c.stackHostId && c.heightMm);\n      const groups = ckGroup(tall, c => ckTallHeight(c), c => ckTallHeight(c));\n      add({\n        key: 'tall-heights', ...CK.tall, applies: groups.length > 0, flagged: groups.length > 1,\n        detail: groups.length > 1 ? `${ckList(groups)}.`\n                                  : `All ${groups.length ? groups[0].n : 0} are ${groups.length ? groups[0].label : ''}.`,\n        advice: ckByCount(groups.length, CK.tall),\n        signature: groups.map(g => g.key).sort().join(',')\n      });\n    }\n\n    // Cornice, Pelmet and Plinth - one card each (Arden, 2026-10-13), showing\n    // the chosen profile's picture (its tileImageUrl, as the Trims popup\n    // shows it) and colour. The profile is the one the plan's main range\n    // renders: the chosen name, else that range's first usable one, as the\n    // Trims popup and the renderer fall back to. Each card only appears with\n    // units it runs along, and only for a range that sells that trim.\n    const trimOf = (kind, runUnits) => {\n      const plan = planTrimStyle();\n      const trim = plan.styleId && Catalogue.getTrimForStyle ? Catalogue.getTrimForStyle(plan.styleId) : null;\n      const list = (trim && trim[kind]) || [];\n      const fs = featureStyles || {};\n      const cur = fs[kind];\n      // Ceiling Filler is a choice, not \"no cornice\": its own card, in the\n      // door colour (the fillers are door colour, like end panels).\n      const filler = kind === 'cornice' && cur === CEILING_FILLER;\n      const profile = (cur === 'none' || cur === CEILING_FILLER) ? null\n        : (list.find(p => (p.name || '') === cur && p.available !== false) || list.find(p => p.available !== false) || null);\n      const colourHandle = filler ? null : (fs[kind + 'Colour'] || null);\n      const colour = colourHandle\n        ? ((Catalogue.getDoorColoursForStyle && Catalogue.getDoorColoursForStyle(plan.styleId)) || []).find(o => o.handle === colourHandle)\n        : null;\n      const label = profile ? (profile.friendlyName || profile.name || '') : '';\n      // \"Cornice Classic\" -> \"Classic\": the kind word out, so the card reads\n      // \"Classic cornice\" and a Classic cornice matches a Classic pelmet.\n      const styleWord = label.split(' ').filter(w => w && w.toLowerCase() !== kind).join(' ') || label;\n      // No colour of its own: it takes the door colour of each run it is\n      // fitted to - named when those units share one door colour (Arden,\n      // 2026-10-13), else said plainly.\n      let caption, phrase;\n      if (colourHandle) {\n        const name = (colour && colour.name) || ckPretty(colourHandle);\n        caption = 'In ' + name; phrase = 'in ' + name;\n      } else {\n        const doors = [...new Set(runUnits.map(c => c.doorColourHandle || globalDoorColourHandle).filter(Boolean))];\n        const c0 = runUnits.find(c => (c.doorColourHandle || globalDoorColourHandle) === doors[0]);\n        const door = doors.length === 1 && c0\n          ? ((Catalogue.getDoorColoursForStyle && Catalogue.getDoorColoursForStyle(c0.kitchenStyleId)) || []).find(o => o.handle === doors[0])\n          : null;\n        const name = doors.length === 1 ? ((door && door.name) || ckPretty(doors[0])) : '';\n        caption = name ? `In ${name}, to match your doors` : 'Same colour as your doors';\n        phrase = name ? `in ${name} to match your doors` : 'in the same colour as your doors';\n      }\n      if (filler) {\n        return { sold: true, none: false, filler: true, profile: null, label: 'Ceiling Filler',\n          styleWord: 'Ceiling filler', caption, phrase, signature: CEILING_FILLER };\n      }\n      return {\n        sold: list.length > 0, none: !profile, profile, label, styleWord, caption, phrase,\n        signature: (profile ? profile.name : 'none') + '|' + (colourHandle || '')\n      };\n    };\n    // Every line of this trim taken out of the quote: nothing to confirm, and\n    // Not In Your Order already lists it (bug sheet, Sales row 75).\n    const trimCharges = Object.keys(quoteExcludedLines || {}).some(k => k.indexOf('q:tr:') === 0) ? computeTrimCharges() : [];\n    const trimOutOfQuote = (kind) => {\n      const lines = trimCharges.filter(ch => ch.feature === kind || (kind === 'plinth' && ch.feature === 'plinthAlt'));\n      return lines.length > 0 && lines.every(ch => quoteExcludedLines['q:' + trimLineKey(ch)]);\n    };\n    const trimCard = (kind, ck, runUnits, extra = () => ({})) => {\n      const t = trimOf(kind, runUnits);\n      t.out = trimOutOfQuote(kind);\n      const applies = runUnits.length > 0 && !t.out;\n      const noneImg = Catalogue.getTrimNoneImage ? Catalogue.getTrimNoneImage(kind) : null;\n      add({\n        key: kind, ...ck, applies: applies && t.sold, flagged: t.none,\n        detail: t.none ? `No ${kind}.`\n          : t.filler ? `Ceiling filler, ${t.phrase}.`\n          : `${t.styleWord} ${kind}, ${t.phrase}.`,\n        advice: t.none ? ck.none : t.filler ? (ck.filler || ck.chosen) : ck.chosen,\n        swatches: [t.none\n          ? { label: `No ${kind}`, img: noneImg || '' }\n          : t.filler ? { label: t.label, img: '', sub: t.caption }\n          : { label: t.label, img: t.profile.tileImageUrl || '', sub: t.caption }],\n        signature: t.signature,\n        ...extra(t)\n      });\n      return t;\n    };\n    {\n      // The units each trim runs along.\n      const inGroup = (...gs) => units.filter(c => gs.includes(epCategoryGroup(c)));\n      const topped = inGroup('wall', 'bridging', 'tall', 'midi');\n      const cornice = trimCard('cornice', CK.cornice, topped, () => ({}));\n      // A pelmet in a different style to the cornice is worth a second look.\n      trimCard('pelmet', CK.pelmet, inGroup('wall', 'bridging'), (t) => {\n        // Not against Ceiling Filler: it is no moulding style to match.\n        const differs = !t.none && !cornice.none && !cornice.filler && !cornice.out && topped.length > 0\n          && t.styleWord.toLowerCase() !== cornice.styleWord.toLowerCase();\n        return differs ? { flagged: true, advice: CK.pelmet.differs } : {};\n      });\n      trimCard('plinth', CK.plinth, inGroup('base', 'tall', 'midi'), () => ({}));\n    }\n\n    // End Panels - each kind of end panel on the plan (Standard, Radius End\n    // Feature, TH Door ...) and its finish, counted, with that feature's\n    // picture (planner_end_feature, as End Panels & Fillers shows it). Read\n    // the same way that popup reads a side (seedEpSide).\n    {\n      const EP_LABELS = {\n        'ep-standard': 'Standard End Panel', 'ep-inline': 'Inline End Panel', 'ep-tall': 'Tall End Panel',\n        'ep-square': 'Square End Feature', 'ep-radius': 'Radius End Feature', 'ep-th-door': 'TH Door End Panel',\n        'ep-th-drawers': 'TH Drawer End Panels', 'ep-door-line-tall': 'Door Line Tall End Panel',\n        'free-base': 'Base End Panel', 'free-tall': 'Tall End Panel', 'free-wall': 'Wall End Panel',\n        'free-island': 'Island End Panel', 'back-panel': 'Breakfast Bar Back Panel'\n      };\n      const featureOf = (ep) => {\n        if (ep.doorLine) return { key: 'ep-door-line-tall', finish: ep.style === 'tng' ? 'tng' : 'plain' };\n        if (ep.style === 'square' || ep.style === 'radius') return { key: 'ep-' + ep.style, finish: ep.tng ? 'tng' : 'plain' };\n        if (ep.style === 'th-door' || ep.style === 'th-drawers') return { key: 'ep-' + ep.style, finish: null };\n        return { key: ep.toFloor ? 'ep-tall' : ep.inline ? 'ep-inline' : 'ep-standard', finish: ep.style === 'tng' ? 'tng' : 'plain' };\n      };\n      const map = new Map();\n      for (const c of cabinets) {\n        if (!c || c.excludeFromQuote || !c.endPanels) continue;\n        for (const side of ['left', 'right']) {\n          const ep = c.endPanels[side];\n          if (!ep || !ep.active) continue;\n          const f = featureOf(ep);\n          const k = f.key + '|' + (f.finish || '');\n          const g = map.get(k) || { key: k, f, n: 0, cab: c };\n          g.n++;\n          map.set(k, g);\n        }\n      }\n      // Free-placed panels and breakfast bar back panels are end panels on the\n      // order too, each in its own finish - a plan mixing Plain and T&G showed\n      // Plain only (Arden, 2026-10-22, Karen Pratt PLN100069).\n      const bump = (f, c) => {\n        const k = f.key + '|' + (f.finish || '');\n        const g = map.get(k) || { key: k, f, n: 0, cab: c };\n        g.n++;\n        map.set(k, g);\n      };\n      for (const c of cabinets) {\n        if (!c || c.excludeFromQuote || !c.endPanelUnit || c.endPanelFiller) continue;\n        const ut = String(c.unitTypeId || '');\n        if (/filler/.test(ut)) continue;\n        const finish = /(?:^|-)t-?g(?:-|$)|tng/.test(ut) ? 'tng' : /grooved/.test(ut) ? 'grooved' : 'plain';\n        const key = /back-panel/.test(ut) ? 'back-panel' : /island/.test(ut) ? 'free-island'\n          : /tall/.test(ut) ? 'free-tall' : /wall/.test(ut) ? 'free-wall' : 'free-base';\n        bump({ key, finish }, c);\n      }\n      // One per panel the run is billed as (its stamped segments; one when the\n      // run has none), not one per unit.\n      const backSeen = new Set();\n      for (const c of cabinets) {\n        if (!c || c.excludeFromQuote || !c.backPanel || !c.backPanel.active || c.backPanel.thProfile) continue;\n        if (c.breakfastBarBack && c.breakfastBarBack.waterfall) continue;\n        const finish = backPanelFinish(c) || 'plain';\n        const segs = Array.isArray(c.backPanel.segments) && c.backPanel.segments.length ? c.backPanel.segments : null;\n        if (!segs) { bump({ key: 'back-panel', finish }, c); continue; }\n        for (const sg of segs) {\n          const id = (sg.ownerCabId || c.id) + ':' + sg.side;\n          if (backSeen.has(id)) continue;\n          backSeen.add(id);\n          bump({ key: 'back-panel', finish }, c);\n        }\n      }\n      const groups = [...map.values()].sort((a, b) => b.n - a.n);\n      const total = groups.reduce((t, g) => t + g.n, 0);\n      const finishName = (f) => f.finish === 'tng' ? 'Tongue & Groove' : f.finish === 'plain' ? 'Plain'\n        : f.finish === 'grooved' ? 'Grooved' : f.finish === 'acoustic' ? 'Acoustic' : '';\n      const kindOf = (c) => { const g = epCategoryGroup(c); return g === 'tall' ? 'tall' : (g === 'wall' || g === 'bridging') ? 'wall' : 'base'; };\n      add({\n        key: 'end-panels', ...CK.endpanels, applies: total > 0, flagged: false,\n        detail: `${total} end panel${total === 1 ? '' : 's'}: `\n          + ckList(groups.map(g => ({ label: `${EP_LABELS[g.f.key] || 'End Panel'}${finishName(g.f) ? ', ' + finishName(g.f) : ''} (${g.n})` })), false) + '.',\n        swatches: groups.map(g => ({\n          label: EP_LABELS[g.f.key] || 'End Panel', sub: finishName(g.f),\n          img: (Catalogue.getEndFeatureImage && Catalogue.getEndFeatureImage(/^(free-|back-panel)/.test(g.f.key) ? 'ep-standard' : g.f.key,\n            (g.f.finish === 'tng' ? 'tng' : 'plain'),\n            g.f.key === 'free-tall' ? 'tall' : g.f.key === 'free-wall' ? 'wall' : /^(free-|back-panel)/.test(g.f.key) ? 'base' : kindOf(g.cab))) || '',\n          n: g.n, nLabel: `${g.n} panel${g.n === 1 ? '' : 's'}`\n        })),\n        signature: groups.map(g => g.key + ':' + g.n).sort().join(',')\n      });\n    }\n\n    // Smart Profile - True Handleless only: the profile (rail) colour, one\n    // choice for the whole kitchen.\n    {\n      const handleless = units.some(c => Catalogue.isStyleTrueRail && Catalogue.isStyleTrueRail(c.kitchenStyleId));\n      const finish = railFinishHandle && Catalogue.getRailFinish ? Catalogue.getRailFinish(railFinishHandle) : null;\n      const n = railFinishHandle ? 1 : 0;\n      add({\n        key: 'profile', ...CK.profile, applies: handleless, flagged: n !== 1,\n        detail: n ? `${(finish && finish.name) || ckPretty(railFinishHandle)}.` : 'No profile colour chosen.',\n        advice: ckByCount(n, CK.profile),\n        signature: railFinishHandle || ''\n      });\n    }\n\n    // Smart Inventory - what types of item the basket holds, and the main\n    // ones it does not. RETIRED (Arden, 2026-10-14): listing basket groups\n    // says nothing useful. The real version is Odoo's Pre-Order Check\n    // (product.template.product_pre_order_check_ids -> pre.order.check names:\n    // Oven, Hob, Dishwasher, Cutlery Tray ...), as the old checkout's Smart\n    // Inventory showed it - names on a basket product are \"in your order\",\n    // every other name is not. Bring it back once those names reach Shopify.\n    const INVENTORY_RETIRED = true;\n    {\n      const lines = ckBasketItems(ckBasket);\n      const have = new Set(lines.map(it => (it && it.attributes && it.attributes.quoteGroup) || 'extras'));\n      const handleless = units.some(c => Catalogue.isStyleTrueRail && Catalogue.isStyleTrueRail(c.kitchenStyleId));\n      // Each type of item in the order, with how many (Arden, 2026-10-13).\n      const included = CK_INVENTORY.filter(([k]) => have.has(k)).map(([k, label]) => ({\n        key: k, label,\n        n: lines.filter(it => ((it && it.attributes && it.attributes.quoteGroup) || 'extras') === k)\n                .reduce((s, it) => s + (Number(it.quantity) || 1), 0)\n      }));\n      // The core groups not in the order, each to be chosen now or marked as\n      // bought elsewhere before the card can be approved.\n      const missing = CK_INVENTORY\n        .filter(([k]) => CK_CORE[k] && !have.has(k))\n        .filter(([k]) => !(k === 'handles' && handleless))\n        .map(([k, label]) => ({ key: k, label, elsewhere: checklistElsewhere.has(k) }));\n      const unresolved = missing.filter(m => !m.elsewhere).length;\n      add({\n        key: 'inventory', ...CK.inventory, applies: !INVENTORY_RETIRED && lines.length > 0, flagged: missing.length > 0,\n        detail: `Your order includes ${included.length} type${included.length === 1 ? '' : 's'} of item`\n          + (missing.length ? `, and there ${missing.length === 1 ? 'is one more' : 'are ' + missing.length + ' more'} you might need.` : '.'),\n        included, missing, blocked: unresolved > 0,\n        signature: CK_INVENTORY.filter(([k]) => have.has(k)).map(([k]) => k).join(',')\n          + '|elsewhere:' + missing.filter(m => m.elsewhere).map(m => m.key).join(',')\n      });\n    }\n\n    // Smart Assembly - how many units come Fully Assembled and how many Flat\n    // Packed (chosen on the basket lines).\n    {\n      // A line with no assembly choice (an appliance door) is not counted.\n      const unitLines = ckBasketItems(ckBasket).filter(it => it && it.attributes && it.attributes.quoteGroup === 'units' && it.attributes.assembly);\n      let assembled = 0, flat = 0;\n      for (const it of unitLines) {\n        const q = Number(it.quantity) || 1;\n        if (/flat/i.test(String(it.attributes.assembly || ''))) flat += q; else assembled += q;\n      }\n      // Why some can't be changed, so nobody goes to the basket to try (bug\n      // sheet, Julian, 2026-10-30): a flat pack delivery holds every unit Flat\n      // Packed; otherwise name the units whose size only comes flat packed\n      // (Odoo's Assembly Options = Flatpacked - the catalogue's flatOnly, the\n      // basket's \"This size only comes flat packed\").\n      let why = '';\n      // The delivery chosen in the basket (basket.deliveryChoice, read here from\n      // the checklist's own copy - the live basket only knows it once opened).\n      const _dc = ckBasket && ckBasket.deliveryChoice;\n      if ((_dc && /flat\\s*-?\\s*pack/i.test(String(_dc.name || '')))\n        || (window.BTKCartAdvanced && window.BTKCartAdvanced.assemblyLocked && window.BTKCartAdvanced.assemblyLocked())) {\n        why = ' Your delivery is flat pack only, so every unit comes Flat Packed. To have units assembled, choose another delivery option in your basket.';\n      } else {\n        const flatOnly = unitLines.filter(it => {\n          const vi = (it.shopifyVariantId && Catalogue.getVariantInfo) ? Catalogue.getVariantInfo(Number(it.shopifyVariantId)) : null;\n          return !!(vi && vi.variant && vi.variant.flatOnly);\n        });\n        const n = flatOnly.reduce((s, it) => s + (Number(it.quantity) || 1), 0);\n        if (n) {\n          const nums = flatOnly.map(it => it.planLineNumber).filter(x => x != null);\n          why = ` ${n === 1 ? 'One unit' : n + ' units'}${nums.length ? ` (item${nums.length === 1 ? '' : 's'} ${nums.join(', ')})` : ''}`\n            + ` only ${n === 1 ? 'comes' : 'come'} flat packed in ${n === 1 ? 'its' : 'their'} size, so ${n === 1 ? 'it' : 'they'} can't be changed to Assembled.`;\n        }\n      }\n      add({\n        key: 'assembly', ...CK.assembly, applies: unitLines.length > 0, flagged: false,\n        detail: `${assembled} Fully Assembled, ${flat} Flat Packed.` + why,\n        // The two ways a unit arrives, each with its count - the pictures from\n        // the old Odoo checkout's Smart Assembly (assembly.hinge.options),\n        // now theme assets passed in as window.BTK_KP_ASSEMBLY_IMAGES.\n        swatches: [\n          { label: 'Fully Assembled', n: assembled, img: (window.BTK_KP_ASSEMBLY_IMAGES || {}).assembled || '' },\n          { label: 'Flat Packed', n: flat, img: (window.BTK_KP_ASSEMBLY_IMAGES || {}).flatpacked || '' }\n        ],\n        signature: assembled + ':' + flat\n      });\n    }\n\n    // Smart Checklist - the basket's own recommended items (its Smart\n    // Checklist panel). Once the basket has been opened and has some.\n    {\n      const p = window.BTKCartAdvanced && window.BTKCartAdvanced.checklistProgress\n        ? window.BTKCartAdvanced.checklistProgress() : null;\n      add({\n        key: 'recommend', ...CK.recommend, applies: !!(p && p.total > 0), flagged: !!(p && p.complete < p.total),\n        detail: p ? `${p.complete} of ${p.total} dealt with in your basket.` : '',\n        signature: p ? p.complete + '/' + p.total : '',\n        extra: { attr: 'data-btk-kp-check-basket', label: 'Open Basket', icon: 'basket' }\n      });\n    }\n\n    return items;\n  }\n\n  // The depth a Reduced On Site unit is bought at.\n  function siteCutFromMm(c) {\n    if (c && c.siteCut && c.siteCut.productDepthMm > 0) return Math.round(c.siteCut.productDepthMm);\n    const vi = c && c.variantId && Catalogue.getVariantInfo ? Catalogue.getVariantInfo(c.variantId) : null;\n    return (vi && Number(vi.depthMm) > 0) ? Math.round(Number(vi.depthMm)) : null;\n  }\n\n  function checklistContent(key) {\n    const all = window.BTK_KP_CHECKLIST;\n    return (all && typeof all === 'object' && all[key]) || {};\n  }\n  const isChecklistApproved = (it) => it.applies && (it.derived ? !!it.approved : checklistApprovals[it.key] === it.signature);\n  // How many checks still want approving - checkout waits for none\n  // (proceedToCheckoutRun). Reads the basket afresh first.\n  // checklistRecord from the checks as they stand: each approved one, with its\n  // words. Only once the basket and ckStaffWorked are read (ckReady), so a\n  // first draw from half the facts never drops a check from it.\n  let ckReady = false;\n  function ckUpdateRecord(items) {\n    if (!ckReady) return;\n    checklistRecord = items.filter(it => it.applies && !it.noApprove && isChecklistApproved(it)).map(it => {\n      const meta = checklistContent(it.key);\n      const rec = { key: it.key, title: meta.title || it.title || it.key, confirm: it.confirm || '',\n                    signature: String(it.derived ? 'accepted' : (it.signature ?? '')) };\n      return rec;\n    });\n  }\n  // The checks still wanting approval, by name, for the message at checkout. An\n  // Advisory has no Approve of its own, so it says which points are open (Steven\n  // Packenas sat at 9 of 10 with nothing to press, Arden 2026-11-03).\n  function checklistLeftNames() {\n    return computeChecklist().filter(it => it.applies && !isChecklistApproved(it)).map(it => {\n      const title = checklistContent(it.key).title || it.title || it.key;\n      if (it.key !== 'advisory') return title;\n      const open = designWarnings.filter(w => !acceptedWarnings.has(warnKey(w)));\n      return `${title}: ${[...new Set(open.map(warnTitle))].join(', ')}`;\n    });\n  }\n  async function checklistOutstanding() {\n    ckBasket = await ckLoadBasket();\n    ckStaffWorked = await ckLoadStaffWorked();\n    ckReady = true;\n    ckUpdateRecord(computeChecklist());\n    return computeChecklist().filter(it => it.applies && !isChecklistApproved(it)).length;\n  }\n\n  async function renderChecklist() {\n    ckReady = false;\n    drawChecklist();                 // at once, from what is known\n    ckBasket = await ckLoadBasket(); // then again with the basket\n    ckStaffWorked = await ckLoadStaffWorked();\n    ckReady = true;\n    drawChecklist();\n  }\n  // The door photos come with the preview feed, fetched after the planner\n  // loads: ask for it, and redraw an open Checklist when it lands.\n  document.addEventListener('btk:previews-ready', () => {\n    if (currentStep === 'checklist') drawChecklist();\n  });\n  // ...and the style cards that show the door: the Add Units style card, the\n  // planning styles' slots, Door & Carcase - so a painted F&B door appears\n  // once its picture is made (Catalogue.getDoorPreviewUrl, Arden 2026-10-10).\n  document.addEventListener('btk:previews-ready', () => {\n    try { renderJourneyStyleSlots(); } catch (_) {}\n    try { if (!psPopup.hidden && psSlot == null) renderPlanningStylesPopup(); } catch (_) {}\n    try { styleColoursHandle?.refresh(); } catch (_) {}\n  });\n  // An F&B card on its carcase step: its picture takes the painted unit on the\n  // chosen carcase when that render lands (the carcase tiles keep their own\n  // pictures - Arden, 2026-10-10). Updated in place, keeping the choice made.\n  function refreshBespokeCarcaseStep() {\n    document.querySelectorAll('.btk-kp-style-card[data-face=\"carcase\"]').forEach(card => {\n      const styleId = card.dataset.btkKpCardStyle;\n      const door = card.dataset.cardDoor || null;\n      if (!styleId || !door) return;\n      const act = card.querySelector('[data-btk-kp-card-carcase].is-active') || card.querySelector('[data-btk-kp-card-carcase]');\n      const overlayEl = card.querySelector('[data-btk-kp-card-overlay]');\n      const ks = Catalogue.getKitchenStyle && Catalogue.getKitchenStyle(styleId);\n      if (act && overlayEl) overlayEl.innerHTML = jCardOverlayHtml(styleId, door, ks && ks.carcaseFamilyHandle, act.dataset.btkKpCardCarcase);\n    });\n  }\n  document.addEventListener('btk:previews-ready', () => { try { refreshBespokeCarcaseStep(); } catch (_) {} });\n  // The F&B style cards' picture: a 600mm drawerline base unit (Single\n  // Drawerline, else Double) in the range, painted and on its carcase, drawn\n  // by the same headless renderer as the Add Units cards (Arden, 2026-10-10).\n  Catalogue.setBespokeUnitRenderer?.(async (styleId, doorHandle, carcaseHandle) => {\n    try { await ensureStyleProducts(styleId); } catch (_) { return null; }\n    const types = (Catalogue.getUnitTypes && Catalogue.getUnitTypes()) || [];\n    // Better Bedrooms: a 500mm Full Door Bedside (Arden, 2026-11-21).\n    for (const [code, wMm] of [['BKBED_10', 500]]) {\n      const ut = types.find(u => u && String(u.code || '').toUpperCase() === code);\n      if (!ut) continue;\n      const info = Catalogue.findVariant && Catalogue.findVariant({ unitTypeId: ut.id, kitchenStyleId: styleId, widthMm: wMm });\n      if (!info || info.widthMm !== wMm || !info.variant) continue;\n      const cab = cabinetsHandle && cabinetsHandle.unitThumbCab\n        ? cabinetsHandle.unitThumbCab({ unitTypeId: ut.id, variantId: info.variant.id, kitchenStyleId: styleId,\n            doorColourHandle: doorHandle, carcaseColourHandle: carcaseHandle || globalCarcaseColourHandle })\n        : null;\n      if (!cab) continue;\n      // Seen from the other side to the unit cards (camDirX), facing the\n      // other way (Arden, 2026-10-10).\n      return await renderCabinetThumbHeadless(cab, { width: 400, height: 400, camDirX: -0.85, frameClosed: true });\n    }\n    return null;\n  });\n  // A picture site's door + carcase pair, swapped for the unit render where\n  // the door is a bespoke paint and its render is ready.\n  function unitPicture(styleId, doorHandle, carcaseHandle, doorImg, carcaseImg) {\n    const u = Catalogue.getBespokeUnitPreview ? Catalogue.getBespokeUnitPreview(styleId, doorHandle, carcaseHandle) : null;\n    return u ? { doorImg: u, carcaseImg: '' } : { doorImg, carcaseImg };\n  }\n  // Cards start closed to their title row, except the first one still to\n  // approve (Arden, 2026-10-14). Show / Hide sets a card's own choice, kept\n  // here until it is approved or un-approved.\n  const ckOpen = new Map();   // check key -> true (open) / false (closed)\n  // The order the cards run in (Arden, 2026-10-14). Checks not listed follow,\n  // in the order computeChecklist adds them.\n  const CK_ORDER = ['room-sizes', 'advisory', 'door-carcase', 'wall-heights', 'tall-heights', 'cornice', 'pelmet', 'plinth', 'plinth-height', 'floating',\n                    'end-panels', 'walkways', 'assembly'];\n  const ckRank = (k) => { const i = CK_ORDER.indexOf(k); return i < 0 ? CK_ORDER.length : i; };\n  function drawChecklist() {\n    const host = root.querySelector('[data-btk-kp-checklist-cards]');\n    const lead = root.querySelector('[data-btk-kp-checklist-lead]');\n    if (!host) return;\n    const items = computeChecklist();\n    ckUpdateRecord(items);\n    // Approvals of a check that no longer applies are dropped, so the saved\n    // list cannot grow stale.\n    // Room Sizes' is kept: whether it applies waits on the basket read\n    // (ckStaffWorked), and its signature already asks again if the room changes.\n    for (const k of Object.keys(checklistApprovals)) {\n      if (k === 'room-sizes') continue;\n      if (!items.some(it => it.key === k && it.applies)) delete checklistApprovals[k];\n    }\n    const due  = items.filter(it => it.applies)\n      .map((it, i) => ({ it, i }))\n      .sort((a, b) => (ckRank(a.it.key) - ckRank(b.it.key)) || (a.i - b.i))\n      .map(x => x.it);\n    const firstKey = (due.find(it => !isChecklistApproved(it)) || {}).key;\n    const done = due.filter(isChecklistApproved).length;\n    // The count sits beside the title (\"2 of 8 approved\"); the line under it\n    // says why the checks are worth doing (Arden, 2026-10-07).\n    const countEl = root.querySelector('[data-btk-kp-checklist-count]');\n    if (countEl) {\n      countEl.hidden = !due.length;\n      countEl.textContent = due.length ? `${done} of ${due.length} approved` : '';\n      countEl.classList.toggle('is-complete', due.length > 0 && done === due.length);\n    }\n    if (lead) {\n      lead.textContent = !due.length\n        ? 'Add units to your plan, then come back here to check them before you order.'\n        : done === due.length\n          ? 'All done - thank you. Your plan has been checked and is ready to order.'\n          : 'We know checking is a chore, but a few minutes here makes a real difference: it catches the small things that cause the biggest delays, so your bedroom arrives right first time. Approve each card when you\\'re happy with it.';\n    }\n    // All approved: carry straight on to checkout from here (the planner's\n    // green button, under the lead).\n    let next = root.querySelector('[data-btk-kp-checklist-next]');\n    if (!next && lead) {\n      next = document.createElement('div');\n      next.className = 'btk-kp-checklist-next';\n      next.setAttribute('data-btk-kp-checklist-next', '');\n      lead.after(next);\n    }\n    if (next) {\n      const ready = due.length > 0 && done === due.length;\n      next.hidden = !ready;\n      next.innerHTML = ready\n        ? `<button type=\"button\" class=\"btk-kp-action-btn btk-kp-action-btn--green\" data-btk-kp-checklist-checkout>\n              <span class=\"btk-kp-action-btn-label\">Continue to Checkout</span>\n              <span class=\"btk-kp-action-btn-arrow\" aria-hidden=\"true\"><svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M9 18l6-6-6-6\"/></svg></span>\n            </button>`\n        : '';\n    }\n    // Only the checks this plan triggers, one per row, on the planner's light\n    // grey (Arden, 2026-10-07). Two columns: on the left, left-aligned, the\n    // check's title, what it found and its advice; on the right a column the\n    // width of two door tiles, holding the pictures and, in the card's bottom\n    // right corner, Approve. A single picture fills that column (double size),\n    // so every card lines up. Inventory's rows run across both columns, the\n    // item on the left and its buttons in the right-hand column.\n    host.className = 'btk-kp-checklist-cards';\n    host.innerHTML = due.map(it => {\n      const meta = checklistContent(it.key);\n      const approved = isChecklistApproved(it);\n      const title = meta.title || it.title;\n      const open = ckOpen.has(it.key) ? ckOpen.get(it.key) : it.key === firstKey;\n      // Closed: folded to its title row until opened (Show). An approved card\n      // opened can be un-approved - checkout then sends the customer back to it.\n      const action = it.noApprove\n        ? ''\n        : approved\n        ? `<button type=\"button\" class=\"btk-kp-action-btn btk-kp-action-btn--light btk-kp-action-btn--sm\" data-btk-kp-check-unapprove=\"${ckEsc(it.key)}\">\n              <span class=\"btk-kp-action-btn-label\">Undo Approval</span>\n            </button>\n            <span class=\"btk-kp-action-btn btk-kp-action-btn--green btk-kp-action-btn--sm btk-kp-ps-state is-current\" aria-current=\"true\">\n              <span class=\"btk-kp-action-btn-icon\" aria-hidden=\"true\">${CHECK_TICK}</span>\n              <span class=\"btk-kp-action-btn-label\">Approved</span>\n            </span>`\n        : `<button type=\"button\" class=\"btk-kp-action-btn btk-kp-action-btn--green btk-kp-action-btn--sm\" data-btk-kp-check-approve=\"${ckEsc(it.key)}\"\n                   aria-label=\"${ckEsc('Approve: ' + it.confirm)}\"${it.blocked ? ' disabled title=\"Choose each item, or mark it as bought elsewhere, first\"' : ''}>\n              <span class=\"btk-kp-action-btn-icon\" aria-hidden=\"true\">${CHECK_TICK}</span>\n              <span class=\"btk-kp-action-btn-label\">Approve</span>\n            </button>`;\n      const extra = it.extra\n        ? `<button type=\"button\" class=\"btk-kp-action-btn btk-kp-action-btn--sm\" ${it.extra.attr}>\n              <span class=\"btk-kp-action-btn-icon\" aria-hidden=\"true\">${CK_ICONS[it.extra.icon] || ''}</span>\n              <span class=\"btk-kp-action-btn-label\">${ckEsc(it.extra.label)}</span>\n              <span class=\"btk-kp-action-btn-arrow\" aria-hidden=\"true\">${CK_CHEVRON}</span>\n            </button>`\n        : '';\n      // Pictures, right-hand column. Door & Carcase: one tile per combination\n      // (the door on its carcase), named and counted - two to a row, or one at\n      // double size when there is only one. Inventory: none. Every other\n      // check: its metaobject picture, or a placeholder until one is added.\n      let media = '';\n      if (Array.isArray(it.swatches) && it.swatches.length) {\n        const big = it.swatches.length === 1 ? ' btk-kp-checklist-tile--big' : '';\n        media = it.swatches.map((s, si) => {\n          const o = s.overlay;\n          // A rendered unit (see the Door & Carcase swatches): an empty slot,\n          // filled once the picture is drawn below.\n          const pic = (s.thumbs && s.thumbs.length) ? `<span class=\"btk-kp-checklist-render\" data-ck-render=\"${ckEsc(it.key)}|${si}\"></span>`\n            : o ? `<span class=\"btk-kp-checklist-overlay\">\n                ${o.carcaseImg ? `<img class=\"btk-kp-restyle-tile-carcase\" src=\"${ckEsc(o.carcaseImg)}\" alt=\"\">` : ''}\n                ${o.doorImg ? `<img class=\"btk-kp-restyle-tile-door\" src=\"${ckEsc(o.doorImg)}\" alt=\"\">` : ''}\n              </span>` : (s.img ? `<img src=\"${ckEsc(s.img)}\" alt=\"\" loading=\"lazy\" decoding=\"async\">` : '');\n          return `\n            <span class=\"btk-kp-checklist-swatch${big}\">\n              <span class=\"btk-kp-checklist-tile${big}${pic ? '' : ' btk-kp-checklist-tile--placeholder'}\" aria-hidden=\"true\">${pic || CK_ICONS[it.key] || ''}</span>\n              <span class=\"btk-kp-checklist-swatch-name\">${ckEsc(s.range || s.door || s.label)}</span>\n              ${s.range ? `<span class=\"btk-kp-checklist-swatch-sub\">${ckEsc(s.door)} on ${ckEsc(s.carcase)}</span>`\n                : s.sub ? `<span class=\"btk-kp-checklist-swatch-sub\">${ckEsc(s.sub)}</span>` : ''}\n              ${s.n != null ? `<span class=\"btk-kp-checklist-swatch-n\">${ckEsc(s.nLabel || ckUnits(s.n))}</span>` : ''}\n            </span>`;\n        }).join('');\n      } else if (it.key !== 'inventory') {\n        media = it.pictureSvg\n          ? `<span class=\"btk-kp-checklist-tile btk-kp-checklist-tile--big btk-kp-checklist-tile--plan\">${it.pictureSvg}</span>`\n          : meta.image\n          ? `<span class=\"btk-kp-checklist-tile btk-kp-checklist-tile--big\" aria-hidden=\"true\"><img src=\"${ckEsc(meta.image)}\" alt=\"\" loading=\"lazy\" decoding=\"async\"></span>`\n          : CK_PICTURES[it.picture || it.key]\n          ? `<span class=\"btk-kp-checklist-tile btk-kp-checklist-tile--big\">${CK_PICTURES[it.picture || it.key]}</span>`\n          : `<span class=\"btk-kp-checklist-tile btk-kp-checklist-tile--big btk-kp-checklist-tile--placeholder\" aria-hidden=\"true\">${CK_ICONS[it.key] || CK_ICONS.advisory}</span>`;\n      }\n      // Inventory: first each type of item in the order, ticked, with how\n      // many; then each core item not in it - the item on the left, and Buy\n      // Elsewhere then a green Choose Now in the right-hand column (or, once\n      // marked, Buying elsewhere and Undo).\n      const included = Array.isArray(it.included) ? it.included : [];\n      const missing = (included.length || (Array.isArray(it.missing) && it.missing.length))\n        ? `<div class=\"btk-kp-checklist-missing\">${included.map(g => `\n            <div class=\"btk-kp-checklist-missing-row is-included\">\n              <span class=\"btk-kp-checklist-missing-label\">${ckEsc(g.label)} (${g.n})</span>\n              <span class=\"btk-kp-checklist-missing-btns\">\n                <span class=\"btk-kp-checklist-missing-note\">${CHECK_TICK} In your order</span>\n              </span>\n            </div>`).join('')}${(it.missing || []).map(m => `\n            <div class=\"btk-kp-checklist-missing-row${m.elsewhere ? ' is-elsewhere' : ''}\">\n              <span class=\"btk-kp-checklist-missing-label\">${ckEsc(m.label)}</span>\n              <span class=\"btk-kp-checklist-missing-btns\">\n              ${m.elsewhere\n                ? `<span class=\"btk-kp-checklist-missing-note\">${CHECK_TICK} Buying elsewhere</span>\n                   <button type=\"button\" class=\"btk-kp-action-btn btk-kp-action-btn--light btk-kp-action-btn--sm\" data-btk-kp-check-elsewhere=\"${ckEsc(m.key)}\">\n                     <span class=\"btk-kp-action-btn-label\">Undo</span>\n                   </button>`\n                : `<button type=\"button\" class=\"btk-kp-action-btn btk-kp-action-btn--light btk-kp-action-btn--sm\" data-btk-kp-check-elsewhere=\"${ckEsc(m.key)}\">\n                     <span class=\"btk-kp-action-btn-label\">Buy Elsewhere</span>\n                   </button>\n                   <button type=\"button\" class=\"btk-kp-action-btn btk-kp-action-btn--green btk-kp-action-btn--sm\" data-btk-kp-check-choose=\"${ckEsc(m.key)}\">\n                     <span class=\"btk-kp-action-btn-label\">Choose Now</span>\n                   </button>`}\n              </span>\n            </div>`).join('')}</div>`\n        : '';\n      const intro = ckEsc(it.detail);\n      const head = `\n            <div class=\"btk-kp-checklist-head\">\n              <h3 class=\"btk-kp-checklist-title\">\n                <span class=\"btk-kp-checklist-title-icon\" aria-hidden=\"true\">${CK_ICONS[it.key] || CK_ICONS.advisory}</span>\n                <span>${ckEsc(title)}</span>\n                ${approved ? `<span class=\"btk-kp-checklist-tick\">${CHECK_TICK}<span>Approved</span></span>` : ''}\n              </h3>\n              <button type=\"button\" class=\"btk-kp-action-btn btk-kp-action-btn--light btk-kp-action-btn--sm btk-kp-checklist-fold\"\n                      data-btk-kp-check-toggle=\"${ckEsc(it.key)}\" aria-expanded=\"${open ? 'true' : 'false'}\">\n                <span class=\"btk-kp-action-btn-label\">${open ? 'Hide' : 'Show'}</span>\n                <span class=\"btk-kp-action-btn-arrow\" aria-hidden=\"true\">${CK_CHEVRON}</span>\n              </button>\n            </div>`;\n      if (!open) {\n        return `\n        <div class=\"btk-kp-checklist-card${approved ? ' is-approved' : ''} is-folded\" role=\"group\" aria-label=\"${ckEsc(title)}\" data-btk-kp-check=\"${ckEsc(it.key)}\">\n          <div class=\"btk-kp-checklist-main\">${head}</div>\n        </div>`;\n      }\n      return `\n        <div class=\"btk-kp-checklist-card${approved ? ' is-approved' : ''}${it.flagged ? ' is-flagged' : ''}${missing ? ' has-missing' : ''}\"\n             role=\"group\" aria-label=\"${ckEsc(title)}\" data-btk-kp-check=\"${ckEsc(it.key)}\">\n          <div class=\"btk-kp-checklist-main\">\n            ${head}\n            ${intro ? `<p class=\"btk-kp-checklist-statement\">${intro}</p>` : ''}\n            ${it.points && it.points.length ? `<ol class=\"btk-kp-checklist-points\">${it.points.map(pt => `<li><strong>${ckEsc(pt.title)}</strong> ${ckEsc(pt.message)}</li>`).join('')}</ol>` : ''}\n            <p class=\"btk-kp-checklist-advice\">${ckEsc(meta.advice || it.advice)}</p>\n          </div>\n          ${media ? `<div class=\"btk-kp-checklist-tiles\">${media}</div>` : ''}\n          ${missing}\n          <div class=\"btk-kp-checklist-actions\">${extra}${action}</div>\n        </div>`;\n    }).join('');\n    // Draw the rendered units into their slots: the first of the combination's\n    // units the Add Units pictures can draw. None drawable (no 3D model): the\n    // door-on-carcase photo, as before.\n    host.querySelectorAll('[data-ck-render]').forEach(slot => {\n      const [key, si] = slot.dataset.ckRender.split('|');\n      const s = ((due.find(x => x.key === key) || {}).swatches || [])[Number(si)];\n      if (!s) return;\n      const pick = (s.thumbs || []).find(t => cabinetsHandle.unitThumbCab && cabinetsHandle.unitThumbCab(t));\n      if (pick && cabinetsHandle.renderUnitThumb && cabinetsHandle.renderUnitThumb(slot, pick)) return;\n      const o = s.overlay;\n      if (o && (o.carcaseImg || o.doorImg)) {\n        slot.outerHTML = `<span class=\"btk-kp-checklist-overlay\">\n          ${o.carcaseImg ? `<img class=\"btk-kp-restyle-tile-carcase\" src=\"${ckEsc(o.carcaseImg)}\" alt=\"\">` : ''}\n          ${o.doorImg ? `<img class=\"btk-kp-restyle-tile-door\" src=\"${ckEsc(o.doorImg)}\" alt=\"\">` : ''}\n        </span>`;\n      }\n    });\n    return firstKey;\n  }\n  // After an approval, glide the next card to approve to the middle of the\n  // screen (Arden, 2026-10-14) - or, with none left, Continue to Checkout.\n  function ckSlideTo(key) {\n    const el = key\n      ? root.querySelector(`[data-btk-kp-check=\"${CSS.escape(key)}\"]`)\n      : root.querySelector('[data-btk-kp-checklist-next]:not([hidden])');\n    if (el && el.scrollIntoView) el.scrollIntoView({ behavior: 'smooth', block: 'center' });\n  }\n\n  // Accept Advisory panel points (all of them, or one rule's), the same as\n  // its own Accept does.\n  function acceptAdvisory(ruleId) {\n    for (const w of designWarnings) {\n      if (!ruleId || w.ruleId === ruleId) acceptedWarnings.add(warnKey(w));\n    }\n    renderWarningsButton();\n    renderWarningsPanel();\n  }\n\n  root.addEventListener('click', (e) => {\n    const approve = e.target.closest('[data-btk-kp-check-approve]');\n    if (approve) {\n      const key = approve.dataset.btkKpCheckApprove;\n      const it = computeChecklist().find(x => x.key === key);\n      const ok = !!(it && it.applies && !it.blocked);\n      if (ok) {\n        if (key === 'advisory') acceptAdvisory(null);\n        else if (key === 'walkways') acceptAdvisory('walkway-too-small');\n        else if (key === 'belfast-worktop') acceptAdvisory('belfast-worktop-edge');\n        else checklistApprovals[it.key] = it.signature;\n        ckOpen.delete(it.key);   // closes, and the next card to approve opens\n        scheduleAutosave?.();\n      }\n      const next = drawChecklist();\n      if (ok) ckSlideTo(next);\n      return;\n    }\n    // Show / Hide on a card.\n    const toggle = e.target.closest('[data-btk-kp-check-toggle]');\n    if (toggle) {\n      const k = toggle.dataset.btkKpCheckToggle;\n      ckOpen.set(k, toggle.getAttribute('aria-expanded') !== 'true');\n      drawChecklist();\n      return;\n    }\n    // Undo Approval: the check is outstanding again, so checkout will send\n    // the customer back to it. Walkways un-accepts its Advisory points.\n    const unapprove = e.target.closest('[data-btk-kp-check-unapprove]');\n    if (unapprove) {\n      const k = unapprove.dataset.btkKpCheckUnapprove;\n      if (k === 'walkways' || k === 'belfast-worktop') {\n        const rule = k === 'walkways' ? 'walkway-too-small' : 'belfast-worktop-edge';\n        for (const w of designWarnings) if (w.ruleId === rule) acceptedWarnings.delete(warnKey(w));\n        renderWarningsButton();\n        renderWarningsPanel();\n      } else {\n        delete checklistApprovals[k];\n      }\n      ckOpen.set(k, true);   // stays open, to look at again\n      scheduleAutosave?.();\n      drawChecklist();\n      return;\n    }\n    // Inventory: Buy Elsewhere marks a missing item as bought elsewhere (Undo\n    // takes it back); Choose Now goes to where it is chosen and opens it.\n    const elsewhere = e.target.closest('[data-btk-kp-check-elsewhere]');\n    if (elsewhere) {\n      const k = elsewhere.dataset.btkKpCheckElsewhere;\n      if (checklistElsewhere.has(k)) checklistElsewhere.delete(k); else checklistElsewhere.add(k);\n      scheduleAutosave?.();\n      drawChecklist();\n      return;\n    }\n    const choose = e.target.closest('[data-btk-kp-check-choose]');\n    if (choose) {\n      const core = CK_CORE[choose.dataset.btkKpCheckChoose];\n      if (core) {\n        stepperHandle.setStep(core.stage);\n        requestAnimationFrame(() => {\n          root.querySelector(`[data-btk-kp-panel=\"${core.stage}\"] [data-btk-kp-open-popup=\"${core.popup}\"]`)?.click();\n        });\n      }\n      return;\n    }\n    // Room Sizes' Check My Room: Room Setup, where the walls and features are.\n    if (e.target.closest('[data-btk-kp-check-room]')) { stepperHandle.setStep('room-setup'); return; }\n    // Advisory Points' View on Plan: the plan, with the Advisory list open.\n    if (e.target.closest('[data-btk-kp-check-advisory]')) {\n      stepperHandle.setStep('add-units');\n      // With the first open point showing, its Accept in view.\n      const firstOpen = designWarnings.find(w => !acceptedWarnings.has(warnKey(w)));\n      expandedWarnKey = firstOpen ? warnKey(firstOpen) : null;\n      openWarningsPanel();\n      if (firstOpen) focusWarningOnPlan(firstOpen);\n      return;\n    }\n    // Smart Checklist's Open Basket: its recommendations live there.\n    if (e.target.closest('[data-btk-kp-check-basket]')) { openLiveQuote(); return; }\n    if (e.target.closest('[data-btk-kp-checklist-checkout]')) { proceedToCheckout(); return; }\n    // The left menu's Raise a Support Ticket.\n    if (e.target.closest('[data-btk-kp-checklist-ticket]')) { openTicketPopup(); return; }\n    // (The older Get Help button, should a cached page still have it.)\n    if (e.target.closest('[data-btk-kp-checklist-gethelp]')) {\n      root.querySelector('[data-btk-kp-header-gethelp]')?.click();\n    }\n  });\n\n  // ---- Raise a Support Ticket (Checklist left menu) --------------------\n  // A ticket in the customer's own account (Arden, 2026-10-07): the planner\n  // API's POST /my/tickets (through the App Proxy, so it knows who they are)\n  // creates it in Odoo's Website Support - numbered, Open, the usual emails -\n  // and it appears under Support Tickets in their account. They write the\n  // question; the plan's name and reference are added for the team. Signed\n  // out, there is no account to put it in, so the popup says so.\n  const ticketPopup = document.createElement('div');\n  ticketPopup.className = 'btk-kp-popup';\n  ticketPopup.hidden = true;\n  ticketPopup.innerHTML = `\n    <div class=\"btk-kp-popup-backdrop\" data-btk-kp-ticket-close></div>\n    <div class=\"btk-kp-popup-panel btk-kp-saveas-panel btk-kp-ticket-panel\" role=\"dialog\" aria-labelledby=\"btk-kp-ticket-title\">\n      <header class=\"btk-kp-popup-head\">\n        <h2 id=\"btk-kp-ticket-title\">Raise a Support Ticket</h2>\n        <button type=\"button\" class=\"btk-kp-popup-close\" data-btk-kp-ticket-close aria-label=\"Close\">&times;</button>\n      </header>\n      <div class=\"btk-kp-popup-body\" data-btk-kp-ticket-body></div>\n      <footer class=\"btk-kp-cab-detail-footer\" data-btk-kp-ticket-foot></footer>\n    </div>`;\n  (saveAsPopup && saveAsPopup.parentNode ? saveAsPopup.parentNode : root).appendChild(ticketPopup);\n  const ticketBody = ticketPopup.querySelector('[data-btk-kp-ticket-body]');\n  const ticketFoot = ticketPopup.querySelector('[data-btk-kp-ticket-foot]');\n  let ticketSending = false;\n  const TICKET_PHONE = '<a href=\"tel:01934813201\">01934 813 201</a>';\n\n  // Just the saved plan's name - the customer sees the ticket in their account,\n  // and the team opens the plan by that name from the contact's Planner Plans\n  // tab (Arden, 2026-10-07: no internal reference or basket ids).\n  function ticketPlanLines() {\n    // The planner version, so a reported glitch can be matched to the build it was seen on.\n    return [`Saved plan: ${activePlanName || 'not saved yet'}`,\n      `Planner: Better Planner v${PLANNER_VERSION} (beta), build ${BETA_VERSION || 'unknown'}`];\n  }\n  function closeTicketPopup() { if (!ticketSending) ticketPopup.hidden = true; }\n  function openTicketPopup() {\n    ticketSending = false;\n    if (!root.dataset.customerId) {\n      ticketBody.innerHTML = `<p class=\"btk-kp-ticket-done\">Please sign in to raise a ticket, so we can link it to your account and your plan. Or call us on ${TICKET_PHONE}.</p>`;\n      ticketFoot.innerHTML = '';\n    } else {\n      ticketBody.innerHTML = `\n        <div class=\"btk-kp-field\">\n          <label for=\"btk-kp-ticket-msg\">What do you need help with?</label>\n          <textarea id=\"btk-kp-ticket-msg\" data-btk-kp-ticket-msg maxlength=\"4000\" placeholder=\"Tell us what you would like us to look at\"></textarea>\n          <p class=\"btk-kp-ticket-note\">Your plan (${ckEsc(activePlanName || 'unsaved plan')}) is attached for our team. We'll reply by email, and you can follow the ticket in your account under Support Tickets.</p>\n          <p class=\"btk-kp-panel-note\" data-btk-kp-ticket-error hidden></p>\n        </div>`;\n      ticketFoot.innerHTML = `\n        <button type=\"button\" class=\"btk-kp-action-btn btk-kp-action-btn--green btk-kp-action-btn--sm\" data-btk-kp-ticket-send>\n          <span class=\"btk-kp-btn-spinner\" aria-hidden=\"true\"></span>\n          <span class=\"btk-kp-action-btn-label\">Send Ticket</span>\n        </button>`;\n    }\n    ticketPopup.hidden = false;\n    const box = ticketBody.querySelector('[data-btk-kp-ticket-msg]');\n    if (box) setTimeout(() => box.focus(), 40);\n  }\n  async function sendTicket() {\n    if (ticketSending) return;\n    const box = ticketBody.querySelector('[data-btk-kp-ticket-msg]');\n    const errEl = ticketBody.querySelector('[data-btk-kp-ticket-error]');\n    const btn = ticketFoot.querySelector('[data-btk-kp-ticket-send]');\n    const text = String((box && box.value) || '').trim();\n    if (!text) {\n      if (errEl) { errEl.textContent = 'Please tell us what you need help with.'; errEl.hidden = false; }\n      if (box) box.focus();\n      return;\n    }\n    ticketSending = true;\n    if (errEl) errEl.hidden = true;\n    if (btn) {\n      btn.disabled = true;\n      btn.classList.add('is-saving');\n      btn.querySelector('.btk-kp-action-btn-label').textContent = 'Sending\u2026';\n    }\n    const message = [text, '', '---', ...ticketPlanLines()].join(String.fromCharCode(10));\n    try {\n      const res = await fetch('/apps/planner/my/tickets', {\n        method: 'POST',\n        headers: { 'Content-Type': 'application/json' },\n        // Filed under Help with planning, the Odoo ticket category for it.\n        body: JSON.stringify({ topic: 'Help with planning', subject: `Bedroom planner help - ${activePlanName || 'unsaved plan'}`, message })\n      });\n      const data = await res.json().catch(() => null);\n      if (!res.ok || !data || !data.ok) throw new Error((data && data.error) || ('HTTP ' + res.status));\n      const num = data.ticket && data.ticket.number ? ` #${ckEsc(data.ticket.number)}` : '';\n      ticketBody.innerHTML = `<p class=\"btk-kp-ticket-done\"><strong>Thank you - ticket${num} is raised.</strong> Our team will reply by email, and you can follow it in your account under Support Tickets.</p>`;\n      ticketFoot.innerHTML = `\n        <button type=\"button\" class=\"btk-kp-action-btn btk-kp-action-btn--green btk-kp-action-btn--sm\" data-btk-kp-ticket-close>\n          <span class=\"btk-kp-action-btn-label\">Close</span>\n        </button>`;\n    } catch (err) {\n      console.warn('[BTK Kitchen Planner] support ticket not sent', err);\n      if (errEl) {\n        errEl.innerHTML = `Sorry, we couldn't send that just now. Please try again, or call us on ${TICKET_PHONE}.`;\n        errEl.hidden = false;\n      }\n      if (btn) {\n        btn.disabled = false;\n        btn.classList.remove('is-saving');\n        btn.querySelector('.btk-kp-action-btn-label').textContent = 'Send Ticket';\n      }\n    } finally {\n      ticketSending = false;\n    }\n  }\n  ticketPopup.addEventListener('click', (e) => {\n    if (e.target.closest('[data-btk-kp-ticket-close]')) { closeTicketPopup(); return; }\n    if (e.target.closest('[data-btk-kp-ticket-send]')) sendTicket();\n  });\n  document.addEventListener('keydown', (e) => {\n    if (e.key === 'Escape' && !ticketPopup.hidden) closeTicketPopup();\n  });\n\n  // A wall picked from a list - the drawn room's wall panel, or Room Setup's\n  // Edit Wall Size menu - is the same act as clicking it on the plan: routed\n  // through the selection so the panel and the plan's highlight can never\n  // point at different walls.\n  function selectWallFromList(wi) {\n    selectItem({ kind: 'wall', wallIndex: wi });\n    // ...and light it, the way clicking the wall on the plan does. A row and a\n    // wall that do not visibly belong to each other leave you counting round\n    // the room to find out which is which. The whole run: a wall is one\n    // section unless a door splits it, and the row stands for the wall either way.\n    const segs = wallSegments(wi);\n    const whole = segs.find(sg => sg.kind !== 'opening') || segs[0];\n    if (whole) requestAnimationFrame(() => showWallSegmentSpan(wi, whole.key));\n  }\n\n selectionPanelHandle = initSelectionPanel(sidebar, {\n    // Products are fetched per buying style ON DEMAND, so a placed unit that\n    // belongs to a DIFFERENT style has no product in the index yet - and with\n    // no product there are no variants, so its size pills come out empty. The\n    // Add Units popup already gets this loader; the panel needs it for the\n    // same reason.\n    hasStyleProducts:    (styleId) => Catalogue.hasProductsForStyle(styleId),\n    ensureStyleProducts: (styleId) => ensureStyleProducts(styleId),\n    getRoom:        () => room,\n    onShowOpeningSpan:  showOpeningSpan,\n    onClearOpeningSpan: clearOpeningSpan,\n    getOpeningGaps,\n    onSetOpeningGap:    handleSetOpeningGap,\n    getWallSegments,\n    onSetSegmentSize:   handleSetSegmentSize,\n    onToggleSegmentLock: handleToggleSegmentLock,\n    onShowSegmentSpan:  showWallSegmentSpan,\n    // A drawn room's panel lists every wall, so picking one there is the same\n    // act as clicking it on the plan (see selectWallFromList).\n    onSelectWall:       (wi) => selectWallFromList(wi),\n    // Every wall of the room, for the Edit Wall Size menu's list.\n    getWallList:        () => getWalls(room),\n    onShowFeatureRun:   showFeatureRun,\n    getRoomConfig,\n    getCabinets:        () => cabinets,\n    Catalogue,\n    // The same GLB render the Doors & Windows popup previews with, so the\n    // opening in the panel is the one that will be built.\n    renderOpeningThumbnail,\n    getWorktopColourHex: () => worktopColourHex,\n    // Off-screen 3D thumbnail of the selected unit: the same buildCabinetGLB\n    // path as the main 3D view, so colours / handles / hardware match, but\n    // drawn by the HEADLESS renderer (renderCabinetThumbHeadless) so a click\n    // in 2D never starts the whole live 3D view.\n    renderCabinetThumbnail: (cab, opts) => renderCabinetThumbHeadless(cab, opts),\n    // The Swap Unit cards draw each unit the way the Add Units cards do.\n    renderUnitThumb: (slot, o) => cabinetsHandle?.renderUnitThumb?.(slot, o),\n    // ...and its details page draws a unit larger, and its dimension drawing.\n    unitThumbCab: (o) => cabinetsHandle?.unitThumbCab?.(o) || null,\n    renderCabinetDimensionThumbnail: async (cab, opts) => {\n      await ensure3DReady();\n      if (!handle3D || typeof handle3D.renderCabinetDimensionThumbnail !== 'function') return null;\n      return handle3D.renderCabinetDimensionThumbnail(cab, opts);\n    },\n    onUpdateFeature:      handleUpdateFeature,\n    onUpdateOpening:      handleUpdateOpening,\n    onUpdateCabinetSize:       handleUpdateCabinetSize,\n    onSetUnitNote:             handleSetUnitNote,\n    onUpdateCabinetHinge:      handleUpdateCabinetHinge,\n    onUpdateCabinetMountLevel: handleUpdateCabinetMountLevel,\n    onUpdateCabinetMountAnchor: handleUpdateCabinetMountAnchor,\n    onSetCabinetAsBase: handleSetCabinetAsBase,\n    canMakeBaseUnit: (id) => canMakeBaseUnit((cabinets || []).find(c => c && c.id === id)),\n    onSetCabinetAlign: handleSetCabinetAlign,\n    getAlignCandidates: (id) => getAlignCandidates(id),\n    getWallUnitHeights: (id) => wallUnitHeights(id),\n    onOpenPositionMenu:        openUnitPositionMenu,\n    getCabinetNearestGaps,\n    onSetCabinetNearestDistance: handleSetCabinetNearestDistance,\n    onShowPositionSpan:        showPositionSpan,\n    onClearPositionSpan:       clearPositionSpan,\n    onSetCabinetStackMode:     handleSetCabinetStackMode,\n    onSetCabinetStackTrim:     handleSetCabinetStackTrim,\n    onApplyCabinetStack:       handleApplyCabinetStack,\n    renderStackPreview,\n    renderHandlePreview,\n    hideStackPreview,\n    onUpdateCabinetEndPanel:   handleUpdateCabinetEndPanel,\n    onUpdateCabinetFiller:     handleUpdateCabinetFiller,\n    onSetCabinetSideAuto:      handleSetCabinetSideAuto,\n    getAutoEndPanels:          () => autoEndPanels,\n    onSetAutoEndPanels:        handleSetAutoEndPanels,\n    onUpdateCornerUnit:        handleUpdateCornerUnit,\n    onAutoCornerPost:          handleAutoCornerPost,\n    getCornerPostNote,\n    onToggleCushionTop:        handleToggleCushionTop,\n    onSetCushionColour:        handleSetCushionColour,\n    getHobCatalogue:           () => (getWorktopItemCatalogue().hobs || []),\n    onSetCabinetHob:           handleSetCabinetHob,\n    getSinkCatalogue:          () => (getWorktopItemCatalogue().sinks || []),\n    onSetCabinetSink:          handleSetCabinetSink,\n    getReadyPlannerSinks:      () => (Catalogue?.getReadyPlannerSinks?.() || []),\n    onSetCabinetPlannerSink:   handleSetCabinetPlannerSink,\n    // Why a sink of this install type cannot go on this plan, or null.\n    sinkWorktopBlock:          (installType, cabId) => sinkWorktopBlock(installType, false, cabId ? (cabinets || []).find(c => c && c.id === cabId) : null),\n    onSetCabinetPlannerSinkDrainer: handleSetCabinetPlannerSinkDrainer,\n    onSetCabinetPlannerSinkFitting: handleSetCabinetPlannerSinkFitting,\n    // The Sink Unit switch (any suitable base unit can take the sink).\n    onSetCabinetSinkUnit:      handleSetCabinetSinkUnit,\n    onSetCabinetSinkLeg:       handleSetCabinetSinkLeg,\n    sinkUnitAllowed:           (c) => sinkUnitAllowed(c),\n    onSetCabinetPlannerSinkOffset:  handleSetCabinetPlannerSinkOffset,\n    // Cab panel's green \"Choose Appliance\" button \u2192 the appliance-picker\n    // popup (cards + Select) owned by the cabinets-UI module.\n    onOpenChooseAppliancePopup: (cabinetId) => cabinetsHandle?.openChooseAppliancePopup?.(cabinetId),\n    onOpenWalkInSets:          (cabinetId) => openWalkInSetsPopup(cabinetId),\n    // Forward to the cabinets-UI module so the cab panel's Choose\n    // Sink button opens the SAME popup as the To Do's button.\n    onOpenChooseSinkPopup:     (cabinetId) => cabinetsHandle?.openChooseSinkPopup?.(cabinetId),\n    onOpenChooseTapPopup:      (cabinetId) => cabinetsHandle?.openChooseTapPopup?.(cabinetId),\n    onShowSinkSet:             (cabinetId) => showSinkSet(cabinetId),\n    getTapsOnCabinet:          (cabinetId) => tapsOnCabinet(cabinetId),\n    getSinkMoveInfo:           (cabinetId) => sinkMoveInfo(cabinetId),\n    onSetEndPanelColour:       handleSetEndPanelColour,\n    onSetSegmentColour:        handleSetSegmentColour,\n    getSegmentColours:         () => segmentColours,\n    getPlinthSectionInfo:      (cabIds) => plinthSectionInfo(cabIds),\n    onSetPlinthType:           handleSetPlinthType,\n    onSetTrimOff:              handleSetTrimOff,\n    onSetPastryShelf:          handleSetPastryShelf,\n    onSetPantry:               handleSetPantry,\n    getUnitWorktopInfo:        unitWorktopInfo,\n    onChangeUnitsWorktop:      (cabIds, label) => openWorktopForUnits([...new Set([...(cabIds || []), ...selectedCabinetIds])],\n                                 selectedCabinetIds.size > 1 ? 'the selected units' : label),\n    onChangeSectionWorktop:    (worktopId) => openWorktopForUnits(worktopSectionCabIds(worktopId), 'this worktop'),\n    getPastryShelfOptions:     pastryShelfOptions,\n    onSetPlinthPosition:       handleSetPlinthPosition,\n    getUnitPlinthInfo:         (cabId) => unitPlinthInfo(cabId),\n    getMediaInfo:              (cabId) => getMediaInfo(cabId),\n    onApplyMedia:              handleApplyMedia,\n    renderMediaPreview,\n    onSetUnitPlinth:           handleSetUnitPlinth,\n    onSetUnitFloatHeight:      handleSetUnitFloatHeight,\n    // Trim TYPE colours ('plinthColour' ...) live in featureStyles.\n    getFeatureStyles:          () => featureStyles,\n    onSetWorktopColour:        handleSetWorktopColour,\n    getWorktopColour:          () => worktopColourHex,\n    getWorktopColours:         () => worktopColours,\n    onSetWorktopCornerRadius:  handleSetWorktopCornerRadius,\n    onSetWorktopWaterfall:     handleSetWorktopWaterfall,\n    getWorktopWaterfallInfo,\n    getWorktopPlanOutline,\n    getCabinetWorktopId,\n    getCabinetWorktopShape,\n    onSetCabinetBarWaterfall:  handleSetCabinetBarWaterfall,\n    canCabinetBarWaterfall:    cabinetCanBarWaterfall,\n    isCabinetWaterfallBarred:  cabinetWaterfallBarred,\n    getBackPanelRunInfo,\n    renderBackPanelPreview,\n    onApplyBackPanel:          handleApplyBackPanel,\n    getWorktopCornerRadii:     () => worktopCornerRadii,\n    onSetWorktopMaterial:      handleSetWorktopMaterial,\n    getWorktopMaterialHandle:  () => worktopMaterialHandle,\n    getWorktopSectionMaterials: () => worktopMaterialsBySection,\n    // Every material the catalogue holds - worktop BLANKS (laminate, real\n    // wood, FENIX, solid surface) as well as any slab-tier range. The catalogue\n    // only emits products that carry a worktop_pricing_model, so upstands,\n    // edging and adhesives in the same collections never reach the picker.\n    getWorktopMaterialOptions: () => rangeWorktopMaterials(),\n    onUpdateCabinetWorktop:    handleUpdateCabinetWorktop,\n    onRotateCabinet:    (id, stepDeg) => { const c = cabinets.find(x => x.id === id); if (c) rotateCabinet(c, stepDeg || 90); },\n    onSetCabinetRotationLock: (id, locked) => setCabinetRotationLock(id, locked),\n    onSetCabinetPositionLock: (id, locked) => setCabinetPositionLock(id, locked),\n    // Free-standing appliances (their own panel - see the selection panel).\n    getPlanApplianceEntry:       (id) => planApplianceEntry(cabinets.find(x => x.id === id)),\n    onSetPlanApplianceColour:    (id, code) => handleSetPlanApplianceColour(id, code),\n    onSetPlanApplianceStacked:   (id, on) => handleSetPlanApplianceStacked(id, on),\n    onSetPlanApplianceHinge:     (id, side) => handleSetPlanApplianceHinge(id, side),\n    onDuplicateCabinet: (id) => { const c = cabinets.find(x => x.id === id); if (c) duplicateCabinet(c); },\n    onSwapCabinetUnitType: swapCabinetUnitType,\n    onSwapPanelFinish: swapPanelFinish,\n    onSetPanelSize: setPanelSize,\n    onSetFillerSize: setFillerSize,\n    getFillerStock: fillerStockOf,\n    onSetCabinetRailBoth: setCabinetRailBoth,\n    getAlternativeUnitTypes: (unitTypeId, styleId, variantId) => (Catalogue?.getAlternativeUnitTypes?.(unitTypeId, styleId, variantId) || []),\n    onDeleteCabinet:    (id) => { const c = cabinets.find(x => x.id === id); if (c) deleteCabinet(c); },\n    onToggleCabinetOpen: (id) => handle3D?.toggleCabinetOpen?.(id),\n    getCabinetIsOpen:    (id) => !!handle3D?.cabinetIsOpen?.(id),\n    onSnapCabinet:      snapCabinetToSide,\n    onNudgeCabinet:     handleNudgeCabinet,\n    // A selected group's panel (see getGroupGaps).\n    getGroupGaps:        getGroupGaps,\n    onSetGroupDistance:  handleSetGroupDistance,\n    onNudgeGroup:        handleNudgeGroup,\n    onSnapGroup:         handleSnapGroup,\n    onShowGroupSpan:     showGroupSpan,\n    onRotateGroup:       (ids) => { const g = groupIdOf(ids); if (g) rotateCabinetGroup(g); },\n    onEditIsland:        (ids) => {\n      const g = groupIdOf(ids);\n      const c = g && cabinets.find(x => x.groupId === g && x.islandDesign);\n      if (c && cabinetsHandle.openIslandDesigner) cabinetsHandle.openIslandDesigner(c.islandDesign, g);\n    },\n    onUngroupGroup:      (ids) => { const g = groupIdOf(ids); if (g) { ungroupCabinet(g); selectItem(null); } },\n    onDeleteGroup:       (ids) => { const g = groupIdOf(ids); if (g) { deleteCabinetGroup(g); selectItem(null); } },\n    getCabinetWallGaps: getCabinetWallGaps,\n    getCabinetFillGap:  getCabinetFillGap,\n    onSetCabinetWallDistance: handleSetCabinetWallDistance,\n    onFillCabinetSide:  fillCabinetSide,\n    onUpdateCabinetSetback: handleUpdateCabinetSetback,\n    onUpdateCabinetMountBottom: handleUpdateCabinetMountBottom,\n    onSetCabinetPlinthHeight: handleSetCabinetPlinthHeight,\n    onSetCabinetHandle:     handleSetCabinetHandle,\n    onSetCabinetOwnHandles: handleSetCabinetOwnHandles,\n    getGlobalHandle:        () => handleGroups.base,\n    getHandleGroups:        () => handleGroups,\n    onRotateFeature:    handleRotateFeatureById,\n    onDeleteFeature:    handleRemovePerimeterItem,\n    onDeleteOpening:    handleRemoveOpening,\n    onDuplicateOpening: handleDuplicateOpening,\n    onApplyStyleToIds:  handleApplyStyleToIds,\n    getEndPanelLayout:  () => endPanelLayout,\n    getWorktopItems:    () => worktopItems,\n    getFurnitureItems:  () => furnitureItems,\n    onRotateFurniture:    rotateFurniture,\n    onDuplicateFurniture: duplicateFurniture,\n    getFurnitureWallHeight: furnitureWallHeight,\n    mountFurnitureControls: (box, item) => mountFurnitureControls(box, item, {\n      Furniture: (Catalogue.getFurniture && Catalogue.getFurniture()) || [],\n      OpeningColours: (Catalogue.getOpeningColours && Catalogue.getOpeningColours()) || [],\n      onChange: (patch) => updateFurniture(item.id, patch),\n    }),\n    onSetFurnitureWallHeight: setFurnitureWallHeight,\n    onDeleteFurniture:    deleteFurniture,\n    onRotateWorktopItem: rotateWorktopItem,\n    onDeleteWorktopItem: deleteWorktopItem,\n    onUpdateWorktopItem(id, patch) {\n      const i = worktopItems.findIndex(it => it.id === id);\n      if (i === -1) return;\n      worktopItems[i] = { ...worktopItems[i], ...patch };\n      rerender();\n    },\n    onUpdateSplashbackSection(keys, patch) {\n      // Per-section override: keyed by `${slabId}:${wallIndex}`.\n      // patch === null clears the override (revert to kitchen-wide\n      // settings). Otherwise merge into the existing override. A strip\n      // joined across several worktops (engine-splashbacks joinStrips)\n      // passes every worktop's key, so the whole strip changes together\n      // and stays one strip.\n      const sp = (roomConfig.splashbacks = roomConfig.splashbacks || {});\n      const overrides = (sp.overrides = sp.overrides || {});\n      for (const key of (Array.isArray(keys) ? keys : [keys])) {\n        if (patch === null) {\n          delete overrides[key];\n        } else {\n          overrides[key] = { ...(overrides[key] || {}), ...patch };\n        }\n      }\n      rerender();\n    }\n  });\n\n  // ---- Plan report (PDF download) ----------------------------------------\n  //\n  // One document instead of the two it used to be: the 3D/plan imagery that\n  // lived here and the numbered quote that only the basket could print.\n  //\n  // A4 LANDSCAPE throughout, and saved as a file rather than opened in a tab\n  // to print - a download survives pop-up blockers and gives the customer\n  // something to keep.\n  //\n  //   1  branded cover\n  //   2+ full-bleed 3D views, one per page\n  //   n  the measured floor plan\n  //   n  the plan schedule, numbered to match the plan\n  //   n  terms\n  const RPT = {\n    W: 297, H: 210,               // A4 landscape, mm\n    M: 16,                        // page margin\n    red:   [206, 4, 2],           // BK red #CE0402\n    black: [17, 17, 17],\n    ink:   [34, 34, 34],\n    mute:  [120, 120, 120],\n    rule:  [222, 222, 222],\n    green: [46, 125, 50]          // the basket's savings green\n  };\n\n  // Placeholder copy. Replace with the real marketing / terms wording.\n  const RPT_COVER_BLURB =\n    'This report sets out your bedroom as designed in the Better Bedrooms planner: ' +\n    'how it looks in three dimensions, the measured floor plan it is built from, and every ' +\n    'item that makes it up with its own plan number. The numbers on the plan and the numbers ' +\n    'in the schedule are the same throughout.';\n  // Print Plan Only (staff): the same report with no schedule and no prices.\n  const RPT_COVER_BLURB_PLAN_ONLY =\n    'This report sets out your bedroom as designed in the Better Bedrooms planner: ' +\n    'how it looks in three dimensions and the measured floor plan it is built from, with ' +\n    'every item marked by its own plan number.';\n\n  const RPT_TERMS = [\n    ['About this document',\n     'This report is a record of a bedroom design and the items specified for it at the date ' +\n     'shown on the cover. It is provided for planning purposes and is not a VAT invoice or an ' +\n     'order confirmation. Quantities, sizes and prices are taken from the plan as it stood when ' +\n     'the report was produced; changing the plan changes them.'],\n    ['Pricing',\n     'All prices are shown inclusive of VAT at the current rate. Prices are subject to change ' +\n     'and product availability is subject to stock at the time of order. Better Bedrooms ' +\n     'reserves the right to amend pricing without notice. The delivery shown is an estimate, ' +\n     'to your postcode where we have it; your delivery option, its charge and lead times are ' +\n     'confirmed at checkout.'],\n    ['Measurements and fitting',\n     'Dimensions shown on the floor plan are those entered into the planner and should be ' +\n     'checked against the room before ordering. Appliance apertures, service positions, and ' +\n     'any structural work are the responsibility of the installer. Worktops are quoted from the ' +\n     'planned layout and are templated separately where the material requires it.'],\n    ['Images',\n     'The three-dimensional views in this report are illustrations generated from the plan. ' +\n     'Colours, finishes, handles and appliances are represented as closely as the medium allows ' +\n     'but should not be relied on for exact colour matching - order a sample where colour matters.'],\n    ['Contact',\n     'Questions about this plan can be raised with your Better Bedrooms contact, quoting ' +\n     'the plan reference on the cover of this document.']\n  ];\n\n  function rptText(doc, txt, x, y, { size = 10, bold = false, colour = RPT.ink, align = 'left', maxW = null, lh = 1.35 } = {}) {\n    doc.setFont('helvetica', bold ? 'bold' : 'normal');\n    doc.setFontSize(size);\n    doc.setTextColor(colour[0], colour[1], colour[2]);\n    const lines = maxW ? doc.splitTextToSize(String(txt), maxW) : [String(txt)];\n    doc.text(lines, x, y, { align });\n    return y + lines.length * size * 0.3528 * lh;   // pt \u2192 mm\n  }\n\n  // A was-price: the text with a line through it.\n  function rptStruck(doc, txt, x, y, opts = {}) {\n    const size = opts.size || 10, colour = opts.colour || RPT.mute, align = opts.align || 'left';\n    rptText(doc, txt, x, y, { ...opts, size, colour, align });\n    const w = doc.getTextWidth(String(txt));\n    const x0 = align === 'right' ? x - w : align === 'center' ? x - w / 2 : x;\n    doc.setDrawColor(colour[0], colour[1], colour[2]);\n    doc.setLineWidth(0.25);\n    doc.line(x0, y - size * 0.3528 * 0.32, x0 + w, y - size * 0.3528 * 0.32);\n  }\n\n  // \"Ends Saturday 25 October\" - when an offer runs out, for a printed page.\n  // The date only: the report is emailed and read days later, so \"N days\n  // left\" would be wrong by the time it is read (Arden, 2026-10-19).\n  function rptOfferEnds(endsAt) {\n    const t = Date.parse(endsAt || '');\n    if (!(t > Date.now())) return '';\n    return 'Ends ' + new Date(t).toLocaleDateString('en-GB', { weekday: 'long', day: 'numeric', month: 'long' });\n  }\n\n  // The running campaign's top bar banner (snippets/btk-sales-bar-fixed), so the\n  // report follows the same entry: move its end date and the next report says the\n  // new date, end the campaign and the banner goes (Arden, 2026-11-03). No days\n  // left, unlike the bar: a PDF is kept, and the count would go out of date.\n  function rptCampaignBanner() {\n    const el = document.querySelector('[data-btk-sales-banner][data-ends]');\n    if (!el) return null;\n    const ends = String(el.getAttribute('data-ends'));\n    const p = ends.split('-').map(Number);\n    if (p.length !== 3 || p.some(n => !n)) return null;\n    const today = new Intl.DateTimeFormat('en-CA', { timeZone: 'Europe/London', year: 'numeric', month: '2-digit', day: '2-digit' }).format(new Date());\n    if (ends < today) return null;\n    const when = new Date(Date.UTC(p[0], p[1] - 1, p[2]))\n      .toLocaleDateString('en-GB', { weekday: 'long', day: 'numeric', month: 'long', timeZone: 'UTC' }).replace(',', '');\n    const text = (el.querySelector('.btk-kp-utilitybar-fixed-text')?.textContent || '').trim();\n    if (!text) return null;\n    const hex = /#([0-9a-f]{6})/i.exec(getComputedStyle(el).getPropertyValue('--btk-banner-bg') || el.getAttribute('style') || '');\n    const rgb = hex ? [0, 2, 4].map(i => parseInt(hex[1].slice(i, i + 2), 16)) : [230, 0, 126];\n    return { line: `${text} - Order by ${when}`, rgb };\n  }\n  // The bar's look: black to the campaign's colour and back, as a picture because\n  // jsPDF has no simple gradient.\n  function rptCampaignStrip(doc, banner, x, y, w, h) {\n    const c = document.createElement('canvas');\n    c.width = 1400; c.height = 8;\n    const g2d = c.getContext('2d');\n    const grad = g2d.createLinearGradient(0, 0, c.width, 0);\n    const colour = `rgb(${banner.rgb.join(',')})`;\n    grad.addColorStop(0, '#000');\n    grad.addColorStop(0.3, colour);\n    grad.addColorStop(0.7, colour);\n    grad.addColorStop(1, '#000');\n    g2d.fillStyle = grad;\n    g2d.fillRect(0, 0, c.width, c.height);\n    doc.addImage(c.toDataURL('image/jpeg', 0.92), 'JPEG', x, y, w, h);\n    rptText(doc, banner.line, x + w / 2, y + h / 2 + 1.7, { size: 12, bold: true, colour: [255, 255, 255], align: 'center' });\n  }\n\n  // One offer as a big red panel across the page: its name large, what it\n  // means for this quote under it, and on the right when it ends and what it\n  // saves - for the schedule, after the total.\n  const RPT_OFFER_PANEL_H = 24;\n  function rptOfferPanel(doc, o, fmt, x, y, w) {\n    const white = [255, 255, 255], pale = [255, 214, 214];\n    doc.setFillColor(...RPT.red);\n    doc.roundedRect(x, y, w, RPT_OFFER_PANEL_H, 2.5, 2.5, 'F');\n    const right = x + w - 8;\n    // Right-hand side first, so the name knows how much room it has.\n    let rightW = 0;\n    if (o.savingGbp > 0.005) {\n      const save = `SAVE ${fmt.format(o.savingGbp)}`;\n      doc.setFont('helvetica', 'bold'); doc.setFontSize(13);\n      const sw = doc.getTextWidth(save) + 10;\n      doc.setFillColor(255, 255, 255);\n      doc.roundedRect(right - sw, y + 5, sw, 9, 1.8, 1.8, 'F');\n      rptText(doc, save, right - 5, y + 11.4, { size: 13, bold: true, colour: RPT.red, align: 'right' });\n      rightW = sw;\n    }\n    const ends = rptOfferEnds(o.endsAt);\n    if (ends) {\n      rptText(doc, ends, right, y + 19.5, { size: 10, bold: true, colour: white, align: 'right' });\n      doc.setFont('helvetica', 'bold'); doc.setFontSize(10);\n      rightW = Math.max(rightW, doc.getTextWidth(ends));\n    }\n    const nameW = w - 16 - rightW - 10;\n    rptText(doc, doc.splitTextToSize(String(o.title), nameW)[0], x + 8, y + 10.5, { size: 16, bold: true, colour: white });\n    const text = String(o.text || '').trim();\n    if (text) rptText(doc, doc.splitTextToSize(text, nameW)[0], x + 8, y + 18.5, { size: 10, colour: pale });\n  }\n\n  // The cover's Today's Price panel: the price large on red, the high street\n  // price struck through and the saving beside it.\n  function rptPriceBadge(doc, total, sum, fmt, x, y, w, h) {\n    const white = [255, 255, 255];\n    doc.setFillColor(...RPT.red);\n    doc.roundedRect(x, y, w, h, 2, 2, 'F');\n    rptText(doc, \"TODAY'S PRICE\", x + 6, y + 7, { size: 8, bold: true, colour: [255, 214, 214] });\n    rptText(doc, fmt.format(total || 0), x + 6, y + 17.5, { size: 22, bold: true, colour: white });\n    if (sum && sum.savingGbp > 0.005) {\n      rptStruck(doc, `Was ${fmt.format(sum.wasTotal)}`, x + w - 6, y + 8.5,\n                { size: 9, colour: [255, 214, 214], align: 'right' });\n      doc.setFillColor(255, 255, 255);\n      const save = `SAVE ${fmt.format(sum.savingGbp)}`;\n      doc.setFont('helvetica', 'bold'); doc.setFontSize(11);\n      const sw = doc.getTextWidth(save) + 8;\n      doc.roundedRect(x + w - 6 - sw, y + 11.5, sw, 8, 1.5, 1.5, 'F');\n      rptText(doc, save, x + w - 10, y + 17.2, { size: 11, bold: true, colour: RPT.red, align: 'right' });\n    }\n  }\n\n  // The Your Price page: the price and the saving large, the basket's Price\n  // Breakdown line by line on the left, its Current Offers on a red panel on\n  // the right - the same figures the planner basket shows.\n  function rptYourPricePage(doc, total, sum, fmt, top = 32) {\n    const L = RPT.M;\n    rptText(doc, \"Today's Price\", L, top + 6, { size: 12, bold: true, colour: RPT.mute });\n    rptText(doc, fmt.format(total || 0), L, top + 22, { size: 34, bold: true, colour: RPT.red });\n    let y = top + 32;\n    if (sum.savingGbp > 0.005) {\n      rptStruck(doc, `Was ${fmt.format(sum.wasTotal)}`, L, y, { size: 12, colour: RPT.mute });\n      const pct = sum.wasTotal > 0 ? Math.round(sum.savingGbp / sum.wasTotal * 100) : 0;\n      const save = `You save ${fmt.format(sum.savingGbp)}${pct >= 1 ? ` (${pct}%)` : ''}`;\n      doc.setFont('helvetica', 'bold'); doc.setFontSize(13);\n      const sw = doc.getTextWidth(save) + 10;\n      doc.setFillColor(...RPT.green);\n      doc.roundedRect(L, y + 4, sw, 10, 2, 2, 'F');\n      rptText(doc, save, L + 5, y + 11, { size: 13, bold: true, colour: [255, 255, 255] });\n      y += 22;\n    } else {\n      y += 4;\n    }\n\n    // Price breakdown, all inc VAT, adding up to Today's Price.\n    // Beside the Current Offers when there are any; across the page when\n    // there are none, rather than half a page with nothing beside it.\n    const offers = (sum.offers || []).filter(o => o && o.title);\n    const colW = offers.length ? 150 : RPT.W - RPT.M * 2, amountX = L + colW;\n    rptText(doc, 'Price breakdown', L, y + 4, { size: 11, bold: true });\n    y += 10;\n    const row = (label, amount, { colour = RPT.ink, bold = false, struck = false, note = '' } = {}) => {\n      rptText(doc, label, L, y, { size: 10, bold, colour: RPT.ink });\n      if (note) rptText(doc, note, L + doc.getTextWidth(label) + 3, y, { size: 8, colour: RPT.mute });\n      if (struck) rptStruck(doc, amount, amountX, y, { size: 10, colour: RPT.mute, align: 'right' });\n      else rptText(doc, amount, amountX, y, { size: 10, bold, colour, align: 'right' });\n      doc.setDrawColor(...RPT.rule); doc.setLineWidth(0.2);\n      doc.line(L, y + 2.4, amountX, y + 2.4);\n      y += 7.2;\n    };\n    if (sum.highStreetGbp > sum.onlineGbp + 0.005) row('High street price', fmt.format(sum.highStreetGbp), { struck: true });\n    row('Online price', fmt.format(sum.onlineGbp), { colour: RPT.red, bold: true });\n    (sum.lineExtras || []).forEach(e => row(e.title, '-' + fmt.format(e.amountGbp), { colour: RPT.green, bold: true, note: 'extra discount' }));\n    (sum.discounts || []).forEach(d => row(d.title, '-' + fmt.format(d.amountGbp), { colour: RPT.green, bold: true, note: d.staff ? 'just for you' : 'discount' }));\n    if (sum.upgradesGbp > 0.005) row('Upgrades', fmt.format(sum.upgradesGbp));\n    if (sum.delivery) row(sum.delivery.name || 'Delivery', sum.delivery.priceGbp > 0.005 ? fmt.format(sum.delivery.priceGbp) : 'FREE',\n                          { colour: sum.delivery.priceGbp > 0.005 ? RPT.ink : RPT.green, bold: !(sum.delivery.priceGbp > 0.005) });\n    y += 1;\n    doc.setFillColor(...RPT.red);\n    doc.rect(L, y - 5, colW, 10, 'F');\n    rptText(doc, \"Today's Price (inc. VAT)\", L + 4, y + 1.6, { size: 11, bold: true, colour: [255, 255, 255] });\n    rptText(doc, fmt.format(total || 0), amountX - 4, y + 1.6, { size: 11, bold: true, colour: [255, 255, 255], align: 'right' });\n\n    // Current offers, on red like the basket's.\n    if (!offers.length) return;\n    const ox = L + colW + 14, ow = RPT.W - RPT.M - ox;\n    let oy = top;\n    const panelH = Math.min(RPT.H - 20 - oy, 18 + offers.length * 27);\n    doc.setFillColor(...RPT.red);\n    doc.roundedRect(ox, oy, ow, panelH, 2, 2, 'F');\n    rptText(doc, 'Current Offers', ox + 6, oy + 10, { size: 14, bold: true, colour: [255, 255, 255] });\n    oy += 15;\n    for (const o of offers) {\n      if (oy + 24 > top + panelH) break;\n      doc.setFillColor(255, 255, 255);\n      doc.roundedRect(ox + 5, oy, ow - 10, 23, 1.5, 1.5, 'F');\n      rptText(doc, o.title, ox + 9, oy + 6.5, { size: 10.5, bold: true, maxW: ow - 18 });\n      const ends = rptOfferEnds(o.endsAt);\n      if (ends) rptText(doc, ends, ox + 9, oy + 12, { size: 8.5, bold: true, colour: RPT.red });\n      const text = o.savingGbp > 0.005 ? `${o.text ? o.text.replace(/\\.$/, '') + ', saving ' : 'Saving '}${fmt.format(o.savingGbp)}.` : (o.text || '');\n      if (text) rptText(doc, text, ox + 9, oy + (ends ? 17.5 : 12), { size: 8.5, maxW: ow - 18 });\n      oy += 27;\n    }\n  }\n\n  // The bar every page carries, so the document reads as one thing rather\n  // than a stack of screenshots. It names the SECTION and nothing else - who\n  // the plan is for and what it is called belong to the footer, and saying\n  // either twice on one page just crowds it.\n  //\n  // Drawn like the planner's own header (Arden, 2026-10-06): the logo on red,\n  // the red ending in a chevron that points into a black bar, the title just\n  // past the point. `right` is optional grey text at the far end (the\n  // cover's date).\n  const RPT_HEADER_H = 20;\n  function rptHeaderBar(doc, title, logo, right) {\n    const H = RPT_HEADER_H, CHEVRON = 6, logoH = 9;\n    // Capped so a wide logo can't push the title off the bar.\n    const logoW = logo ? Math.min(60, logoH * (logo.w / logo.h)) : 0;\n    const redEnd = RPT.M + (logo ? logoW : 36) + 10;\n    doc.setFillColor(...RPT.black);\n    doc.rect(0, 0, RPT.W, H, 'F');\n    doc.setFillColor(...RPT.red);\n    doc.lines([[redEnd, 0], [CHEVRON, H / 2], [-CHEVRON, H / 2], [-redEnd, 0]], 0, 0, [1, 1], 'F', true);\n    if (logo) doc.addImage(logo.url, 'PNG', RPT.M, (H - logoH) / 2, logoW, logoH);\n    else rptText(doc, 'BETTER BEDROOMS', RPT.M, 12.5, { size: 11, bold: true, colour: [255, 255, 255] });\n    rptText(doc, title, redEnd + CHEVRON + 8, 13, { size: 13, bold: true, colour: [255, 255, 255] });\n    if (right) rptText(doc, right, RPT.W - RPT.M, 13, { size: 11, colour: [190, 190, 190], align: 'right' });\n  }\n\n  // Fit an image inside a box without distorting it (CSS `contain`).\n  // `fmt` defaults to PNG so the floor-plan overlay - which needs its\n  // transparency to sit over the vector walls - is unaffected.\n  function rptFitImage(doc, img, natW, natH, bx, by, bw, bh, fmt) {\n    const scale = Math.min(bw / natW, bh / natH);\n    const w = natW * scale, h = natH * scale;\n    doc.addImage(img, fmt || 'PNG', bx + (bw - w) / 2, by + (bh - h) / 2, w, h);\n  }\n\n  // The site logo is a single-colour black SVG, so the white version for the\n  // red header is made by drawing it and keeping only its silhouette.\n  // Falls back to the wordmark if the image can't be read (a CORS-tainted\n  // canvas throws on toDataURL rather than returning anything usable).\n  async function rptWhiteLogo() {\n    try {\n      const src = document.querySelector('.header__logo img, .header__logo-image, .logo img');\n      const url = src && (src.currentSrc || src.src);\n      if (!url) return null;\n      const img = new Image();\n      img.crossOrigin = 'anonymous';\n      const loaded = new Promise((res, rej) => { img.onload = res; img.onerror = rej; });\n      img.src = url;\n      await loaded;\n      const w = 1200;\n      const h = Math.max(1, Math.round(w * (img.naturalHeight || 1) / (img.naturalWidth || 1)));\n      const cv = document.createElement('canvas');\n      cv.width = w; cv.height = h;\n      const ctx = cv.getContext('2d');\n      ctx.drawImage(img, 0, 0, w, h);\n      ctx.globalCompositeOperation = 'source-in';\n      ctx.fillStyle = '#ffffff';\n      ctx.fillRect(0, 0, w, h);\n      return { url: cv.toDataURL('image/png'), w, h };\n    } catch (e) {\n      console.warn('[BTK Kitchen Planner] Logo unavailable for the report', e);\n      return null;\n    }\n  }\n\n  // Crop the flat border off a capture. Both the 3D snapshots and the plan\n  // raster frame their subject with a lot of empty room, which is why they\n  // landed small on the page - the picture was mostly background. The corner\n  // pixel is taken as the background colour and everything matching it is\n  // trimmed away, so what is left is the drawing itself.\n  // The Lifestyle photo staff kept for the plan (planner-api, kind\n  // 'lifestyle-photo'), as { url: dataURL, w, h, fmt }, or null. Never fails\n  // the report: no photo, no page.\n  const RPT_LIFESTYLE_NOTE = 'Illustrative photograph of your planned bedroom. Lighting, styling, accessories and furniture are for illustration only and are not included.';\n  async function rptLifestylePhoto() {\n    try {\n      const api = window.BTKBasketAPI;\n      if (!api || !api.lifestylePhotoKept) return null;\n      const signedIn = (api.isStaffMode && api.isStaffMode()) || (api.isLoggedIn && api.isLoggedIn());\n      if (!signedIn) return null;\n      const basketId = lastQuoteBasketId || (api.getActivePlannerBasketId && await api.getActivePlannerBasketId());\n      if (!basketId) return null;\n      const blob = await api.lifestylePhotoKept(basketId);\n      if (!blob || !/^image\\/(jpeg|png)$/.test(blob.type)) return null;\n      const url = await new Promise((res, rej) => {\n        const fr = new FileReader();\n        fr.onload = () => res(fr.result);\n        fr.onerror = rej;\n        fr.readAsDataURL(blob);\n      });\n      const dims = await new Promise((res) => {\n        const im = new Image();\n        im.onload = () => res({ w: im.naturalWidth, h: im.naturalHeight });\n        im.onerror = () => res(null);\n        im.src = url;\n      });\n      return dims ? { url, ...dims, fmt: blob.type === 'image/png' ? 'PNG' : 'JPEG' } : null;\n    } catch (e) {\n      return null;\n    }\n  }\n  function rptTrim(dataUrl, padPx = 12) {\n    return new Promise(resolve => {\n      const img = new Image();\n      img.onerror = () => resolve(null);\n      img.onload = () => {\n        try {\n          const w = img.naturalWidth, h = img.naturalHeight;\n          const cv = document.createElement('canvas');\n          cv.width = w; cv.height = h;\n          const ctx = cv.getContext('2d', { willReadFrequently: true });\n          ctx.drawImage(img, 0, 0);\n          const d = ctx.getImageData(0, 0, w, h).data;\n          const at = (x, y) => (y * w + x) * 4;\n          const bg = [d[0], d[1], d[2], d[3]];\n          const TOL = 10;\n          const same = (i) => Math.abs(d[i] - bg[0]) <= TOL && Math.abs(d[i + 1] - bg[1]) <= TOL &&\n                              Math.abs(d[i + 2] - bg[2]) <= TOL && Math.abs(d[i + 3] - bg[3]) <= TOL;\n          let minX = w, minY = h, maxX = -1, maxY = -1;\n          // Every 2nd pixel - a border this size never hides in one column.\n          for (let y = 0; y < h; y += 2) {\n            for (let x = 0; x < w; x += 2) {\n              if (same(at(x, y))) continue;\n              if (x < minX) minX = x;\n              if (x > maxX) maxX = x;\n              if (y < minY) minY = y;\n              if (y > maxY) maxY = y;\n            }\n          }\n          if (maxX < 0) { resolve({ url: dataUrl, w, h, fmt: 'PNG' }); return; }\n          minX = Math.max(0, minX - padPx); minY = Math.max(0, minY - padPx);\n          maxX = Math.min(w - 1, maxX + padPx); maxY = Math.min(h - 1, maxY + padPx);\n          const cw = maxX - minX + 1, ch = maxY - minY + 1;\n          const out = document.createElement('canvas');\n          out.width = cw; out.height = ch;\n          const octx = out.getContext('2d');\n          // JPEG has no alpha, so anything transparent would come out BLACK.\n          octx.fillStyle = '#ffffff';\n          octx.fillRect(0, 0, cw, ch);\n          octx.drawImage(cv, minX, minY, cw, ch, 0, 0, cw, ch);\n          // The 3D views are photographic - JPEG is worth an order of\n          // magnitude here and the difference is invisible on a render.\n          resolve({ url: out.toDataURL('image/jpeg', 0.82), w: cw, h: ch, fmt: 'JPEG' });\n        } catch (e) { resolve(null); }\n      };\n      img.src = dataUrl;\n    });\n  }\n\n  // ---- The floor plan -----------------------------------------------------\n  //\n  // Half captured, half drawn, and each half does what it is good at.\n  //\n  // The DRAWING - walls as a continuous perimeter, corner posts, L-shapes,\n  // radius units, appliance faces, every unit type's own footprint - comes\n  // from the 2D renderer itself, captured as an image. Redrawing all of that a\n  // second time in PDF primitives means re-deriving geometry that already\n  // exists, and every unit family would have to be kept in step by hand.\n  //\n  // The DIMENSIONS are drawn as vector on top. They are the one thing a\n  // capture cannot do: they live outside the SVG's own box and rasterising\n  // clips them. They come from computeDimensionTiers(), the same source the\n  // on-screen dimensions come from, so the two always measure alike.\n  //\n  // The two halves line up because both use one mm-to-page mapping, derived\n  // from the grid's own pixels-per-mm rather than from anything measured off\n  // the finished image.\n  const PLAN_DIM = [102, 102, 102];\n\n  // The floor plan, drawn by the PLANNER'S OWN 2D renderer into a container we\n  // build for the purpose, and photographed.\n  //\n  // renderGrid() and renderCabinets() take a container - they are not bound to\n  // the live planner - so every unit type comes out right without the report\n  // knowing anything about any of them. Angled, radius, corner, splay, end\n  // panels, fillers, stacks: all of it, because this IS the 2D plan.\n  //\n  // \u26A0 NOT THE RASTERISE THAT FAILED BEFORE. That one photographed the LIVE\n  // screen and inherited its view mode, the basket embed, the customer's pan\n  // and zoom and the interactive chrome - four separate faults in a day, every\n  // one of them from the screen rather than from rasterising. This container is\n  // built here, sized here, never transformed, never shown, and thrown away.\n  //\n  // Returns { url, mm } where mm maps room millimetres to pixels IN THE IMAGE,\n  // or null. The walls and every dimension are still drawn as vector over it.\n  // \u26A0 LAY IT OUT AT SCREEN SIZE, NOT AT PRINT SIZE.\n  //\n  // The 2D renderer scales its badges and door lines by\n  //     labelScale = clamp(pxPerMm / 0.16, 0.5, 1)\n  // which is CAPPED AT 1. Lay the room out 2400px wide and the room grows\n  // while every badge stays 22px, so on an A4 page they come out as specks\n  // (Arden, 2026-09-27: \"too small\"). This is the width the planner itself\n  // works at, so everything is in the proportion it draws.\n  const RPT_PLAN_CSS_PX = 950;          // room long edge, in CSS pixels\n  // Resolution comes from html2canvas instead: it multiplies DEVICE pixels\n  // and leaves the CSS layout alone, so the picture is sharp without\n  // changing a single proportion.\n  const RPT_PLAN_DENSITY = 3;\n  // opts.roomOnly: the room as set up, with no units - the walls' doors and\n  // windows plus every room item (boilers, sockets, steps, radiators...),\n  // which the kitchen floor plan leaves out. For the measurements check page.\n  async function rptRenderPlanImage(opts = {}) {\n    const roomOnly = !!(opts && opts.roomOnly);\n    const host = document.createElement('div');\n    // Off screen rather than hidden: display:none has no layout, and the\n    // renderer needs real boxes to measure.\n    host.setAttribute('data-btk-kp-report-plan', '');\n    const bb = getBoundingBox(baseRoom);\n    const roomW = Math.max(1, bb.widthMm || 1);\n    const roomH = Math.max(1, bb.heightMm || 1);\n    const scale = RPT_PLAN_CSS_PX / Math.max(roomW, roomH);\n    host.style.cssText = 'position:fixed;left:-30000px;top:0;pointer-events:none;'\n      // TRANSPARENT, deliberately. A white host paints a solid rectangle into\n      // the capture, which then hides the vector floor and walls the PDF has\n      // already drawn underneath it. html2canvas is called with\n      // backgroundColor:null so nothing puts one back.\n      + 'background:transparent;overflow:hidden;z-index:-1;'\n      + 'width:' + Math.round(roomW * scale * 1.25) + 'px;'\n      + 'height:' + Math.round(roomH * scale * 1.25) + 'px;';\n    // \u26A0 INSIDE THE PLANNER ROOT, not on the body. Hung off the body it sat\n    // outside every rule and custom property scoped to the planner, and came\n    // out in the wrong colours (Arden, 2026-09-27: \"diag wall is blue\").\n    // position:fixed keeps it out of the planner's own layout regardless.\n    (root || document.body).appendChild(host);\n\n    const handles = [];\n    try {\n      const grid = renderGrid(host, room, {\n        wallOpenings:   roomConfig.wallOpenings   || [],\n        perimeterItems: roomConfig.perimeterItems || [],\n        baseRoom,\n        insetFor: (op) => openingInsetMm(op)\n      });\n      handles.push(grid);\n      // No callbacks: nothing here is ever clicked, and the report has no\n      // business wiring the live planner's handlers to a throwaway element.\n      if (roomOnly) {\n        // The room items, by the planner's own renderer, as Room Setup draws\n        // them - pillars and internal walls included, as the Floor plan page\n        // draws them. The grid only draws the ones touching a wall, and never\n        // their sizes; this layer draws the free-standing ones and the sizes\n        // (a wall-touching one keeps only its figures - its body is the grid's).\n        // Sales line 103: free-standing internal walls were missing.\n        handles.push(renderFeatures(grid.el,\n          (roomConfig.perimeterItems || []).filter(Boolean),\n          grid.pxPerMm, room));\n      } else {\n        const cabs = renderCabinets(grid.el, cabinets, grid.pxPerMm, Catalogue, {\n          endPanelNumbers:    endPanelLayout?.cabSideToNumber || {},\n          endFeatureNumbers:  endPanelLayout?.cabSideToFeatureNumber || {},\n          endPanelFaces:      endPanelLayout?.cabSideToFace || {}\n        });\n        handles.push(cabs);\n        if (window.BTK_PLANNER_V11) {\n          // v1.1: the printed plan shows what the live plan shows - worktops,\n          // waterfall sides, hobs and other worktop items, splashbacks, furniture -\n          // by the planner's own renderers. Nothing here is wired: never clicked.\n          const rptSlabs = buildWorktops();\n          stampWaterfalls(rptSlabs, cabinets);\n          handles.push(renderWorktops(grid.el, rptSlabs, grid.pxPerMm, {\n            waterfallBands: rptSlabs.flatMap(s => waterfallBands(s, worktopThicknessMm()))\n          }));\n          handles.push(renderWorktopItems(grid.el, worktopItems, grid.pxPerMm));\n          const rptSplash = renderSplashbacks(grid.el, computeSplashbackStrips({\n            cabinets,\n            worktopItems,\n            worktopSlabs: rptSlabs,\n            room,\n            perimeterItems: roomConfig.perimeterItems,\n            wallOpenings: roomConfig.wallOpenings,\n            settings: roomConfig.splashbacks\n          }).strips, grid.pxPerMm);\n          if (rptSplash) handles.push(rptSplash);\n          if (furnitureItems.length) {\n            const furnLayer = document.createElement('div');\n            furnLayer.className = 'btk-kp-furniture-layer';\n            const furnUnderLayer = document.createElement('div');\n            furnUnderLayer.className = 'btk-kp-furniture-layer btk-kp-furniture-layer--under';\n            const furnBlockers = furnitureUnitBlockers();\n            furnitureItems.forEach((item) => {\n              const w = item.widthMm || 500, d = item.depthMm || 500;\n              const el = document.createElement('div');\n              el.className = 'btk-kp-furniture-2d';\n              el.style.width  = `${w * grid.pxPerMm}px`;\n              el.style.height = `${d * grid.pxPerMm}px`;\n              el.style.left   = `${(item.x - w / 2) * grid.pxPerMm}px`;\n              el.style.top    = `${(item.y - d / 2) * grid.pxPerMm}px`;\n              if (item.rotationDeg) el.style.transform = `rotate(${item.rotationDeg}deg)`;\n              const furnCat = (Catalogue.getFurniture?.() || []).find(f => f.id === item.furnitureId)?.category;\n              const drawn = appendFurnitureDrawing(el, item, furnCat, w, d);\n              if (drawn) {\n                el.style.background = 'none';\n                el.style.border = 'none';\n              } else {\n                const lab = document.createElement('div');\n                lab.className = 'btk-kp-furniture-2d-label';\n                lab.textContent = item.name || '';\n                el.appendChild(lab);\n              }\n              (drawn && furniturePlacement(item) === 'floor' && !furnitureHitsUnit(item, item.x, item.y, furnBlockers) ? furnUnderLayer : furnLayer).appendChild(el);\n            });\n            grid.el.appendChild(furnUnderLayer);\n            grid.el.appendChild(furnLayer);\n          }\n          // Room items as the Check your measurements page draws them, but not\n          // the sloped and vaulted ceilings: big shapes that would lie over the units.\n          handles.push(renderFeatures(grid.el,\n            (roomConfig.perimeterItems || []).filter(it => it\n              && it.type !== 'sloped-ceiling' && it.type !== 'vaulted-ceiling'),\n            grid.pxPerMm, room));\n        }\n      }\n      // (Both pages: the room page draws pillar sizes as SVG too.)\n      // Sized by style alone, html2canvas takes these SVGs as zero size.\n      host.querySelectorAll('.btk-kp-feature svg').forEach((svg) => {\n        const cs = window.getComputedStyle(svg);\n        svg.setAttribute('width', String(parseFloat(cs.width) || 0));\n        svg.setAttribute('height', String(parseFloat(cs.height) || 0));\n      });\n      // The electrical symbol stands outside its plate, where html2canvas\n      // loses inline SVG. As an image it comes through.\n      host.querySelectorAll('.btk-kp-feature-elec').forEach((svg) => {\n        // A margin for the line that runs past the drawing's edge, and a\n        // large natural size so rounding cannot change its proportions.\n        const [, , vw, vh] = svg.getAttribute('viewBox').split(' ').map(Number);\n        const k = parseFloat(svg.style.width) / vw;\n        const pad = 10;\n        svg.setAttribute('viewBox', `${-pad} ${-pad} ${vw + pad * 2} ${vh + pad}`);\n        svg.setAttribute('width', String((vw + pad * 2) * 10));\n        svg.setAttribute('height', String((vh + pad) * 10));\n        const img = new Image();\n        img.className = 'btk-kp-feature-elec';\n        img.style.maxWidth = 'none';   // wider than the plate it stands on\n        img.style.width = `${(vw + pad * 2) * k}px`;\n        img.style.height = `${(vh + pad) * k}px`;\n        img.src = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(new XMLSerializer().serializeToString(svg));\n        svg.replaceWith(img);\n      });\n      // html2canvas serialises inline SVG without the stylesheet, so each\n      // polygon's look is copied onto it.\n      host.querySelectorAll('.btk-kp-worktop-layer polygon, .btk-kp-feature svg *, .btk-kp-grid-svg-overlay--pillars *').forEach((el) => {\n        if (!(el instanceof SVGGeometryElement)) return;\n        const cs = window.getComputedStyle(el);\n        el.setAttribute('fill', cs.fill);\n        el.setAttribute('stroke', cs.stroke);\n        el.setAttribute('stroke-width', String(parseFloat(cs.strokeWidth) || 1));\n      });\n\n      // Doors and windows, by the planner's own renderer, as the live plan\n      // draws them (rerender: renderOpenings after the units). They used to\n      // come with the walls overlay, which the capture hides (below), so the\n      // PDF showed each opening as a bare gap (Arden, 2026-10-13). Each sits\n      // in the wall band, 100mm outward of the wall line - the same band the\n      // PDF's vector walls are drawn in - so they land in their gaps. Placed\n      // openings only: a floating one is mid-placement, not part of the room.\n      handles.push(renderOpenings(grid.el, {\n        ...roomConfig,\n        wallOpenings: (roomConfig.wallOpenings || []).filter(op => op && !op.floating)\n      }, room, grid.pxPerMm, { insetFor: (op) => openingInsetMm(op) }));\n\n      // The sink and appliance PROMPTS are working controls - a green \"+\" asking\n      // to be clicked - and have no place on a printed plan. Hidden on OUR\n      // container only, so the live view is untouched.\n      const prompts = host.querySelectorAll(\n        '.btk-kp-cabinet-sink-pose, .btk-kp-cabinet-number--over-sink-empty,'\n        + ' .btk-kp-appliance-badge, .btk-kp-cabinet-number--appliance,'\n        + ' .btk-kp-viewport-overlay, .btk-kp-dim-layer');\n      prompts.forEach((el) => { el.style.display = 'none'; });\n\n      // \u26A0 THE CAPTURE MUST CONTRIBUTE UNITS ONLY, AND BE TRANSPARENT.\n      //\n      // rptDrawFloorPlan draws the floor and then the walls as VECTORS, and\n      // lays this image over them - so anything the renderer paints underneath\n      // the units arrives as an opaque rectangle on top of both and hides them.\n      // That is why the walls vanished and why the image's own wall line sat a\n      // step away from the vector floor beneath it: the same things were being\n      // drawn twice, from two different scales (Arden, 2026-09-28: \"the walls\n      // are not showing and there's a small step in the wall line to the grid\n      // below\"). The layering comment further down says floor -> walls ->\n      // units; this is what actually makes that true.\n      //\n      // .btk-kp-grid carries background-color:#fff AND the graph-paper\n      // background-image, so `background:none` clears both in one go.\n      grid.el.style.background = 'none';\n      // The walls overlay, and with it .btk-kp-grid-outside-mask, whose opaque\n      // #f5f5f5 fill covers everything outside a non-rectangular room.\n      // NOT the pillar overlay: it is a wall-shaped clone clipped to the\n      // structural pillars, and nothing in the PDF draws those, so hiding it\n      // would lose them from the plan altogether.\n      host.querySelectorAll(\n        '.btk-kp-grid-svg-overlay:not(.btk-kp-grid-svg-overlay--pillars)'\n      ).forEach((el) => { el.style.display = 'none'; });\n\n      // \u26A0 CORNER UNITS: BOTH THEIR SHAPE AND THEIR OUTLINE COME FROM CSS THAT\n      // html2canvas CANNOT DRAW.\n      //\n      // The L-shape, diagonal, splay and radius bodies take their footprint\n      // from a clip-path, which html2canvas ignores, and their carcase stroke\n      // from an INSET box-shadow, which it paints as a solid fill. Together\n      // those turned every corner unit into a solid dark blue square - #1565C0\n      // is the wall-unit stroke (Arden, 2026-09-28: \"why does the L shape and\n      // diag corner wall get a dark blue full square?\").\n      //\n      // Inline SVG it DOES serialise faithfully, so each body gets a polygon of\n      // exactly the same points, fill and stroke, and its own background and\n      // shadow are switched off. The points are already in element pixels, so\n      // nothing is recomputed here and the shapes cannot drift from the\n      // planner's - which is the whole reason the report renders through the\n      // planner's own renderer rather than reimplementing the geometry.\n      host.querySelectorAll('[style*=\"clip-path\"]').forEach((el) => {\n        const m = /^polygon\\(([^)]*)\\)$/.exec(String(el.style.clipPath || '').trim());\n        if (!m) return;                       // circle()/ellipse() - leave alone\n        const pts = m[1].split(',')\n          .map((p) => p.trim().split(/\\s+/).map(parseFloat))\n          .filter((xy) => xy.length === 2 && xy.every((n) => isFinite(n)));\n        if (pts.length < 3) return;\n        const cs = (window.getComputedStyle && window.getComputedStyle(el)) || {};\n        const w = el.offsetWidth, h = el.offsetHeight;\n        if (!(w > 0 && h > 0)) return;\n        // The carcase stroke is read OFF the inset box-shadow rather than\n        // hard-coding the category colours a second time - they live in\n        // btk-kitchen-planner-base.css and would drift.\n        const sh = String(cs.boxShadow || '');\n        const colour = (/rgba?\\([^)]*\\)/.exec(sh) || [])[0] || '';\n        const spread = (sh.match(/-?[\\d.]+px/g) || [])[3];\n        const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');\n        svg.setAttribute('width',  String(w));\n        svg.setAttribute('height', String(h));\n        svg.setAttribute('viewBox', '0 0 ' + w + ' ' + h);\n        svg.setAttribute('data-btk-kp-report-shape', '');\n        svg.style.cssText = 'position:absolute;left:0;top:0;overflow:visible;pointer-events:none;';\n        const poly = document.createElementNS('http://www.w3.org/2000/svg', 'polygon');\n        poly.setAttribute('points', pts.map((p) => p[0] + ',' + p[1]).join(' '));\n        poly.setAttribute('fill', cs.backgroundColor || 'none');\n        if (colour) {\n          poly.setAttribute('stroke', colour);\n          poly.setAttribute('stroke-width', String(Math.max(1, parseFloat(spread) || 1)));\n        }\n        svg.appendChild(poly);\n        // Off, or the unclipped box paints its square behind the polygon.\n        el.style.background = 'transparent';\n        el.style.boxShadow  = 'none';\n        // FIRST child, so the door strokes and badges still sit on top.\n        el.insertBefore(svg, el.firstChild);\n      });\n\n      // \u26A0 NO PATTERN ON ANYTHING UNDER A PIXEL INSIDE ITS BORDER.\n      //\n      // html2canvas tiles a background-image through createPattern, which\n      // THROWS on a zero-size tile - and one throw loses the whole capture,\n      // so the PDF came out with walls and dimensions and not one unit. A long\n      // thin room is laid out small (8022 x 3215 gave 0.069 px/mm), so a 40mm\n      // island-back batten is 2.8px with a 1px border each side and under a\n      // pixel of striping between (Arden, 2026-10-13: \"dropped the kitchen\n      // unit images in the plan view\"). At that size the stripes cannot show\n      // anyway; the fill colour and border stay.\n      // Measured two ways and the smaller taken: inside a rotated unit the\n      // screen box is the rotated outline, which can be larger than the\n      // element itself, while the computed size is the element's own.\n      host.querySelectorAll('*').forEach((el) => {\n        const cs = window.getComputedStyle(el);\n        if (!cs.backgroundImage || cs.backgroundImage === 'none') return;\n        const bx = (parseFloat(cs.borderLeftWidth) || 0) + (parseFloat(cs.borderRightWidth)  || 0);\n        const by = (parseFloat(cs.borderTopWidth)  || 0) + (parseFloat(cs.borderBottomWidth) || 0);\n        const px = (parseFloat(cs.paddingLeft) || 0) + (parseFloat(cs.paddingRight)  || 0);\n        const py = (parseFloat(cs.paddingTop)  || 0) + (parseFloat(cs.paddingBottom) || 0);\n        const border = cs.boxSizing === 'border-box';\n        const ownW = (parseFloat(cs.width)  || 0) - (border ? bx : -px);\n        const ownH = (parseFloat(cs.height) || 0) - (border ? by : -py);\n        const r = el.getBoundingClientRect();\n        const w = Math.min(ownW, r.width  - bx);\n        const h = Math.min(ownH, r.height - by);\n        if (w < 1 || h < 1) el.style.backgroundImage = 'none';\n      });\n\n      // Our own copy (html2canvas@1.4.1 bundled), never a public CDN.\n      const mod = await import('./btk-vendor-html2canvas.js?v=1');\n      const html2canvas = mod.default || mod;\n      const canvas = await html2canvas(host, {\n        backgroundColor: null, scale: RPT_PLAN_DENSITY, useCORS: true, logging: false\n      });\n\n      // Room (0,0) is the grid element's own origin. No transform is applied\n      // here, so this is exact - it is the mapping that went wrong when the\n      // live view carried a pan and a zoom.\n      // The rects are CSS pixels; the canvas is that times the density. The\n      // mapping is reported in CSS pixels throughout, so the extra density\n      // never leaks into the geometry.\n      const g = grid.el.getBoundingClientRect();\n      const h = host.getBoundingClientRect();\n      return {\n        url: canvas.toDataURL('image/png'),\n        w: canvas.width / RPT_PLAN_DENSITY,\n        h: canvas.height / RPT_PLAN_DENSITY,\n        ppm: grid.pxPerMm,\n        ox: g.left - h.left,\n        oy: g.top - h.top\n      };\n    } catch (e) {\n      console.warn('[BTK Kitchen Planner] offscreen plan render failed', e);\n      return null;\n    } finally {\n      for (const x of handles) { try { x && x.destroy && x.destroy(); } catch (e) {} }\n      try { host.remove(); } catch (e) {}\n    }\n  }\n\n  // The boxes the floor plan needs, worked out from the MODEL alone - no DOM,\n  // no layout, no view mode. Returns null when there is nothing to draw.\n  //\n  // \u26A0 STILL LIVE. This was deleted by accident on 2026-09-27 along with the\n  // capture code either side of it, because the delete was anchored on a\n  // RANGE (rptPlanMapping .. the new drawing) rather than on this function's\n  // own text - and rptDrawFloorPlan calls it on its first line, so the whole\n  // report died with 'rptPlanBoxes is not defined'.\n  // Lay dimension labels out along ONE tier.\n  //\n  // Pure: millimetres in, positions out, so it can be tested without a PDF.\n  // A label sits on its own span's centre when the text fits there. When it\n  // cannot - an end panel is 22mm, a filler little more - it drops to the first\n  // row with clear space, and if every row is taken it is pushed along the wall\n  // past whatever is already there. `moved` tells the caller it has left its\n  // own centre and needs a leader drawn back to the span it measures.\n  function rptPackDimLabels(items, opts) {\n    const rows = (opts && opts.rows) || [0];\n    const pad  = (opts && opts.padMm) || 0;\n    const end  = rows.map(() => -Infinity);\n    const out  = [];\n    // In order ALONG THE WALL, or the packing compares against whatever\n    // happened to come first in the segment list rather than the neighbour.\n    for (const it of items.slice().sort((p, q) => (p.a - q.a) || (p.b - q.b))) {\n      const span   = it.b - it.a;\n      const centre = it.a + span / 2;\n      const half   = (it.widthMm || 0) / 2;\n      let row = -1;\n      let x   = centre;\n      if (it.widthMm <= span && centre - half >= end[0]) {\n        row = 0;                                  // fits between its own ticks\n      } else {\n        for (let r = 0; r < rows.length; r++) {\n          if (centre - half >= end[r] + pad) { row = r; break; }\n        }\n        if (row < 0) {\n          row = 0;                                // every row busy here:\n          for (let r = 1; r < rows.length; r++) if (end[r] < end[row]) row = r;\n          x = end[row] + pad + half;              // take the emptiest, slide on\n        }\n      }\n      end[row] = x + half;\n      out.push({ ...it, x, centre, row, off: rows[row],\n                 moved: row > 0 || Math.abs(x - centre) > 0.5 });\n    }\n    return out;\n  }\n\n  function rptPlanBoxes(opts = {}) {\n    const roomOnly = !!(opts && opts.roomOnly);\n    const walls = getWalls(room);\n    if (!walls.length) return null;\n\n    // Worked out in MILLIMETRES first, then mapped onto the page once.\n    //\n    // Tier spacing is set from the ROOM's size rather than taken from the\n    // screen's pixel constants. Those are 15 and 30 - fine at screen zoom, but\n    // read as millimetres they put four tiers within 100mm of the wall.\n    const rb   = getBoundingBox(baseRoom);\n    const SPAN = Math.hypot(rb.widthMm || 0, rb.heightMm || 0) || 5000;\n    const STEP = Math.max(200, SPAN * 0.040);\n    const WT   = 100;                     // wall band thickness, mm\n    const tiers = computeDimensionTiers({\n      walls,\n      labels:         deriveWallLabels(walls),\n      pxPerMm:        1,\n      wallOpenings:   roomConfig.wallOpenings   || [],\n      perimeterItems: roomConfig.perimeterItems || [],\n      cabinets:       roomOnly ? [] : cabinets,\n      hideUnits:      roomOnly,\n      off1:           WT + STEP * 0.55,\n      stepPx:         STEP\n    });\n\n    // ---- the box the IMAGE covers: room, wall band, and anything placed\n    //      outside them (an island's dims, a peninsula overhang) ------------\n    let iMinX = Infinity, iMinY = Infinity, iMaxX = -Infinity, iMaxY = -Infinity;\n    const growImg = (x, y) => {\n      if (x < iMinX) iMinX = x;\n      if (x > iMaxX) iMaxX = x;\n      if (y < iMinY) iMinY = y;\n      if (y > iMaxY) iMaxY = y;\n    };\n    for (const w of walls) {\n      const ux = (w.to.x - w.from.x) / (w.lengthMm || 1);\n      const uy = (w.to.y - w.from.y) / (w.lengthMm || 1);\n      for (const p of [w.from, w.to]) {\n        growImg(p.x, p.y);\n        growImg(p.x + uy * WT, p.y - ux * WT);\n      }\n    }\n    for (const c of (roomOnly ? [] : cabinets)) {\n      const bb = getEffectiveAABB(c, c.x, c.y);\n      if (!bb) continue;\n      growImg(bb.x, bb.y);\n      growImg(bb.x + bb.widthMm, bb.y + bb.depthMm);\n    }\n    if (!(iMaxX > iMinX) || !(iMaxY > iMinY)) return null;\n    const imgBox = { x: iMinX - 20, y: iMinY - 20,\n                     w: (iMaxX - iMinX) + 40, h: (iMaxY - iMinY) + 40 };\n\n    // ---- the box the PAGE has to hold: that, plus every dimension tier ----\n    let minX = imgBox.x, minY = imgBox.y;\n    let maxX = imgBox.x + imgBox.w, maxY = imgBox.y + imgBox.h;\n    const LABEL_ALLOW = STEP * 0.75;\n    for (const t of tiers) {\n      for (const s of t.segs) {\n        for (const at of [s.a != null ? s.a : s.start, s.b != null ? s.b : s.end]) {\n          const px = t.geom.fromPx.x + t.geom.ux * at + t.geom.nx * (t.off + LABEL_ALLOW);\n          const py = t.geom.fromPx.y + t.geom.uy * at + t.geom.ny * (t.off + LABEL_ALLOW);\n          if (px < minX) minX = px;\n          if (px > maxX) maxX = px;\n          if (py < minY) minY = py;\n          if (py > maxY) maxY = py;\n        }\n      }\n    }\n\n    return { walls, tiers, STEP, WT, imgBox, minX, minY, maxX, maxY };\n  }\n\n  // Under a floor plan with any L / M / H unit on it (row 3): what the letter\n  // after a width means.\n  function rptHeightKey(doc) {\n    if (!(cabinets || []).some(c => c && heightLetterOf(c, Catalogue))) return;\n    rptText(doc, 'L, M or H after a width: a Low, Medium or High height unit.', RPT.M, RPT.H - 14 - 3,\n      { size: 8, colour: RPT.mute });\n  }\n\n  async function rptDrawFloorPlan(doc, box, opts = {}) {\n    const boxes = rptPlanBoxes(opts);\n    if (!boxes) return false;\n    const plan = await rptRenderPlanImage(opts);\n    const { walls, tiers, STEP, WT, imgBox, minX, minY, maxX, maxY } = boxes;\n\n    // The early capture if it matches this plan, otherwise take one now. The\n    // key is the millimetre box: if the plan changed after the shot was taken,\n    // the box moves and the stale picture is ignored rather than drawn.\n\n    const k  = Math.min(box.w / (maxX - minX), box.h / (maxY - minY));\n    const ox = box.x + (box.w - (maxX - minX) * k) / 2;\n    const oy = box.y + (box.h - (maxY - minY) * k) / 2;\n    const P  = (x, y) => ({ x: ox + (x - minX) * k, y: oy + (y - minY) * k });\n\n    // ---- the floor, under everything -------------------------------------\n    // The graph paper the 2D view draws, redrawn here so the layering can be\n    // floor \u2192 walls \u2192 units. Taking it from the capture instead meant either\n    // the angled walls sat under the grid, or the item numbers sat under the\n    // walls; there was no order that worked with the floor inside the image.\n    {\n      const bb = getBoundingBox(baseRoom);\n      const x0 = bb.minX != null ? bb.minX : 0, y0 = bb.minY != null ? bb.minY : 0;\n      const x1 = x0 + (bb.widthMm || 0), y1 = y0 + (bb.heightMm || 0);\n      const p0 = P(x0, y0), p1 = P(x1, y1);\n      doc.setFillColor(255, 255, 255);\n      doc.rect(p0.x, p0.y, p1.x - p0.x, p1.y - p0.y, 'F');\n      // \u26A0 CLIPPED TO THE ROOM, not drawn across the bounding box. An L-shaped\n      // or angled room is smaller than its bbox, and graph paper ruled over the\n      // part that is not room reads as floor that is not there. The capture\n      // used to cover that with its own mask, but the capture no longer brings\n      // a floor at all (see rptRenderPlanImage), so the clip has to be real.\n      //\n      // Even-odd scanline: where a line crosses the polygon boundary an odd\n      // number of times it is entering, so sorted crossings pair up into\n      // inside spans. The half-open test (>= one end, < the other) counts a\n      // vertex exactly once, which is what stops a span collapsing at a corner.\n      const verts = (room && room.vertices && room.vertices.length >= 3)\n        ? room.vertices\n        : [{ x: x0, y: y0 }, { x: x1, y: y0 }, { x: x1, y: y1 }, { x: x0, y: y1 }];\n      const insideSpans = (vertical, at, lo, hi) => {\n        const cuts = [];\n        for (let i = 0; i < verts.length; i++) {\n          const a = verts[i], b = verts[(i + 1) % verts.length];\n          const a0 = vertical ? a.x : a.y, b0 = vertical ? b.x : b.y;\n          const a1 = vertical ? a.y : a.x, b1 = vertical ? b.y : b.x;\n          if (a0 === b0) continue;                       // parallel: no crossing\n          if ((a0 <= at && b0 > at) || (b0 <= at && a0 > at)) {\n            cuts.push(a1 + ((at - a0) / (b0 - a0)) * (b1 - a1));\n          }\n        }\n        cuts.sort((p, q) => p - q);\n        const out = [];\n        for (let i = 0; i + 1 < cuts.length; i += 2) {\n          const s = Math.max(lo, cuts[i]), e = Math.min(hi, cuts[i + 1]);\n          if (e - s > 0.5) out.push([s, e]);\n        }\n        return out;\n      };\n      for (const [stepMm, shade, lw] of [[100, 238, 0.08], [1000, 210, 0.16]]) {\n        doc.setDrawColor(shade, shade, shade);\n        doc.setLineWidth(lw);\n        for (let x = Math.ceil(x0 / stepMm) * stepMm; x <= x1; x += stepMm) {\n          for (const [s, e] of insideSpans(true, x, y0, y1)) {\n            const a = P(x, s), b = P(x, e);\n            doc.line(a.x, a.y, b.x, b.y);\n          }\n        }\n        for (let y = Math.ceil(y0 / stepMm) * stepMm; y <= y1; y += stepMm) {\n          for (const [s, e] of insideSpans(false, y, x0, x1)) {\n            const a = P(s, y), b = P(e, y);\n            doc.line(a.x, a.y, b.x, b.y);\n          }\n        }\n      }\n    }\n\n\n    // ---- walls, as one continuous perimeter ------------------------------\n    // Each edge's band is bounded by the OUTER polygon, whose vertices are\n    // where neighbouring offset edges meet (a mitre). Offsetting each edge on\n    // its own and stopping at the ends is what left the corners open and made\n    // the perimeter read as separate blocks.\n    const poly = (pts, fill, stroke, lw) => {\n      const q = pts.map(pt => P(pt.x, pt.y));\n      if (fill)   doc.setFillColor(fill[0], fill[1], fill[2]);\n      if (stroke) { doc.setDrawColor(stroke[0], stroke[1], stroke[2]); doc.setLineWidth(lw || 0.2); }\n      const rel = q.slice(1).map((r, i) => [r.x - q[i].x, r.y - q[i].y]);\n      doc.lines(rel, q[0].x, q[0].y, [1, 1], fill && stroke ? 'FD' : fill ? 'F' : 'S', true);\n    };\n    const N = walls.length;\n    const seg = walls.map(w => {\n      const L  = w.lengthMm || 1;\n      const ux = (w.to.x - w.from.x) / L, uy = (w.to.y - w.from.y) / L;\n      // The room polygon runs clockwise, so (uy, -ux) points OUT of it.\n      return { w, L, ux, uy, nx: uy, ny: -ux };\n    });\n    // Where the offset of edge i-1 meets the offset of edge i.\n    const outerAt = (i) => {\n      const a = seg[(i - 1 + N) % N], b = seg[i % N];\n      const ax = a.w.from.x + a.nx * WT, ay = a.w.from.y + a.ny * WT;\n      const bx = b.w.from.x + b.nx * WT, by = b.w.from.y + b.ny * WT;\n      const den = a.ux * (-b.uy) - a.uy * (-b.ux);\n      if (Math.abs(den) < 1e-6) return { x: bx, y: by };      // parallel - no mitre to make\n      const t = ((bx - ax) * (-b.uy) - (by - ay) * (-b.ux)) / den;\n      return { x: ax + a.ux * t, y: ay + a.uy * t };\n    };\n    const outer = seg.map((_, i) => outerAt(i));\n\n    const openingsByWall = {};\n    for (const op of (roomConfig.wallOpenings || [])) {\n      (openingsByWall[op.wallIndex] = openingsByWall[op.wallIndex] || []).push(op);\n    }\n    seg.forEach((sg, i) => {\n      const A = sg.w.from, B = sg.w.to;\n      const OA = outer[i], OB = outer[(i + 1) % N];\n      const inner = (f) => ({ x: A.x + (B.x - A.x) * f, y: A.y + (B.y - A.y) * f });\n      // The outer boundary runs parallel to the inner one between the mitres,\n      // so the same fraction along each gives matching points.\n      // \u26A0 ONLY AT THE CORNERS. The outer edge runs between the two mitres, so\n      // it is longer (or shorter) than the inner edge, and the same fraction\n      // along it is NOT opposite the inner point: at a door or window the end\n      // of the wall came out slanted (Arden, 2026-10-13: \"the end look\n      // angled\"). Anywhere along the wall, the outer point is straight out\n      // from the inner one; f = 0 / 1 keep the mitre so corners stay closed.\n      const outerP = (f) => (f <= 0 ? OA : f >= 1 ? OB\n        : { x: A.x + (B.x - A.x) * f + sg.nx * WT, y: A.y + (B.y - A.y) * f + sg.ny * WT });\n\n      const ops = (openingsByWall[i] || []).slice()\n        .sort((a, b) => (a.offsetMm || 0) - (b.offsetMm || 0));\n      let cursor = 0;\n      const runs = [];\n      for (const op of ops) {\n        const a = Math.max(0, Math.min(sg.L, op.offsetMm || 0));\n        const b = Math.max(a, Math.min(sg.L, a + (op.widthMm || 0)));\n        if (a - cursor > 1) runs.push([cursor, a]);\n        cursor = b;\n      }\n      if (sg.L - cursor > 1) runs.push([cursor, sg.L]);\n\n      for (const [a, b] of runs) {\n        const f0 = a / sg.L, f1 = b / sg.L;\n        // Filled with no outline, then the INNER and OUTER edges stroked on\n        // their own. Stroking the quad drew its short ends too, which is the\n        // diagonal across each corner - a join in the drawing, not a wall.\n        poly([inner(f0), inner(f1), outerP(f1), outerP(f0)], [216, 216, 216], null, 0);\n        doc.setDrawColor(51, 51, 51);\n        doc.setLineWidth(0.25);\n        for (const pair of [[inner(f0), inner(f1)], [outerP(f0), outerP(f1)]]) {\n          const p0 = P(pair[0].x, pair[0].y), p1 = P(pair[1].x, pair[1].y);\n          doc.line(p0.x, p0.y, p1.x, p1.y);\n        }\n      }\n      // A door or window keeps a reveal line at each end so its width reads.\n      for (const op of ops) {\n        const f0 = Math.max(0, Math.min(1, (op.offsetMm || 0) / sg.L));\n        const f1 = Math.max(f0, Math.min(1, ((op.offsetMm || 0) + (op.widthMm || 0)) / sg.L));\n        for (const f of [f0, f1]) {\n          const p0 = P(inner(f).x,  inner(f).y);\n          const p1 = P(outerP(f).x, outerP(f).y);\n          doc.setDrawColor(51, 51, 51);\n          doc.setLineWidth(0.25);\n          doc.line(p0.x, p0.y, p1.x, p1.y);\n        }\n      }\n    });\n\n\n    // The plan itself, from the planner's own renderer, placed at exactly the\n    // room coordinates it covers. A missing image is not a failure: the room,\n    // walls, openings and every dimension are vector and worth having alone.\n    if (plan && plan.ppm > 0) {\n      const x0 = -plan.ox / plan.ppm;           // image left edge, in room mm\n      const y0 = -plan.oy / plan.ppm;\n      const tl = P(x0, y0);\n      const br = P(x0 + plan.w / plan.ppm, y0 + plan.h / plan.ppm);\n      doc.addImage(plan.url, 'PNG', tl.x, tl.y, br.x - tl.x, br.y - tl.y);\n    }\n\n    // ---- dimensions, in vector on top ------------------------------------\n    const hex = (h, fallback) => {\n      const m = /^#?([0-9a-f]{6})$/i.exec(String(h || ''));\n      if (!m) return fallback;\n      const n = parseInt(m[1], 16);\n      return [(n >> 16) & 255, (n >> 8) & 255, n & 255];\n    };\n    const line = (a, b, colour, lw) => {\n      const p0 = P(a.x, a.y), p1 = P(b.x, b.y);\n      doc.setDrawColor(colour[0], colour[1], colour[2]);\n      doc.setLineWidth(lw);\n      doc.line(p0.x, p0.y, p1.x, p1.y);\n    };\n    const TICK = STEP * 0.10;\n    for (const t of tiers) {\n      const g = t.geom;\n      const at = (mm, off) => ({ x: g.fromPx.x + g.ux * mm + g.nx * off,\n                                 y: g.fromPx.y + g.uy * mm + g.ny * off });\n      const bounds = new Set([0, t.L]);\n      for (const s of t.segs) {\n        const a = s.a != null ? s.a : s.start;\n        const b = s.b != null ? s.b : s.end;\n        if (b - a <= 0.5) continue;\n        line(at(a, t.off), at(b, t.off), hex(s.colour, PLAN_DIM), s.colour ? 0.35 : 0.2);\n        bounds.add(a); bounds.add(b);\n      }\n      for (const b of bounds) {\n        line(at(b, t.off - TICK), at(b, t.off + TICK), PLAN_DIM, 0.2);\n      }\n      // Labels sit just outside their own line, reading along the wall and\n      // never upside down.\n      let angle = (Math.atan2(g.uy, g.ux) * 180) / Math.PI;\n      if (angle > 90) angle -= 180;\n      if (angle <= -90) angle += 180;\n      // EVERY span keeps its number, however narrow. An end panel is 22mm\n      // and a filler little more, so their text can never fit between their\n      // own ticks - and a flat `span * k < 4` test dropped them outright,\n      // leaving a dimension line with nothing measured against it (Arden,\n      // 2026-09-28). Drawing them all where they fall would overlap them into\n      // a smudge, so they are packed instead.\n      const items = [];\n      for (const s of t.segs) {\n        const a = s.a != null ? s.a : s.start;\n        const b = s.b != null ? s.b : s.end;\n        const span = b - a;\n        if (span <= 0.5) continue;\n        const text = s.text != null ? s.text : String(Math.round(span));\n        if (!text) continue;\n        // Font first: the width is MEASURED, not guessed from a character\n        // count, so \"22\" and \"1000\" are judged on what they actually take.\n        doc.setFont('helvetica', s.text ? 'bold' : 'normal');\n        doc.setFontSize(s.text ? 6.5 : 5.5);\n        items.push({ a, b, seg: s, text, widthMm: doc.getTextWidth(text) / k });\n      }\n      // Two rows, both inside this tier's own gap: tiers are STEP apart, so\n      // 0.30 and 0.62 of a STEP each clear the next line.\n      const placed = rptPackDimLabels(items, {\n        rows: [STEP * 0.30, STEP * 0.62],\n        padMm: 0.8 / k\n      });\n      for (const pl of placed) {\n        const s = pl.seg;\n        if (pl.moved) {\n          // A leader back to the true centre, or a shifted number reads as\n          // belonging to the span next to it.\n          line(at(pl.centre, t.off), at(pl.x, t.off + pl.off - STEP * 0.12),\n               PLAN_DIM, 0.1);\n        }\n        const q = at(pl.x, t.off + pl.off);\n        const p = P(q.x, q.y);\n        doc.setFont('helvetica', s.text ? 'bold' : 'normal');\n        doc.setFontSize(s.text ? 6.5 : 5.5);\n        const col = s.colour ? hex(s.colour, PLAN_DIM) : PLAN_DIM;\n        doc.setTextColor(col[0], col[1], col[2]);\n        doc.text(pl.text, p.x, p.y, { align: 'center', angle: -angle });\n      }\n    }\n    return true;\n  }\n\n  // ---- Check your measurements (Arden, 2026-10-27) -----------------------\n  // The customer's room as they entered it, with no kitchen in it, so they\n  // can measure their own room against it before ordering: a dimensioned\n  // plan, then every wall and room item listed with its size and where it is.\n  const RPT_ROOM_CHECK_NOTE =\n    'This is your room as entered in the planner, without the bedroom: the walls, doors, ' +\n    'windows and everything on them, in millimetres. Please measure your room and check each ' +\n    'figure here before you order. If anything is different, change it in Room Setup or let us ' +\n    'know, so your bedroom is planned to fit.';\n  const RPT_ROOM_CHECK_FOOT =\n    'Positions are measured along the wall from its left-hand corner, as you stand in the room ' +\n    'facing that wall. Height off floor is to the bottom of the item.';\n\n  function rptRoomItemName(it) {\n    switch (it.type) {\n      case 'boiler':           return it.preset === 'floor' ? 'Floor boiler' : 'Wall boiler';\n      case 'electrical-point': {\n        const kind  = it.preset === 'switch' ? 'Switch' : 'Socket';\n        const style = it.plateStyle && it.plateStyle !== 'single' ? ' (' + it.plateStyle + ')' : '';\n        return kind + style;\n      }\n      case 'consumer-unit':    return 'Consumer unit';\n      case 'water-tank':       return 'Water tank';\n      case 'radiator':         return 'Radiator';\n      case 'stopcock':         return 'Stopcock';\n      case 'step-block':       return 'Step block' + (it.stepCount ? ' (' + it.stepCount + ' steps)' : '');\n      case 'beam':             return 'Ceiling beam';\n      case 'sloped-ceiling':   return 'Ceiling wedge';\n      case 'vaulted-ceiling':  return 'Vaulted ceiling';\n      case 'free-block':       return 'Custom block';\n      case 'cooker-alcove':    return 'Chimney breast';\n      case 'wall':             return 'Internal wall';\n      // Internal walls are saved as columns too (100 x 1000 from the Internal\n      // wall button) - a thin one is a wall, not a pillar.\n      case 'column':           return (Math.min(it.widthMm || 0, it.depthMm || 0) < 200) ? 'Internal wall' : 'Pillar';\n      default:                 return 'Room item';\n    }\n  }\n\n  // Which wall a room item stands against, and how far along it from the\n  // wall's left-hand corner (its `from` end: the polygon runs clockwise, so\n  // facing a wall from inside the room `from` is on your left). The same\n  // footprint test the plan's dimension lines use. One that touches no wall\n  // reports the nearest wall and its distance from it instead.\n  function rptRoomItemWall(it, walls) {\n    const w = it.widthMm, d = it.depthMm;\n    if (!(w > 0) || !(d > 0)) return null;\n    const cx = it.x + w / 2, cy = it.y + d / 2;\n    const th = ((it.rotationDeg || 0) * Math.PI) / 180;\n    const cos = Math.cos(th), sin = Math.sin(th);\n    const pts = [[-w / 2, -d / 2], [w / 2, -d / 2], [w / 2, d / 2], [-w / 2, d / 2]]\n      .map(([lx, ly]) => ({ x: cx + lx * cos - ly * sin, y: cy + lx * sin + ly * cos }));\n    let best = null;\n    walls.forEach((wall, i) => {\n      const L = wall.lengthMm || 0;\n      if (L < 1) return;\n      const ux = (wall.to.x - wall.from.x) / L, uy = (wall.to.y - wall.from.y) / L;\n      let minT = Infinity, maxT = -Infinity, gap = Infinity;\n      for (const p of pts) {\n        const rx = p.x - wall.from.x, ry = p.y - wall.from.y;\n        const t = rx * ux + ry * uy;\n        const inward = -(rx * uy - ry * ux);           // distance into the room\n        if (t < minT) minT = t;\n        if (t > maxT) maxT = t;\n        if (inward < gap) gap = inward;\n      }\n      if (maxT < 0 || minT > L) return;                // not alongside this wall\n      const g = Math.max(0, gap);\n      if (!best || g < best.gap) best = { index: i, gap: g, start: Math.max(0, minT) };\n    });\n    return best;\n  }\n\n  function rptRoomCheckRows() {\n    const walls = getWalls(room);\n    const labels = deriveWallLabels(walls);\n    const mm = (v) => (Number.isFinite(v) ? String(Math.round(v)) : '');\n    // Listed A, B, C, D (or 1, 2, 3...), not in the polygon's own order,\n    // which on a four-wall room is A, D, C, B.\n    const order = walls.map((_, i) => i)\n      .sort((p, q) => String(labels[p]).localeCompare(String(labels[q]), 'en', { numeric: true }));\n    const rank = [];\n    order.forEach((wi, r) => { rank[wi] = r; });\n    const rows = [];\n    order.forEach((i) => rows.push({\n      item: 'Wall ' + labels[i], wall: '', from: '', len: mm(walls[i].lengthMm),\n      h: '', d: '', floor: '', sortWall: -1, sortAt: rank[i]\n    }));\n    if (Number.isFinite(roomConfig.ceilingHeightMm)) {\n      rows.push({ item: 'Ceiling height', wall: '', from: '', len: '',\n                  h: mm(roomConfig.ceilingHeightMm), d: '', floor: '', sortWall: -1, sortAt: walls.length });\n    }\n    for (const op of (roomConfig.wallOpenings || [])) {\n      if (!op || op.floating || !walls[op.wallIndex]) continue;\n      const name = (op.type === 'window' ? 'Window' : 'Door') + (op.bay ? ' (bay)' : '');\n      rows.push({\n        item: name, wall: labels[op.wallIndex], from: mm(op.offsetMm || 0), len: mm(op.widthMm),\n        h: mm(op.heightMm), d: '', floor: mm(op.heightFromFloorMm || 0),\n        sortWall: rank[op.wallIndex], sortAt: op.offsetMm || 0\n      });\n    }\n    for (const it of (roomConfig.perimeterItems || [])) {\n      if (!it || !it.type) continue;\n      const at = rptRoomItemWall(it, walls);\n      const against = at && at.gap <= 20;\n      rows.push({\n        item: rptRoomItemName(it),\n        wall: at ? labels[at.index] : '',\n        from: against ? mm(at.start) : (at ? mm(at.gap) + ' out from the wall' : ''),\n        len: mm(it.widthMm), h: mm(it.heightMm), d: mm(it.depthMm),\n        floor: mm(it.restMm || 0),\n        sortWall: against ? rank[at.index] : walls.length + (at ? rank[at.index] : 0),\n        sortAt: against ? at.start : (at ? at.gap : 0)\n      });\n    }\n    rows.sort((p, q) => (p.sortWall - q.sortWall) || (p.sortAt - q.sortAt));\n    return rows;\n  }\n\n  // The plan's basket as saved (the planner's own, by id; else the cart's), for\n  // the notes page. No sync and no pricing: only its lines' notes are read.\n  async function rptPlanBasket() {\n    try {\n      const api = window.BTKBasketAPI;\n      if (!api) return null;\n      const id = (planStore && typeof planStore.getActiveBasketId === 'function')\n        ? await planStore.getActiveBasketId() : null;\n      if (id) {\n        const project = await api.getProject();\n        const b = project && (project.baskets || []).find(x => x && x.id === id);\n        if (b) return b;\n      }\n      return await api.getActiveBasket();\n    } catch (e) { return null; }\n  }\n\n  // The customer's notes, after the floor plan and numbered as it is, so each\n  // reads against its unit or item: the units' notes (Add Note -\n  // handleSetUnitNote) and, since Sales row 144 (Julian, 2026-11-20), the notes\n  // on every other basket line - loose doors, panels, hinges, worktops, trims -\n  // which are often the fitter's instructions (\"used to create a faux housing\n  // for the dryer\"). The customer's note only: a staff note (staffNote) is for\n  // our team and never printed. No page when nothing has a note.\n  async function rptUnitNotesPages(doc, logo) {\n    const unitName = (c) => {\n      const info = c.variantId ? Catalogue.getVariantInfo?.(String(c.variantId)) : null;\n      const ut = c.unitTypeId ? Catalogue.getUnitType?.(c.unitTypeId) : null;\n      return (info && info.product && info.product.title)\n        || (c.freestandingAppliance && c.freestandingAppliance.title)\n        || (ut && (ut.name || ut.title)) || c.code || 'Unit';\n    };\n    const rows = (cabinets || [])\n      .filter(c => c && c.note && c.displayNumber != null)\n      .map(c => ({ n: c.displayNumber, num: String(c.displayNumber), name: unitName(c), note: String(c.note).trim() }));\n    // A unit's line carries the unit's own note (the two are kept as one), so\n    // a line note already listed against that number is not repeated.\n    const seen = new Set(rows.map(r => r.num + '|' + r.note));\n    const basket = await rptPlanBasket();\n    if (basket) {\n      const lines = [...(basket.sections || []).flatMap(sec => sec.items || []), ...(basket.items || [])];\n      for (const it of lines) {\n        const a = (it && it.attributes) || {};\n        const note = String(a.notes || '').trim();\n        if (!note) continue;\n        const n = it.planLineNumber != null ? Number(it.planLineNumber) : null;\n        const num = n != null ? String(n) : '';\n        if (seen.has(num + '|' + note)) continue;\n        seen.add(num + '|' + note);\n        const qty = Number(it.quantity || it.qty || 1);\n        const title = String(it.productTitle || it.title || 'Item');\n        rows.push({ n, num, name: (qty > 1 ? qty + ' x ' : '') + title, note });\n      }\n    }\n    if (!rows.length) return;\n    rows.sort((p, q) => (p.n == null ? 9e9 : p.n) - (q.n == null ? 9e9 : q.n));\n    const TOP = 30, BOTTOM = RPT.H - 20, NUM_W = 14, NAME_W = 80;\n    const noteW = RPT.W - RPT.M * 2 - NUM_W - NAME_W - 4;\n    const LH = 4.4;\n    const start = (title) => { doc.addPage(); rptHeaderBar(doc, title, logo); return TOP; };\n    let y = start('Notes');\n    rptText(doc, 'Notes on your units and items, numbered as on the floor plan.', RPT.M, y - 2, { size: 8.5, colour: RPT.mute });\n    y += 4;\n    for (const r of rows) {\n      doc.setFont('helvetica', 'normal'); doc.setFontSize(9);\n      const lines = doc.splitTextToSize(r.note, noteW);\n      const nameLines = doc.splitTextToSize(r.name, NAME_W - 7);\n      const h = Math.max(lines.length, nameLines.length) * LH + 4;\n      if (y + h > BOTTOM) y = start('Notes (continued)');\n      rptText(doc, r.num, RPT.M + 2, y + 4.5, { size: 9.5, bold: true, colour: RPT.red });\n      nameLines.forEach((ln, i) => rptText(doc, ln, RPT.M + NUM_W, y + 4.5 + i * LH, { size: 9, bold: true }));\n      lines.forEach((ln, i) => rptText(doc, ln, RPT.M + NUM_W + NAME_W, y + 4.5 + i * LH, { size: 9 }));\n      y += h;\n      doc.setDrawColor(...RPT.rule);\n      doc.line(RPT.M, y, RPT.W - RPT.M, y);\n    }\n  }\n\n  async function rptRoomCheckPages(doc, logo) {\n    doc.addPage();\n    rptHeaderBar(doc, 'Check your measurements', logo);\n    rptText(doc, RPT_ROOM_CHECK_NOTE, RPT.M, 27, { size: 8.5, colour: RPT.mute, maxW: RPT.W - RPT.M * 2 });\n    await rptYield();\n    const drew = await rptDrawFloorPlan(doc, {\n      x: RPT.M, y: 38, w: RPT.W - RPT.M * 2, h: RPT.H - 38 - 20\n    }, { roomOnly: true });\n    if (!drew) rptText(doc, 'The room plan could not be generated.', RPT.M, 46, { size: 10, colour: RPT.mute });\n\n    // The list. Columns total the 265mm between the margins.\n    const COLS = [\n      { key: 'item',  label: 'Item',              w: 66, align: 'left'  },\n      { key: 'wall',  label: 'Wall',              w: 18, align: 'left'  },\n      { key: 'from',  label: 'From left corner',  w: 49, align: 'right' },\n      { key: 'len',   label: 'Width / length',    w: 34, align: 'right' },\n      { key: 'h',     label: 'Height',            w: 30, align: 'right' },\n      { key: 'd',     label: 'Depth',             w: 30, align: 'right' },\n      { key: 'floor', label: 'Height off floor',  w: 38, align: 'right' }\n    ];\n    const TABLE_TOP = 30, TABLE_BOTTOM = RPT.H - 20, ROW_H = 7;\n    const colX = (i) => RPT.M + COLS.slice(0, i).reduce((a, c) => a + c.w, 0);\n    const head = (y) => {\n      doc.setFillColor(...RPT.red);\n      doc.rect(RPT.M, y, RPT.W - RPT.M * 2, 8, 'F');\n      COLS.forEach((c, i) => {\n        const x = c.align === 'right' ? colX(i) + c.w - 2 : colX(i) + 2;\n        rptText(doc, c.label, x, y + 5.5, { size: 8.5, bold: true, colour: [255, 255, 255], align: c.align });\n      });\n      return y + 8;\n    };\n    doc.addPage();\n    rptHeaderBar(doc, 'Room measurements (mm)', logo);\n    let ty = head(TABLE_TOP);\n    let zebra = false;\n    for (const r of rptRoomCheckRows()) {\n      if (ty + ROW_H > TABLE_BOTTOM) {\n        doc.addPage();\n        rptHeaderBar(doc, 'Room measurements (continued)', logo);\n        ty = head(TABLE_TOP);\n        zebra = false;\n      }\n      if (zebra) {\n        doc.setFillColor(248, 248, 246);\n        doc.rect(RPT.M, ty, RPT.W - RPT.M * 2, ROW_H, 'F');\n      }\n      zebra = !zebra;\n      COLS.forEach((c, i) => {\n        const x = c.align === 'right' ? colX(i) + c.w - 2 : colX(i) + 2;\n        const val = r[c.key] == null ? '' : String(r[c.key]);\n        const lines = doc.splitTextToSize(val, c.w - 4);\n        rptText(doc, lines[0] + (lines.length > 1 ? '\u2026' : ''), x, ty + 4.8,\n                { size: 8.5, bold: c.key === 'item', align: c.align });\n      });\n      doc.setDrawColor(...RPT.rule);\n      doc.line(RPT.M, ty + ROW_H, RPT.W - RPT.M, ty + ROW_H);\n      ty += ROW_H;\n    }\n    if (ty + 12 > TABLE_BOTTOM) {\n      doc.addPage();\n      rptHeaderBar(doc, 'Room measurements (continued)', logo);\n      ty = TABLE_TOP;\n    }\n    rptText(doc, RPT_ROOM_CHECK_FOOT, RPT.M, ty + 7, { size: 8.5, colour: RPT.mute, maxW: RPT.W - RPT.M * 2 });\n  }\n\n  // Every numbered line on the plan, not just the units.\n  //\n  // The numbering sweep gives a number to units, appliances, sinks, rails AND\n  // to each end panel / filler / board - and the basket is built from that same\n  // sweep, so its lines already carry planLineNumber. Reading the cabinets\n  // directly only ever produced the units, which is why the schedule stopped\n  // short of the numbers drawn on the plan. The basket is kept in step with the\n  // plan by the debounced re-sync, so this needs no write of its own.\n  async function rptSchedule() {\n\n    const colourName = (handle, styleId) => {\n      if (!handle) return null;\n      try {\n        const list = Catalogue.getDoorColoursForStyle?.(styleId) || [];\n        const hit  = list.find(c => c.handle === handle);\n        return hit ? hit.name : null;\n      } catch (e) { return null; }\n    };\n\n    // Bring the basket in line with the plan FIRST. Plan numbers are handed out\n    // by the numbering sweep on every render, so adding or removing anything\n    // renumbers what follows - and a basket built before that still carries the\n    // old numbers. That is why the schedule showed a 14 for a plan whose\n    // highest number is 12. This is the same quiet re-sync the planner runs on\n    // a debounce (one saveBasket, no cart writes); doing it here just makes\n    // sure it has happened before the numbers are read.\n    const canSync = !!window.BTKBasketAPI &&\n      (cabinets || []).some(c => !c.excludeFromQuote && c.variantId && !c.endPanelUnit);\n    if (canSync) {\n      try { await transferPlanToBasket(false, { quiet: true }); }\n      catch (e) { console.warn('[BTK Kitchen Planner] Report basket sync failed', e); }\n    }\n\n    // getActiveBasket() returns whatever basket the CART is currently on -\n    // which is where the sample packs came from. The planner's own basket is\n    // the one planStore points at, so it is looked up by id in the project.\n    let basket = null;\n    try {\n      const api = window.BTKBasketAPI;\n      const id  = (planStore && typeof planStore.getActiveBasketId === 'function')\n        ? await planStore.getActiveBasketId() : null;\n      if (api && id) {\n        const project = await api.getProject();\n        basket = (project && (project.baskets || []).find(b => b && b.id === id)) || null;\n      }\n      if (!basket && api) basket = await api.getActiveBasket();\n    } catch (e) { basket = null; }\n    // Priced the way the planner basket prices it - the free boiling tap at\n    // \u00A30 - so every line, and the total, is the basket's own (Arden,\n    // 2026-10-19: the tap was charged here, \u00A3319.98 over Today's Price).\n    try {\n      const CA = window.BTKCartAdvanced;\n      if (basket && CA && typeof CA.pricedForQuote === 'function') basket = await CA.pricedForQuote(basket);\n    } catch (e) {\n      console.warn('[BTK Kitchen Planner] Report basket pricing failed', e);\n    }\n    const lines = [];\n    const sectionOf = new Map();\n    if (basket) {\n      (basket.sections || []).forEach(sec => (sec.items || []).forEach(it => { lines.push(it); sectionOf.set(it, sec.name); }));\n      (basket.items || []).forEach(it => lines.push(it));\n    }\n\n    if (lines.length) {\n      const groupFor = window.BTKCartAdvanced && window.BTKCartAdvanced.quoteGroupFor;\n      const rows = lines.map(it => {\n        const a = it.attributes || {};\n        const opts = [\n          colourName(a.doorColour, a.style),\n          a.hinge ? ('Hinge ' + String(a.hinge).toLowerCase()) : null,\n          a.rail  ? ('Rail '  + String(a.rail).toLowerCase())  : null,\n          a.config || null\n        ].filter(Boolean).join(' / ');\n        const dims = (a.widthMm && a.depthMm)\n          ? (Math.round(a.widthMm) + ' x ' + Math.round(a.depthMm) + ' mm')\n          : (it.variantTitle || '').split('/').map(t => t.trim()).filter(Boolean).join(' x ');\n        return {\n          num:     it.planLineNumber != null ? it.planLineNumber : '',\n          sort:    it.planLineNumber != null ? it.planLineNumber : 9e9,\n          group:   groupFor ? groupFor(it, sectionOf.get(it) || '') : null,\n          title:   it.productTitle || 'Item',\n          dims,\n\n          options: opts || '-',\n          qty:     it.quantity || 1,\n          price:   (parseFloat(it.price) || 0) * (it.quantity || 1),\n          // The high street price, struck through beside the price when it is\n          // higher - the saving the basket shows on the line.\n          was:     Math.max(parseFloat(it.compareAtPrice) || 0, parseFloat(it.originalPrice || it.price) || 0)\n                   * (it.quantity || 1)\n        };\n      });\n      rows.sort((a, b) => a.sort - b.sort);\n\n      // Everything else checkout charges, after the lines, priced by the\n      // basket itself so the schedule's total is the basket's total: the\n      // upgrades chosen on the lines, the estimated delivery and any discount\n      // code (Arden, 2026-10-13: \"so it matches the checkout price\"). Extras\n      // are basket lines already and are in the rows above.\n      let summary = null;\n      try {\n        const CA = window.BTKCartAdvanced;\n        if (CA && typeof CA.quoteSummary === 'function') summary = await CA.quoteSummary(basket);\n      } catch (e) {\n        console.warn('[BTK Kitchen Planner] Report basket summary failed', e);\n      }\n      if (summary) {\n        for (const u of (summary.upgrades || [])) {\n          const nums = (u.units || []).map(s => String(s).split(' - ')[0]).filter(Boolean);\n          rows.push({ num: u.number, group: 'upgrades', title: u.name, dims: '',\n                      options: nums.length ? `For ${nums.length > 1 ? 'units' : 'unit'} ${nums.join(', ')}` : 'Upgrade',\n                      qty: u.qty, price: u.priceGbp });\n        }\n        if (summary.delivery) {\n          rows.push({ num: '', group: 'delivery', title: `Estimated delivery - ${summary.delivery.name}`, dims: '',\n                      options: summary.delivery.postcode\n                        ? `To ${summary.delivery.postcode} \u00B7 confirmed at checkout`\n                        : 'Standard estimate \u00B7 confirmed at checkout',\n                      qty: 1, price: summary.delivery.priceGbp });\n        }\n        for (const d of (summary.discounts || [])) {\n          rows.push({ num: '', group: 'discounts', title: d.title, dims: '', options: 'Discount', qty: 1, price: -d.amountGbp });\n        }\n        rows.total = summary.total;\n        // The basket's price breakdown and offers, for the Your Price page.\n        rows.summary = summary;\n      } else {\n        // No basket panel to price the rest: the lines, at least, add up.\n        rows.total = rows.reduce((s, r) => s + (r.price || 0), 0);\n      }\n      // In the planner basket's groups, in its order and each in plan-number\n      // order (Arden, 2026-11-03). Only the printing regroups: the plan numbers\n      // are the lines' own, so a group's numbers can skip, as they do in the basket.\n      const groups = (window.BTKCartAdvanced && window.BTKCartAdvanced.quoteGroups) || [];\n      if (groupFor && groups.length) {\n        rows.groupLabels = new Map([...groups, ['discounts', 'Discounts']]);\n        const order = [...rows.groupLabels.keys()];\n        const stable = rows.map((r, i) => [order.indexOf(r.group), i, r]);\n        stable.sort((a, b) => (a[0] - b[0]) || (a[1] - b[1]));\n        stable.forEach((e, i) => { rows[i] = e[2]; });\n      }\n      return rows;\n    }\n\n    // No basket yet - fall back to the units in the plan so the report still\n    // says something, rather than printing an empty table.\n    return (cabinets || [])\n      .filter(c => !c.excludeFromQuote && c.variantId && !c.endPanelUnit)\n      .slice()\n      .sort((a, b) => (a.displayNumber ?? 9e9) - (b.displayNumber ?? 9e9))\n      .map(c => {\n        const def  = findCabinet(c) || {};\n        const info = c.variantId ? Catalogue.getVariantInfo(c.variantId) : null;\n        const _pc = unitPriceCents(c, info);\n        const priceCents = (_pc != null) ? _pc\n                         : (def.priceGbp != null) ? Math.round(def.priceGbp * 100) : 0;\n        return {\n          num:   c.displayNumber != null ? c.displayNumber : '',\n          title: (info && info.product && info.product.title) || def.name || c.code || 'Cabinet',\n          dims:  (c.widthMm && c.depthMm) ? (Math.round(c.widthMm) + ' x ' + Math.round(c.depthMm) + ' mm') : '',\n\n          options: colourName(c.doorColourHandle || globalDoorColourHandle,\n                              c.kitchenStyleId || kitchenStyleId) || '-',\n          qty:   1,\n          price: priceCents / 100\n        };\n      });\n  }\n\n  // `mode` decides only the LAST step: 'save' downloads it (the Print\n  // button, unchanged), 'blob' hands the bytes back so they can be posted to\n  // the planner API and attached to the Odoo sale order. Everything before\n  // that - the 3D captures, the floor plan, the schedule - is identical, so\n  // the customer's download and the copy the factory sees can never differ.\n  // Run a background job once the page is genuinely FREE - never on a deadline.\n  //\n  // \u26A0 `requestIdleCallback(fn, { timeout: N })` IS A DEADLINE, NOT A DELAY: if\n  // the page is still busy at N the browser runs fn anyway. Both background\n  // jobs on the add-to-basket path used `{ timeout: 8000 }`, and the basket\n  // embed needs longer than that to settle (it rebuilds every line AND mounts\n  // the live 3D view), so idle never came, the deadline always won, and the work\n  // landed on the main thread behind the basket the customer was waiting for:\n  // 10-20 seconds to appear (Arden, 2026-09-26).\n  //\n  // So: wait out a settle period before even ASKING for idle, then set a\n  // deadline long enough to be a backstop rather than a target. Nothing here is\n  // urgent - the plan report has flushCartForCheckout and the API's late attach\n  // behind it (planner-api #60), and the thumbnail is a preview. The customer's\n  // basket wins every time.\n  const PAGE_FREE_SETTLE_MS = 2500;\n  const PAGE_FREE_DEADLINE_MS = 120000;\n  function whenPageFree(job, opts) {\n    if (typeof job !== 'function') return;\n    const settle = (opts && opts.settleMs) || PAGE_FREE_SETTLE_MS;\n    const deadline = (opts && opts.deadlineMs) || PAGE_FREE_DEADLINE_MS;\n    const run = () => { try { job(); } catch (e) {} };\n    const ask = () => {\n      try {\n        if (typeof window.requestIdleCallback === 'function') {\n          window.requestIdleCallback(run, { timeout: deadline });\n        } else {\n          setTimeout(run, 6000);          // no idle API: a plain, unhurried wait\n        }\n      } catch (e) { try { setTimeout(run, 6000); } catch (_) {} }\n    };\n    try { setTimeout(ask, settle); }\n    catch (e) { try { setTimeout(run, 8000); } catch (_) {} }\n  }\n\n  // Give the browser the main thread back. The report is built in the\n  // background while the customer is using the page, so every heavy step has\n  // to be separated by one of these or the page stops responding.\n  // scheduler.yield() where the browser has it (it yields to input and paint\n  // properly); otherwise a frame followed by a task, so a pending paint\n  // happens AND queued work gets a turn before we take the thread back.\n  function rptYield() {\n    return new Promise((resolve) => {\n      try {\n        const sch = window.scheduler;\n        if (sch && typeof sch.yield === 'function') { sch.yield().then(resolve, resolve); return; }\n        requestAnimationFrame(() => setTimeout(resolve, 0));\n      } catch (e) { setTimeout(resolve, 0); }\n    });\n  }\n  // opts.prices === false: Print Plan Only, the staff print menu's first\n  // option - the views and the floor plan with no schedule, no total and no\n  // pricing terms, for showing a design without a quote (Arden, 2026-10-13).\n  async function downloadPlanReport(mode = 'save', opts = {}) {\n    const withPrices = !(opts && opts.prices === false);\n    // A 'blob' build runs in the BACKGROUND for the order, so it must be\n    // INVISIBLE: the loader, the failure dialog and clearing the selection all\n    // belong to the Print button. Without this the basket took 5-10 seconds to\n    // open behind a 'Preparing your plan report' overlay (Arden, 2026-09-26) -\n    // not awaiting the call was never enough on its own, because the work and\n    // the overlay are both on the main thread.\n    const background = (mode === 'blob');\n    if (withPrices && planPricesPending()) {\n      if (!background) window.BTKKPDialog.alert('We are still getting today\\'s prices for your plan. Please try again in a moment.', { title: 'Getting Today\\'s Prices' });\n      loadPlanPrices();\n      return null;\n    }\n    const loader = background ? null : window.BTKLoader;\n    let prevDisp = null;\n    try {\n      // show() takes an options object - a bare string falls through to the\n      // loader's generic copy, which said nothing about a report. The lines\n      // track what the report is actually doing, and hold on the last one\n      // because the PDF assembly has no further stages to announce.\n      loader?.show?.({\n        messages: [\n          'Preparing your plan report\u2026',\n          'Rendering your bedroom in 3D\u2026',\n          'Drawing the measured floor plan\u2026',\n          'Listing every item in your plan\u2026',\n          'Building your PDF\u2026'\n        ],\n        intervalMs: 1600,\n        holdLast: true\n      });\n      // Clean capture - no selection or clearance overlays in the images.\n      // Never in the background: deselecting the customer's unit while they are\n      // looking at it is not ours to do.\n      if (!background) selectItem(null);\n\n      // The 3D engine is built lazily when the 3D step is opened. Make sure\n      // it exists and holds the current scene.\n      //\n      // The viewport is not hidden at all: these captures go through\n      // snapshotOffscreen(), which has its own renderer and camera, and the\n      // floor plan is drawn in vector from the model. Nothing in this build\n      // reads the screen any more.\n      await ensure3DReady();\n      handle3D?.render({ room, roomConfig, openingFaceInsets: openingFaceInsetMap(), cabinets, baseRoom, featureStyles, railFinishHandle, segmentColours, worktops: buildWorktops(), worktopColourHex, worktopColours, worktopCornerRadii, worktopItems: worktopItems3D(), furnitureItems, handleGroups, lights, lightsOn });\n      // GLB models and textures need a moment to land before capturing.\n      await new Promise(r => setTimeout(r, 1500));\n\n      // Page-shaped captures (297 x 210 = 1.4143) so a view fills its page\n      // edge to edge with nothing letterboxed.\n      const PW = 2100, PH = 1485;\n      // \u26A0 ONE CAPTURE AT A TIME, YIELDING BETWEEN THEM. As a .map() this fired\n      // three 2100x1485 WebGL renders back to back with no chance for the\n      // browser to paint, which is a visible stall on the page behind it. The\n      // report is built while the customer reads their basket, so a step that\n      // blocks for a second is a step that reads as a hang.\n      const views = [];\n      for (const v of [\n        { key: 'iso',  title: 'Three-dimensional view - 1' },\n        { key: 'iso2', title: 'Three-dimensional view - 2' },\n        { key: 'top',  title: 'Overhead view' }\n      ]) {\n        await rptYield();\n        const img = handle3D?.snapshotOffscreen?.({ view: v.key, width: PW, height: PH })\n                 || handle3D?.snapshot?.({ view: v.key, width: PW, height: PH }) || null;\n        if (!img) continue;\n        await rptYield();\n        // Trimmed, so the kitchen fills its page instead of floating in the\n        // middle of the camera's empty room.\n        views.push({ ...v, img, trim: await rptTrim(img) });\n      }\n      await rptYield();\n      const heroRaw = handle3D?.snapshotOffscreen?.({ view: 'plan', width: 2100, height: 1200 })\n                   || handle3D?.snapshot?.({ view: 'plan', width: 2100, height: 1200 }) || null;\n      await rptYield();\n      const hero    = heroRaw ? await rptTrim(heroRaw) : null;\n      // The Lifestyle photo staff kept for this plan, if there is one.\n      const lifestyle = await rptLifestylePhoto();\n      await rptYield();\n      // The floor plan is drawn into the PDF directly - see rptDrawFloorPlan.\n      const logo = await rptWhiteLogo();\n\n      // activePlanName is what the planner itself calls this plan - the name in\n      // the Save pill. Going via the basket returned the basket's own default\n      // when the plan had never been pushed, which is where \"Kitchen Plan\"\n      // came from instead of the name on screen.\n      const planName = activePlanName || 'Bedroom Plan';\n      const dateStr = new Date().toLocaleDateString('en-GB', { day: 'numeric', month: 'long', year: 'numeric' });\n      const bbox = getBoundingBox(baseRoom);\n      const fmt  = new Intl.NumberFormat('en-GB', { style: 'currency', currency: context.currency || 'GBP' });\n      // Plan Only never reads the basket: no schedule, so nothing to sync.\n      const schedule = withPrices ? await rptSchedule() : [];\n      // The basket's own total when the schedule came from the basket, so the\n      // cover, the schedule and checkout all show one figure. computeTotal() is\n      // the planner's estimate and has no delivery or discount code in it.\n      const reportTotal = !withPrices ? null\n        : (typeof schedule.total === 'number') ? schedule.total : computeTotal();\n\n      // Our own copy (jspdf@2.5.1 bundled), never a public CDN.\n      const { jsPDF } = await import('./btk-vendor-jspdf.js?v=1');\n      // \u26A0 compress: true is NOT the default. Without it jsPDF writes every\n      // stream RAW, so a full-page render is 2100 x 1485 x 3 bytes = 9.3MB of\n      // uncompressed pixels EACH. A two-unit plan came out at 74MB (Arden,\n      // 2026-09-26). This plus the JPEG re-encode below is the whole fix; it\n      // also shrinks the floor-plan overlay, which has to stay PNG for its\n      // transparency and compresses very well as line art.\n      const doc = new jsPDF({ orientation: 'landscape', unit: 'mm', format: 'a4', compress: true });\n      // Priced reports only, and not the copy kept with an order, already bought.\n      const campaign = (withPrices && !background) ? rptCampaignBanner() : null;\n      // ---- 1. Cover -------------------------------------------------------\n      // The same bar as every other page, with the date at the far end.\n      rptHeaderBar(doc, 'Bedroom plan report', logo, dateStr);\n\n      // Hero stops short of the text block, which in turn stops short of the\n      // footer bar the cover now carries like every other page.\n      doc.setFillColor(246, 246, 246);\n      doc.rect(0, RPT_HEADER_H, RPT.W, 168 - RPT_HEADER_H, 'F');\n      if (hero) rptFitImage(doc, hero.url, hero.w, hero.h, 0, RPT_HEADER_H, RPT.W, 168 - RPT_HEADER_H, hero.fmt);\n      if (campaign) rptCampaignStrip(doc, campaign, 0, RPT_HEADER_H, RPT.W, 12);\n\n      rptText(doc, planName, RPT.M, 180, { size: 20, bold: true });\n      rptText(doc,\n        `Room ${Math.round(bbox.widthMm)} x ${Math.round(bbox.heightMm)} mm` +\n        `   \u00B7   ${cabinets.length} unit${cabinets.length === 1 ? '' : 's'}`,\n        RPT.M, 187, { size: 10, colour: RPT.mute });\n      if (withPrices) {\n        // The price the basket shows as Today's Price, with the high street\n        // price struck through and the saving - the report goes out by email\n        // and is read on a phone, so the cover carries it (Julian, 2026-10-19).\n        rptPriceBadge(doc, reportTotal, schedule.summary, fmt, RPT.W - RPT.M - 128, 171, 128, 23);\n      } else {\n        rptText(doc, RPT_COVER_BLURB_PLAN_ONLY,\n                RPT.W / 2, 176, { size: 8.5, colour: RPT.mute, maxW: RPT.W / 2 - RPT.M });\n      }\n\n      // ---- 2. Full-page 3D views -----------------------------------------\n      for (const v of views) {\n        doc.addPage();\n        // Full-bleed, with the two bars laid over it rather than inset - the\n        // render still fills the page and the furniture behind a bar is never\n        // the part you were looking at.\n        // Fitted between the two bars, as large as the page allows and with\n        // nothing cropped off the render.\n        const im = v.trim || { url: v.img, w: PW, h: PH, fmt: 'PNG' };\n        rptFitImage(doc, im.url, im.w, im.h, 0, 20, RPT.W, RPT.H - 20 - 14, im.fmt);\n        rptHeaderBar(doc, v.title, logo);\n      }\n      // The Lifestyle photo after the 3D views, with a line under it saying\n      // what is illustration and what is the kitchen.\n      if (lifestyle) {\n        doc.addPage();\n        rptFitImage(doc, lifestyle.url, lifestyle.w, lifestyle.h, 0, 20, RPT.W, RPT.H - 20 - 14 - 8, lifestyle.fmt);\n        rptHeaderBar(doc, 'Lifestyle view', logo);\n        rptText(doc, RPT_LIFESTYLE_NOTE, RPT.M, RPT.H - 14 - 3, { size: 8, colour: RPT.mute });\n      }\n\n      // ---- 3. Floor plan --------------------------------------------------\n      doc.addPage();\n      rptHeaderBar(doc, 'Floor plan', logo);\n      const drewPlan = await rptDrawFloorPlan(doc, {\n        x: RPT.M, y: 26, w: RPT.W - RPT.M * 2, h: RPT.H - 26 - 20\n      });\n      if (!drewPlan) rptText(doc, 'The floor plan could not be generated.', RPT.M, 40, { size: 10, colour: RPT.mute });\n      else rptHeightKey(doc);\n\n      // ---- 3a. Notes: each unit's and item's note, by its number on the plan\n      await rptUnitNotesPages(doc, logo);\n\n      // ---- 3b. Check your measurements: the room alone, then the list -----\n      await rptRoomCheckPages(doc, logo);\n\n      // ---- 4. Plan schedule ----------------------------------------------\n      // Plan Only has no schedule at all: no list, no prices, no total.\n      if (withPrices) {\n        doc.addPage();\n        rptHeaderBar(doc, 'Plan schedule', logo);\n        // Columns total the 265mm between the margins.\n        // No SKU column: the planner's catalogue never carried a unit variant's\n        // sku (only worktops do), so it printed '-' on every row for a customer\n        // who has no use for it anyway. Its 34mm went to Item, which was\n        // truncating most unit names (Arden, 2026-09-26). Still totals the 265mm\n        // between the margins.\n        // Was = the high street price, struck through where the line is\n        // cheaper, beside the online price in red - the saving the basket shows\n        // on each line (Julian, 2026-10-19).\n        const COLS = [\n          { key: 'num',     label: '#',       w: 13,  align: 'left'  },\n          { key: 'title',   label: 'Item',    w: 115, align: 'left'  },\n          { key: 'options', label: 'Options', w: 66,  align: 'left'  },\n          { key: 'qty',     label: 'Qty',     w: 13,  align: 'right' },\n          { key: 'was',     label: 'Was',     w: 27,  align: 'right' },\n          { key: 'price',   label: 'Price',   w: 31,  align: 'right' }\n        ];\n        const TABLE_TOP = 30, TABLE_BOTTOM = RPT.H - 20, ROW_H = 7;\n        const colX = (i) => RPT.M + COLS.slice(0, i).reduce((a, c) => a + c.w, 0);\n\n        const drawTableHead = (y) => {\n          doc.setFillColor(...RPT.red);\n          doc.rect(RPT.M, y, RPT.W - RPT.M * 2, 8, 'F');\n          COLS.forEach((c, i) => {\n            const x = c.align === 'right' ? colX(i) + c.w - 2 : colX(i) + 2;\n            rptText(doc, c.label, x, y + 5.5, { size: 8.5, bold: true, colour: [255, 255, 255], align: c.align });\n          });\n          return y + 8;\n        };\n\n        let firstTop = TABLE_TOP;\n        if (campaign) {\n          rptCampaignStrip(doc, campaign, RPT.M, RPT_HEADER_H + 4, RPT.W - RPT.M * 2, 11);\n          firstTop = RPT_HEADER_H + 19;\n        }\n        let ty = drawTableHead(firstTop);\n        let zebra = false;\n        // A group's heading, as the basket's: its name, item count and total.\n        const groupLabels = schedule.groupLabels || null;\n        const groupSum = (g) => schedule.filter(r => r.group === g).reduce((s, r) => s + (r.price || 0), 0);\n        const groupCount = (g) => schedule.filter(r => r.group === g).reduce((n, r) => n + (Number(r.qty) || 1), 0);\n        const GROUP_H = 8;\n        const drawGroupHead = (g, y, continued) => {\n          const label = groupLabels.get(g) || '';\n          doc.setFillColor(232, 232, 228);\n          doc.rect(RPT.M, y, RPT.W - RPT.M * 2, GROUP_H, 'F');\n          rptText(doc, continued ? `${label} (continued)` : label, RPT.M + 2, y + 5.5, { size: 9.5, bold: true });\n          if (!continued) {\n            if (g !== 'delivery' && g !== 'discounts') {\n              const n = groupCount(g);\n              doc.setFont('helvetica', 'bold'); doc.setFontSize(9.5);\n              rptText(doc, `${n} ${n === 1 ? 'item' : 'items'}`, RPT.M + 2 + doc.getTextWidth(label) + 4, y + 5.5, { size: 8.5, colour: RPT.mute });\n            }\n            rptText(doc, fmt.format(groupSum(g)), RPT.W - RPT.M - 2, y + 5.5, { size: 9.5, bold: true, align: 'right' });\n          }\n          return y + GROUP_H;\n        };\n        let inGroup = null;\n        if (!schedule.length) {\n          rptText(doc, 'No units have been placed in this plan yet.', RPT.M + 2, ty + 8,\n                  { size: 10, colour: RPT.mute });\n          ty += 14;\n        }\n        for (const r of schedule) {\n          const grouped = !!(groupLabels && groupLabels.has(r.group));\n          const starts = grouped && r.group !== inGroup;\n          // A heading never sits alone at the foot of a page.\n          if (ty + ROW_H + (starts ? GROUP_H : 0) > TABLE_BOTTOM) {\n            doc.addPage();\n            rptHeaderBar(doc, 'Plan schedule (continued)', logo);\n            ty = drawTableHead(TABLE_TOP);\n            zebra = false;\n            if (grouped && !starts) ty = drawGroupHead(r.group, ty, true);\n          }\n          if (starts) {\n            ty = drawGroupHead(r.group, ty, false);\n            inGroup = r.group;\n            zebra = false;\n          }\n          if (zebra) {\n            doc.setFillColor(248, 248, 246);\n            doc.rect(RPT.M, ty, RPT.W - RPT.M * 2, ROW_H, 'F');\n          }\n          zebra = !zebra;\n          const reduced = (r.was || 0) > (r.price || 0) + 0.005 && (r.price || 0) >= 0;\n          const cell = { ...r, price: fmt.format(r.price || 0), was: reduced ? fmt.format(r.was) : '' };\n          COLS.forEach((c, i) => {\n            const x = c.align === 'right' ? colX(i) + c.w - 2 : colX(i) + 2;\n            let val = cell[c.key] == null ? '' : String(cell[c.key]);\n            if (c.key === 'title' && r.dims) val += `  (${r.dims})`;\n            if (c.key === 'was') {\n              if (val) rptStruck(doc, val, x, ty + 4.8, { size: 8, colour: RPT.mute, align: 'right' });\n              return;\n            }\n            // One line per row - trimmed rather than wrapped, so the table keeps\n            // a fixed grid and the plan numbers line up down the page.\n            const lines = doc.splitTextToSize(val, c.w - 4);\n            const isPrice = c.key === 'price';\n            const priceColour = (r.price || 0) < 0 ? RPT.green : (reduced ? RPT.red : RPT.ink);\n            rptText(doc, lines[0] + (lines.length > 1 ? '\u2026' : ''), x, ty + 4.8,\n                    { size: 8.5, bold: c.key === 'num' || (isPrice && (reduced || (r.price || 0) < 0)),\n                      align: c.align, colour: isPrice ? priceColour : RPT.ink });\n          });\n          doc.setDrawColor(...RPT.rule);\n          doc.line(RPT.M, ty + ROW_H, RPT.W - RPT.M, ty + ROW_H);\n          ty += ROW_H;\n        }\n\n        if (ty + 16 > TABLE_BOTTOM) {\n          doc.addPage();\n          rptHeaderBar(doc, 'Plan schedule (continued)', logo);\n          ty = TABLE_TOP;\n        }\n        ty += 4;\n        const sum = schedule.summary || null;\n        if (sum && sum.savingGbp > 0.005) {\n          rptText(doc, `You save ${fmt.format(sum.savingGbp)}`,\n                  RPT.W - RPT.M - 94, ty + 6.5, { size: 9.5, bold: true, colour: RPT.green, align: 'right' });\n        }\n        doc.setFillColor(...RPT.red);\n        doc.rect(RPT.W - RPT.M - 90, ty, 90, 10, 'F');\n        rptText(doc, \"Today's Price (inc. VAT)\", RPT.W - RPT.M - 86, ty + 6.5, { size: 9.5, bold: true, colour: [255, 255, 255] });\n        rptText(doc, fmt.format(reportTotal), RPT.W - RPT.M - 4, ty + 6.5,\n                { size: 9.5, bold: true, colour: [255, 255, 255], align: 'right' });\n        ty += 10;\n\n        // The offers on this quote, each a big red panel with when it ends,\n        // straight after the total (Arden, 2026-10-19).\n        const quoteOffers = ((sum && sum.offers) || []).filter(o => o && o.title);\n        if (quoteOffers.length) {\n          ty += 8;\n          for (const o of quoteOffers) {\n            if (ty + RPT_OFFER_PANEL_H > TABLE_BOTTOM) {\n              doc.addPage();\n              rptHeaderBar(doc, 'Your offers', logo);\n              ty = TABLE_TOP;\n            }\n            rptOfferPanel(doc, o, fmt, RPT.M, ty, RPT.W - RPT.M * 2);\n            ty += RPT_OFFER_PANEL_H + 5;\n          }\n        }\n\n        // ---- 4b. Your price -----------------------------------------------\n        // The basket's Price Breakdown and Current Offers on one page, so the\n        // emailed report shows the same price, offers and saving the customer\n        // sees in the planner (Julian, 2026-10-19).\n        if (sum) {\n          doc.addPage();\n          rptHeaderBar(doc, 'Your price', logo);\n          if (campaign) rptCampaignStrip(doc, campaign, RPT.M, RPT_HEADER_H + 4, RPT.W - RPT.M * 2, 11);\n          rptYourPricePage(doc, reportTotal, sum, fmt, campaign ? 40 : 32);\n        }\n      }\n\n      // ---- 5. Terms -------------------------------------------------------\n      doc.addPage();\n      rptHeaderBar(doc, 'Terms and notes', logo);\n      let ny = 34;\n      const COL_W = (RPT.W - RPT.M * 2 - 12) / 2;\n      let col = 0;\n      // No prices in Plan Only, so no paragraph about them.\n      for (const [heading, body] of RPT_TERMS.filter(([h]) => withPrices || h !== 'Pricing')) {\n        const x = RPT.M + col * (COL_W + 12);\n        const after = rptText(doc, heading, x, ny, { size: 10.5, bold: true, colour: RPT.red });\n        ny = rptText(doc, body, x, after + 2, { size: 8.5, colour: RPT.ink, maxW: COL_W }) + 6;\n        // Second column once the first runs past the page.\n        if (ny > RPT.H - 34 && col === 0) { col = 1; ny = 34; }\n      }\n\n      // ---- Black footer bar, every page including the cover ---------------\n      // Who the plan is for and what it is called - the two things worth\n      // having on every sheet if the report is split up or printed loose.\n      // The red bar above says which section you are in, so neither repeats\n      // the other. Stamped last, because \"of N\" isn't known until the\n      // schedule has taken as many pages as it needs.\n      const total = doc.getNumberOfPages();\n      // Whose plan this is - NOT who is signed in. When a salesperson is working\n      // on a customer's plan the Shopify session is the salesperson's, so\n      // context.customerName is THEIR name: printing it would put the wrong\n      // person on every page of the customer's own report.\n      const who = (window.BTKBasketAPI && window.BTKBasketAPI.isStaffMode\n                   && window.BTKBasketAPI.isStaffMode())\n        ? (window.BTKBasketAPI.actingAsName && window.BTKBasketAPI.actingAsName()) || null\n        : (context.customerName || null);\n      for (let i = 1; i <= total; i++) {\n        doc.setPage(i);\n        doc.setFillColor(...RPT.black);\n        doc.rect(0, RPT.H - 14, RPT.W, 14, 'F');\n        let fx = RPT.M;\n        if (who) {\n          rptText(doc, who, fx, RPT.H - 5, { size: 9, bold: true, colour: [255, 255, 255] });\n          fx += doc.getTextWidth(who) + 4;\n          rptText(doc, '\u00B7', fx, RPT.H - 5, { size: 9, colour: [150, 150, 150] });\n          fx += 3;\n        }\n        rptText(doc, planName, fx, RPT.H - 5,\n                { size: 9, bold: !who, colour: who ? [225, 225, 225] : [255, 255, 255] });\n        rptText(doc, `Page ${i} of ${total}`, RPT.W - RPT.M, RPT.H - 5,\n                { size: 9, colour: [235, 235, 235], align: 'right' });\n      }\n\n      const safe = planName.replace(/[^\\w\\d\\- ]+/g, '').trim().replace(/\\s+/g, '-') || 'kitchen-plan';\n      if (mode === 'blob') return { blob: doc.output('blob'), planName, filename: `${safe}-plan-report.pdf` };\n      doc.save(withPrices ? `${safe}-plan-report.pdf` : `${safe}-plan.pdf`);\n    } catch (e) {\n      console.error('[BTK Kitchen Planner] Report failed', e);\n      // ?btktime=1: the actual error, on screen. console.log is filtered in\n      // this storefront, so without this the exception reaches nobody and the\n      // only way to find a fault is to guess at it. Temporary.\n      let _why = '';\n      try {\n        if (new URLSearchParams(window.location.search).get('btktime') === '1') {\n          _why = String((e && (e.stack || e.message)) || e).slice(0, 700);\n        }\n      } catch (_) {}\n      // A background build failing is not the customer's problem - they lose\n      // the PDF on the order, not the order.\n      if (!background) {\n        window.BTKKPDialog?.alert?.(_why\n          ? ('The plan report could not be generated.' + String.fromCharCode(10)\n             + String.fromCharCode(10) + _why)\n          : 'The plan report could not be generated. Please try again.',\n                                    { title: 'Report' });\n      }\n    } finally {\n      // prevDisp is only set if something hid the viewport (the floor-plan\n      // capture does, briefly). Restore only when it did.\n      if (viewport3D && prevDisp !== null) viewport3D.style.display = prevDisp;\n      loader?.hide?.();\n    }\n  }\n\n\n  // \u2500\u2500 My Kitchen Manual \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n  // The manual for a BOUGHT kitchen (Arden, 2026-10-26), built here for the\n  // same reason as the plan report: the views and floor plan come from the\n  // live renderer. The words come from the planner API - the installation\n  // guide Claude wrote from the Fitting rule entries, the always-printed\n  // \"before you start\" rules, and the order lines - all frozen when the guide\n  // was written. Only ever run from the bought-plan viewer, on the plan exactly\n  // as it was ordered. Staff build it, check it and approve it; the approved\n  // file is what the customer and their fitter download.\n  //\n  // Pages: cover, your kitchen, the 3D views, floor plan, what's in your\n  // delivery (no prices), getting ready, the installation guide, help.\n  // An appliance line in the order: no door/carcase colour (units, panels and\n  // housings carry one) and an appliance word in its name. Same test as the\n  // server's kitchen-manual-pdf.js appliancesOrdered.\n  function kmAppliancesOrdered(lines) {\n    return (lines || []).some(l => !String(l.colour || '').trim()\n      && /\\b(oven|hob|microwave|dishwasher|fridge|freezer|extractor|cooker hood|hood|washing machine|washer dryer|tumble dryer|wine cooler|warming drawer|coffee machine|range cooker)\\b/i.test(String(l.name || ''))\n      && !/\\b(housing|unit|panel|filler|door|plinth|cornice|pelmet)\\b/i.test(String(l.name || '')));\n  }\n\n  async function buildKitchenManual(m) {\n    const order = (m && m.order) || {};\n    const guide = (m && m.guide) || { intro: '', steps: [] };\n    const fixed = (m && m.fixed) || [];\n    const lines = Array.isArray(order.lines) ? order.lines : [];\n    await ensure3DReady();\n    handle3D?.render({ room, roomConfig, openingFaceInsets: openingFaceInsetMap(), cabinets, baseRoom, featureStyles, railFinishHandle, segmentColours, worktops: buildWorktops(), worktopColourHex, worktopColours, worktopCornerRadii, worktopItems: worktopItems3D(), furnitureItems, handleGroups, lights, lightsOn });\n    await new Promise(r => setTimeout(r, 1500));\n    const PW = 2100, PH = 1485;\n    const views = [];\n    for (const v of [\n      { key: 'iso',  title: 'Three-dimensional view - 1' },\n      { key: 'iso2', title: 'Three-dimensional view - 2' },\n      { key: 'top',  title: 'Overhead view' }\n    ]) {\n      await rptYield();\n      const img = handle3D?.snapshotOffscreen?.({ view: v.key, width: PW, height: PH })\n               || handle3D?.snapshot?.({ view: v.key, width: PW, height: PH }) || null;\n      if (!img) continue;\n      await rptYield();\n      views.push({ ...v, img, trim: await rptTrim(img) });\n    }\n    await rptYield();\n    const heroRaw = handle3D?.snapshotOffscreen?.({ view: 'plan', width: 2100, height: 1200 })\n                 || handle3D?.snapshot?.({ view: 'plan', width: 2100, height: 1200 }) || null;\n    const hero = heroRaw ? await rptTrim(heroRaw) : null;\n    const logo = await rptWhiteLogo();\n    const planName = order.planName || activePlanName || 'Your bedroom';\n    const who = order.customer || '';\n    const ref = String((m && m.orderRef) || '').replace(/^Online Order\\s*/i, '').trim();\n    const dateStr = new Date().toLocaleDateString('en-GB', { day: 'numeric', month: 'long', year: 'numeric' });\n\n    // Style and colours as the order lines name them: the range is the part\n    // of the title before the first \" - \" that most lines share.\n    const counts = {};\n    for (const l of lines) { const head = String(l.name || '').split(' - ')[0].trim(); if (head) counts[head] = (counts[head] || 0) + 1; }\n    const styleName = Object.keys(counts).sort((a, b) => counts[b] - counts[a])[0] || '';\n    // A unit line carries both colours (Door / Carcase); panels only the door.\n    const doorColour = (lines.find(l => String(l.colour || '').includes(' / ')) || lines.find(l => l.colour) || {}).colour || '';\n    const [doorName, carcaseName] = doorColour.split(' / ');\n    const unitLines = lines.filter(l => l.assembly);   // units carry an assembly choice\n\n    const { jsPDF } = await import('./btk-vendor-jspdf.js?v=1');\n    const doc = new jsPDF({ orientation: 'landscape', unit: 'mm', format: 'a4', compress: true });\n    const LH = (size, lh = 1.35) => size * 0.3528 * lh;\n    const BOTTOM = RPT.H - 20;\n\n    // ---- 1. Cover ---------------------------------------------------------\n    rptHeaderBar(doc, 'My Bedroom Manual', logo, dateStr);\n    doc.setFillColor(246, 246, 246);\n    doc.rect(0, RPT_HEADER_H, RPT.W, 168 - RPT_HEADER_H, 'F');\n    if (hero) rptFitImage(doc, hero.url, hero.w, hero.h, 0, RPT_HEADER_H, RPT.W, 168 - RPT_HEADER_H, hero.fmt);\n    rptText(doc, planName, RPT.M, 180, { size: 20, bold: true });\n    rptText(doc, [styleName, doorName && carcaseName ? `${doorName} on ${carcaseName}` : doorName].filter(Boolean).join('   \u00B7   '),\n            RPT.M, 187, { size: 10, colour: RPT.mute, maxW: RPT.W / 2 });\n    if (ref) {\n      doc.setFillColor(...RPT.red);\n      doc.roundedRect(RPT.W - RPT.M - 90, 171, 90, 23, 2, 2, 'F');\n      rptText(doc, 'YOUR ORDER', RPT.W - RPT.M - 84, 179, { size: 8, bold: true, colour: [255, 255, 255] });\n      rptText(doc, ref, RPT.W - RPT.M - 84, 188, { size: 15, bold: true, colour: [255, 255, 255] });\n    }\n\n    // ---- 2. Your kitchen ---------------------------------------------------\n    doc.addPage();\n    rptHeaderBar(doc, 'Your bedroom', logo);\n    let y = 34;\n    y = rptText(doc, 'This manual holds everything about the bedroom you ordered: how it looks, every item in your delivery, '\n      + 'and an installation guide for this layout. Keep it with your bedroom and pass it on to your fitter.',\n      RPT.M, y, { size: 10, maxW: RPT.W - RPT.M * 2 }) + 6;\n    const colW = (RPT.W - RPT.M * 2 - 16) / 2;\n    const spec = [\n      ['Bedroom style', styleName],\n      ['Door colour', doorName],\n      ['Cabinet colour', carcaseName],\n      ['Room', order.room ? `${order.room.widthMm} x ${order.room.depthMm} mm` : ''],\n      ['Units', unitLines.length ? String(unitLines.reduce((a, l) => a + (l.qty || 1), 0)) : ''],\n      ['Units supplied', [...new Set(unitLines.map(l => l.assembly))].join(', ')],\n    ].filter(([, v]) => v);\n    let sy = y;\n    rptText(doc, 'Style and colours', RPT.M, sy, { size: 11, bold: true, colour: RPT.red });\n    sy += 4;\n    for (const [k, v] of spec) {\n      rptText(doc, k, RPT.M, sy + 5, { size: 9.5, colour: RPT.mute });\n      rptText(doc, v, RPT.M + 45, sy + 5, { size: 9.5, bold: true, maxW: colW - 45 });\n      doc.setDrawColor(...RPT.rule); doc.line(RPT.M, sy + 8, RPT.M + colW, sy + 8);\n      sy += 8;\n    }\n    const rx = RPT.M + colW + 16;\n    let ry = y;\n    rptText(doc, 'In your bedroom', rx, ry, { size: 11, bold: true, colour: RPT.red });\n    ry += 6;\n    const feats = [...new Set(unitLines.map(l => String(l.name || '').split(' - ').slice(styleName && String(l.name).startsWith(styleName) ? 1 : 0).join(' - ').replace(/\\s*-\\s*[\\d\\/ .A-Za-z]*$/, '').trim()))].filter(Boolean).slice(0, 14);\n    for (const f of feats) { ry = rptText(doc, '\u2022  ' + f, rx, ry, { size: 9.5, maxW: colW }) + 0.5; }\n    ry += 4;\n    rptText(doc, 'Not part of this order', rx, ry, { size: 11, bold: true, colour: RPT.red });\n    ry += 6;\n    // Appliances bought with the kitchen are in the delivery list, so only\n    // the rest are \"not ours\" (WKIT-SO300152 had a CDA oven and microwave and\n    // was told appliances weren't part of the order - Arden, 2026-11-13).\n    const notOurs = [kmAppliancesOrdered(lines) ? 'Any appliances not in your delivery list' : 'Appliances (oven, hob, dishwasher, fridge and so on)'];\n    if (!order.worktopOrdered) notOurs.push('Worktop, sink and tap');\n    if (!order.handles && !order.trueHandleless) notOurs.push('Handles');\n    for (const f of notOurs) { ry = rptText(doc, '\u2022  ' + f, rx, ry, { size: 9.5, maxW: colW }) + 0.5; }\n\n    // ---- 3. Views and floor plan --------------------------------------------\n    for (const v of views) {\n      doc.addPage();\n      const im = v.trim || { url: v.img, w: PW, h: PH, fmt: 'PNG' };\n      rptFitImage(doc, im.url, im.w, im.h, 0, 20, RPT.W, RPT.H - 20 - 14, im.fmt);\n      rptHeaderBar(doc, v.title, logo);\n    }\n    doc.addPage();\n    rptHeaderBar(doc, 'Floor plan', logo);\n    const drewPlan = await rptDrawFloorPlan(doc, { x: RPT.M, y: 26, w: RPT.W - RPT.M * 2, h: RPT.H - 26 - 20 });\n    if (!drewPlan) rptText(doc, 'The floor plan could not be generated.', RPT.M, 40, { size: 10, colour: RPT.mute });\n    else {\n      rptHeightKey(doc);\n      // Units left out of the order show a red cross on the plan in place of\n      // their number: say what it means (WKIT-SO300152, Arden 2026-11-13).\n      if ((cabinets || []).some(c => c && c.excludeFromQuote === true)) {\n        rptText(doc, 'A red cross marks a unit that is in the plan but not part of this order.', RPT.W - RPT.M, RPT.H - 14 - 3,\n          { size: 8, colour: RPT.mute, align: 'right' });\n      }\n    }\n\n    // ---- 4. What's in your delivery: the order lines, no prices -------------\n    doc.addPage();\n    rptHeaderBar(doc, \"What's in your delivery\", logo);\n    const COLS = [\n      { key: 'item',     label: '#',        w: 12  },\n      { key: 'wall',     label: 'Wall',     w: 26  },\n      { key: 'name',     label: 'Item',     w: 134 },\n      { key: 'colour',   label: 'Colour',   w: 48  },\n      { key: 'hinge',    label: 'Hinge',    w: 15  },\n      { key: 'assembly', label: 'Assembly', w: 30  }\n    ];\n    const colX = (i) => RPT.M + COLS.slice(0, i).reduce((a, c) => a + c.w, 0);\n    const head = (yy) => {\n      doc.setFillColor(...RPT.red);\n      doc.rect(RPT.M, yy, RPT.W - RPT.M * 2, 8, 'F');\n      COLS.forEach((c, i) => rptText(doc, c.label, colX(i) + 2, yy + 5.5, { size: 8.5, bold: true, colour: [255, 255, 255] }));\n      rptText(doc, 'Qty', RPT.W - RPT.M - 2, yy + 5.5, { size: 8.5, bold: true, colour: [255, 255, 255], align: 'right' });\n      return yy + 8;\n    };\n    let ty = head(30), zebra = false;\n    for (const l of lines) {\n      if (ty + 7 > BOTTOM) { doc.addPage(); rptHeaderBar(doc, \"What's in your delivery (continued)\", logo); ty = head(30); zebra = false; }\n      if (zebra) { doc.setFillColor(248, 248, 246); doc.rect(RPT.M, ty, RPT.W - RPT.M * 2, 7, 'F'); }\n      zebra = !zebra;\n      COLS.forEach((c, i) => {\n        const val = String(l[c.key] == null ? '' : l[c.key]);\n        const cut = doc.splitTextToSize(val, c.w - 4);\n        rptText(doc, (cut[0] || '') + (cut.length > 1 ? '\u2026' : ''), colX(i) + 2, ty + 4.8, { size: 8.5, bold: c.key === 'item' });\n      });\n      rptText(doc, String(l.qty || 1), RPT.W - RPT.M - 2, ty + 4.8, { size: 8.5, align: 'right' });\n      doc.setDrawColor(...RPT.rule); doc.line(RPT.M, ty + 7, RPT.W - RPT.M, ty + 7);\n      ty += 7;\n    }\n    if (ty + 10 < BOTTOM) rptText(doc, 'Check your delivery against this list on the day, and tell us about anything missing or damaged within 48 hours.',\n      RPT.M, ty + 7, { size: 8.5, colour: RPT.mute });\n\n    // ---- 4b. Panel cut plans ------------------------------------------------\n    // End panels and fillers are cut from stock boards (the nester in\n    // engine-end-panel-yield) and the delivery lists BOARDS, not panels. Each\n    // board is drawn to scale with its pieces lettered and its factory-\n    // finished edges bold, so the installation guide can say \"cut from board\n    // #4\" and the fitter can see where (Arden, 2026-10-26). Same layout the\n    // planner priced the order from, so the pieces match the delivery.\n    // Only boards that are lines in THIS order are drawn. A plan with units\n    // left out of the order still nests their panels, onto boards with no\n    // number (\"Board #null\" on WKIT-SO300152, Arden 2026-11-13). Their pieces\n    // for units that ARE in the order are listed after the boards instead;\n    // pieces only for units left out of the order are dropped.\n    const cpOrdered = new Set(lines.map(l => String(l.item)).filter(Boolean));\n    const cpAll = ((endPanelLayout && endPanelLayout.boards) || [])\n      .filter(b => b && !b.acoustic && (b.pieces || []).length && b.depthMm > 0 && b.heightMm > 0);\n    const cpBoards = cpAll.filter(b => b.itemNumber != null && cpOrdered.has(String(b.itemNumber)))\n      .sort((a, b) => (a.itemNumber || 0) - (b.itemNumber || 0));\n    const cpInOrder = (face) => ((face && face.cabIds) || []).some(id => {\n      const c = cabinets.find(cc => cc.id === id);\n      return c && !c.excludeFromQuote && c.displayNumber != null;\n    });\n    const cpLoose = cpAll.filter(b => !cpBoards.includes(b))\n      .flatMap(b => b.pieces.filter(p => cpInOrder(p.face)));\n    if (cpBoards.length || cpLoose.length) {\n      const CP_ROLE = { base: 'Base end panel', tall: 'Tall end panel', ceiling: 'Ceiling filler', wall: 'Wall end panel',\n                        dresser: 'Dresser end panel', filler: 'Filler', 'breakfast-bar': 'Breakfast bar panel', under: 'Under panel' };\n      const cpFor = (face) => {\n        const nums = ((face && face.cabIds) || []).map(id => {\n          const c = cabinets.find(cc => cc.id === id);\n          return c && c.displayNumber != null ? '#' + c.displayNumber : null;\n        }).filter(Boolean);\n        const side = face && face.side;\n        const sideTxt = (side === 'left' || side === 'right') ? ` ${side} side` : (side === 'back' ? ' back' : '');\n        return nums.length ? `for ${nums.join(', ')}${sideTxt}` : '';\n      };\n      const cpName = (n) => {\n        const l = lines.find(x => String(x.item) === String(n));\n        const nm = l ? String(l.name || '') : '';\n        return styleName && nm.startsWith(styleName + ' - ') ? nm.slice(styleName.length + 3) : nm;\n      };\n      // One scale for every board, so their sizes compare at a glance.\n      const cpScale = 118 / Math.max(1, ...cpBoards.map(b => b.heightMm));\n      const CP_LIST_W = 64, CP_TOP = 44;\n      let cpx = RPT.M, cpy = CP_TOP, cpRowH = 0;\n      let cpLast = null;   // where the last board's piece list ended\n      const cpPageNo = () => doc.getNumberOfPages();\n      const cpPage = (cont) => {\n        doc.addPage();\n        rptHeaderBar(doc, cont ? 'Panel cut plans (continued)' : 'Panel cut plans', logo);\n        rptText(doc, 'Each end panel and filler is cut from a board in your delivery, numbered as in the item list. '\n          + 'The pieces are lettered. Bold edges are the board\\'s factory-finished edges: they face the front of the unit '\n          + '(and the bottom of a wall end panel). Grey areas are off-cuts. The cuts allow 5 mm for the saw.',\n          RPT.M, 28, { size: 8.5, colour: RPT.mute, maxW: RPT.W - RPT.M * 2 });\n        cpx = RPT.M; cpy = CP_TOP; cpRowH = 0;\n      };\n      cpPage(false);\n      for (const b of cpBoards) {\n        const bw = b.depthMm * cpScale, bh = b.heightMm * cpScale;\n        const blockW = bw + 6 + CP_LIST_W;\n        const blockH = Math.max(bh, 14 + b.pieces.length * 10) + 12;\n        if (cpx + blockW > RPT.W - RPT.M) { cpx = RPT.M; cpy += cpRowH + 8; cpRowH = 0; }\n        if (cpy + blockH > BOTTOM) cpPage(true);\n        rptText(doc, `Board #${b.itemNumber}`, cpx, cpy, { size: 10, bold: true, colour: RPT.red });\n        rptText(doc, cpName(b.itemNumber), cpx, cpy + 4.5, { size: 7.5, colour: RPT.mute, maxW: blockW });\n        const oy = cpy + 11;\n        // The board: grey is off-cut, the pieces are laid over it.\n        doc.setFillColor(232, 232, 232); doc.setDrawColor(...RPT.ink); doc.setLineWidth(0.3);\n        doc.rect(cpx, oy, bw, bh, 'FD');\n        b.pieces.forEach((p, i) => {\n          const x = cpx + p.x * cpScale, y = oy + bh - (p.y + p.h) * cpScale;\n          const w = p.w * cpScale, h = p.h * cpScale;\n          doc.setFillColor(214, 236, 221); doc.setDrawColor(...RPT.ink); doc.setLineWidth(0.25);\n          doc.rect(x, y, w, h, 'FD');\n          doc.setLineWidth(1.1); doc.setDrawColor(...RPT.black);\n          if (p.finL) doc.line(x, y, x, y + h);\n          if (p.finR) doc.line(x + w, y, x + w, y + h);\n          if (p.finT) doc.line(x, y, x + w, y);\n          if (p.finB) doc.line(x, y + h, x + w, y + h);\n          doc.setLineWidth(0.2);\n          if (w > 2.5 && h > 4) rptText(doc, String.fromCharCode(65 + i), x + w / 2, y + h / 2 + 1.3,\n            { size: Math.min(10, Math.max(5.5, w * 1.4)), bold: true, align: 'center' });\n        });\n        // The pieces, lettered as drawn: what each one is, who it is for, its size.\n        const lx = cpx + bw + 6;\n        let ly = oy + 3;\n        ly = rptText(doc, `Board ${Math.round(b.heightMm)} mm high x ${Math.round(b.depthMm)} mm wide`, lx, ly, { size: 7.5, colour: RPT.mute }) + 1;\n        b.pieces.forEach((p, i) => {\n          ly = rptText(doc, `${String.fromCharCode(65 + i)}   ${CP_ROLE[p.role] || 'Piece'} ${cpFor(p.face)}`.trim(),\n                       lx, ly, { size: 8, maxW: CP_LIST_W });\n          ly = rptText(doc, `${Math.round(p.h)} mm high x ${Math.round(p.w)} mm wide`, lx + 4.5, ly, { size: 7.5, colour: RPT.mute }) + 1.5;\n        });\n        cpLast = { x: lx, y: ly, page: cpPageNo() };\n        cpRowH = Math.max(cpRowH, bh + 11, ly - cpy);\n        cpx += blockW + 8;\n      }\n      // Pieces the plan needs for units in this order with no board for them\n      // in it: a plain list, under the boards.\n      // Placed in the first free space on the page: under the last board's\n      // piece list (tall boards leave that column mostly empty), else beside\n      // the last board, else below the boards, else on a new page\n      // (WKIT-SO300152's one line took a page of its own).\n      if (cpLoose.length) {\n        const lh = 14 + cpLoose.length * 5;\n        let lx = RPT.M, ly, lw = RPT.W - RPT.M * 2;\n        if (cpLast && cpLast.page === cpPageNo() && cpLast.y + 8 + lh <= BOTTOM) {\n          lx = cpLast.x; ly = cpLast.y + 8; lw = RPT.W - RPT.M - lx;\n        } else if (cpBoards.length && cpx + 92 <= RPT.W - RPT.M && cpy + lh <= BOTTOM) {\n          lx = cpx; ly = cpy; lw = 92;\n        } else ly = cpBoards.length ? cpy + cpRowH + 10 : CP_TOP;\n        if (ly + lh > BOTTOM) { cpPage(true); lx = RPT.M; ly = CP_TOP; lw = RPT.W - RPT.M * 2; }\n        rptText(doc, 'Not from a board in this order', lx, ly, { size: 10, bold: true, colour: RPT.red });\n        ly = rptText(doc, 'The plan has these pieces, but there is no board for them in this order.', lx, ly + 5,\n          { size: 8, colour: RPT.mute, maxW: lw }) + 1;\n        for (const p of cpLoose) {\n          if (ly + 6 > BOTTOM) { cpPage(true); lx = RPT.M; ly = CP_TOP; lw = RPT.W - RPT.M * 2; }\n          ly = rptText(doc, `\u2022  ${`${CP_ROLE[p.role] || 'Piece'} ${cpFor(p.face)}`.trim()}: ${Math.round(p.h)} mm high x ${Math.round(p.w)} mm wide`,\n            lx, ly, { size: 8.5, maxW: lw }) + 0.5;\n        }\n      }\n    }\n\n    // ---- 5 & 6. Getting ready, then the guide, flowed in two columns --------\n    // A column-flow writer: blocks drop to the next column, then the next page.\n    const GCOL = (RPT.W - RPT.M * 2 - 14) / 2;\n    let gPage = null, gCol = 0, gy = 0;\n    const startPage = (title) => { doc.addPage(); rptHeaderBar(doc, title, logo); gPage = title; gCol = 0; gy = 32; };\n    const need = (h, cont) => {\n      if (gy + h <= BOTTOM) return;\n      if (gCol === 0) { gCol = 1; gy = 32; return; }\n      startPage(cont);\n    };\n    const gx = () => RPT.M + gCol * (GCOL + 14);\n    const para = (txt, { size = 9, bold = false, colour = RPT.ink, indent = 0, gap = 1.6, cont } = {}) => {\n      const rows = doc.splitTextToSize(String(txt), GCOL - indent);\n      need(rows.length * LH(size) + gap, cont);\n      gy = rptText(doc, String(txt), gx() + indent, gy, { size, bold, colour, maxW: GCOL - indent }) + gap;\n    };\n    // The delivery this customer chose, in its own words from Odoo - who\n    // carries what and how many people are needed differ by delivery method,\n    // so no one rule can say it (Arden, 2026-10-26).\n    const delivery = order.delivery && order.delivery.description ? order.delivery : null;\n    if (fixed.length || delivery) {\n      startPage('Getting ready');\n      if (delivery) {\n        para(`Your delivery: ${delivery.name || 'Delivery'}`, { size: 11, bold: true, colour: RPT.red, gap: 1.2, cont: 'Getting ready (continued)' });\n        for (const s of String(delivery.description).split(/\\n+/).map(x => x.trim()).filter(Boolean)) {\n          para(s, { cont: 'Getting ready (continued)' });\n        }\n        gy += 3;\n      }\n      for (const r of fixed) {\n        need(LH(11) + LH(9) * 2 + 4, 'Getting ready (continued)');\n        para(r.title, { size: 11, bold: true, colour: RPT.red, gap: 1.2, cont: 'Getting ready (continued)' });\n        for (const s of r.steps || []) para('\u2022  ' + s, { indent: 0, cont: 'Getting ready (continued)' });\n        gy += 3;\n      }\n    }\n    // The guide, in two columns. Laid out once without drawing to measure it:\n    // when its last page would hold only a few lines (WKIT-SO300152's page 13\n    // had one), the spacing between steps is closed up so they fit on the page\n    // before (Arden, 2026-11-13). k scales the gaps, never the text.\n    const GC = 'Installation guide (continued)';\n    const flowGuide = (draw, k) => {\n      let pages = 0, col = 0, y = 0;\n      const start = () => {\n        pages++; col = 0; y = 32;\n        if (draw) { doc.addPage(); rptHeaderBar(doc, pages === 1 ? 'Installation guide for this bedroom' : GC, logo); }\n      };\n      const fit = (h) => { if (y + h <= BOTTOM) return; if (col === 0) { col = 1; y = 32; return; } start(); };\n      const put = (txt, { size = 9, bold = false, colour = RPT.ink, gap = 1.6 } = {}) => {\n        doc.setFont('helvetica', bold ? 'bold' : 'normal'); doc.setFontSize(size);\n        const rows = doc.splitTextToSize(String(txt), GCOL);\n        fit(rows.length * LH(size) + gap * k);\n        if (draw) rptText(doc, String(txt), RPT.M + col * (GCOL + 14), y, { size, bold, colour, maxW: GCOL });\n        y += rows.length * LH(size) + gap * k;\n      };\n      start();\n      if (guide.intro) put(guide.intro, { size: 9.5, gap: 4 });\n      (guide.steps || []).forEach((s, i) => {\n        // A heading keeps its first three lines with it; closed up, just the first.\n        fit(LH(11) + LH(9) * (k < 1 ? 1 : 3) + 6 * k);\n        put(`${i + 1}.  ${s.title}`, { size: 11, bold: true, colour: RPT.red, gap: 0.8 });\n        if (s.items) put(s.items, { size: 8.5, colour: RPT.mute, gap: 1.4 });\n        for (const p of s.points || []) put('\u2022  ' + p);\n        y += 3 * k;\n      });\n      return { pages, col, y };\n    };\n    let guideK = 1;\n    const guideFull = flowGuide(false, 1);\n    if (guideFull.pages > 1 && guideFull.col === 0 && guideFull.y < 32 + 45) {\n      for (const k of [0.7, 0.45]) { if (flowGuide(false, k).pages < guideFull.pages) { guideK = k; break; } }\n    }\n    flowGuide(true, guideK);\n\n    // ---- 7. Help and aftercare ---------------------------------------------\n    doc.addPage();\n    rptHeaderBar(doc, 'Help and aftercare', logo);\n    let hy = 34;\n    for (const [h, body] of [\n      ['Need a hand?', `Questions about your bedroom, parts or fitting can go to Better Bedrooms on 01934 813 201 or bettersupport@betteronline.co.uk.${ref ? ' Please quote order ' + ref + '.' : ''} You can download this manual again at any time from your Better Bedrooms account, and send it to your fitter from there.`],\n      ['About this guide', 'There are many ways to fit a bedroom, and the installation guide shows one of them. If you\\'re using a professional fitter, they may have their own preferred way of working. Always follow the appliance makers\\' instructions and current building regulations.'],\n      ['Looking after your bedroom', 'Clean every part of your units (doors, drawer fronts, panels and the cabinets inside) with a soft cloth that is damp, not wet, and a little mild washing-up liquid, then dry straight away. Never soak them or let water sit on them. Wipe up spills as they happen, and keep the units around the sink and dishwasher dry. Never use abrasive cleaners, scourers or steam cleaners anywhere on your bedroom units. Keep any touch-up paint for small chips.'],\n      ['Images', 'The views in this manual are drawn from your plan. Colours and finishes are shown as closely as the medium allows.']\n    ]) {\n      const after = rptText(doc, h, RPT.M, hy, { size: 10.5, bold: true, colour: RPT.red });\n      hy = rptText(doc, body, RPT.M, after + 2, { size: 9, maxW: RPT.W / 2 }) + 6;\n    }\n\n    // ---- Footer on every page ----------------------------------------------\n    const total = doc.getNumberOfPages();\n    for (let i = 1; i <= total; i++) {\n      doc.setPage(i);\n      doc.setFillColor(...RPT.black);\n      doc.rect(0, RPT.H - 14, RPT.W, 14, 'F');\n      let fx = RPT.M;\n      if (who) {\n        rptText(doc, who, fx, RPT.H - 5, { size: 9, bold: true, colour: [255, 255, 255] });\n        fx += doc.getTextWidth(who) + 4;\n        rptText(doc, '\u00B7', fx, RPT.H - 5, { size: 9, colour: [150, 150, 150] });\n        fx += 3;\n      }\n      rptText(doc, `My Bedroom Manual${ref ? ' \u00B7 ' + ref : ''}`, fx, RPT.H - 5, { size: 9, bold: !who, colour: who ? [225, 225, 225] : [255, 255, 255] });\n      rptText(doc, `Page ${i} of ${total}`, RPT.W - RPT.M, RPT.H - 5, { size: 9, colour: [235, 235, 235], align: 'right' });\n    }\n    return doc.output('blob');\n  }\n\n  function blobToBase64(blob) {\n    return new Promise((resolve, reject) => {\n      const r = new FileReader();\n      r.onload = () => resolve(String(r.result).split(',')[1] || '');\n      r.onerror = reject;\n      r.readAsDataURL(blob);\n    });\n  }\n\n  function saveBlob(blob, filename) {\n    const a = document.createElement('a');\n    a.href = URL.createObjectURL(blob);\n    a.download = filename;\n    a.setAttribute('data-btk-kp-save-file', '');   // let through the bought-plan viewer's lock\n    document.body.appendChild(a);\n    a.click();\n    setTimeout(() => { URL.revokeObjectURL(a.href); a.remove(); }, 4000);\n  }\n\n  // The Kitchen Manual button in the bought-plan viewer. Customers download\n  // the approved file. The server writes, builds and releases it on its own\n  // once the order is confirmed (Arden, 2026-11-13), so staff download the\n  // released copy or have it written again. Only a draft the server could not\n  // build (no plan report saved with the plan) is built here, checked and\n  // approved by staff as before.\n  async function kitchenManualAction() {\n    const api = window.BTKBasketAPI;\n    const dialog = window.BTKKPDialog;\n    const id = _bootOrdered;\n    if (!isStaffOrderedView()) {\n      window.location.href = `/apps/planner/my/kitchen-manual/${encodeURIComponent(id)}/pdf`;\n      return;\n    }\n    let m;\n    try { m = await api.kitchenManual(id); }\n    catch (e) { dialog?.alert?.('The Bedroom Manual could not be loaded just now. Please try again.', { title: 'Bedroom Manual' }); return; }\n    if (m.status === 'writing') {\n      dialog?.alert?.('The installation guide is being written. It takes about a minute; click Bedroom Manual again shortly.', { title: 'Bedroom Manual' });\n      return;\n    }\n    if (m.status === 'none' || m.status === 'failed' || !m.guide) {\n      const go = await dialog?.confirm?.(\n        (m.status === 'failed' ? 'Writing the installation guide failed last time.' : 'The installation guide for this order hasn\\'t been written yet. It is written automatically once the order is confirmed in Odoo.')\n        + '\\n\\nWrite it now?', { title: 'Bedroom Manual', confirmText: 'Write Guide' });\n      if (!go) return;\n      try { await api.rewriteKitchenManual(id); } catch (e) {}\n      dialog?.alert?.('The installation guide is being written. It takes about a minute; click Bedroom Manual again shortly.', { title: 'Bedroom Manual' });\n      refreshKitchenManualStatus({ watch: true });\n      return;\n    }\n    if (m.status === 'approved' && typeof api.kitchenManualPdf === 'function') {\n      const when = m.approvedAt ? new Date(m.approvedAt).toLocaleDateString('en-GB', { day: 'numeric', month: 'long', year: 'numeric' }) : '';\n      const ref0 = String(m.orderRef || 'Order').replace(/^Online Order\\s*/i, '').replace(/[^\\w-]+/g, '');\n      const again = await dialog?.confirm?.(\n        `This manual was released to the customer${when ? ' on ' + when : ''}. Download it to see exactly what they have.\\n\\nIf the installation guide needs changing, choose Write Again. It is written, built and released again in about a minute.`,\n        { title: 'Bedroom Manual', confirmText: 'Write Again', cancelText: 'Close',\n          // The button itself shows Downloading..., Downloaded or Try Again.\n          extra: { text: 'Download', onClick: async () => {\n            try { saveBlob(await api.kitchenManualPdf(id), `${ref0}-Bedroom-Manual.pdf`); return true; }\n            catch (e) { return false; }\n          } } });\n      if (again) {\n        try { await api.rewriteKitchenManual(id); } catch (e) {}\n        dialog?.alert?.('The installation guide is being written again. It is released to the customer again once it is ready, in about a minute.', { title: 'Bedroom Manual' });\n        refreshKitchenManualStatus({ watch: true });\n      }\n      return;\n    }\n    const loader = window.BTKLoader;\n    let blob;\n    try {\n      loader?.show?.({ messages: ['Preparing the Bedroom Manual\u2026', 'Rendering the bedroom in 3D\u2026', 'Drawing the floor plan\u2026', 'Laying out the installation guide\u2026'], intervalMs: 1600, holdLast: true });\n      blob = await buildKitchenManual(m);\n    } catch (e) {\n      console.error('[BTK planner] Kitchen Manual failed', e);\n      dialog?.alert?.('The Bedroom Manual could not be built. Please try again.', { title: 'Bedroom Manual' });\n      return;\n    } finally { loader?.hide?.(); }\n    const ref = String(m.orderRef || 'Order').replace(/^Online Order\\s*/i, '').replace(/[^\\w-]+/g, '');\n    const filename = `${ref}-Kitchen-Manual${m.status === 'approved' ? '' : '-to-check'}.pdf`;\n    const choice = await dialog?.confirm?.(\n      (m.status === 'approved'\n        ? 'This manual is already released to the customer. This copy is built again from the same guide. Download it to check it.\\n\\nRelease this copy in its place?'\n        : 'Your manual is ready. Download it and check it, then Approve to attach it to the order in Odoo and release it to the customer\\'s account.\\n\\nIf the installation guide needs changing, click Write Again.'),\n      // Cancel just closes. Write Again (drafts) has the guide rewritten - it\n      // was hidden behind a \"Not Yet\" that asked a second question, which read\n      // as unclear (Arden, 2026-11-13).\n      { title: 'Bedroom Manual', confirmText: m.status === 'approved' ? 'Release This Copy' : 'Approve', cancelText: 'Cancel',\n        alt: m.status === 'approved' ? null : { text: 'Write Again', value: 'rewrite' },\n        extra: { text: 'Download', onClick: () => saveBlob(blob, filename) } });\n    // Straight to it: the button says what it does, no second question.\n    if (choice === 'rewrite') {\n      try { await api.rewriteKitchenManual(id); } catch (e) {}\n      dialog?.alert?.('The installation guide is being written again. Click Bedroom Manual again in about a minute.', { title: 'Bedroom Manual' });\n      refreshKitchenManualStatus({ watch: true });\n      return;\n    }\n    if (choice !== true) return;\n    try {\n      await api.approveKitchenManual(id, await blobToBase64(blob));\n      dialog?.alert?.('Approved. The manual is attached to the order in Odoo and the customer can download it from their account.', { title: 'Bedroom Manual' });\n    } catch (e) {\n      dialog?.alert?.('The manual could not be approved just now. Please try again.', { title: 'Bedroom Manual' });\n    }\n    refreshKitchenManualStatus();\n  }\n\n  // The line under the Kitchen Manual button: where this order's manual is.\n  // A customer only sees the button once their manual is released.\n  // While the guide is being written the line checks again every 10 seconds,\n  // so it moves on to Waiting for your check / Released to the customer /\n  // Writing failed by itself (Arden, 2026-11-13). opts.watch: just asked for a\n  // rewrite, so keep checking a couple of times even if the server has not\n  // switched to \"writing\" yet. Gives up after 5 minutes.\n  let _kmStatusPoll = null;\n  async function refreshKitchenManualStatus(opts = {}) {\n    clearTimeout(_kmStatusPoll); _kmStatusPoll = null;\n    const bar = root.querySelector('[data-btk-kp-ordered-bar]');\n    const btn = bar && bar.querySelector('[data-btk-kp-ordered-manual]');\n    const note = bar && bar.querySelector('[data-btk-kp-ordered-manual-note]');\n    if (!btn) return;\n    const api = window.BTKBasketAPI;\n    let m = null;\n    try { m = api && typeof api.kitchenManual === 'function' ? await api.kitchenManual(_bootOrdered) : null; } catch (e) { m = null; }\n    const staffView = isStaffOrderedView();\n    if (!staffView) { btn.hidden = !(m && m.available); return; }\n    btn.hidden = false;\n    if (note) {\n      const words = { none: 'Not written yet', writing: 'Guide being written', failed: 'Writing failed', draft: 'Waiting for your check', approved: 'Released to the customer' };\n      note.textContent = m ? (words[m.status] || '') : '';\n      note.hidden = !note.textContent;\n    }\n    const tries = opts.tries || 0;\n    if (tries < 30 && ((m && m.status === 'writing') || (opts.watch && tries < 2))) {\n      _kmStatusPoll = setTimeout(() => {\n        if (root.querySelector('[data-btk-kp-ordered-manual-note]')) refreshKitchenManualStatus({ watch: opts.watch, tries: tries + 1 });\n      }, 10000);\n    }\n  }\n\n  // \u2500\u2500 The plan report, into the order \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n  // Built HERE because it needs jsPDF over a live WebGL render - neither\n  // exists on the server. Posted to the planner API at transfer-to-basket and\n  // parked against the basket; the order webhook attaches it to the Odoo sale\n  // order beside the order confirmation.\n  //\n  // \u26A0 NOTHING HERE MAY BLOCK OR BREAK THE BASKET. A customer whose device\n  // cannot render 3D, or who is offline, must still be able to buy a kitchen\n  // (Arden's call). So: no await on the caller's path, every failure swallowed,\n  // and a timeout so a hung upload cannot pin a request open.\n  let _reportUploadFor = null;        // basket id of the last upload started\n  const PLAN_REPORT_TIMEOUT_MS = 60000;\n\n  // Build and post the report for this basket, once the page is free. The\n  // WAITING is whenPageFree's business, and the reason it has to be patient is\n  // written there; what matters here is that being late is harmless. The report\n  // no longer waits for the 3D view to be off screen either - the captures go\n  // through snapshotOffscreen(), which has its own renderer, and that old gate\n  // never opened on the path from basket to checkout, so four real orders\n  // arrived with no PDF at all (Arden, 2026-09-26).\n  function scheduleReportUpload(basketId) {\n    if (!basketId) return;\n    whenPageFree(() => { try { uploadPlanReport(basketId); } catch (e) {} });\n  }\n  async function uploadPlanReport(basketId) {\n    if (!basketId) return false;\n    // One upload per basket per session: the report is rebuilt on every\n    // transfer, and re-posting an identical document costs a render each time.\n    if (_reportUploadFor === basketId) return false;\n    _reportUploadFor = basketId;\n    try {\n      const built = await downloadPlanReport('blob');\n      if (!built || !built.blob) return false;\n      const buf = await built.blob.arrayBuffer();\n      // btoa needs a binary string; chunked so a megabyte does not blow the\n      // argument limit on String.fromCharCode.\n      const bytes = new Uint8Array(buf);\n      let bin = '';\n      for (let i = 0; i < bytes.length; i += 0x8000) {\n        bin += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000));\n      }\n      const ctrl = (typeof AbortController === 'function') ? new AbortController() : null;\n      const timer = ctrl ? setTimeout(() => ctrl.abort(), PLAN_REPORT_TIMEOUT_MS) : null;\n      const res = await fetch('/apps/planner/my/plan-document', {\n        method: 'POST',\n        headers: { 'Content-Type': 'application/json' },\n        signal: ctrl ? ctrl.signal : undefined,\n        body: JSON.stringify({\n          basketId,\n          kind: 'plan-report',\n          planName: built.planName || activePlanName || 'Bedroom Plan',\n          filename: built.filename,\n          dataBase64: btoa(bin),\n        }),\n      });\n      if (timer) clearTimeout(timer);\n      if (!res.ok) { _reportUploadFor = null; return false; }   // let a later transfer retry\n      return true;\n    } catch (e) {\n      _reportUploadFor = null;   // a failure must not stop the next attempt\n      return false;\n    }\n  }\n\n  // Push the current plan into the basket and hand off to the advanced\n  // basket / checkout. Assumes the plan is already saved (named) - the\n  // drawer gate below names an unsaved plan first.\n  // Set when a plan edit has changed the basket but the SHOPIFY cart hasn't\n  // been re-pushed yet (quiet re-syncs skip that - see below).\n  let cartNeedsSync = false;\n  // The basket the plan was last derived into, so the cart can be pointed at it\n  // when we finally fill it.\n  let lastQuoteBasketId = null;\n\n  // FILL THE CART. The only place the planner does, because the cart is only\n  // ever read at checkout. Awaited by proceedToCheckout so nobody can reach\n  // payment with a stale cart; also fired best-effort when the page is hidden,\n  // for the customer who wanders off to /checkout by another route.\n  //\n  // Guarded by btk-tests/check-quote.js (CHECKOUT).\n  // Is the Shopify cart already the one we would write? A GET, deliberately:\n  // a cart WRITE makes Shopify requote the delivery carrier service, a GET\n  // does not. Returns false on any doubt at all - a needless rewrite costs\n  // seconds, a wrong cart costs the order.\n  async function cartAlreadyMatches(basketId) {\n    // By CONTENTS (BTKBasketAPI.cartHolds): a tagged, non-empty cart was taken\n    // as right, so a product added from a product page while the plan was in\n    // the cart went through checkout inside the plan's order. The id-only test\n    // below remains only for an older basket-api still in a browser's cache.\n    const api = window.BTKBasketAPI;\n    if (api && typeof api.cartHolds === 'function') {\n      try { return (await api.cartHolds(basketId)) === true; } catch (e) { return false; }\n    }\n    try {\n      const r = await fetch('/cart.js', { headers: { Accept: 'application/json' } });\n      if (!r.ok) return false;\n      const cart = await r.json();\n      const attrs = cart.attributes || {};\n      return String(attrs._btk_basket_id || '') === String(basketId)\n        && (cart.item_count || 0) > 0;\n    } catch (e) { return false; }\n  }\n\n  async function flushCartForCheckout() {\n    const api = window.BTKBasketAPI;\n    if (!api) return false;\n    try {\n      // cartNeedsSync is set by every path that changes what should be in the\n      // cart, and cleared once it has been written. When it is clear AND the\n      // cart still carries this basket, there is nothing to do: skipping saves\n      // an App Proxy PUT and three cart writes, each with its own carrier\n      // requote behind it (Arden, 2026-09-27: 8-10 seconds to pre-checkout).\n      ckMark('cart check started');\n      if (!cartNeedsSync && lastQuoteBasketId\n          && await cartAlreadyMatches(lastQuoteBasketId)) {\n        ckMark('cart was already right, nothing written');\n        if (lastQuoteBasketId) scheduleReportUpload(lastQuoteBasketId);\n        return true;\n      }\n      // Fill the cart FROM THIS BASKET, BY ID. This used to call\n      // setActiveBasket first, purely so syncToShopifyCart's getActiveBasket\n      // would pick the right one - and that PUT the whole project (~500 kB for\n      // a real kitchen) to move one boolean: 5.1s of a 17.9s checkout (Arden,\n      // 2026-09-28). It was writing the wrong boolean too. `isActive` is\n      // /cart's notion of the current basket, which must never be a planner\n      // basket (see the note on getActivePlannerBasket), so the old call left\n      // the flag on a planner basket until /cart forced it back.\n      await api.syncToShopifyCart(lastQuoteBasketId || undefined);\n      ckMark('cart written (clear + add + update)');\n      cartNeedsSync = false;\n      // \u26A0 ASK FOR THE PLAN REPORT HERE TOO, not only on Add to Basket.\n      // A plan already sitting in the basket goes straight to checkout without\n      // that button ever being pressed, so nothing asked for a report and the\n      // order arrived with no PDF - and which buttons the customer happened to\n      // press is invisible to them (Arden, 2026-09-26). Not awaited: the\n      // captures are offscreen now, so this costs the customer nothing, and\n      // checkout must never wait on it. uploadPlanReport already skips a\n      // basket it has done this session.\n      if (lastQuoteBasketId) scheduleReportUpload(lastQuoteBasketId);\n      return true;\n    } catch (e) {\n      console.error('[BTK Kitchen Planner] could not fill the cart for checkout', e);\n      cartRefusalMessage = e && e.cartCleared ? await describeCartRefusal(e) : '';\n      return false;\n    }\n  }\n  // Shopify refused a line: a connection is not the problem, so don't send them\n  // looking for one. Its own message rarely says which item, so look each one up.\n  let cartRefusalMessage = '';\n  async function describeCartRefusal(err) {\n    const titles = new Map();\n    try {\n      const basket = lastQuoteBasketId && await window.BTKBasketAPI.getBasket?.(lastQuoteBasketId);\n      (basket?.sections || []).forEach(s => (s.items || []).forEach(it => {\n        if (it.shopifyVariantId) titles.set(String(it.shopifyVariantId), it.productTitle || it.title || '');\n      }));\n    } catch (e) { /* the message still goes out, without the plan's own name */ }\n    const refused = [];\n    await Promise.all((err.variantIds || []).map(async (id) => {\n      try {\n        const r = await fetch(`/variants/${id}.js`, { headers: { Accept: 'application/json' } });\n        if (r.status === 404) { refused.push(titles.get(String(id)) || 'An accessory on your plan'); return; }\n        if (!r.ok) return;\n        const v = await r.json();\n        if (v.available === false) refused.push(v.name || titles.get(String(id)) || 'An item on your plan');\n      } catch (e) { /* unknown, not refused */ }\n    }));\n    const names = [...new Set(refused)];\n    const help = 'Please remove or change it and try again, or call us on 01934 813 201 and we will sort it out.';\n    if (names.length === 1) return `${names[0]} is no longer available, so we could not prepare your basket for checkout. ${help}`;\n    if (names.length > 1) return `These items are no longer available, so we could not prepare your basket for checkout: ${names.join(', ')}. ${help.replace('remove or change it', 'remove or change them')}`;\n    return 'We could not add one of your items to the basket, so we could not prepare it for checkout. Please call us on 01934 813 201 and we will sort it out.';\n  }\n\n  // opts.quiet - a background correction after a plan edit, not a deliberate\n  // \"add to basket\". Skips the loader, the plan re-save, and the Shopify cart\n  // push, leaving ONE call (saveBasket). The full flow does 3 App Proxy round\n  // trips plus /cart/clear + /cart/add + /cart/update, and every cart write\n  // makes the delivery carrier service requote - which is why toggling a panel\n  // finish sat on the loader for ~20s. The cart is brought back in line the\n  // moment the basket is actually opened.\n  // Show a plan edit in the open basket AT ONCE, and save it after.\n  //\n  // Deriving the quote is local and cheap (buildQuote), so an edit that only\n  // changes what a line says - a handing, a unit dropped from the quote - is\n  // derived straight into the basket the panel is already showing and repainted.\n  // No network, no loader, nothing to wait for.\n  //\n  // Persisting then rides the debounce that plan edits already use\n  // (scheduleBasketResync, ~300ms), which saves the basket without writing the\n  // cart. The cart is brought up to date when the basket is opened or at\n  // checkout, which is when it actually matters.\n  //\n  // This replaced a full transferPlanToBasket() per toggle: a whole-plan save,\n  // six storage round trips and a loader held for at least 1.9 seconds, to\n  // change one attribute on one line.\n  function refreshQuoteLocally() {\n    try {\n      const CA = window.BTKCartAdvanced;\n      const basket = CA && CA.getBasket && CA.getBasket();\n      // Only worth doing while the basket is on screen and is this plan's.\n      if (basket && basket.source === 'planner' && !basketHoldsOtherPlan(basket)) {\n        buildQuote(basket, { silent: true });\n        if (CA.renderOnly) CA.renderOnly();\n        // The repaint rebuilds the cards, so put the selected line's highlight\n        // back on the new one. Without this, changing a handing visibly\n        // deselects the line you are working on.\n        const key = embedSelectedKey;\n        if (key) {\n          if (key.indexOf('cab:') === 0)     setSelectedLineCard({ cabId: key.slice(4) });\n          else if (key.indexOf('ep:') === 0) setSelectedLineCard({ epFaces: key.slice(3) });\n          else if (key.indexOf('np:') === 0) setSelectedLineCard({ itemId: key.slice(3) });\n        }\n      }\n    } catch (e) {\n      console.warn('[BTK Kitchen Planner] local quote refresh failed', e);\n    }\n    // Save in the background either way, so the change is not lost if the\n    // basket panel was closed.\n    scheduleBasketResync();\n  }\n\n  // \u2500\u2500\u2500 DERIVE THE QUOTE FROM THE PLAN \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n  // Fills `basket` with the lines the plan implies: units and their panels,\n  // appliances and sinks, worktops, free-placed hobs/sinks/taps, trims, handles,\n  // and any picker-added Extras carried over. Numbering is applied at the end.\n  //\n  // PURE: no network, no saving, no cart. Deriving is cheap and local (the heavy\n  // nesting it reads has already run during the plan's own render), so the UI can\n  // do it as often as it likes. Persisting is a separate decision, made by the\n  // caller. Keeping the two apart is what lets an edit repaint immediately\n  // instead of waiting on storage.\n  //\n  // It reads the basket's CURRENT contents before replacing them, to carry over\n  // the two things the plan does not hold: each unit's assembly choice (chosen\n  // on the basket line) and any picker-added Extras section.\n  //\n  // Covered by btk-tests/check-quote.js (REPEATABLE, SHAPE, NUMBERING).\n  // opts.silent: a background update (a plan edit re-deriving the open or\n  // saved basket), not the customer pressing Add to Basket - an empty plan then\n  // returns quietly. The alert below used to pop up on its own just after a\n  // new plan was started: its first save gave it a basket, and the next plan\n  // edit quietly re-derived that basket from a plan with no units yet (Arden,\n  // 2026-10-08).\n  function buildQuote(basket, opts) {\n    const api = window.BTKBasketAPI;\n    if (!api || !basket) return basket;\n  // Assembly is chosen on the basket line, not in the plan, and every\n  // transfer rebuilds the lines - so carry each unit's choice across the\n  // rebuild (filled from the existing basket below).\n  const prevAssemblyByCab = new Map();\n  // Upgrades (glass drawer sides, cutlery trays) are chosen in the basket too,\n  // so they are carried across the rebuild the same way (Arden, 2026-10-11).\n  const prevAddonsByCab = new Map();\n  // Last line of defence: a corner unit's line must be the panel side it's\n  // drawn with, whatever route the plan took to get here.\n  (cabinets || []).forEach(syncCornerHandVariant);\n  // Free-placed panels/fillers are excluded here for the same reason as in\n  // computeTotal - their charge is the board line, not a unit line.\n  // A wine cooler is a freestanding appliance we SELL - no kitchen variant,\n  // but a product of its own (freestandingAppliance.productHandle).\n  const quoteItems = (cabinets || []).filter(c => !c.excludeFromQuote && !c.endPanelUnit\n    && (c.variantId || (c.freestandingAppliance && c.freestandingAppliance.productHandle)));\n  // \u2500\u2500\u2500 STABLE DERIVED IDS \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n  // A derived line's identity is the PLAN thing it comes from, not a fresh\n  // random id per rebuild. Rebuilding an unchanged plan then produces an\n  // identical quote, which is what lets anything downstream match a line to\n  // the one it replaced: the cart can be diffed instead of cleared and\n  // re-added wholesale, and the cart-to-basket reconcile cannot mis-match a\n  // line (which is how a plan's lines were once replaced by detail-less\n  // copies). Picker-added extras keep their own ids: they are authored by\n  // the customer, not derived from the plan.\n  //\n  // addedAt is stamped too. It is never read anywhere, and leaving it as the\n  // clock would keep every rebuild different for no gain.\n  // Covered by btk-tests/check-quote.js (REPEATABLE).\n  const DERIVED_AT = '2020-01-01T00:00:00.000Z';\n  const derivedIds = new Set();\n  const _lineIdMoves = [];   // [old number-based id, piece-based id] - see the migrate step\n  const derivedId = (obj, key) => {\n    if (!obj) return obj;\n    const id = 'q:' + key;\n    if (derivedIds.has(id)) {\n      // Two lines claiming one plan identity would silently collide\n      // downstream, so say so rather than letting the later one vanish.\n      console.error('[BTK Kitchen Planner] duplicate derived line id', id);\n    }\n    derivedIds.add(id);\n    obj.id = id;\n    if ('addedAt' in obj) obj.addedAt = DERIVED_AT;\n    return obj;\n  };\n  if (!api) {\n    window.BTKKPDialog.alert('Basket is unavailable right now. Please refresh and try again.', { title: 'Basket unavailable', danger: true });\n    return;\n  }\n  // Free-placed end panels are billed as the BOARDS they're cut from, not as\n  // units, so a plan of nothing but panels has boards to buy even though\n  // quoteItems is empty.\n  if (!quoteItems.length && !(endPanelLayout?.boards || []).length) {\n    if (opts && opts.silent) return;\n    window.BTKKPDialog.alert('There are no purchasable units in your plan to add yet.', { title: 'Nothing to add' });\n    return;\n  }\n\n  // Translate planner cabinets \u2192 basket line items. One row per\n  // cabinet, each carrying its door-style / door-colour / carcase\n  // attributes so they survive to the advanced basket + Shopify props.\n  const buildItem = (c) => {\n    const def        = findCabinet(c) || {};\n    const info       = c.variantId ? Catalogue.getVariantInfo(c.variantId) : null;\n    // No catalogue entry: this unit's style products have not loaded (or the\n    // load failed). Ask again - when they land, ensureStyleProducts rebuilds\n    // the basket with the real names and prices.\n    if (c.variantId && !info) ensureStyleProducts(c.kitchenStyleId || kitchenStyleId).catch(() => {});\n    // Carcase Only: the hidden carcase-only variant of this unit (see\n    // carcaseOnlyVariant), its own name and price.\n    const _co = c.carcaseOnly ? carcaseOnlyVariant(c) : null;\n    const _pc = unitPriceCents(c, info);\n    const priceCents = (_pc != null) ? _pc\n                     : (!c.carcaseOnly && def.priceGbp != null) ? Math.round(def.priceGbp * 100)\n                     : 0;\n    // Name = the Shopify product title (\"Lynton - Tall Single Larder Unit\"),\n    // which carries the style and the full name. The unit-type record name\n    // is only a fallback: on some types it holds the bare code (\"TSLUSBD\").\n    const item = derivedId(api.createItem(\n      String(_co ? _co.variantId : c.variantId),\n      (_co && _co.title) || (info && info.product && info.product.title) || def.name || c.code || 'Cabinet',\n      (_co && _co.variantTitle) || (info && info.variant && info.variant.title) || '',\n      1,\n      (priceCents / 100).toFixed(2)\n    ), 'u:' + c.id);\n    const styleHandle = c.kitchenStyleId || kitchenStyleId || null;\n    item.attributes.doorStyle     = styleHandle;\n    // `style` marks the line as a kitchen unit in the advanced basket\n    // (isKitchenUnit) AND scopes its door-colour lookup to this style.\n    item.attributes.style         = styleHandle;\n    // Which group this line totals into in the basket's Pricing bar.\n    // Stamped at build time so the basket never has to infer it.\n    item.attributes.quoteGroup    = 'units';\n    item.attributes.doorColour    = c.doorColourHandle    || globalDoorColourHandle     || null;\n    item.attributes.carcaseColour = c.carcaseColourHandle || globalCarcaseColourHandle  || null;\n    // Carcase-only (the oven fitting panels): no Door row on the line.\n    item.attributes.carcaseOnly = Catalogue.getUnitType?.(c.unitTypeId)?.cutoutSchema?.fittingPanels ? true : null;\n    // Staff's Carcase Only: no doors or fronts, so no door colour; the line\n    // carries staff's permission to checkout (planner-api src/carcase-only.js).\n    if (c.carcaseOnly) {\n      item.attributes.carcaseOnly = true;\n      item.attributes.doorColour = null;\n      item.attributes.carcaseOnlyToken = c.carcaseOnly.token || null;\n    }\n    // Carry the plan's hinge so the basket reflects it (read-only on\n    // planner lines). cab.hingeSide is lowercase user-perspective L/R.\n    // Only log a hand when THIS variant's door actually has a selectable\n    // one - a top-hung flap (or any non-selectable variant) must not push\n    // a Hinge property to the cart / Odoo. hingeSelectable is resolved per\n    // variant from the schema (see isHingeSelectable in engine-catalogue).\n    const hingeRaw = String(c.hingeSide || '').toLowerCase();\n    item.attributes.hinge = c.hingeSelectable\n      ? (hingeRaw === 'left' ? 'Left' : hingeRaw === 'right' ? 'Right' : null)\n      : null;\n    // True Handleless HANDED tall units: L/R is a separate product, so the\n    // line must carry the hand for the Odoo import to resolve LH/RH. Unlike\n    // `hinge` above, stamp it EVEN when the hinge isn't selectable\n    // (flap-&-drawer housings) - there the rail side is the only handing.\n    // `hand` mirrors the 3D renderer's default (unset hingeSide \u2192 left).\n    item.attributes.handed = c.trueHandlelessHanded ? 'true' : null;\n    item.attributes.hand   = c.trueHandlelessHanded\n      ? (hingeRaw === 'right' ? 'Right' : 'Left')\n      : null;\n    // Visible customer sign-off: the grip RAIL side = OPPOSITE the hinge, on\n    // every True Handleless tall / midi unit (all carry the vertical rail), as\n    // the 2D / 3D draw it (bug sheet, Neil, 2026-10-26).\n    const _railGrip = thGripSide(c);\n    item.attributes.rail   = _railGrip ? (_railGrip === 'left' ? 'Left' : 'Right') : null;\n    // Assembly: the customer's basket choice, else Assembled (the product\n    // pages' default). Always stored so the line sends an Assembly property -\n    // an unset line sent nothing, and Odoo got no assembly at all. Odoo's\n    // import drops it for products that have no assembly option.\n    // A size only supplied flat packed (Odoo: Assembly Options = Flatpacked,\n    // the catalogue's flatOnly) is always Flatpack (Arden, 2026-10-18).\n    // A product with no assembly choice at all (Odoo's Assembly Option off -\n    // appliance doors, extractor doors) gets none, so no toggle and nothing\n    // sent (Arden, 2026-10-25). Only an explicit false: an older catalogue\n    // without the flag keeps the toggle.\n    // Flat pack only is asked FIRST, as the basket does: a product with the\n    // option off and a flat-pack-only size flipped between Flatpack (basket)\n    // and none (here) on every rebuild. That changed the checklist's Assembly\n    // count, undid its approval, and sent checkout round in a loop (Ellie Wing,\n    // Lewis, 2026-11-02).\n    {\n      const _vi = (c.variantId != null && Catalogue.getVariantInfo) ? Catalogue.getVariantInfo(Number(c.variantId)) : null;\n      item.attributes.assembly = (_vi && _vi.variant && _vi.variant.flatOnly)\n        ? 'Flatpack'\n        : (_vi && _vi.product && _vi.product.assemblyOption === false)\n        ? null\n        : (prevAssemblyByCab.get(c.id) || 'Fully Assembled');\n    }\n    // The unit type code (e.g. 2DB) - planner lines have no SKU to read it from,\n    // and the basket's upgrades are matched on it (Arden, 2026-10-11).\n    item.attributes.unitCode = (() => {\n      const _p = info && info.product;\n      const _ut = _p && Catalogue.getUnitType ? Catalogue.getUnitType(_p.unitTypeId) : null;\n      return (_ut && _ut.code) || (_p && _p.kbbUnitTypeCode) || null;\n    })();\n    { const _ad = prevAddonsByCab.get(c.id); if (_ad && _ad.length) item.attributes.addons = _ad; }\n    // Non-dimension config options - e.g. \"Small Door Position: Top\" \u2014\n    // surfaced on the basket line as NAME: VALUE so the customer can see\n    // exactly what they're ordering. The variant id already carries it for\n    // pricing + Odoo, so this is display-only. Width/depth/height are dropped\n    // (shown as dims); the option name is cleaned of any [hint] suffix.\n    const optInfo = Catalogue.variantOptionInfo ? Catalogue.variantOptionInfo(c.variantId) : [];\n    const cfgPairs = optInfo\n      // Shopify's placeholder option on a product with none of its own\n      // (\"Title: Default Title\" - the integrated appliance doors) says nothing.\n      .filter(o => !o.isDimension && o.value != null && o.value !== 'Default Title')\n      .map(o => o.label + ': ' + o.value);\n    item.attributes.config = cfgPairs.length ? cfgPairs.join(' \u00B7 ') : null;\n    // Height VARIANT (Low/Medium/High or a numeric height) - shown on the\n    // line only for units that offer a height CHOICE (wall / tall / larder).\n    // Units with a fixed height carry no Height option, so nothing shows \u2014\n    // no \"720mm High\" noise on every base unit.\n    const heightOpt = optInfo.find(o => /^height\\b/.test(o.labelKey));\n    item.attributes.heightLabel = (heightOpt && heightOpt.value != null)\n      ? String(heightOpt.value) : null;\n    // Explicit footprint so the basket shows the real size instead of\n    // guessing from a variant title whose option order isn't always\n    // [Width, Depth] (corner/diagonal larders are [Width, Height, Door]).\n    // A blank corner unit's footprint on the plan includes the void beside\n    // it; the product is the cabinet alone (Arden, 2026-10-11).\n    item.attributes.widthMm = (c.cornerUnit && c.cornerUnit.cabinetMm) || c.widthMm || null;\n    item.attributes.depthMm = c.depthMm || null;\n    // Reduced On Site (Arden, 2026-11-19): bought at its own depth, cut down\n    // by the fitter to the plan's.\n    {\n      const _cut = reducedOnSiteMm(c);\n      if (_cut) {\n        const _from = siteCutFromMm(c);\n        if (_from) item.attributes.depthMm = _from;\n        item.attributes.config = [item.attributes.config, `Reduced On Site to ${_cut}mm Deep`].filter(Boolean).join(' \u00B7 ');\n      }\n    }\n    // An integrated APPLIANCE DOOR is bought by its door size - width and\n    // height, as its name gives them (\"... Door (490 x 596mm)\", height x\n    // width). Its depth is the appliance's, not the door's, and only confused\n    // (Arden, 2026-10-12).\n    {\n      const _ut = Catalogue.getUnitType ? Catalogue.getUnitType(c.unitTypeId) : null;\n      if (_ut && _ut.unitTypeGroupHandle === 'ap-integrated-appliance-doors') {\n        const _m = /\\((\\d+)\\s*x\\s*(\\d+)\\s*mm\\)/i.exec(String((info && info.product && info.product.title) || ''));\n        item.attributes.depthMm = null;\n        if (_m) {\n          item.attributes.widthMm = Number(_m[2]);\n          item.attributes.heightLabel = _m[1];\n        }\n      }\n    }\n    // Product handle \u2192 URL, so the embedded basket's detail panel can\n    // fetch the full product (description, images) for a PDP-style view.\n    item.url = (!c.carcaseOnly && info && info.product && info.product.handle)\n      ? ('/products/' + info.product.handle) : null;\n    // Before/after price from the catalogue variant (available now, so the\n    // list + panel show \"Was \u2026\" without waiting on a Shopify round-trip).\n    const _cmpCents = unitCompareAtCents(c, info);\n    item.compareAtPrice = (_cmpCents && _cmpCents > priceCents) ? (_cmpCents / 100).toFixed(2) : null;\n    // Link the line back to its planner cabinet so the embedded cart\n    // can highlight it in the live view when the line is clicked.\n    item.plannerCabinetId = c.id;\n    // Show the PLAN's item number on the basket line (not the basket's\n    // own sequential index) so basket \u2194 plan numbering matches.\n    item.planLineNumber = (c.displayNumber != null) ? c.displayNumber : null;\n    return item;\n  };\n\n  // A 'panel'-anchored stacked wall unit adds an 18mm divider-panel\n  // line alongside its cabinet line. Only emitted once the divider's\n  // end-panel product resolves to a real variant.\n  const dividerItemFor = (c) => {\n    const dp = dividerPanelFor(c);\n    if (!dp || !dp.variantId) return null;\n    const item = derivedId(api.createItem(\n      String(dp.variantId), dp.name, '18mm divider panel', 1,\n      ((dp.priceCents || 0) / 100).toFixed(2)\n    ), 'dv:' + c.id);\n    item.attributes.style = c.kitchenStyleId || kitchenStyleId || null;\n    item.attributes.quoteGroup = 'panels';\n    item.plannerCabinetId = c.id;\n    // Divider belongs to its host unit - share its plan number.\n    item.planLineNumber = (c.displayNumber != null) ? c.displayNumber : null;\n    return item;\n  };\n  // End-panel BOARD line - one chargeable line per physical board,\n  // numbered to match the plan. Gated on the EP product resolving\n  // (one product per stock type, priced per style), like the divider.\n  // A board is linked to ITS OWN faces (cabId:side) so clicking the line\n  // highlights the panel/filler itself in the mini-3D, not the host unit.\n  // ACOUSTIC PANELLING back (Arden, 2026-10-21): the product the unit asked for\n  // (window.BTKAcousticPanels, loaded from Shopify), in panels - \"2 x Panels\"\n  // packs, and a \"Single Panel\" for an odd one. Its own photo shows on the line.\n  const acousticItemsFor = (board) => {\n    const list = (typeof window !== 'undefined' && window.BTKAcousticPanels) || [];\n    const prod = list.find(p => p.handle === board.acousticHandle) || list[0];\n    if (!prod) return null;\n    const n = acousticPanelCount(board.runMm, board.heightMm);\n    if (!(n > 0)) return null;\n    const faces = (board.pieces || [])\n      .map(p => (p.face.cabIds || []).map(id => `${id}:${p.face.side}`)).flat()\n      .filter(k => !k.endsWith(':undefined') && !k.endsWith(':null'));\n    const cover = `${n} panel${n === 1 ? '' : 's'} for a ${Math.round(board.runMm)} x ${Math.round(board.heightMm)}mm back`;\n    const out = [];\n    const line = (v, qty, key) => {\n      if (!v || !(qty > 0)) return;\n      const item = derivedId(api.createItem(String(v.id), prod.title, `${v.title} \u00B7 ${cover}`, qty,\n        ((v.priceCents || 0) / 100).toFixed(2)), boardLineKey(board) + ':' + key);\n      item.attributes.quoteGroup = 'panels';\n      item.attributes.doorColour = null;\n      item.attributes.carcaseColour = null;\n      item.attributes.endPanelBoard = board.itemNumber;\n      item.image = prod.image || null;\n      item.url = '/products/' + prod.handle;\n      item.compareAtPrice = (v.compareAtCents && v.compareAtCents > (v.priceCents || 0))\n        ? (v.compareAtCents / 100).toFixed(2) : null;\n      item.planLineNumber = board.itemNumber;\n      item.plannerEndPanelFaces = faces;\n      item.plannerCabinetId = board.ownerCabId || null;\n      out.push(item);\n    };\n    if (prod.pair) { line(prod.pair, Math.floor(n / 2), 'pair'); line(prod.single, n % 2, 'single'); }\n    else line(prod.single, n, 'single');\n    return out.length ? out : null;\n  };\n  const boardItemFor = (board) => {\n    if (board && board.acoustic) return acousticItemsFor(board);\n    const prod = endPanelBoardProduct(board, kitchenStyleId || null);\n    if (!prod || !prod.variantId) {\n      if (typeof window !== 'undefined' && window.BTK_FILLER_DEBUG)\n        console.warn('[BTK_FILLER_DEBUG] board', board.itemNumber, 'type', board.type,\n          'stock', board.code, 'finish', board.finish, 'style', board.styleId,\n          '\u2192 NO matching product for codes', board.productCodes);\n      return null;\n    }\n    // CUT LIST on the line: name what this one board is actually cut into, so\n    // the basket shows why 3 panels can be 1 charge. Roles are counted, not\n    // listed one-per-piece, and the leftover off-cuts are mentioned.\n    const _roleLabel = { base: 'base end panel', tall: 'tall end panel', ceiling: 'ceiling filler',\n                         wall: 'wall end panel', dresser: 'dresser end panel',\n                         filler: 'filler', 'breakfast-bar': 'breakfast bar panel',\n                         under: 'under panel' };\n    const _counts = new Map();\n    for (const pc of (board.pieces || [])) {\n      const k = _roleLabel[pc.role] || pc.role || 'piece';\n      _counts.set(k, (_counts.get(k) || 0) + 1);\n    }\n    const _cut = [..._counts.entries()]\n      .map(([k, n]) => (n > 1 ? `${n} \u00D7 ${k}s` : `1 \u00D7 ${k}`)).join(', ');\n    // Only worth saying when the board really IS shared. One panel per board is\n    // the ordinary case and \"cut into 1 x base end panel\" only restates the\n    // product name. Off-cuts are never named: they are the nester's leftover\n    // scrap rather than anything the customer is supplied, and the count took\n    // everything above EP_MIN_OFFCUT_MM (20), so a 22mm strip read as an\n    // off-cut on the line.\n    const _desc = (board.pieces || []).length > 1\n      ? `Board ${board.itemNumber} \u00B7 cut into ${_cut}`\n      : '';\n    const item = derivedId(api.createItem(\n      String(prod.variantId), prod.name, _desc, 1,\n      ((prod.priceCents || 0) / 100).toFixed(2)\n    ), boardLineKey(board));\n    _lineIdMoves.push(['q:b:' + (board.ownerCabId || 'x') + ':' + board.itemNumber, item.id, item.productTitle]);\n    // Style + colour come from the BOARD (the nester groups faces by material,\n    // so a board is one style / one colour / one finish) - not from the global\n    // style, which would mislabel a board in a mixed-style plan.\n    item.attributes.style = board.styleId || kitchenStyleId || null;\n    item.attributes.quoteGroup = 'panels';\n    // Panels / fillers are painted the DOOR colour and carry NO carcase\n    // colour, so the Door chip shows (in its colour) and the carcase chip\n    // is hidden.\n    const _epOwner = cabinets.find(cc => cc.id === board.ownerCabId);\n    item.attributes.doorColour = board.colour\n      || (_epOwner && _epOwner.doorColourHandle) || globalDoorColourHandle || null;\n    item.attributes.carcaseColour = null;\n    item.attributes.endPanelBoard = board.itemNumber;\n    item.url = prod.handle ? ('/products/' + prod.handle) : null;\n    item.compareAtPrice = (prod.compareAtCents && prod.compareAtCents > (prod.priceCents || 0))\n      ? (prod.compareAtCents / 100).toFixed(2) : null;\n    item.planLineNumber = board.itemNumber;\n    // The panel/filler faces cut into this board: \"cabId:side\" keys the\n    // 3D renderer uses to highlight + frame the panel itself.\n    item.plannerEndPanelFaces = (board.pieces || [])\n      .map(p => (p.face.cabIds || []).map(id => `${id}:${p.face.side}`)).flat()\n      .filter(k => !k.endsWith(':undefined') && !k.endsWith(':null'));\n    // Still link a host cabinet so the line counts as a planner line (badge,\n    // thumbnail); the face list above overrides where the 3D focus lands.\n    item.plannerCabinetId = board.ownerCabId || null;\n    // Radius filler board: its \"face\" is a standalone filler CAB, not an\n    // end-panel mesh focusOnEndPanel can find - clear the face list so the\n    // line click routes to focus/select the filler cab itself.\n    if (_epOwner && _epOwner.radiusGroup && _epOwner.radiusGroup.role === 'filler') {\n      item.plannerEndPanelFaces = [];\n    }\n    // Same for a board holding a FREE-PLACED panel: its face is a standalone\n    // cab, not a per-side end-panel mesh, so clear the face list and let the\n    // click focus/select the panel cab itself.\n    const _unitFace = (board.pieces || []).find(p => p.face && p.face.side === 'unit');\n    if (_unitFace) {\n      item.plannerEndPanelFaces = [];\n      item.plannerCabinetId = (_unitFace.face.cabIds || [])[0] || item.plannerCabinetId;\n    }\n    return item;\n  };\n  // Boards \"owned\" by this unit (numbered when this unit was reached in\n  // the clockwise sweep) sit in the unit's section, right after it - so\n  // a panel lives with the unit it's against.\n\n  // End features sit WITH the unit whose panel they belong to, right after\n  // its boards - not in a section of their own. One line per pooled set of\n  // ends; its number is shared by every corner it covers, and the face list\n  // makes the row highlight all of them at once.\n  const _efCharges = computeEndFeatureCharges();\n  const _cpCharges = computeCornerPostCharges();\n  const cornerPostItemsOwnedBy = (c) => {\n    try {\n      return _cpCharges.filter(ch => ch.ownerCabId === c.id).map(ch => {\n        const p = ch.product;\n        const item = derivedId(api.createItem(\n          String(p.variantId), ch.name, ch.detail, 1,\n          ((p.priceCents || 0) / 100).toFixed(2)\n        ), 'cp:' + c.id + ':' + ch.side + ':' + ch.pos);\n        item.attributes.style = c.kitchenStyleId || kitchenStyleId || null;\n        item.attributes.quoteGroup = 'panels';\n        item.attributes.doorColour    = c.doorColourHandle || globalDoorColourHandle || null;\n        item.attributes.carcaseColour = null;\n        item.url = p.handle ? ('/products/' + p.handle) : null;\n        item.compareAtPrice = (p.compareAtCents && p.compareAtCents > (p.priceCents || 0))\n          ? (p.compareAtCents / 100).toFixed(2) : null;\n        if (ch.number != null) item.planLineNumber = ch.number;\n        item.plannerEndPanelFaces = ch.faces || [];\n        item.plannerCabinetId = c.id;\n        return item;\n      });\n    } catch (err) {\n      console.error('[BTK] corner post line failed', err);\n      return [];\n    }\n  };\n  const doorEndItemsOwnedBy = (c) => {\n    try {\n      const out = [];\n      for (const s of ['left', 'right']) {\n        const de = ((c.endPanels || {})[s] || {}).doorEnd;\n        if (!de || !de.variantId) continue;\n        const p = doorEndProduct(c, de);\n        if (!p) { console.warn('[BTK door end] no door product for', c.id, s); continue; }\n        const item = derivedId(api.createItem(\n          String(p.variantId), p.title, `${de.widthMm}mm wide \u00B7 ${s === 'left' ? 'left' : 'right'} end`, 1,\n          ((p.priceCents || 0) / 100).toFixed(2)\n        ), 'de:' + c.id + ':' + s);\n        item.attributes.style = c.kitchenStyleId || kitchenStyleId || null;\n        item.attributes.quoteGroup = 'panels';\n        item.attributes.doorColour    = c.doorColourHandle || globalDoorColourHandle || null;\n        item.attributes.carcaseColour = null;\n        item.url = p.handle ? ('/products/' + p.handle) : null;\n        item.compareAtPrice = (p.compareAtCents && p.compareAtCents > (p.priceCents || 0))\n          ? (p.compareAtCents / 100).toFixed(2) : null;\n        const num = c.doorEndNumbers && c.doorEndNumbers[s];\n        if (num != null) item.planLineNumber = num;\n        item.plannerCabinetId = c.id;\n        out.push(item);\n      }\n      return out;\n    } catch (err) {\n      console.error('[BTK] door end line failed', err);\n      return [];\n    }\n  };\n  const legItemsOwnedBy = (c) => {\n    try {\n      const p = c && c.asBase ? window.BTKLegPack : null;\n      if (!p) return [];\n      const item = derivedId(api.createItem(\n        String(p.variantId), p.title, 'Make Base Unit legs', 1, ((p.priceCents || 0) / 100).toFixed(2)\n      ), 'legs:' + c.id);\n      item.attributes.style = c.kitchenStyleId || kitchenStyleId || null;\n      item.attributes.quoteGroup = 'panels';\n      item.attributes.doorColour = null;\n      item.attributes.carcaseColour = null;\n      item.url = p.handle ? ('/products/' + p.handle) : null;\n      item.compareAtPrice = (p.compareAtCents && p.compareAtCents > (p.priceCents || 0))\n        ? (p.compareAtCents / 100).toFixed(2) : null;\n      if (c.legsNumber != null) item.planLineNumber = c.legsNumber;\n      item.plannerCabinetId = c.id;\n      return [item];\n    } catch (err) {\n      console.error('[BTK] leg pack line failed', err);\n      return [];\n    }\n  };\n  // SUPPLIED AS PARTS (Arden, 2026-11-19): a unit the planner places whole but\n  // that is supplied as its parts for the customer's fitter to build - flagged\n  // on its unit type (cutout_schema.suppliedAsParts).\n  function unitSuppliedAsParts(c) {\n    try {\n      const ut = c && c.unitTypeId && Catalogue.getUnitType ? Catalogue.getUnitType(c.unitTypeId) : null;\n      return !!((ut && ut.cutoutSchema && ut.cutoutSchema.suppliedAsParts) || (c && c.cutoutSchema && c.cutoutSchema.suppliedAsParts));\n    } catch (e) { return false; }\n  }\n  // Worktop Pantry Unit (row 142): the fitters panels its carcase is cut from.\n  const pantryPanelItemsOwnedBy = (c) => {\n    try {\n      const p = isPantryCab(c) ? window.BTKFittersPanel : null;\n      if (!p) return [];\n      const n = pantryCutSummary(c).boards;\n      if (!n) return [];\n      const item = derivedId(api.createItem(\n        String(p.variantId), p.title, 'Worktop Pantry Unit panels', n, ((p.priceCents || 0) / 100).toFixed(2)\n      ), 'pp:' + c.id);\n      item.attributes.style = c.kitchenStyleId || kitchenStyleId || null;\n      item.attributes.quoteGroup = 'panels';\n      item.attributes.doorColour = null;\n      item.attributes.carcaseColour = c.carcaseColourHandle || null;\n      if (unitSuppliedAsParts(c)) item.attributes.suppliedAsParts = true;\n      item.url = p.handle ? ('/products/' + p.handle) : null;\n      item.compareAtPrice = (p.compareAtCents && p.compareAtCents > (p.priceCents || 0))\n        ? (p.compareAtCents / 100).toFixed(2) : null;\n      if (c.pantryPanelsNumber != null) item.planLineNumber = c.pantryPanelsNumber;\n      item.plannerCabinetId = c.id;\n      return [item];\n    } catch (err) {\n      console.error('[BTK] pantry panels line failed', err);\n      return [];\n    }\n  };\n  const featureItemsOwnedBy = (c) => {\n    try {\n      return _efCharges.filter(ch => ch.ownerCabId === c.id).map(ch => {\n        const p = ch.product;\n        const item = derivedId(api.createItem(\n          String(p.variantId), ch.name, ch.detail, ch.qty,\n          ((p.priceCents || 0) / 100).toFixed(2)\n        ), featureLineKey(ch.faces, ch.ownerCabId, ch.number));\n        _lineIdMoves.push(['q:ef:' + (ch.ownerCabId || 'x') + ':' + ch.number, item.id, item.productTitle]);\n        item.attributes.style = ch.product.styleId || kitchenStyleId || null;\n        item.attributes.quoteGroup = 'panels';\n        // The posts' own colour (their end's), not the plan-wide one.\n        item.attributes.doorColour    = ch.colour || globalDoorColourHandle || null;\n        item.attributes.carcaseColour = null;\n        item.url = p.handle ? ('/products/' + p.handle) : null;\n        item.compareAtPrice = (p.compareAtCents && p.compareAtCents > (p.priceCents || 0))\n          ? (p.compareAtCents / 100).toFixed(2) : null;\n        item.planLineNumber = ch.number;\n        item.plannerEndPanelFaces = ch.faces || [];\n        item.plannerCabinetId = ch.ownerCabId || null;\n        return item;\n      });\n    } catch (err) {\n      console.error('[BTK] end-feature line failed', err);\n      return [];\n    }\n  };\n\n  // Vertical profiles (computeRailCharges): each its own numbered line, with\n  // the unit it stands against - like the corner posts above. Filed in the\n  // HANDLES group like the other profiles. The face key routes a line click to\n  // the unit (no mesh of its own to frame) and a plan-number click to the line.\n  let _rlCharges = [];\n  try { _rlCharges = computeRailCharges().filter(ch => ch.ownerCabId); } catch (err) { _rlCharges = []; }\n  const railItemsOwnedBy = (c) => {\n    try {\n      return _rlCharges.filter(ch => ch.ownerCabId === c.id).map(ch => {\n        const p = ch.product;\n        const item = derivedId(api.createItem(\n          String(p.variantId), ch.name, ch.detail, 1,\n          ((p.priceCents || 0) / 100).toFixed(2)\n        ), 'rl:' + c.id + ':' + ch.side);\n        item.attributes.style = kitchenStyleId || null;\n        item.attributes.quoteGroup = 'handles';\n        item.attributes.doorColour    = null;   // metal - no colour chips\n        item.attributes.carcaseColour = null;\n        item.url = p.url || null;\n        item.image = p.imageUrl || item.image || null;\n        item.compareAtPrice = (p.compareAtCents && p.compareAtCents > (p.priceCents || 0))\n          ? (p.compareAtCents / 100).toFixed(2) : null;\n        if (ch.number != null) item.planLineNumber = ch.number;\n        item.plannerEndPanelFaces = ch.faces || [];\n        item.plannerCabinetId = c.id;\n        return item;\n      });\n    } catch (err) {\n      console.error('[BTK] profile line failed', err);\n      return [];\n    }\n  };\n\n  const boardItemsOwnedBy = (c) => (endPanelLayout?.boards || [])\n    .filter(b => b.ownerCabId === c.id)\n    .sort((a, b) => (a.itemNumber || 0) - (b.itemNumber || 0))\n    .map(boardItemFor).flat().filter(Boolean);\n\n  // Chosen appliances sitting in this housing's oven apertures - each is a\n  // real purchasable product (its own Shopify variant) so it adds to the\n  // basket as its own line, right after the housing. Linked to the housing\n  // cab so the basket groups + highlights them together. No `style`\n  // attribute \u2192 the advanced basket treats it as a simple product line\n  // (not a kitchen unit), so it shows its own image + price with no\n  // door-colour machinery. See [[appliance-products]].\n  // A freestanding appliance we sell (a wine cooler): the PRODUCT is the line,\n  // carrying the unit's own plan number - the cab is the appliance itself.\n  const soldApplianceItemFor = (c) => {\n    const handle = c.freestandingAppliance && c.freestandingAppliance.productHandle;\n    const appl = handle && Catalogue.getAppliance ? Catalogue.getAppliance(handle) : null;\n    if (!appl || !appl.variantId) return null;\n    const priceCents = (typeof appl.priceCents === 'number') ? appl.priceCents : 0;\n    const item = derivedId(api.createItem(String(appl.variantId), appl.title || handle, '', 1,\n      (priceCents / 100).toFixed(2)), 'fsa:' + c.id);\n    item.attributes.appliance  = true;\n    item.attributes.quoteGroup = 'appliances';\n    item.attributes.brand      = appl.brand || null;\n    item.compareAtPrice = (appl.compareAtCents && appl.compareAtCents > priceCents) ? (appl.compareAtCents / 100).toFixed(2) : null;\n    item.url = '/products/' + handle;\n    item.plannerCabinetId = c.id;\n    item.planLineNumber   = (c.displayNumber != null) ? c.displayNumber : null;\n    return item;\n  };\n  // A built-under double oven's fitting-panel pair, at its own number.\n  const fittingKitItemFor = (c) => {\n    const kit = fittingKitFor(c);\n    if (!kit) return null;\n    const item = derivedId(api.createItem(String(kit.variantId), kit.title, '', 1,\n      (kit.priceCents / 100).toFixed(2)), 'fp:' + c.id);\n    // A carcase-only no-door unit (Arden, 2026-11-05): Units, not Appliances.\n    const styleHandle = c.kitchenStyleId || kitchenStyleId || null;\n    item.attributes.doorStyle     = styleHandle;\n    item.attributes.style         = styleHandle;\n    item.attributes.quoteGroup    = 'units';\n    item.attributes.carcaseColour = c.carcaseColourHandle || globalCarcaseColourHandle || null;\n    item.attributes.carcaseOnly   = true;\n    item.compareAtPrice = (kit.compareAtCents && kit.compareAtCents > kit.priceCents) ? (kit.compareAtCents / 100).toFixed(2) : null;\n    item.url = kit.handle ? ('/products/' + kit.handle) : null;\n    item.plannerCabinetId = c.id;\n    item.planLineNumber   = (c.fittingKitNumber != null) ? c.fittingKitNumber : null;\n    return item;\n  };\n  const applianceItemsFor = (c) => {\n    const chosen  = c.appliances || {};\n    const numbers = c.applianceNumbers || {};\n    const keys = Object.keys(chosen).filter(k => chosen[k]);\n    if (!keys.length || typeof Catalogue.getAppliance !== 'function') return [];\n    return keys.map(k => {\n      const handle = chosen[k];\n      const appl = Catalogue.getAppliance(handle);\n      if (!appl || !appl.variantId) return null;\n      const priceCents = (typeof appl.priceCents === 'number') ? appl.priceCents : 0;\n      const item = derivedId(api.createItem(\n        String(appl.variantId),\n        appl.title || handle,\n        '',\n        1,\n        (priceCents / 100).toFixed(2)\n      ), 'ap:' + c.id + ':' + k);\n      item.attributes.appliance = true;\n      item.attributes.quoteGroup = 'appliances';\n      item.attributes.brand     = appl.brand || null;\n      // Its was price too, like every other line (Arden, 2026-10-11).\n      item.compareAtPrice = (appl.compareAtCents && appl.compareAtCents > priceCents) ? (appl.compareAtCents / 100).toFixed(2) : null;\n      item.url = '/products/' + handle;\n      // Linked to the host housing so it groups + highlights with it, but\n      // carries its OWN plan item number.\n      item.plannerCabinetId = c.id;\n      item.planLineNumber   = (numbers[k] != null) ? numbers[k]\n                            : (c.displayNumber != null ? c.displayNumber : null);\n      return item;\n    }).filter(Boolean);\n  };\n\n  // A chosen Planner Sink on a sink-base unit - a real purchasable\n  // product (its own Shopify variant) that adds to the basket as its\n  // own line, right after the sink base, with its OWN plan number.\n  // Same \"simple product line\" treatment as appliances (no `style`\n  // attribute \u2192 no door-colour machinery). See [[sink-units-and-sink-selection]].\n  const sinkItemFor = (c) => {\n    if (!c || !(c.sinkBase || c.belfastSink) || !c.plannerSinkHandle) return null;\n    if (typeof Catalogue.getPlannerSink !== 'function') return null;\n    const sink = Catalogue.getPlannerSink(c.plannerSinkHandle);\n    if (!sink || !sink.variantId) return null;\n    const priceCents = (typeof sink.productPrice === 'number') ? sink.productPrice : 0;\n    const item = derivedId(api.createItem(\n      String(sink.variantId),\n      sink.productTitle || sink.sinkName || c.plannerSinkHandle,\n      '',\n      1,\n      (priceCents / 100).toFixed(2)\n    ), 'sk:' + c.id);\n    item.attributes.sink = true;\n    item.attributes.quoteGroup = 'appliances';\n    // How it is fitted (sales row 133), on the line and - as the planner's\n    // own note - on the Odoo line (item_note: delivery note, worktop PO), so\n    // the fabricator and fitter know an Inset or Undermount sink goes under.\n    if (c.sinkBase) {\n      const _m = sinkMountFor(c, sink);\n      const _info = Catalogue.plannerSinkMountInfo(sink);\n      const _label = _m === 'under-mount' ? 'Undermount' : (_m === 'top-mount' && _info.either) ? 'Inset' : null;\n      if (_label) {\n        item.attributes.config = 'Fitting: ' + _label;\n        item.attributes.fixedNote = 'Fitting: ' + _label;\n      }\n    }\n    item.compareAtPrice = (sink.productCompareAt && sink.productCompareAt > priceCents) ? (sink.productCompareAt / 100).toFixed(2) : null;   // was price (Arden, 2026-10-11)\n    item.url = sink.productHandle ? ('/products/' + sink.productHandle) : (sink.productUrl || null);\n    item.plannerCabinetId = c.id;\n    item.planLineNumber   = (c.sinkNumber != null) ? c.sinkNumber\n                          : (c.displayNumber != null ? c.displayNumber : null);\n    return item;\n  };\n\n  // A 2 drawer base Sink Unit's Steel Under-Sink Drawer Insert (Arden,\n  // 2026-11-16): the top drawer clears the sink's plumbing. Its own line,\n  // right after the sink.\n  const sinkInsertItemFor = (c) => {\n    const ins = sinkInsertFor(c);\n    if (!ins || !ins.variantId) return null;\n    const item = derivedId(api.createItem(String(ins.variantId), ins.title || 'Steel Under-Sink Drawer Insert',\n      '', 1, ((ins.priceCents || 0) / 100).toFixed(2)), 'si:' + c.id);\n    item.attributes.quoteGroup = 'appliances';\n    item.compareAtPrice = (ins.compareAtCents && ins.compareAtCents > ins.priceCents) ? (ins.compareAtCents / 100).toFixed(2) : null;\n    item.url = '/products/' + SINK_INSERT_HANDLE;\n    item.plannerCabinetId = c.id;\n    item.planLineNumber   = (c.sinkInsertNumber != null) ? c.sinkInsertNumber : null;\n    return item;\n  };\n\n  // A Pastry Bench Set's own part lines (side fronts, plinth frame, oak\n  // shelf), each at its number, linked to the unit and noted as part of it.\n  const pastryItemsOwnedBy = (c) => {\n    try {\n      const nums = c.pastryNumbers || {};\n      return pastryCharges(c).map(ch => {\n        const item = derivedId(api.createItem(String(ch.variantId), ch.title, ch.detail, ch.qty,\n          ((ch.priceCents || 0) / 100).toFixed(2)), 'ps:' + c.id + ':' + ch.part);\n        if (ch.style) item.attributes.style = ch.style;\n        item.attributes.quoteGroup    = 'panels';\n        item.attributes.doorColour    = ch.colour || null;\n        item.attributes.carcaseColour = ch.carcase ? (ch.carcaseColour || null) : null;\n        if (ch.carcase) item.attributes.carcaseOnly = true;\n        item.attributes.fixedNote = pastrySetNote(c);\n        item.compareAtPrice = (ch.compareAtCents && ch.compareAtCents > (ch.priceCents || 0))\n          ? (ch.compareAtCents / 100).toFixed(2) : null;\n        item.url = ch.handle ? ('/products/' + ch.handle) : null;\n        if (ch.swatchUrl) item.image = ch.swatchUrl;\n        item.plannerCabinetId = c.id;\n        item.planLineNumber   = (nums[ch.part] != null) ? nums[ch.part] : null;\n        return item;\n      });\n    } catch (err) {\n      console.error('[BTK] pastry set line failed', err);\n      return [];\n    }\n  };\n  const pastrySetNote = (c) => {\n    const k = (c.pastryParts && c.pastryParts.kind) || 'square';\n    const withItem = c.displayNumber != null ? ' with item ' + c.displayNumber : '';\n    if (k === 'open') return 'Part of the Open Pastry Bench' + withItem\n      + ': 4 Floor Column legs, 50mm drawer front rails on the front and sides, back panel, plinth shelf frame and shelf.';\n    return 'Part of the Pastry Bench Set' + withItem + ': drawer unit, '\n      + (k === 'column' ? '4 Floor Column legs' : '4 Square End Feature legs')\n      + ', back panel, plinth shelf frame, shelf and side drawer fronts.';\n  };\n\n  // Count a unit's HANDLED fronts into `acc` (variantId \u2192 {product, qty}),\n  // priced by each front's position group (door \u2192 base/wall/tall; drawer \u2192\n  // Drawers, or Pan Drawers when deep). Skipped for J-pull/Gola styles\n  // (groove in the door) and any opening authored `handle:false`. Front\n  // classification mirrors the renderer (deep drawer \u2265 threshold \u2192 Pan).\n  // Handles do NOT become unit lines - they collect into a plan-wide\n  // \"Handles\" section (buildHandlesSection) so they never touch a unit's\n  // number or ordering.\n  const PAN_DRAWER_MIN_FRONT_MM = 200;\n  const accumulateHandles = (c, acc) => {\n    if (!c) return;\n    // Customise Handle > Handles in your basket > Supplying my own: the unit\n    // keeps its handles on the plan, but they are bought elsewhere, so they\n    // are not counted here (bug sheet row 79).\n    if (c.ownHandles) return;\n    if (c.carcaseOnly) return;   // Carcase Only: no fronts, so no handles\n    const ks = Catalogue.getKitchenStyle?.(c.kitchenStyleId);\n    // No handle lines for handleless styles (J-pull / Gola / True Handleless).\n    if ((Catalogue.isStyleHandleless?.(ks)) ?? ks?.doorGeometry?.hasIntegratedHandle) return;\n    const openings = (c.cutoutSchema && c.cutoutSchema.openings) || [];\n    const norm = (t) => String(t || '').toLowerCase().replace(/[\\s_-]/g, '');\n    // A base pull-out's door front takes a drawer handle (pullOutFrontIsDrawer).\n    const _poDrawer = !!(Catalogue.pullOutFrontIsDrawer && Catalogue.pullOutFrontIsDrawer(c.cutoutSchema));\n    for (const op of openings) {\n      if (op.handle === false) continue;\n      if (c.lShapeUnit && op === openings[0] && openings.length > 1) continue;   // one handle per L-shape pair\n      const t = norm(op.type);\n      let frontType = null;\n      if (_poDrawer && t === 'door') frontType = ((Number(op.height) || 0) >= PAN_DRAWER_MIN_FRONT_MM) ? 'pan' : 'drawer';\n      else if (t === 'door' || t === 'glass' || t === 'bifoldh' || t === 'bifoldv') frontType = 'door';\n      else if (t === 'drawer' || t === 'topdrawer') {\n        frontType = ((Number(op.height) || 0) >= PAN_DRAWER_MIN_FRONT_MM) ? 'pan' : 'drawer';\n      } else continue;   // blank / open / oven aperture - no handle\n      const eff = effectiveHandle(c, frontType);\n      const product = eff && eff.product;\n      if (!product || !product.variantId) continue;\n      const key = String(product.variantId);\n      const prev = acc.get(key) || { product, qty: 0 };\n      prev.qty += 1;\n      acc.set(key, prev);\n    }\n  };\n\n  // A single plan-wide \"Handles\" section: every handle across the plan,\n  // aggregated by product (design \u00D7 finish \u00D7 size = one line per\n  // style/colour/size) with a total quantity. Null when the plan has none.\n  const buildHandlesSection = (cabs) => {\n    const acc = new Map();\n    for (const c of cabs) accumulateHandles(c, acc);\n    if (!acc.size) return null;\n    const section = derivedId(api.createSection('Handles'), 's:handles');\n    section.items = [...acc.values()].map(({ product, qty }) => {\n      const priceCents = (typeof product.price === 'number') ? product.price : 0;\n      const item = derivedId(api.createItem(\n        String(product.variantId),\n        product.title || 'Handle',\n        '',\n        qty,\n        (priceCents / 100).toFixed(2)\n      ), 'h:' + product.variantId);\n      item.attributes.handle = true;\n      item.compareAtPrice = (product.compareAtPrice && product.compareAtPrice > priceCents) ? (product.compareAtPrice / 100).toFixed(2) : null;   // was price (Arden, 2026-10-11)\n      item.attributes.quoteGroup = 'handles';\n      item.image = product.featuredImageUrl || null;   // see fillLineImages\n      item.url = product.handle ? ('/products/' + product.handle) : null;\n      return item;\n    });\n    return section;\n  };\n\n  // A LINE'S PICTURE. The planner builds its basket lines itself, and none\n  // of them carried a picture: the basket's 3D drawing covers units only, and\n  // the Shopify photo is merged in only on the /cart basket, never a planner\n  // one - so in the planner basket every appliance, sink, tap, hob, handle and\n  // worktop line showed an empty frame (Arden, 2026-10-08). Every line still\n  // without one takes its product photo from the catalogue: appliances, sinks,\n  // hobs and taps their product photo, worktops their material swatch, and\n  // anything else the catalogue holds its product's featured image. Lines\n  // whose product has no photo at all (most style products - trims, panels,\n  // posts) stay as they were.\n  function lineImageMap() {\n    const m = new Map();\n    const put = (vid, url) => { if (vid != null && url && !m.has(String(vid))) m.set(String(vid), url); };\n    try { (Catalogue.getAllAppliances?.() || []).forEach(a => put(a.variantId, a.productImageUrl || a.imageUrl)); } catch (_) {}\n    try { (Catalogue.getPlannerSinks?.() || []).forEach(sk => put(sk.variantId, sk.productImageUrl)); } catch (_) {}\n    try {\n      const wic = getWorktopItemCatalogue() || {};\n      [...(wic.hobs || []), ...(wic.sinks || []), ...(wic.taps || [])].forEach(w => put(w.variantId, w.imageUrl));\n    } catch (_) {}\n    try { (Catalogue.getWorktopMaterials?.() || []).forEach(wm => (wm.variants || []).forEach(v => put(v.id, wm.swatchUrl))); } catch (_) {}\n    return m;\n  }\n  function fillLineImages(basket) {\n    let map = null;\n    for (const sec of (basket.sections || [])) {\n      for (const it of (sec.items || [])) {\n        if (!it || it.image || !it.shopifyVariantId) continue;\n        if (!map) map = lineImageMap();\n        const vid = String(it.shopifyVariantId);\n        let url = map.get(vid) || null;\n        if (!url) {\n          try { const info = Catalogue.getVariantInfo?.(vid); url = (info && info.product && info.product.featuredImageUrl) || null; } catch (_) {}\n        }\n        if (url) it.image = url;\n      }\n    }\n  }\n\n  // A unit's lines: the cabinet, its chosen appliance(s), its chosen\n  // sink, then its panel board(s) - in plan-number order. Handles are NOT\n  // here; they live in their own section (see buildHandlesSection).\n  // A free-placed end panel is billed through the cut list as the BOARD it's\n  // cut from (boardItemsOwnedBy below) - never as a unit line of its own,\n  // which would charge it twice. It can now reach here via boardOwnerCabs,\n  // so the unit line has to be suppressed explicitly.\n  // A unit X'd out of the quote reaches here only as a board owner (see\n  // boardOwnerCabs): its panels are still bought, the unit itself is not.\n  // \"Add Rail to both sides\": the second profile means the FITTER adapts\n  // the cabinet on site (not us - Arden, 2026-10-21), so the unit's line says so in a note the customer\n  // can't edit or remove (attributes.fixedNote - rebuilt with every quote,\n  // shown above their own note, sent with the order). Arden, 2026-10-21.\n  const RAIL_BOTH_NOTE = 'Profile on both sides: your fitter will need to adapt this cabinet on site to fit the second profile.';\n  // A unit's OWN line (not its kit, sink or panels): the one that carries the\n  // unit's note (handleSetUnitNote). Keyed by the line object, for buildQuote.\n  const unitNoteLineCab = new WeakMap();\n  const unitItemFor = (c) => {\n    const it = (c.freestandingAppliance && c.freestandingAppliance.productHandle) ? soldApplianceItemFor(c)\n      : (c.variantId && !c.endPanelUnit ? buildItem(c) : null);\n    if (it && it.attributes && c.railSecondSide) it.attributes.fixedNote = RAIL_BOTH_NOTE;\n    if (it && it.attributes && c.pastryParts) it.attributes.fixedNote = pastrySetNote(c);\n    if (it && it.attributes && isPantryCab(c)) it.attributes.fixedNote = pantryFitterNote(c);\n    // Supplied as Parts (unit_type cutout_schema.suppliedAsParts): the basket\n    // badges the line so the customer knows what turns up.\n    if (it && it.attributes && unitSuppliedAsParts(c)) it.attributes.suppliedAsParts = true;\n    if (it) unitNoteLineCab.set(it, c.id);\n    return it;\n  };\n  const buildItemsFor = (c) => c.excludeFromQuote\n    ? [...boardItemsOwnedBy(c), ...featureItemsOwnedBy(c), ...railItemsOwnedBy(c), ...cornerPostItemsOwnedBy(c), ...doorEndItemsOwnedBy(c), ...legItemsOwnedBy(c), ...pantryPanelItemsOwnedBy(c)].filter(Boolean)\n    : [unitItemFor(c), fittingKitItemFor(c), ...applianceItemsFor(c), sinkItemFor(c), sinkInsertItemFor(c), ...pastryItemsOwnedBy(c),\n     ...boardItemsOwnedBy(c), ...featureItemsOwnedBy(c), ...railItemsOwnedBy(c), ...cornerPostItemsOwnedBy(c), ...doorEndItemsOwnedBy(c), ...legItemsOwnedBy(c), ...pantryPanelItemsOwnedBy(c)].filter(Boolean);\n\n  // Wall label for a section name (4-wall room: A/D/C/B; else \"Wall N\").\n  const wallLabelName = (walls, i) => {\n    const letters = (walls.length === 4) ? ['A', 'D', 'C', 'B'] : null;\n    return letters ? `Wall ${letters[i] || (i + 1)}` : `Wall ${i + 1}`;\n  };\n\n  // Group plannable cabinets into basket sections by the wall they sit\n  // against - sections in the SAME clockwise-from-bottom-left order as\n  // the numbering, units (any category) by position along the wall,\n  // each unit's panels right after it. Islands \u2192 \"Island / Other Units\".\n  const buildWallSections = (cabs) => {\n    const walls = getWalls(room);\n    const order = wallOrderClockwiseFromTop(walls);\n    const buckets = new Map();   // wallIndex \u2192 [{ c, t }]\n    const other = [];\n    for (const c of cabs) {\n      const slot = cabWallSlot(c, cabs, walls, order);\n      if (slot) (buckets.get(slot.wi) || buckets.set(slot.wi, []).get(slot.wi)).push({ c, t: slot.t });\n      else other.push(c);\n    }\n    // Within a wall, order lines by their PLAN number so the basket reads\n    // 1\u2192N exactly like the 2D plan. Grouping by owner unit alone put a\n    // unit's left-side panel/filler (a lower number) AFTER the unit, so\n    // the sequence dipped (e.g. 2, 1, 4). A stable sort keeps a unit's\n    // divider (which shares the unit's number) next to it.\n    const byPlanNumber = (x, y) =>\n      ((x.planLineNumber == null ? 1e9 : x.planLineNumber) -\n       (y.planLineNumber == null ? 1e9 : y.planLineNumber));\n    const sections = [];\n    order.forEach(i => {\n      if (!buckets.has(i)) return;\n      const section = derivedId(api.createSection(wallLabelName(walls, i)), 's:wall:' + i);\n      section.items = buckets.get(i).sort((a, b) => a.t - b.t)\n        .flatMap(e => buildItemsFor(e.c)).sort(byPlanNumber);\n      sections.push(section);\n    });\n    if (other.length) {\n      const section = derivedId(api.createSection('Island / Other Units'), 's:island');\n      section.items = other.flatMap(buildItemsFor).sort(byPlanNumber);\n      sections.push(section);\n    }\n    return sections;\n  };\n    // Plannable units now live in per-wall sections. Preserve any\n    // non-plannable \"Extras\" section (added via the picker) and keep\n    // it LAST. Nothing stays unsectioned.\n    const existingExtras = (basket.sections || []).find(s => s.name === 'Extras');\n    // Panels now live in their unit's wall / island section (added by\n    // buildItemsFor), so there's no separate End Panels section.\n    // Include no-variant cabs that OWN a board (the radius filler is cut from\n    // a filler panel and owns its board) so their board LINE is emitted;\n    // buildItemsFor skips their (non-existent) unit line.\n    // Cabinets that aren't quote lines themselves but OWN a board, so their\n    // board line is only emitted if they're walked here. The numbering pass\n    // makes a free-placed end panel the owner of its own board\n    // (face.cabIds[0] is the panel cab), and quoteItems drops endPanelUnit\n    // cabs - so without them here the board line was never emitted. The\n    // plan showed 1, 2, 3 and the basket 1, 3: the panel's number existed\n    // but its line didn't, while computeTotal still charged the board, so\n    // the basket didn't even add up to the total. Radius fillers had the\n    // identical problem and were re-admitted here first.\n    // ...and a unit X'd out of the quote that OWNS a board or an end-feature\n    // line. The appliances a customer supplies (washing machine, range cooker,\n    // fridge freezer) are excluded, but the end panels either side of them are\n    // ours, and a board belongs to the first face the numbering reaches. When\n    // that was the appliance's, the board took a plan number and never got a\n    // line - the schedule went 37 then 42, and four panels went unbilled\n    // (Arden, 2026-10-13). buildItemsFor emits only the panels for these.\n    const _ownsPanelLine = (c) =>\n      (endPanelLayout?.boards || []).some(b => b.ownerCabId === c.id)\n      || (endPanelLayout?.endFeatureBins || []).some(b => b.ownerCabId === c.id);\n    const boardOwnerCabs = (cabinets || []).filter(c =>\n      c.excludeFromQuote\n        ? _ownsPanelLine(c)\n        : ((!c.variantId && c.radiusGroup && c.radiusGroup.role === 'filler')\n           || c.endPanelUnit));\n    (basket.sections || []).forEach(sec => (sec.items || []).forEach(it => {\n      if (it && it.plannerCabinetId != null && it.attributes && it.attributes.assembly\n          && it.attributes.quoteGroup === 'units') {\n        prevAssemblyByCab.set(it.plannerCabinetId, it.attributes.assembly);\n      }\n      if (it && it.plannerCabinetId != null && it.attributes && Array.isArray(it.attributes.addons)\n          && it.attributes.addons.length && it.attributes.quoteGroup === 'units') {\n        prevAddonsByCab.set(it.plannerCabinetId, it.attributes.addons);\n      }\n    }));\n    // NOTES are written on the basket line too (the customer's, and staff's\n    // note for our team), so they are carried across the rebuild like the\n    // assembly - they vanished on every reload of a plan (bug sheet, Sales\n    // row 35). By the line's own id first (derived ids are stable for the same\n    // plan thing), then by its unit for a unit line whose id moved. Staff's\n    // Send Direct tick rides along the same way, and a manager's goodwill\n    // discount (attributes.gwg, planner-api src/gwg.js) - the basket only\n    // shows it while the line is the same item (btk-cart-advanced.js lineGwg).\n    const prevNotesById = new Map(), prevNotesByCab = new Map();\n    // The lines already there (by their derived id, stable for the same plan\n    // thing): only one of those can have had its note changed in the basket -\n    // a new line has nothing to say about a unit's note.\n    const prevLineIds = new Set();\n    for (const list of [...(basket.sections || []).map(sec => sec.items || []), basket.items || []]) {\n      for (const it of list) {\n        const a = it && it.attributes;\n        if (it && it.id) prevLineIds.add(it.id);\n        if (!a || !(a.notes || a.staffNote || a.sendDirect || a.gwg)) continue;\n        const n = { notes: a.notes || null, staffNote: a.staffNote || null, sendDirect: !!a.sendDirect, gwg: a.gwg || null };\n        if (it.id) prevNotesById.set(it.id, n);\n        if (it.plannerCabinetId != null && a.quoteGroup === 'units') prevNotesByCab.set(it.plannerCabinetId, n);\n      }\n    }\n    basket.sections = buildWallSections([...quoteItems, ...boardOwnerCabs]);\n    // Worktops - one line per slab-tier material group (the nested tier\n    // variant). Its own section, after the unit walls, before Extras.\n    // Uses the SAME computeWorktopCharges the running total does, so the\n    // basket lines and the quote total always agree.\n    const wtCharges = computeWorktopCharges();\n    if (wtCharges.length) {\n      const wtSection = derivedId(api.createSection('Worktops'), 's:worktops');\n      wtSection.items = wtCharges.map(ch => {\n        const v = ch.variant;\n        // A slab-tier charge is one tier variant (\"1.5 slabs\"); a board\n        // charge is N of one stock size (\"3000 \u00D7 600 \u00D7 38mm\"), so both the\n        // label and the quantity come off the charge.\n        const item = derivedId(api.createItem(\n          String(v.variantId), v.name || 'Worktop',\n          ch.label || (ch.bill && ch.bill.tierLabel) || '', ch.qty || 1,\n          ((v.priceCents || 0) / 100).toFixed(2)\n        ), 'wt:' + (ch.handle || '') + ':' + v.variantId);\n        item.attributes.style = kitchenStyleId || null;\n        item.attributes.quoteGroup = 'worktops';\n        // Its picture: the material's swatch (its photo where it has none).\n        // The charge's variant is a price tier / band, not one of the\n        // material's own variants, so it is looked up by material.\n        { const _wm = Catalogue.getWorktopMaterial?.(ch.handle || v.materialHandle);\n          item.image = (_wm && _wm.swatchUrl) || null; }\n        // The words after the product name in the basket: the board size, or\n        // the colour and thickness of a bespoke job. Never read off the\n        // variant title (\"Band 0308\" is a price step, not a size).\n        item.attributes.worktopDetail = ch.detail || ch.label || '';\n        // The made-to-measure specification, one item per line. Rides to Odoo\n        // as a hidden cart property and lands on the sale order line's\n        // item_note, which bk_stock copies onto the supplier's PO line.\n        item.attributes.worktopSpec = (ch.spec && ch.spec.length) ? ch.spec.join('\\n') : null;\n        item.url = v.url || (v.materialHandle ? ('/products/' + v.materialHandle) : null);\n        item.compareAtPrice = (v.compareAtCents && v.compareAtCents > (v.priceCents || 0))\n          ? (v.compareAtCents / 100).toFixed(2) : null;\n        return item;\n      });\n      basket.sections.push(wtSection);\n    }\n    // AUTOMATIC ITEMS (computeAutoItemCharges): worktop kits join the Worktops\n    // section; touch up paint and the fittings pack are Accessories, in a\n    // section of their own after Handles. Each line is tagged autoItem so the\n    // basket's Exclude popup can warn before it is taken out.\n    const autoCharges = computeAutoItemCharges();\n    const autoLine = (ch) => {\n      const p = ch.product;\n      const item = derivedId(api.createItem(\n        String(p.variantId), p.title || ch.rule.title || 'Item', ch.detail || '', ch.qty,\n        ((p.priceCents || 0) / 100).toFixed(2)\n      ), ch.key);\n      item.attributes.quoteGroup = ch.group;\n      item.attributes.autoItem   = ch.rule.key;\n      item.attributes.style      = ch.style || null;\n      // Touch up paint is made in the door colour it is for.\n      item.attributes.doorColour    = ch.colour || null;\n      item.attributes.carcaseColour = null;\n      item.image = p.image || null;\n      item.url = p.url || null;\n      item.compareAtPrice = (p.compareAtCents && p.compareAtCents > (p.priceCents || 0))\n        ? (p.compareAtCents / 100).toFixed(2) : null;\n      return item;\n    };\n    const autoWorktop = autoCharges.filter(ch => ch.group === 'worktops');\n    if (autoWorktop.length) {\n      let wtSec = (basket.sections || []).find(s => s && s.id === 'q:s:worktops');\n      if (!wtSec) { wtSec = derivedId(api.createSection('Worktops'), 's:worktops'); basket.sections.push(wtSec); }\n      wtSec.items = (wtSec.items || []).concat(autoWorktop.map(autoLine));\n    }\n    const autoOther = autoCharges.filter(ch => ch.group !== 'worktops');\n    // A bespoke worktop our team has to price (a postcode outside the\n    // templating zones): not a Shopify line - there is no price to charge -\n    // but the basket shows it, with Request a Price, and checkout waits for\n    // it. When it was asked for travels with it across rebuilds; if the\n    // worktop has changed since (requestedKey), the basket asks again.\n    if (lastWorktopPriceRequest) {\n      const asked = worktopBespoke.requested;\n      const later = worktopBespoke.deferred;\n      basket.priceRequest = {\n        ...lastWorktopPriceRequest,\n        requestedAt: (asked && asked.at) || null,\n        requestedKey: (asked && asked.key) || null,\n        requestedTicket: (asked && asked.ticket) || null,\n        deferredAt: (later && later.at) || null,\n        deferredKey: (later && later.key) || null,\n      };\n    } else {\n      delete basket.priceRequest;\n    }\n    // Worktop items - free-placed hobs / sinks / taps, each a real Shopify\n    // product. One priced line each, grouped into a section per kind, in the\n    // SAME plan-number order as their 2D badges (stamped in the numbering\n    // sweep). Own sections after Worktops.\n    const WI_SECTION = [['hob', 'Hobs'], ['extractor', 'Extractors'], ['sink', 'Sinks'], ['tap', 'Taps']];\n    for (const [kind, label] of WI_SECTION) {\n      const placed = (worktopItems || [])\n        // Canopy extractors bill in the Extractors section with the wall hoods.\n        .filter(it => it && (it.kind === kind || (kind === 'extractor' && it.kind === 'canopy')) && it.variantId)\n        .sort((a, b) => ((a.planLineNumber == null ? 1e9 : a.planLineNumber)\n                       - (b.planLineNumber == null ? 1e9 : b.planLineNumber)));\n      if (!placed.length) continue;\n      const sec = derivedId(api.createSection(label), 's:wi:' + kind);\n      sec.items = placed.map(wi => {\n        const priceCents = (typeof wi.priceCents === 'number') ? wi.priceCents : 0;\n        const item = derivedId(api.createItem(\n          String(wi.variantId), wi.name || label, '', 1,\n          (priceCents / 100).toFixed(2)\n        ), 'wi:' + kind + ':' + (wi.id || wi.variantId));\n        item.attributes.appliance  = true;\n        item.attributes.quoteGroup = 'appliances';\n        item.attributes.brand      = wi.brand || null;\n        // The free tap offer's tap, put in place of this one from the basket\n        // (window.__btkPlannerSwapTap) - so the cart sends it as the gift.\n        if (kind === 'tap' && wi.freeGift) item.attributes.freeGift = true;\n        item.url = wi.handle ? ('/products/' + wi.handle) : (wi.productUrl || null);\n        item.planLineNumber = (wi.planLineNumber != null) ? wi.planLineNumber : null;\n        item.compareAtPrice = (wi.compareAtCents && wi.compareAtCents > priceCents)\n          ? (wi.compareAtCents / 100).toFixed(2) : null;\n        return item;\n      });\n      basket.sections.push(sec);\n    }\n    // Trims - plinth / cornice / pelmet, billed by stock length, plus the\n    // per-piece External Curved Plinth. Own section after Worktops.\n    const trimCharges = computeTrimCharges();\n    if (trimCharges.length) {\n      const trSection = derivedId(api.createSection('Trims'), 's:trims');\n      trSection.items = trimCharges.map(ch => {\n        const p = ch.product;\n        const item = derivedId(api.createItem(\n          String(p.variantId), ch.name, ch.detail, ch.qty,\n          ((p.priceCents || 0) / 100).toFixed(2)\n        ), trimLineKey(ch));\n        // The range the line is billed in (computeTrimCharges): the trim over\n        // F&B wall units in a Lacquered Oak plan is the F&B range's.\n        item.attributes.style = ch.style || kitchenStyleId || null;\n        item.attributes.quoteGroup = 'trims';\n        // Trim is painted, so show the door chip only - in the colour this\n        // line is billed in (its trim type's colour, or its units').\n        item.attributes.doorColour    = ch.colour || globalDoorColourHandle || null;\n        item.attributes.carcaseColour = null;\n        item.url = p.url || (p.handle ? ('/products/' + p.handle) : null);\n        item.compareAtPrice = (p.compareAtCents && p.compareAtCents > (p.priceCents || 0))\n          ? (p.compareAtCents / 100).toFixed(2) : null;\n        return item;\n      });\n      basket.sections.push(trSection);\n    }\n    // True Handleless profiles - lengths, corner joints, end plates, verticals\n    // and spacers, in the Profile Finish (computeRailCharges). Filed in the\n    // HANDLES group: a profile is a True Handleless kitchen's handle, and the\n    // quote, basket, checklist and order import all know that group.\n    const railCharges = computeRailCharges().filter(ch => !ch.ownerCabId);\n    if (railCharges.length) {\n      const pfSection = derivedId(api.createSection('Profiles'), 's:profiles');\n      pfSection.items = railCharges.map(ch => {\n        const p = ch.product;\n        const item = derivedId(api.createItem(\n          String(p.variantId), ch.name, ch.detail, ch.qty,\n          ((p.priceCents || 0) / 100).toFixed(2)\n        ), 'pf:' + p.variantId);\n        item.attributes.style = kitchenStyleId || null;\n        item.attributes.quoteGroup = 'handles';\n        // Metal, not painted: no door / carcase chip.\n        item.attributes.doorColour    = null;\n        item.attributes.carcaseColour = null;\n        item.url = p.url || null;\n        item.image = p.imageUrl || item.image || null;\n        item.compareAtPrice = (p.compareAtCents && p.compareAtCents > (p.priceCents || 0))\n          ? (p.compareAtCents / 100).toFixed(2) : null;\n        return item;\n      });\n      basket.sections.push(pfSection);\n    }\n    // Handles - one plan-wide section, aggregated per product (style /\n    // colour / size), after Trims. Like trims and worktops these carry no\n    // PLAN number of their own; the continuation pass below numbers them\n    // after the last plan-numbered item, so they never disturb the units.\n    const handlesSection = buildHandlesSection(quoteItems);\n    if (handlesSection) basket.sections.push(handlesSection);\n    // Touch up paint, the fittings pack (automatic items, above).\n    // Bar stools go in with them.\n    const furnitureLine = (ch) => {\n      const p = ch.product;\n      const item = derivedId(api.createItem(String(p.variantId), p.name || 'Item', '', ch.qty,\n        ((p.priceCents || 0) / 100).toFixed(2)), ch.key);\n      item.attributes.quoteGroup    = 'other';\n      item.attributes.planQty       = true;   // how many are on the plan\n      item.attributes.doorColour    = null;\n      item.attributes.carcaseColour = null;\n      item.image = p.productImageUrl || p.imageUrl || null;\n      item.url = '/products/' + p.id;\n      item.compareAtPrice = (p.compareAtCents && p.compareAtCents > (p.priceCents || 0))\n        ? (p.compareAtCents / 100).toFixed(2) : null;\n      return item;\n    };\n    const furnitureCharges = computeFurnitureCharges();\n    if (autoOther.length || furnitureCharges.length) {\n      const acSection = derivedId(api.createSection('Accessories'), 's:auto');\n      acSection.items = [...autoOther.map(autoLine), ...furnitureCharges.map(furnitureLine)];\n      basket.sections.push(acSection);\n    }\n    // Extras section (LAST): picker-added items PLUS anything carried over by a\n    // \"Convert Basket to Plan\" (worktops/appliances/accessories + units that\n    // couldn't be laid out). Merge the convert extras in ONCE, then clear them\n    // so a later re-sync doesn't duplicate the lines.\n    let extrasSection = existingExtras;\n    if (convertExtras && convertExtras.length) {\n      if (!extrasSection) extrasSection = derivedId(api.createSection('Extras'), 's:extras');\n      for (const ex of convertExtras) {\n        const exItem = derivedId(api.createItem(\n          String(ex.variantId), ex.productTitle || 'Item', ex.variantTitle || '',\n          ex.quantity || 1, ex.price || '0'\n        ), 'x:' + ex.variantId + ':' + (ex.variantTitle || ''));\n        exItem.image = ex.image || null;\n        if (exItem.attributes) {\n          exItem.attributes.doorColour    = ex.doorColour || null;\n          exItem.attributes.carcaseColour = ex.carcaseColour || null;\n          if (ex.style) exItem.attributes.style = ex.style;\n        }\n        extrasSection.items.push(exItem);\n      }\n      convertExtras = [];\n    }\n    // Every line worked out from the plan has its quantity locked in the\n    // basket: the plan sets it, and a rebuild puts the plan's count back, so\n    // a + or - there was lost on the next save (bug sheet row 79: handle\n    // quantities \"go back to the original amount\"). Extras keep theirs.\n    for (const sec of basket.sections) {\n      for (const it of (sec && sec.items) || []) {\n        if (it && derivedIds.has(it.id) && it.attributes) it.attributes.planQty = true;\n      }\n    }\n    if (extrasSection) basket.sections.push(extrasSection);\n    // Exclusions / free lines saved under the OLD number-based board and\n    // end-feature ids move to the piece-based ids (boardLineKey) where the old\n    // number still names a line on the same unit; old keys that match nothing\n    // are dropped, so a stale one can never land on another piece.\n    {\n      const moves = new Map(_lineIdMoves.filter(([o, n]) => o !== n).map(([o, n, t]) => [o, { id: n, title: t }]));\n      const current = new Set(_lineIdMoves.map(([, n]) => n));   // ids in use now (a fallback id can be old-form)\n      const migrate = (bag) => {\n        let next = null;\n        for (const k of Object.keys(bag)) {\n          if (!/^q:(?:b|ef):[^,]+:\\d+$/.test(k) || current.has(k)) continue;   // only a stale old-form key\n          // The same number on the same unit can be a DIFFERENT piece now (the\n          // plan was renumbered since): carry it over only if it is still the\n          // same product - the exclusion saved its name. Else drop it.\n          const mv = moves.get(k);\n          const sameThing = mv && !(bag[k] && bag[k].name && mv.title && bag[k].name !== mv.title);\n          if (mv && sameThing) {\n            next = next || { ...bag };\n            if (!next[mv.id]) next[mv.id] = bag[k];\n            delete next[k];\n          } else if (mv) {\n            next = next || { ...bag };\n            delete next[k];\n          } else if (!moves.has(k) && _lineIdMoves.length) {   // (never on a build with no panel lines yet)\n            next = next || { ...bag };\n            delete next[k];\n          }\n        }\n        return next;\n      };\n      const ex2 = migrate(quoteExcludedLines);\n      if (ex2) { quoteExcludedLines = ex2; setTimeout(refreshHiddenPlanNumbers, 0); }   // the plan drew its numbers before this\n      const fr2 = migrate(quoteFreeLines);\n      if (fr2) quoteFreeLines = fr2;\n    }\n    // Lines excluded in the basket's Exclude popup are left out (see\n    // quoteExcludedLines), before the lines are numbered, so the numbers run on\n    // without gaps. A section left with nothing in it goes too.\n    if (Object.keys(quoteExcludedLines).length) {\n      // An appliance line's id is its SLOT (q:ap:<unit>:<slot>), not the\n      // appliance, so swapping the appliance in that slot kept the exclusion:\n      // Alex Williams' BEKIA microwave was excluded, a CDA VM551SS went in its\n      // place and never reached the basket (Julian, 2026-10-22). The exclusion\n      // saved the product's name - a different product in the slot is not the\n      // thing that was excluded, so the exclusion goes.\n      let stale = null;\n      basket.sections = (basket.sections || []).filter(sec => {\n        const had = (sec.items || []).length;\n        sec.items = (sec.items || []).filter(it => {\n          const ex = it && it.id && quoteExcludedLines[it.id];\n          if (!ex) return true;\n          // Sinks, hobs and extractors on the worktop work the same way (their\n          // line is the worktop item, whatever model is in it). NOT taps: the\n          // free tap offer keeps the tap's line excluded while it swaps the tap.\n          if (/^q:(?:ap:|wi:(?:sink|hob|extractor|canopy):)/.test(it.id) && ex.name && ex.name !== 'Item' && it.productTitle && ex.name !== it.productTitle) {\n            (stale = stale || []).push(it.id);\n            return true;\n          }\n          return false;\n        });\n        return sec.items.length || !had;\n      });\n      if (stale) {\n        const next = { ...quoteExcludedLines };\n        stale.forEach(id => { delete next[id]; });\n        quoteExcludedLines = next;\n        if (typeof scheduleAutosave === 'function') scheduleAutosave();\n      }\n    }\n    fillLineImages(basket);\n    basket.items = [];\n    // A Worktop Quote's basket is the worktop order alone (Sales line 108).\n    if (worktopQuote) applyWorktopQuoteToBasket(basket);\n    // CONTINUATION NUMBERING. Every line carries a number and the numbers go\n    // through to Odoo, so they must not collide and must not restart.\n    // Plan-numbered items - units, panels, END PANELS, appliances, the ones\n    // whose number is drawn on the plan - keep theirs. The categories added\n    // AFTER the plan (worktops, trims, handles, extras) are numbered from the\n    // last plan number upward, in basket order.\n    //\n    // \u26A0 STRICTLY OPT-IN, by quote group. An earlier version numbered EVERY\n    // item that had no planLineNumber, which was wrong and broke the plan:\n    // units, dividers and end-panel boards all set\n    // `planLineNumber = displayNumber ?? null`, so any of them without a\n    // number got stamped with a continuation one, lifting it above the plan\n    // range and sorting it to the bottom of the schedule - end panels looked\n    // like they had disappeared and plan numbers stopped matching the list.\n    // Those must keep falling back to the basket's own lineNumber exactly as\n    // they always did. Only the groups below are ours to number.\n    // Accessories and Extras are numbered afresh on every build (Arden,\n    // 2026-10-30: everything supplied gets a number). An Extras line used to\n    // keep the number it was first given, so once the plan had fewer numbered\n    // items the trims counted on from that old number and left a gap (John\n    // Jones, WKIT-SO300096: the loose door kept 25, trims 26-28, nothing at\n    // 23-24), and the auto accessories had no number at all, so they fell back\n    // to their basket position and took 26 and 27 a second time.\n    const NUMBER_AFTER_PLAN = new Set(['worktops', 'trims', 'handles']);\n    const RENUMBERED_SECTIONS = new Set(['Accessories', 'Extras']);\n    (() => {\n      for (const sec of (basket.sections || [])) {\n        if (!RENUMBERED_SECTIONS.has(sec.name)) continue;\n        for (const it of (sec.items || [])) it.planLineNumber = null;\n      }\n      let next = 0;\n      for (const sec of (basket.sections || [])) {\n        for (const it of (sec.items || [])) {\n          if (it.planLineNumber != null && it.planLineNumber > next) next = it.planLineNumber;\n        }\n      }\n      next += 1;\n      for (const sec of (basket.sections || [])) {\n        const renumbered = RENUMBERED_SECTIONS.has(sec.name);\n        for (const it of (sec.items || [])) {\n          if (it.planLineNumber != null) continue;\n          const group = (it.attributes && it.attributes.quoteGroup) || '';\n          if (!NUMBER_AFTER_PLAN.has(group) && !renumbered) continue;\n          it.planLineNumber = next++;\n        }\n      }\n    })();\n    // EXTRA DISCOUNT (Arden, 2026-10-11): the extra 10% (or whichever is live) is\n    // already in the catalogue's prices. Give each line what the cart page gets\n    // from Shopify - the discount's name and amount, and the price before it -\n    // so the basket's Price Breakdown shows its Extra Discounts row and the\n    // line its flag. Only for products the catalogue says carry one (xd).\n    for (const list of [...(basket.sections || []).map(s => s.items || []), basket.items || []]) {\n      for (const it of list) {\n        try {\n          const vi = it && it.shopifyVariantId && Catalogue.getVariantInfo\n            ? Catalogue.getVariantInfo(String(it.shopifyVariantId)) || Catalogue.getVariantInfo(Number(it.shopifyVariantId)) : null;\n          const xd = vi && vi.product && vi.product.xd != null && window.BTKExtraDiscount\n            ? window.BTKExtraDiscount.byIndex(vi.product.xd) : null;\n          const nowCents = Math.round((parseFloat(it.price) || 0) * 100);\n          if (!xd || !(xd.percent > 0 && xd.percent < 100) || !(nowCents > 0)) continue;\n          const before = Math.round(nowCents / (1 - xd.percent / 100));\n          it.originalPrice  = (before / 100).toFixed(2);\n          it.extraDiscounts = [{ title: xd.title, percent: xd.percent,\n                                 amount: (before - nowCents) * (Number(it.quantity) || 1) / 100 }];\n        } catch (e) { /* no flag for this line */ }\n      }\n    }\n    // FREE LINES (see quoteFreeLines): \u00A30 here, the planner's price kept as the\n    // \"Was\", and the code on the line for the cart sync to put on the cart\n    // (btk-basket-api.js applyFreeItemCodes) - Shopify makes it \u00A30 at checkout.\n    // After the extra discount, which the free line no longer carries.\n    if (Object.keys(quoteFreeLines).length) {\n      for (const sec of (basket.sections || [])) {\n        for (const it of (sec.items || [])) {\n          const f = it && it.id ? quoteFreeLines[it.id] : null;\n          if (!f || !f.code) continue;\n          if (String(f.variantId) !== String(it.shopifyVariantId)\n              || Number(f.quantity || 1) !== Number(it.quantity || 1)) continue;\n          // An offer past its end pays again (the code has expired too).\n          if (f.endsAt && !(Date.parse(f.endsAt) > Date.now())) continue;\n          const was = parseFloat(it.originalPrice) > parseFloat(it.price) ? parseFloat(it.originalPrice) : parseFloat(it.price);\n          const wasGbp = was > 0 ? was : 0;\n          it.originalPrice = wasGbp.toFixed(2);\n          it.price = '0.00';\n          // The whole line as one saving, so the Price Breakdown still adds up\n          // (online price less extra discounts = total). `free` keeps it out of\n          // the extra-10% test that decides the Kitchen Units block.\n          const freeTitle = 'Free ' + (it.productTitle || 'item');\n          it.extraDiscounts = [{ title: freeTitle, percent: 100, amount: wasGbp * (Number(it.quantity) || 1), free: true }];\n          if (it.attributes) it.attributes.freeItem = { code: f.code, amount: f.amount || null, by: f.by || null,\n                                                        endsAt: f.endsAt || null, title: freeTitle };\n        }\n      }\n    }\n    // FREE DELIVERY (staff, the basket's Make Delivery Free): kept in\n    // quoteFreeLines under '__delivery', and put on the basket for the cart\n    // sync to put its code on the cart. An offer past its end is gone.\n    {\n      const fd = quoteFreeLines.__delivery;\n      if (fd && fd.code && !(fd.endsAt && !(Date.parse(fd.endsAt) > Date.now()))) {\n        basket.freeDelivery = { code: fd.code, endsAt: fd.endsAt || null, by: fd.by || null, title: 'Free delivery' };\n      } else delete basket.freeDelivery;\n    }\n    // BESPOKE PAINT (Arden, 2026-10-10): a line in an F&B / RAL paint is the\n    // range's own colour product (\"Farrow & Ball Colour\") with the paint named\n    // beside it, exactly as the website adds one - attributes.bespokeColour,\n    // sent as _btk_bespoke_colour - so the order carries the colour to paint.\n    // Every line kind (units, panels, trims, extras) in one place.\n    for (const list of [...(basket.sections || []).map(s => s.items || []), basket.items || []]) {\n      for (const it of list) {\n        const a = it && it.attributes;\n        // A Doors, Panels & Accessories extra follows the plan's colour.\n        if (a) backfillExtraColour(it);\n        if (a && a.extraColour) stampExtraColour(it);\n        const bp = a && Catalogue.getBespokePaint ? Catalogue.getBespokePaint(a.doorColour) : null;\n        if (!bp) continue;\n        a.bespokeColour = { type: bp.type, value: bp.value, ...(bp.own && bp.hex ? { hex: bp.hex } : {}) };\n        a.doorColour = bp.baseHandle;\n      }\n    }\n    // The notes read before the rebuild, back on their lines (see prevNotesById).\n    for (const list of [...(basket.sections || []).map(sec => sec.items || []), basket.items || []]) {\n      for (const it of list) {\n        const a = it && it.attributes;\n        if (!a) continue;\n        const n = prevNotesById.get(it.id)\n          || (it.plannerCabinetId != null && a.quoteGroup === 'units' ? prevNotesByCab.get(it.plannerCabinetId) : null);\n        if (!n) continue;\n        if (n.notes && !a.notes) a.notes = n.notes;\n        if (n.staffNote && !a.staffNote) a.staffNote = n.staffNote;\n        if (n.sendDirect) a.sendDirect = true;\n        if (n.gwg && !a.gwg) a.gwg = n.gwg;\n      }\n    }\n    // A unit's note and its own line's note are one note (handleSetUnitNote).\n    // Typed on the unit since the last rebuild: onto the line. Otherwise the\n    // line's - typed, changed or cleared in the basket - back onto the unit.\n    let unitNotesFromBasket = false;\n    for (const list of [...(basket.sections || []).map(sec => sec.items || []), basket.items || []]) {\n      for (const it of list) {\n        const cabId = it && it.attributes ? unitNoteLineCab.get(it) : undefined;\n        const cab = cabId != null ? (cabinets || []).find(c => c && c.id === cabId) : null;\n        if (!cab) continue;\n        const lineNote = String(it.attributes.notes || '').trim() || null;\n        if (cab.notePending || !prevLineIds.has(it.id)) {\n          if (cab.note || cab.notePending) it.attributes.notes = cab.note || null;\n          delete cab.notePending;\n        } else if (lineNote !== (cab.note || null)) {\n          cab.note = lineNote;\n          unitNotesFromBasket = true;\n        }\n      }\n    }\n    if (unitNotesFromBasket) {\n      // Its marker on the plan, and the plan saved with it.\n      setTimeout(() => { try { applySelectionVisual(); } catch (_) {} scheduleAutosave(); }, 0);\n    }\n    api.recalculateLineNumbers(basket);\n    return basket;\n  }\n\n  async function transferPlanToBasket(openEmbed = true, opts = {}) {\n    await awaitJourneySave();   // the plan's basket may still be being created\n    const quiet = !!opts.quiet;\n    const api = window.BTKBasketAPI;\n\n    if (window.BTKLoader && !quiet) window.BTKLoader.show({\n      messages: ['Checking Plan\u2026', 'Building Parts List\u2026', 'Generating Quote\u2026'],\n      intervalMs: 550,      // fairly quick rotation\n      holdLast: true,       // settle on \"Generating Quote\u2026\"\n      // Just long enough not to flash. It used to be 1900, which made every\n      // transfer feel like 2 seconds even when the work took 200ms; the messages\n      // rotating was never worth the wait.\n      minVisibleMs: 400\n    });\n    try {\n      // Persist the current design first so the planner basket carries\n      // both the 3D plan AND its line items (one save object).\n      // A quiet correction waits for the prices (ensureStyleProducts resyncs);\n      // opening the basket gets them first if it can.\n      if (planPricesPending()) {\n        if (quiet) return;\n        await loadPlanPrices();\n      }\n      const design = currentDesign();   // priced by planStore.save (stampPlanPrice)\n      // The plan itself is saved by its own autosave; a quiet correction only\n      // needs to restamp the basket, so skip this round trip.\n      // OPENING THE BASKET does not wait for the server: the lines are built\n      // from this page's copy and shown at once, and the writes finish behind\n      // (Arden, 2026-09-28: \"show the basket immediately and save in the\n      // background\"). Checkout, and a quiet correction, still wait as before.\n      const background = openEmbed && !quiet && !!api.saveBasketSoon;\n      const savePayload = quiet ? null : await planStore.save(design, { soon: background });\n      try { window.BTKKPMark && window.BTKKPMark(\"plan stored\"); } catch (_) {}\n      const workingId = await (planStore.getActiveBasketId ? planStore.getActiveBasketId() : Promise.resolve(null));\n\n      const project = await api.getProject();\n      const planId  = design.plannerPlanId;\n      // Reuse THIS plan's basket: by the working pointer, else by the\n      // plan's intrinsic id. Only create one if neither matches - so a\n      // re-add updates the same basket instead of duplicating it.\n      // Never a basket holding another plan (basketHoldsOtherPlan).\n      let basket = (project.baskets || []).find(b => b.id === workingId && !basketHoldsOtherPlan(b))\n        || (project.baskets || []).find(b => b.source === 'planner'\n              && b.plannerDesign && b.plannerDesign.design\n              && b.plannerDesign.design.plannerPlanId === planId);\n      // A quiet correction with no basket of this plan's: nothing to correct.\n      if (!basket && quiet) return;\n      if (!basket) basket = await api.createBasket(activePlanName || 'Planner Quote', 'planner');\n\n      // Keep the user's saved name; only fall back if somehow unnamed.\n      if (basket.isDraft || !basket.name || basket.name === 'Unsaved Plan') {\n        basket.name = activePlanName || 'Planner Quote';\n      }\n\n      basket.isDraft = false;\n      basket.source  = 'planner';\n      // Derive every line from the plan. Pure and local: see buildQuote.\n      buildQuote(basket, { silent: quiet });\n      try { window.BTKKPMark && window.BTKKPMark(\"basket lines worked out\"); } catch (_) {}\n      // Stamp the design onto the basket itself so it always carries the\n      // 3D plan (and so \"Edit Plan\" can restore it) - independent of\n      // whatever planStore.save targeted.\n      if (savePayload) basket.plannerDesign = savePayload;\n      let savedOnServer = null;   // set only on the background path\n      if (planPricesPending()) { /* the lines are not at today's prices: not saved */ }\n      else if (background) savedOnServer = (await api.saveBasketSoon(basket)).saved;\n      else await api.saveBasket(basket);\n      try { window.BTKKPMark && window.BTKKPMark(\"basket stored (server save continues behind)\"); } catch (_) {}\n\n      // The cart is NOT written here. It is a checkout staging area, not\n      // storage: one cart per browser, which whichever surface you are on\n      // claims for itself (/cart re-points it to the manual basket the moment\n      // you go there). Filling it on every rebuild meant clearing and re-adding\n      // every line just to open the basket, which is the slowest step there is,\n      // and rebuilding it wholesale is what produced both of this morning's\n      // faults - doubled quantities from two overlapping pushes, and lines\n      // replaced by detail-less copies. So the plan is saved here and the cart\n      // is marked stale; flushCartForCheckout() fills it when it matters.\n      cartNeedsSync = true;\n      lastQuoteBasketId = basket.id;\n      // \"What has just been saved\" - and checkout SKIPS its own save when the\n      // plan matches it. So on the background path it is recorded only once\n      // the server confirms the write. Arming it before would let a failed or\n      // unfinished write reach payment with no basket on the server behind the\n      // order (the other planner session, 2026-09-28). Unset meanwhile, so an\n      // early checkout saves for itself.\n      if (savedOnServer) {\n        transferredSignature = null;\n        const sig = undoSnapshot();\n        const forBasket = basket.id;\n        savedOnServer.then(() => {\n          if (lastQuoteBasketId === forBasket) transferredSignature = sig;\n        }, () => { /* left unset: checkout will save; btk:project-save-failed shows it */ });\n      } else {\n        transferredSignature = undoSnapshot();\n      }\n      // NOTHING is captured here. A full-page rasterise before the basket\n      // opened made it slow again (Arden, 2026-09-27), which was the whole\n      // complaint this work started from. The floor plan is moving to vector\n      // drawing from the model, which needs no picture and no live DOM.\n      if (openEmbed) openBasketEmbed();\n      // Build and post the plan report for this basket, in the BACKGROUND and\n      // ON IDLE. Not awaiting it was not enough: the build renders the 3D views\n      // and scans four full-page canvases, all on the main thread, so starting\n      // it here made the basket take 5-10 seconds to open. Waiting for idle\n      // lets the basket paint first and the customer read it while the report\n      // is made. If it fails, or the device cannot render, they simply do not\n      // get the PDF on the order - they still get the kitchen.\n      if (!quiet) scheduleReportUpload(basket.id);\n    } catch (e) {\n      console.error('[BTK Kitchen Planner] Add to basket failed', e);\n      if (window.BTKLoader) window.BTKLoader.hide();\n      window.BTKKPDialog.alert('Sorry, we could not add your plan to the basket. Please try again.', { title: 'Something went wrong', danger: true });\n    }\n  }\n\n  // The separate planner cart drawer has been removed - it was an extra\n  // step to the same data. \"Live Quote\" (top bar) and the step-5 \"Open\n  // basket\" button now open the embedded advanced basket directly, via\n  // the same transfer flow. basketDrawerHandle stays the no-op stub\n  // declared above, so any leftover .refresh()/.open() calls are harmless.\n  async function openLiveQuote() {\n    startBasketTiming();\n    const hasUnits = (cabinets || []).some(c => !c.excludeFromQuote && c.variantId);\n    if (!hasUnits) {\n      window.BTKKPDialog.alert('There are no purchasable units in your plan to add yet.', { title: 'Nothing to add' });\n      return;\n    }\n    // A new, unsaved plan is named first (converts it to a saved basket);\n    // a saved plan opens the live quote straight away.\n    if (!activePlanName) {\n      openSaveAsPopup(() => transferPlanToBasket());\n      return;\n    }\n    // Nothing changed since the basket was last built from the plan: it is\n    // already right, so just open it. Every open used to rebuild and re-save\n    // it - the whole project PUT twice (planStore.save, then saveBasket), a\n    // few seconds each - before anything appeared (Arden, 2026-09-28: \"very\n    // slow to load\"). The same test proceedToCheckoutRun uses.\n    if (lastQuoteBasketId && transferredSignature && undoSnapshot() === transferredSignature) {\n      try { window.BTKKPMark && window.BTKKPMark(\"plan unchanged - opening the basket as it is\"); } catch (_) {}\n      openBasketEmbed();\n      return;\n    }\n    try {\n      window.BTKKPMark && window.BTKKPMark('rebuilding the basket - ' + (!lastQuoteBasketId\n        ? 'first open since the page loaded'\n        : !transferredSignature ? 'the last save is not confirmed yet' : 'the plan has changed'));\n    } catch (_) {}\n    await transferPlanToBasket();\n  }\n\n  // Bottombar \"Proceed to Checkout\": gate + name the plan if needed, push the\n  // plan down to the Shopify cart (without opening the embed), then go straight\n  // to Shopify checkout.\n  // Where the wait goes, on screen, for one run. console.log is filtered in\n  // this storefront, so a diagnostic has to render. ?btktime=1 only.\n  let ckT0 = 0;\n  let ckMarks = [];\n  const ckTiming = () => {\n    try { return new URLSearchParams(window.location.search).get('btktime') === '1'; }\n    catch (e) { return false; }\n  };\n  // The cart writes happen in btk-basket-api.js, which is where most of the\n  // wait turned out to be - so let it add marks to the SAME list against the\n  // same t0, rather than measuring a black box. ckMark itself is inert without\n  // ?btktime=1, so this costs nothing in normal use.\n  // `at` (a performance.now() time) places a mark at a moment already past -\n  // the Plan Online timing below uses it for the navigation's own milestones.\n  const ckMark = (label, at) => {\n    if (!ckT0) return;\n    try {\n      const t = (typeof at === 'number') ? at : performance.now();\n      ckMarks.push(label + ': ' + Math.round(t - ckT0) + 'ms');\n    }\n    catch (e) {}\n  };\n  try { window.BTKKPMark = (label) => ckMark(label); } catch (e) {}\n  // ?btktime=1 timings for the UI modules (the Add Units list uses it): start\n  // a run, mark steps, and show the list. Same list and dialog as the basket\n  // and checkout timings. Inert without the flag.\n  // start's optional `t0` starts the clock earlier than now - even before\n  // this page existed (negative), as for a click on the page before.\n  // While a Plan Online run is open (below) it owns the list: the boot's own\n  // stage change starts a run of its own, which wiped the Plan Online marks\n  // and showed its panel in their place (Arden, 2026-10-01). Other runs just\n  // add a line until it is shown. try/catch: planNav is declared further down.\n  const planNavOpen = () => { try { return !!planNav; } catch (e) { return false; } };\n  try {\n    window.BTKKPTiming = {\n      start: (label, t0) => {\n        if (!ckTiming()) return;\n        if (planNavOpen()) { ckMark(label); return; }\n        ckT0 = (typeof t0 === 'number' && t0 !== 0) ? t0 : performance.now();\n        ckMarks = [];\n        ckMark(label, ckT0);\n      },\n      mark: (label, at) => ckMark(label, at),\n      show: (title) => {\n        if (!ckT0 || planNavOpen()) return;\n        const text = ckMarks.join(String.fromCharCode(10));\n        ckT0 = 0;\n        if (window.BTKKPDialog) window.BTKKPDialog.alert(text, { title });\n      },\n    };\n  } catch (e) {}\n\n  // ---- Plan Online timing (?btktime=1 only) ------------------------------\n  //\n  // The storefront's Plan Online button (kitchen listing drawer) stamps its\n  // click in sessionStorage and adds ?btktime=1 when the listing page has it.\n  // That wait crosses a page load, so no one timer sees all of it.\n  // performance.timeOrigin is when this navigation began, so the click lands\n  // on this page's clock as a NEGATIVE time, and the browser's navigation\n  // entry fills in what happened before any of our code ran: the server\n  // reply, the download, the parse, the first paint (Arden, 2026-10-01).\n  //\n  // The panel shows once the boot loader is down AND the journey has landed\n  // on its first step, whichever is second; planNavStep() is called from both.\n  let planNav = null;\n  const planNavStep = (key, label) => {\n    if (!planNav || planNav[key]) return;\n    planNav[key] = true;\n    ckMark(label);\n    if (planNav.loader && planNav.landed) planNavReport();\n  };\n  const planNavReport = () => {\n    if (!planNav || planNav.shown) return;\n    planNav.shown = true;\n    clearTimeout(planNav.safety);\n    // Two frames so 'painted' is real, then a pause: the long-animation-frame\n    // entries for the last frames are only delivered after those frames end.\n    requestAnimationFrame(() => requestAnimationFrame(() => {\n      ckMark('painted');\n      setTimeout(() => {\n        try {\n          for (const [l, at] of planNav.late.sort((a, b) => a[1] - b[1])) ckMark('   (late) ' + l, at);\n          const pageEnd = performance.now();\n          // The biggest main-thread blocks between navigation and now, and\n          // which script each was in.\n          const frames = planNav.frames.filter(f => f.duration >= 100)\n            .sort((a, b) => b.duration - a.duration).slice(0, 6);\n          if (frames.length) ckMark('-- longest frames --', pageEnd);\n          for (const f of frames) {\n            ckMark('   frame ' + Math.round(f.duration) + 'ms starting', f.startTime);\n            const scripts = (f.scripts || []).slice().sort((a, b) => b.duration - a.duration);\n            for (const sc of scripts.slice(0, 3)) {\n              const file = String(sc.sourceURL || '').split('/').pop().split('?')[0] || 'inline';\n              ckMark('      ' + Math.round(sc.duration) + 'ms ' + (sc.sourceFunctionName || sc.invoker || '(anon)')\n                + ' ' + file, sc.startTime);\n            }\n          }\n          // What the planner HTML is made of: its biggest inline blocks.\n          const blocks = [...document.querySelectorAll('script:not([src]), style')]\n            .map(s => ({ s, n: (s.textContent || '').length }))\n            .sort((a, b) => b.n - a.n).slice(0, 8);\n          ckMark('-- biggest inline blocks (page ' + Math.round(document.documentElement.outerHTML.length / 1024) + 'kB) --', pageEnd);\n          for (const { s, n } of blocks) {\n            const what = s.id ? '#' + s.id\n              : (s.type ? s.type + ' ' : '') + (s.textContent || '').trim().slice(0, 50).replace(/\\s+/g, ' ');\n            ckMark('   ' + Math.round(n / 1024) + 'kB ' + s.tagName.toLowerCase() + ' ' + what, pageEnd);\n          }\n          // The slowest downloads of the whole load.\n          const res = performance.getEntriesByType('resource')\n            .filter(r => r.duration >= 150)\n            .sort((a, b) => b.duration - a.duration)\n            .slice(0, 8);\n          if (res.length) ckMark('-- slowest downloads (finished at) --', pageEnd);\n          for (const r of res) {\n            const name = String(r.name).split('/').pop().split('?')[0] || r.name;\n            ckMark('   ' + name + ' took ' + Math.round(r.duration) + 'ms'\n              + (r.transferSize ? ', ' + Math.round(r.transferSize / 1024) + 'kB' : ''), r.responseEnd);\n          }\n        } catch (e) {}\n        try { planNav.obs.forEach(o => o.disconnect()); } catch (e) {}\n        planNav = null;\n        window.BTKKPTiming.show('Plan Online timing');\n      }, 600);\n    }));\n  };\n  try {\n    const stamp = Number(sessionStorage.getItem('btk_time_plan_click') || 0);\n    if (stamp) sessionStorage.removeItem('btk_time_plan_click');\n    const clickAt = stamp ? stamp - performance.timeOrigin : 0;\n    // A stamp over a minute old is from some earlier visit, not this click.\n    if (ckTiming() && stamp && clickAt < 0 && clickAt > -60000) {\n      // start BEFORE planNav is set, or start would treat this run as the\n      // other kind and only add a line.\n      window.BTKKPTiming.start('Plan Online clicked (listing page)', clickAt);\n      planNav = { loader: false, landed: false, shown: false, late: [], frames: [], obs: [] };\n      // Everything already past, put in time order.\n      const past = [['navigation began (listing page still showing)', 0]];\n      const nav = performance.getEntriesByType('navigation')[0];\n      if (nav) {\n        if (nav.redirectEnd > 0) past.push(['redirects done', nav.redirectEnd]);\n        past.push(['request sent to the server', nav.requestStart]);\n        past.push(['server started replying (first byte)', nav.responseStart]);\n        past.push(['planner HTML downloaded ('\n          + Math.round((nav.decodedBodySize || 0) / 1024) + 'kB, '\n          + Math.round((nav.transferSize || 0) / 1024) + 'kB over the wire)', nav.responseEnd]);\n        // Shopify's own account of the server side: how long it spent\n        // building the page, as opposed to the time the bytes took to travel.\n        for (const st of (nav.serverTiming || [])) {\n          if (st.duration) past.push(['   server says: ' + st.name + ' ' + Math.round(st.duration) + 'ms'\n            + (st.description ? ' (' + st.description + ')' : ''), nav.responseEnd]);\n        }\n        if (nav.domInteractive) past.push(['HTML parsed (DOM interactive)', nav.domInteractive]);\n        if (nav.domContentLoadedEventEnd) past.push(['DOMContentLoaded done', nav.domContentLoadedEventEnd]);\n      }\n      for (const [l, at] of (window.__btkParseMarks || [])) past.push([l, at]);\n      const seenPaint = {};\n      for (const p of performance.getEntriesByType('paint')) {\n        seenPaint[p.name] = true;\n        past.push([p.name + ' (planner page first drew)', p.startTime]);\n      }\n      // The entry is a modulepreload link now (it waits for the catalogue).\n      const ps = performance.getEntriesByName(\n        [...document.querySelectorAll('script[src], link[rel=\"modulepreload\"]')]\n          .map(s => s.src || s.href).find(s => /btk-kitchen-planner\\.js/.test(s)) || '-');\n      if (ps[0]) past.push(['planner script downloaded', ps[0].responseEnd]);\n      past.push(['planner set-up started', _initAt]);\n      past.sort((a, b) => a[1] - b[1]);\n      for (const [l, at] of past) ckMark(l, at);\n      ckMark('planner set-up reached its timing code');\n      // Paint not yet happened, and every long frame of the load (buffered,\n      // so the ones before this code ran are included).\n      try {\n        const po = new PerformanceObserver((list) => {\n          for (const p of list.getEntries()) {\n            if (!seenPaint[p.name] && planNav) { seenPaint[p.name] = true; planNav.late.push([p.name + ' (planner page first drew)', p.startTime]); }\n          }\n        });\n        po.observe({ type: 'paint', buffered: true });\n        planNav.obs.push(po);\n      } catch (e) {}\n      try {\n        const fo = new PerformanceObserver((list) => {\n          if (planNav) for (const f of list.getEntries()) planNav.frames.push(f);\n        });\n        fo.observe({ type: 'long-animation-frame', buffered: true });\n        planNav.obs.push(fo);\n      } catch (e) {}\n      // Never leave a run open if one of the two steps does not come.\n      planNav.safety = setTimeout(() => {\n        ckMark('(gave up waiting after 20s)');\n        planNavReport();\n      }, 20000);\n    }\n  } catch (e) { planNav = null; }\n\n  // \u26A0 ONE CHECKOUT AT A TIME.\n  //\n  // The wait here can run to several seconds, and nothing stopped a second\n  // click starting a whole second run: two plan holds, two navigations, and\n  // two cart pushes racing (the queue in btk-basket-api keeps those from\n  // doubling the lines, which is the only reason this was not worse). Arden's\n  // 2026-09-28 timings caught it - `plan held` and `cart ready` twice, 113ms\n  // apart, and the first run's opening marks gone because the second run had\n  // reset the list.\n  //\n  // A wrapper rather than a flag threaded through the body, so the guard\n  // cannot be missed at one of the early returns, and `finally` so a failure\n  // can never wedge the button shut for the rest of the session. The unnamed\n  // plan path RETURNS from the inner, so the guard releases while the Save As\n  // popup is open - the button must not sit dead behind a popup the customer\n  // may cancel - and that popup's callback re-enters through this wrapper.\n  let checkoutInFlight = false;\n  async function proceedToCheckout() {\n    if (checkoutInFlight) return;\n    checkoutInFlight = true;\n    const _ckBtns = root\n      ? Array.prototype.slice.call(root.querySelectorAll('[data-btk-kp-footer-checkout]'))\n      : [];\n    // Disabled as well as guarded: silently swallowing the click would leave\n    // them pressing a button that looks live and does nothing.\n    _ckBtns.forEach((b) => { b.disabled = true; b.setAttribute('aria-busy', 'true'); });\n    try {\n      await proceedToCheckoutRun();\n    } finally {\n      checkoutInFlight = false;\n      _ckBtns.forEach((b) => { b.disabled = false; b.removeAttribute('aria-busy'); });\n    }\n  }\n  async function proceedToCheckoutRun() {\n    // A salesperson is working on this plan: no checkout until they finish.\n    if (window.BTKBasketAPI?.staffHeld?.()) { window.BTKBasketAPI.showStaffHold(); return; }\n    // The unit types past the Liquid cap first (a True Handleless unit's hinge\n    // comes with them), or a hinged unit can be ordered with no hand (Sales row\n    // 152). Up to 20 seconds; the button shows busy meanwhile.\n    try { await Promise.race([unitTypeTailDone, new Promise(r => setTimeout(r, 20000))]); } catch (e) { /* go on */ }\n    if (planPricesPending()) {\n      window.BTKKPDialog.alert('We are still getting today\\'s prices for your plan. Checkout will open as soon as they are in.', { title: 'Getting Today\\'s Prices' });\n      loadPlanPrices();\n      return;\n    }\n    const hasUnits = (cabinets || []).some(c => !c.excludeFromQuote && c.variantId);\n    if (!hasUnits) {\n      window.BTKKPDialog.alert('There are no purchasable units in your plan to add yet.', { title: 'Nothing to add' });\n      return;\n    }\n    // A plan is ordered from the customer's account: a signed-out plan only\n    // exists in this browser, so its order could never be matched to it. The\n    // name is no test of this, a guest's plan can already have one.\n    if (!(await requireLoginToSave(activePlanName, {\n      title: 'Log in to check out',\n      lead: 'Your plan is kept on your account when you order, so you and our team can open it again at any time.',\n    }))) return;\n    // A bespoke worktop our team is pricing (a postcode outside the templating\n    // zones): checkout opens once the price is on the plan (Arden, 2026-10-14).\n    // Worktop to Follow (2026-11-06): the customer chose, in the basket, to order\n    // the kitchen now without this worktop; checkout goes ahead (the same test\n    // as the basket's priceRequestState: asked, unchanged since, and deferred).\n    computeWorktopCharges();\n    const _wtAsked = worktopBespoke.requested, _wtLater = worktopBespoke.deferred;\n    const _wtToFollow = !!(lastWorktopPriceRequest && _wtAsked && _wtLater\n      && _wtAsked.at && (!_wtAsked.key || _wtAsked.key === lastWorktopPriceRequest.key) && _wtLater.key === lastWorktopPriceRequest.key);\n    if (lastWorktopPriceRequest && !_wtToFollow) {\n      window.BTKKPDialog.alert(\n        (lastWorktopPriceRequest.poa\n          ? 'Your worktop is priced on application: our team prices each job to your plan. Use Request a Price on the worktop in your basket and we will add the price to your plan. Checkout opens as soon as it is there.'\n          : 'Your postcode is outside our standard installation area, so your worktop is priced individually. Use Request a Price on the worktop in your basket and we will add the price to your plan. Checkout opens as soon as it is there.'),\n        { title: 'Your worktop price is on its way' });\n      return;\n    }\n    // A placed size its door colour isn't made in can't be ordered as it is. No\n    // accepting this one: the colour or the unit has to change.\n    const _notMade = doorColourExclusionWarnings();\n    if (_notMade.length) {\n      window.BTKKPDialog.alert(_notMade.map(w => w.message).join('\\n\\n'), { title: 'Not Available in This Colour' });\n      return;\n    }\n    // THE CHECKLIST COMES FIRST (Arden, 2026-10-07). Checkout waits until every\n    // check that applies to this plan is approved: a friendly word, then the\n    // Checklist stage - however the message is closed, so it cannot be skipped.\n    const _checksLeft = await checklistOutstanding();\n    if (_checksLeft > 0) {\n      await window.BTKKPDialog.alert(\n        'Nearly there! Before you check out, please take a minute to go through your checklist - '\n        + 'a quick look at the colours, heights and choices on your order, so your bedroom '\n        + 'arrives exactly as you want it.\\n\\n'\n        + `You have ${_checksLeft} check${_checksLeft === 1 ? '' : 's'} left to approve:\\n`\n        + checklistLeftNames().map(n => `- ${n}`).join('\\n'),\n        { title: 'One Last Look', okText: 'Go to Checklist' });\n      stepperHandle.setStep('checklist');\n      return;\n    }\n    if (!activePlanName) {\n      openSaveAsPopup(() => proceedToCheckout());\n      return;\n    }\n    ckT0 = ckTiming() ? performance.now() : 0;\n    ckMarks = [];\n    if (window.BTKLoader) window.BTKLoader.show();\n    // An edit made in the embedded basket (a quantity, hinge, assembly) sits on\n    // that panel's autosave debounce for half a second. Leaving before it lands\n    // lost it, or left the cart half-written. Costs nothing when none is\n    // pending; a failure here is caught again when the cart is filled below.\n    try { await window.BTKCartAdvanced?.settleEdits?.(); } catch (e) {\n      console.warn('[BTK Kitchen Planner] the basket edit in progress did not save', e);\n    }\n    ckMark('basket edits settled');\n    // Only if something has actually changed since the last transfer. Opening\n    // the basket, reading it and clicking checkout changes nothing, and that\n    // is the ordinary path - it was re-saving the whole project every time.\n    // First let a background save from opening the basket finish: the plan\n    // only counts as saved once the server has confirmed it (transferPlanToBasket),\n    // and the hold below copies the SERVER's basket. whenSaved never rejects.\n    try { await window.BTKBasketAPI?.whenSaved?.(); } catch (e) {}\n    // A task, not a microtask: the confirmation handler sits a couple of promise\n    // steps behind the write, and all of them run before a timer does.\n    await new Promise((r) => setTimeout(r, 0));\n    ckMark('background saves settled');\n    const _sig = undoSnapshot();\n    if (!lastQuoteBasketId || !transferredSignature || _sig !== transferredSignature) {\n      await transferPlanToBasket(false);\n      ckMark('plan and basket saved');\n    } else {\n      ckMark('nothing had changed, nothing saved');\n    }\n    // The cart is filled HERE, on the way to checkout, rather than on every\n    // edit. If it fails, stop: sending someone to checkout with a stale cart is\n    // worse than any wait.\n    if (!(await flushCartForCheckout())) {\n      if (window.BTKLoader) window.BTKLoader.hide();\n      window.BTKKPDialog.alert(cartRefusalMessage || 'We could not prepare your basket for checkout. Please check your connection and try again.',\n        { title: 'Could not continue', danger: true });\n      return;\n    }\n    // HOLD the plan now in the cart, so it cannot change under an order that is\n    // being paid for: without it, an edit in another tab between here and\n    // payment became the \"purchased\" plan. Released if they come back unpaid\n    // (startFreshIfOrdered), and it expires server-side anyway. Never stops\n    // checkout: holdForCheckout gives up after a few seconds.\n    await window.BTKBasketAPI?.holdForCheckout?.(lastQuoteBasketId);\n    ckMark('plan held');\n    // Refused because a salesperson has just taken the plan over.\n    if (window.BTKBasketAPI?.staffHeld?.()) {\n      if (window.BTKLoader) window.BTKLoader.hide();\n      return;\n    }\n    // Hand off to the SHARED pre-checkout page (Delivery \u00B7 Terms \u00B7 Payment) - the\n    // same step the standard /cart basket now uses. The page's Basket stage\n    // returns here via ?back; we add openbasket=1 so the planner reopens the\n    // embedded basket on return. The page writes the choices as cart attributes\n    // then continues to Shopify checkout.\n    ckMark('cart ready, leaving the planner');\n    if (ckT0 && window.BTKKPDialog) {\n      if (window.BTKLoader) window.BTKLoader.hide();\n      await window.BTKKPDialog.alert(ckMarks.join(String.fromCharCode(10)),\n        { title: 'Checkout timings' });\n      if (window.BTKLoader) window.BTKLoader.show();\n    }\n    const _backParams = new URLSearchParams(window.location.search);\n    _backParams.set('openbasket', '1');\n    const _backUrl = window.location.pathname + '?' + _backParams.toString();\n    window.location.href = '/pages/pre-checkout?back=' + encodeURIComponent(_backUrl);\n  }\n\n  root.querySelectorAll('[data-btk-kp-open-basket]').forEach(btn => {\n    btn.addEventListener('click', openLiveQuote);\n  });\n\n  // \u2500\u2500 Embedded advanced basket (split panel) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n  // \"Add to Basket\" opens this instead of redirecting to /cart. The\n  // advanced-basket script is loaded on the page (embedded mode) but\n  // not auto-initialised - we init it on first open, reload on re-open.\n  const basketEmbedPanel = root.querySelector('[data-btk-kp-basket-embed]');\n  let cartEmbedInited = false;\n\n  // While the basket panel is open, the LIVE planner viewport (#btk-kp-main\n  // - 2D plan, 3D scene, the 2D/3D toggle and zoom) is reparented into the\n  // panel's top-left box, so it's a real interactive mini view rather than\n  // a static image. `embedViewing` marks it read-only (no editing) - the\n  // add-units sidebar is hidden behind the panel anyway.\n  let embedViewing = false;\n  let mainOriginalParent = null;\n  let mainOriginalNext   = null;\n  let embedPrevViewMode  = '2d';\n\n  // Deterministically set what the planner canvas shows for a given stage.\n  // Planner Home + Style Setup cover the canvas with their own opaque overlay\n  // (the process guide / guided journey); every other stage shows the 2D/3D\n  // view. Called from BOTH the stepper's onChange and the basket-close path so\n  // the two can never disagree (the \"mixed views\" bug: coming back from the\n  // basket left the canvas exposed because the home overlay wasn't re-asserted).\n  function applyStageCanvasState(step) {\n    // The Checklist is a page of cards in the same overlay (Arden, 2026-10-07).\n    const onHome = (step === 'planner-home' || step === 'style-setup' || step === 'checklist');\n    const homeEl = root.querySelector('[data-btk-kp-home]');\n    // The opaque home overlay (z-index:2000) covers the whole 2D/3D canvas on\n    // Home / Style Setup - no need to hide the canvas children. Just show/hide\n    // the overlay itself, and keep the 2D/3D display in sync on canvas stages.\n    // Clear any stray inline display (rerender's 3D-hide loop could have set it\n    // while the basket forced 3D) so [hidden]=false actually reveals it.\n    if (homeEl) { homeEl.hidden = !onHome; if (onHome) homeEl.style.display = ''; }\n    if (!onHome) on3DStepActive(viewMode === '3d');\n  }\n\n  function mountLiveViewIntoEmbed() {\n    const box    = root.querySelector('[data-btk-kp-basket-embed-3d]');\n    const mainEl = document.getElementById('btk-kp-main');\n    if (!box || !mainEl || mainEl.parentNode === box) return;\n    // The home overlay is a child of #btk-kp-main, so it rides along into the\n    // mini box - hide it there so it can't cover the mini 3D preview.\n    const homeEl = root.querySelector('[data-btk-kp-home]');\n    if (homeEl) homeEl.hidden = true;\n    mainOriginalParent = mainEl.parentNode;\n    mainOriginalNext   = mainEl.nextSibling;\n    box.innerHTML = '';            // drop the placeholder\n    box.appendChild(mainEl);\n    embedViewing = true;\n    root.classList.add('btk-kp-embed-viewing');\n    window.__btkKpDragLocked = true;   // read-only: block unit dragging\n    // Default the mini view to 3D on open (the mini-view toggle lets the user\n    // switch to the 2D plan); restore the pre-embed mode on close.\n    embedPrevViewMode = viewMode;\n    try { setViewMode('3d'); } catch (e) {}\n    // Wall letter labels retired 2026-09-28 - see WALL_LABELS_ENABLED in\n    // btk-kitchen-planner-3d-renderer.js, which is where they are switched off.\n    // Re-fit both renderers to the new (smaller) container.\n    requestAnimationFrame(() => { try { handle3D?.resize?.(); } catch (e) {} rerender(); });\n  }\n\n  function unmountLiveViewFromEmbed() {\n    const mainEl = document.getElementById('btk-kp-main');\n    if (mainEl && mainOriginalParent) {\n      // Restore #btk-kp-main to the body. insertBefore throws NotFoundError if\n      // the saved next-sibling is no longer a child of the parent - which would\n      // leave #btk-kp-main orphaned inside the (about-to-be-hidden) basket panel\n      // and blank the whole planner. Guard it and fall back to append.\n      try {\n        if (mainOriginalNext && mainOriginalNext.parentNode === mainOriginalParent) {\n          mainOriginalParent.insertBefore(mainEl, mainOriginalNext);\n        } else if (basketEmbedPanel && basketEmbedPanel.parentNode === mainOriginalParent) {\n          // #btk-kp-main normally sits just before the basket panel in the body.\n          mainOriginalParent.insertBefore(mainEl, basketEmbedPanel);\n        } else {\n          mainOriginalParent.appendChild(mainEl);\n        }\n      } catch (e) {\n        try { mainOriginalParent.appendChild(mainEl); } catch (e2) {}\n      }\n    }\n    mainOriginalParent = null;\n    mainOriginalNext   = null;\n    embedViewing = false;\n    root.classList.remove('btk-kp-embed-viewing');\n    // A purchased plan, and a live-session viewer, stay locked: both set the\n    // lock at boot, and closing the basket used to clear it.\n    window.__btkKpDragLocked = !!_bootOrdered || !!(_bootLive.session && _bootLive.role === 'viewer');\n    try { setViewMode(embedPrevViewMode || '2d'); } catch (e) {}\n    requestAnimationFrame(() => { try { handle3D?.resize?.(); } catch (e) {} rerender(); });\n  }\n\n  // The \"Quote & Checkout\" nav button is the active tab while the basket\n  // is open; the step buttons reflect the planner stage otherwise.\n  const quoteCheckoutBtn = root.querySelector('[data-btk-kp-quote-checkout]');\n  function setQuoteCheckoutActive(on) {\n    if (quoteCheckoutBtn) quoteCheckoutBtn.classList.toggle('is-active', on);\n    root.querySelectorAll('[data-btk-kp-step]').forEach(b => {\n      b.classList.toggle('is-active', !on && b.dataset.btkKpStep === currentStep);\n    });\n    // Header CTA stays labelled \"Basket\" at all times now - Proceed to Checkout\n    // lives in the basket-side footer. It just lights up (is-active) while the\n    // basket is open so the user can see they're in it.\n    root.querySelectorAll('[data-btk-kp-proceed-checkout]').forEach(btn => btn.classList.toggle('is-active', on));\n  }\n\n  function openBasketEmbed() {\n    // No cart write here. Looking at the basket is not heading for checkout,\n    // and the basket panel reads the BASKET, not the cart. See\n    // flushCartForCheckout.\n    if (basketEmbedPanel) basketEmbedPanel.hidden = false;\n    const CA = window.BTKCartAdvanced;\n    if (CA) {\n      if (cartEmbedInited) { CA.reload && CA.reload(); }\n      else { cartEmbedInited = true; CA.init && CA.init(); }\n    } else {\n      console.warn('[BTK Kitchen Planner] BTKCartAdvanced not available for embed');\n    }\n    try { window.BTKKPMark && window.BTKKPMark(\"basket panel opened, loading its lines\"); } catch (_) {}\n    mountLiveViewIntoEmbed();\n    try { window.BTKKPMark && window.BTKKPMark(\"3D view moved into the panel\"); } catch (_) {}\n    refreshLiveQuoteLabels();\n    refreshBasketTasks();\n    setQuoteCheckoutActive(true);\n    if (window.BTKLoader) window.BTKLoader.hide();\n  }\n\n  // ?btktime=1: time opening the basket, step by step, into the same list the\n  // checkout timing uses, and show it once the basket has drawn (the\n  // btk:basket-drawn event from btk-cart-advanced.js). Inert without the flag.\n  function startBasketTiming() {\n    if (!ckTiming()) return;\n    ckT0 = performance.now();\n    ckMarks = [];\n    ckMark('basket button clicked');\n    const done = () => {\n      window.removeEventListener('btk:basket-drawn', done);\n      if (!ckT0) return;\n      ckMark('basket drawn');\n      const text = ckMarks.join(String.fromCharCode(10));\n      ckT0 = 0;\n      if (window.BTKKPDialog) window.BTKKPDialog.alert(text, { title: 'Basket Timings' });\n    };\n    window.addEventListener('btk:basket-drawn', done);\n  }\n  // NO cart fill on leaving the page (removed 2026-09-29). It filled a stale\n  // cart when the page was hidden, and a fill is clear-then-add: leaving for\n  // pre-checkout hides the page, so a fill started then could be cut off after\n  // the clear, and pre-checkout opened on an EMPTY basket (Arden hit exactly\n  // that). It is also no longer wanted: the Online cart belongs to the standard\n  // basket and a plan only borrows it for checkout, which fills it itself\n  // (flushCartForCheckout) - leaving the planner any other way hands the cart\n  // back (BTKBasketAPI.handBackBorrowedCart).\n\n  function closeBasketEmbed() {\n    clearEmbedFocus();\n    unmountLiveViewFromEmbed();\n    if (basketEmbedPanel) basketEmbedPanel.hidden = true;\n    setQuoteCheckoutActive(false);\n    // Re-assert the canvas/overlay for whatever stage we're returning to -\n    // the basket teardown (reparent + view-mode restore) can otherwise leave\n    // the raw 2D/3D view showing on the Home / Style Setup stages.\n    applyStageCanvasState(currentStep);\n  }\n  root.querySelectorAll('[data-btk-kp-basket-embed-close]').forEach(btn => {\n    btn.addEventListener('click', closeBasketEmbed);\n  });\n  // \"Quote & Checkout\" nav button opens the embedded basket.\n  if (quoteCheckoutBtn) quoteCheckoutBtn.addEventListener('click', () => openLiveQuote());\n  // Header \"Basket\" CTA: opens the basket. When the basket is already open it's\n  // a no-op (Proceed to Checkout now lives in the basket-side footer).\n  root.querySelectorAll('[data-btk-kp-proceed-checkout]').forEach(btn => {\n    btn.addEventListener('click', () => {\n      const onQuotePage = basketEmbedPanel && !basketEmbedPanel.hidden;\n      if (onQuotePage) return;   // already in the basket\n      openLiveQuote();\n    });\n  });\n  // Basket-side footer: Proceed to Checkout.\n  root.querySelectorAll('[data-btk-kp-footer-checkout]').forEach(btn => {\n    btn.addEventListener('click', () => proceedToCheckout());\n  });\n  // Clicking Help while the basket is open returns to the planner first.\n  root.querySelectorAll('[data-btk-kp-help]').forEach(btn => {\n    btn.addEventListener('click', () => { if (basketEmbedPanel && !basketEmbedPanel.hidden) closeBasketEmbed(); });\n  });\n  // Beta badge, bottom right of the plan in 2D and 3D (Arden, 2026-10-12).\n  // PLANNER_VERSION is the version customers see (\"Better Planner v1.0\" - Arden, 2026-10-12),\n  // moved on by hand for a release worth naming. BETA_VERSION is this build's\n  // own number - the cb the planner page loads it with - which moves on by\n  // itself with every release; it goes on support tickets, not on the badge.\n  const PLANNER_VERSION = window.BTK_PLANNER_V11 ? '1.1' : '1.0';\n  const BETA_VERSION = (() => {\n    try { return new URL(import.meta.url).searchParams.get('cb') || ''; } catch (_) { return ''; }\n  })();\n  root.querySelectorAll('[data-btk-kp-beta]').forEach(btn => {\n    const ver = btn.querySelector('[data-btk-kp-beta-version]');\n    if (ver) ver.textContent = 'Better Planner v' + PLANNER_VERSION;\n    btn.addEventListener('click', async () => {\n      if (!window.BTKKPDialog) return;\n      // Wording: Arden, 2026-10-12.\n      const help = await window.BTKKPDialog.confirm(\n        'Welcome to the brand-new Better Planner!'\n        + '\\n\\nBecause it\u2019s still in beta, you might occasionally spot a small glitch in an item or a size dimension.'\n        + '\\n\\nIf anything looks off, or you just want a second pair of eyes, we\u2019re right here to help you get it perfect.',\n        { title: 'Better Planner v' + PLANNER_VERSION + ' (Beta)',\n          confirmText: 'Ask a Question / Report a Bug', cancelText: 'Close', confirmFirst: true });\n      if (help) {\n        // Straight to Raise a Support Ticket (Arden, 2026-10-12).\n        if (basketEmbedPanel && !basketEmbedPanel.hidden) closeBasketEmbed();\n        openTicketPopup();\n      }\n    });\n  });\n  // Wall features, straight from the Room Setup menu. A pillar or internal\n  // wall simply appears - room centre, then positioned from its own panel -\n  // so only Corners needs a mode.\n  root.querySelectorAll('[data-btk-kp-plan-feature]').forEach(btn => {\n    btn.addEventListener('click', () => {\n      const kind = btn.dataset.btkKpPlanFeature;\n      if (btn.getAttribute('aria-disabled') === 'true') {\n        // Say what it would have done and what to do instead, rather than\n        // leaving a dead button to be pressed twice.\n        window.BTKKPDialog?.alert(\n          'Corners are for the starter room shapes. Those are rectangles with a piece taken out of a named corner, and the corner tools measure from the rectangle - on a room you have drawn there is no rectangle for them to measure from, so they would cut the outline about.\\n\\n' +\n          'Your room is drawn, so a corner is simply a wall: open Room Shape, choose Draw Custom Shape, and put the walls where you want them. Pillars and internal walls still work here as normal.',\n          { title: 'Corners on a drawn room', okText: 'Got it' }\n        );\n        return;\n      }\n      if (kind === 'pillar')        { handleAddPillarFeature(); return; }\n      if (kind === 'internal-wall') { handleAddWall(); return; }\n      setPlanFeatureArmed(kind);\n    });\n  });\n  // Moving on to anything else in the menu ends corner mode. Leaving it armed\n  // behind another task meant the next click on the plan did something the\n  // user was no longer asking for.\n  root.querySelector('[data-btk-kp-panel=\"room-setup\"]')\n      ?.addEventListener('click', (e) => {\n        if (!planFeatureArmed) return;\n        const t = e.target;\n        if (!t || !t.closest) return;\n        if (t.closest('[data-btk-kp-plan-feature=\"corner\"]')) return;   // its own button toggles\n        if (t.closest('button, [role=\"button\"]')) setPlanFeatureArmed(null);\n      }, true);\n\n  // A click anywhere else closes an open corner menu, the way the popup's did.\n  document.addEventListener('pointerdown', (e) => {\n    if (planCornerMenuAt == null) return;\n    const t = e.target;\n    if (t && t.closest && t.closest('.btk-kp-rs-corner-menu, .btk-kp-rs-corner-toggle')) return;\n    planCornerMenuAt = null;\n    try { renderPlanCorners(); } catch (err) {}\n  });\n\n  // The way on from Room Setup. The Add Units picker is built by the cabinets\n  // UI into the add-units panel, so the stage has to change before the popup\n  // exists to open - hence the step first, then the popup on the next frame.\n  function openAddUnitsPopup() {\n    const trigger = root.querySelector('[data-btk-kp-open-popup=\"add-units\"]');\n    if (trigger) { trigger.click(); return; }     // same path as any other opener\n    const popup = root.querySelector('[data-btk-kp-popup=\"add-units\"]');\n    if (popup) popup.hidden = false;\n  }\n  root.querySelector('[data-btk-kp-start-units]')?.addEventListener('click', () => {\n    // A plan with no planning style yet is asked for one FIRST - Add Units was\n    // opening on top of it, too early (Arden, 2026-10-10). Arriving at Add\n    // Items asks; Add Units follows once a style is chosen (pickPlanningStyle).\n    const askFirst = needsPlanningStyle();\n    try { stepperHandle.setStep('add-units'); } catch (e) {}\n    if (askFirst) {\n      psOpenAddUnitsAfter = true;\n      requestAnimationFrame(() => { if (psPopup.hidden) askForPlanningStyle(); });\n      return;\n    }\n    requestAnimationFrame(openAddUnitsPopup);\n  });\n\n  root.querySelectorAll('[data-btk-kp-undo]').forEach(b => b.addEventListener('click', () => undo()));\n  root.querySelectorAll('[data-btk-kp-redo]').forEach(b => b.addEventListener('click', () => redo()));\n  root.querySelectorAll('[data-btk-kp-purchased-plans]')\n    .forEach(b => b.addEventListener('click', openPurchasedPlans));\n  syncUndoButtons();\n  syncAutosaveToggle();\n  // Either this is the read-only view of a plan that was bought, or it is the\n  // normal planner - in which case a bought plan must not be sitting in it.\n  // (The bought-plan check for the normal planner now runs inside the boot\n  // restore - see planStore.load() below - so it can stop the restore.)\n  if (_bootOrdered) openOrderedPlan();\n  if (_bootViewOnly) setupViewOnly();\n  // Ctrl/Cmd+Z and Ctrl/Cmd+Shift+Z, ignored while the user is typing.\n  document.addEventListener('keydown', (e) => {\n    if (!(e.ctrlKey || e.metaKey) || e.altKey) return;\n    if (String(e.key).toLowerCase() !== 'z') return;\n    const t = e.target;\n    if (t && (t.isContentEditable || /^(input|textarea|select)$/i.test(t.tagName || ''))) return;\n    e.preventDefault();\n    if (e.shiftKey) redo(); else undo();\n  });\n\n  // Delete / Backspace removes whatever is selected - by the SAME route that\n  // item's own delete control already takes, so the key can never behave\n  // differently from the button or the right-click menu:\n  //   unit(s)       \u2192 the unit right-click rules: a grouped unit takes its\n  //                   whole group, a multi-selection all of it, else the one\n  //   pillar / nib / beam / radiator \u2026 (a room feature) \u2192 its panel's Delete\n  //   door / window \u2192 the wall panel's remove\n  //   sink / hob on the worktop \u2192 its panel's Delete\n  //   a sink chosen on a sink base \u2192 \"Remove sink\" (the SINK, not the unit)\n  //   a wall section \u2192 whatever stands in it, if it can be removed: an\n  //                    opening, or a pillar / nib standing mid-wall. A plain\n  //                    run of wall is the room itself and is left alone, as\n  //                    is a corner treatment - it is part of the room shape.\n  // Every one of these re-renders, and every render is an undo snapshot, so a\n  // stray key press is one Ctrl+Z away. Returns true when something went.\n  function deleteSelectedItem() {\n    const sel = selectedItem;\n    const primaryCabId = (sel && sel.kind === 'cabinet') ? sel.id\n                       : (selectedCabinetIds.size ? [...selectedCabinetIds][0] : null);\n    if (primaryCabId && (!sel || sel.kind === 'cabinet')) {\n      const cab = cabinets.find(c => c.id === primaryCabId);\n      if (cab && cab.groupId) { deleteCabinetGroup(cab.groupId); return true; }\n      if (selectedCabinetIds.size > 1) { deleteSelectedCabinets(); return true; }\n      if (cab) { deleteCabinet(cab); return true; }\n      return false;\n    }\n    if (!sel) return false;\n    switch (sel.kind) {\n      case 'feature':      handleRemovePerimeterItem(sel.id); return true;\n      case 'opening':      handleRemoveOpening(sel.id);       return true;\n      case 'worktop-item': deleteWorktopItem(sel.id);         return true;\n      case 'planner-sink':\n        if (sel.cabinetId) { handleSetCabinetPlannerSink(sel.cabinetId, null); return true; }\n        return false;\n      case 'wall': {\n        const seg = (wallSegments(sel.wallIndex) || []).find(s => s.key === sel.segKey);\n        if (seg && seg.kind === 'opening') { handleRemoveOpening(seg.id); return true; }\n        if (seg && seg.kind === 'feature' && seg.moveable) { handleRemovePerimeterItem(seg.id); return true; }\n        return false;\n      }\n      default: return false;   // end panels, trims, worktops, splashbacks: no delete control\n    }\n  }\n\n  document.addEventListener('keydown', (e) => {\n    if (e.key !== 'Delete' && e.key !== 'Backspace') return;\n    if (e.ctrlKey || e.metaKey || e.altKey) return;\n    // Never while typing - Backspace in a size box is an edit, not a delete.\n    const t = e.target;\n    if (t && (t.isContentEditable || /^(input|textarea|select)$/i.test(t.tagName || ''))) return;\n    // Only on a stage that shows the plan (not Planner Home / Style Setup).\n    if (!STEP_DEFAULT_VIEW[currentStep]) return;\n    // Not from behind something: a popup or dialog owns the keyboard while it\n    // is up, and the basket is its own view. Popups may be hoisted to <body>,\n    // so ask the document, not the planner root.\n    if (document.querySelector('[data-btk-kp-popup]:not([hidden]), .btk-kp-dialog-overlay')) return;\n    if (basketEmbedPanel && !basketEmbedPanel.hidden) return;\n    // Read-only views: the in-planner basket lock, and a customer watching a\n    // salesperson's live session.\n    if (window.__btkKpDragLocked || root.classList.contains('btk-kp-live-viewing')) return;\n    if (deleteSelectedItem()) e.preventDefault();   // also stops Backspace = \"go back\"\n  });\n\n  // Print button in the embed bar \u2192 the plan report. Staff get a menu like\n  // Save's: Print Plan Only (no list, no prices - for showing a design) or\n  // Print Plan & Prices (the full report). A customer's click prints the\n  // Plan Only report straight away (Arden, 2026-10-27; was the full report).\n  root.querySelectorAll('[data-btk-kp-embed-print]').forEach(btn => {\n    const split = btn.closest('[data-btk-kp-print-split]');\n    const menu  = split && split.querySelector('[data-btk-kp-print-menu]');\n    const closeMenu = () => {\n      if (menu) menu.hidden = true;\n      btn.setAttribute('aria-expanded', 'false');\n    };\n    btn.addEventListener('click', (e) => {\n      const staff = !!(window.BTKBasketAPI && typeof window.BTKBasketAPI.isStaffMode === 'function'\n                       && window.BTKBasketAPI.isStaffMode());\n      if (!staff || !menu) { downloadPlanReport('save', { prices: false }); return; }\n      e.stopPropagation();\n      const open = menu.hidden;\n      menu.hidden = !open;\n      btn.setAttribute('aria-expanded', open ? 'true' : 'false');\n    });\n    if (menu) {\n      menu.querySelectorAll('[data-btk-kp-print-option]').forEach(item => {\n        item.addEventListener('click', (e) => {\n          e.stopPropagation();\n          closeMenu();\n          downloadPlanReport('save', { prices: item.dataset.btkKpPrintOption !== 'plan' });\n        });\n      });\n      document.addEventListener('click', (e) => {\n        if (!split.contains(e.target)) closeMenu();\n      });\n    }\n  });\n\n  // ---- Basket \"Still to do\" tiles -------------------------------------\n  // Outstanding plan choices surfaced in the basket's lower-left tile grid.\n  // Currently: a \"Choose sink\" tile per sink-base cabinet without a sink.\n  // Future choices (ovens, taps, handles) just push more entries onto `tasks`.\n  const SINK_TODO_ICON = '<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"20\" height=\"20\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2.1\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M12 2.5S5 9 5 14a7 7 0 0 0 14 0c0-5-7-11.5-7-11.5z\"/></svg>';\n  function refreshBasketTasks() {\n    const grid = root.querySelector('[data-btk-kp-basket-tiles]');\n    if (!grid) return;\n    // Remove previously-injected to-do tiles (static tiles stay).\n    grid.querySelectorAll('.btk-kp-basket-tile--todo').forEach(el => el.remove());\n    const tasks = [];\n    (cabinets || []).forEach(c => {\n      if (c && (c.sinkBase || c.belfastSink) && !c.plannerSinkHandle) {\n        const spare = spareSinkByCab.has(c.id);\n        tasks.push({ kind: 'sink', cabId: c.id, spare, label: spare ? 'Fit your sink' : 'Choose sink', sub: spare ? 'The sink in your basket can go on this unit.' : 'Pick a sink for this unit.', icon: SINK_TODO_ICON, num: c.displayNumber != null ? String(c.displayNumber) : '' });\n      }\n    });\n    const anchor = grid.firstElementChild;   // inject to-dos ahead of the static tiles\n    tasks.forEach(t => {\n      const btn = document.createElement('button');\n      btn.type = 'button';\n      btn.className = 'btk-kp-basket-tile btk-kp-basket-tile--todo' + (t.spare ? ' btk-kp-basket-tile--spare-sink' : '');\n      btn.dataset.btkKpBasketTodo = t.kind;\n      btn.dataset.btkKpBasketTodoCab = t.cabId;\n      const numEl = document.createElement('span');\n      numEl.className = 'btk-kp-basket-tile-num';\n      numEl.textContent = t.num;\n      btn.innerHTML =\n        '<span class=\"btk-kp-basket-tile-icon\" aria-hidden=\"true\">' + t.icon + '</span>' +\n        '<span class=\"btk-kp-basket-tile-text\">' +\n          '<span class=\"btk-kp-basket-tile-label\">' + t.label + (t.num ? ' ' + numEl.outerHTML : '') + '</span>' +\n          '<span class=\"btk-kp-basket-tile-sub\">' + t.sub + '</span>' +\n        '</span>';\n      grid.insertBefore(btn, anchor);\n    });\n  }\n\n  // Clicking a to-do tile leaves the basket, goes to Add Units, then opens the\n  // relevant chooser (the chooser popups live in that panel's DOM).\n  const basketTilesGrid = root.querySelector('[data-btk-kp-basket-tiles]');\n  if (basketTilesGrid) {\n    basketTilesGrid.addEventListener('click', (e) => {\n      const todo = e.target.closest('[data-btk-kp-basket-todo]');\n      if (!todo) return;\n      const kind  = todo.getAttribute('data-btk-kp-basket-todo');\n      const cabId = todo.getAttribute('data-btk-kp-basket-todo-cab');\n      root.querySelector('[data-btk-kp-step=\"add-units\"]')?.click();   // closes basket + shows the panel\n      if (kind === 'sink') {\n        setTimeout(() => { cabinetsHandle?.openChooseSinkPopup?.(cabId); }, 80);\n      }\n    });\n  }\n\n  // Bridge: the embedded cart calls this when a line is clicked, to\n  // highlight the matching unit in the live view. Maps the line's stored\n  // planner cabinet id \u2192 selection (highlights in both 2D and 3D).\n  // Basket line \u2192 live view + details. Plannable lines (cabId) zoom the\n  // 3D view to the unit; non-plannable lines show the product image over\n  // the 3D box. Both surface details in the lower-left; X / re-click /\n  // panel-close reverts.\n  let embedSelectedKey      = null;\n  const embedDetailsEl      = root.querySelector('[data-btk-kp-line-details]');\n  const embedAdvisoryEl     = root.querySelector('[data-btk-kp-basket-embed-advisory]');\n  const embedImageOverlayEl = root.querySelector('[data-btk-kp-image-overlay]');\n  const escForKp = (s) => String(s == null ? '' : s).replace(/[&<>\"']/g,\n    m => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '\"': '&quot;', \"'\": '&#39;' }[m]));\n\n  function clearEmbedFocus() {\n    embedSelectedKey = null;\n    setSelectedLineCard(null);\n    try { handle3D?.resetView?.(); } catch (e) {}\n    try { handle3D?.setSelectionBadge?.(null); } catch (e) {}\n    resetView2D();\n    try { setCabinetSelection([]); } catch (e) {}\n    const x = root.querySelector('[data-btk-kp-focus-close]');\n    if (x) x.hidden = true;\n    if (embedImageOverlayEl) { embedImageOverlayEl.hidden = true; embedImageOverlayEl.replaceChildren(); }\n    if (embedDetailsEl) { embedDetailsEl.hidden = true; embedDetailsEl.replaceChildren(); }\n    if (embedAdvisoryEl) embedAdvisoryEl.hidden = false;\n  }\n\n  // Draw the blue \"selected line\" border on the matching basket card (and\n  // clear it from any other). Mirrors focusBasketLineForCab's card-matching:\n  // a panel/filler line is keyed by its ep-faces, a unit line by its cab id\n  // (preferring the UNIT's own card over its panel siblings).\n  function setSelectedLineCard(payload) {\n    try {\n      root.querySelectorAll('.btk-ca-card.is-line-selected')\n        .forEach(c => c.classList.remove('is-line-selected'));\n      if (!payload) return;\n      let card = null;\n      if (payload.epFaces) {\n        const ep = String(payload.epFaces);\n        card = [...root.querySelectorAll('.btk-ca-card')]\n          .find(c => (c.dataset.btkPlannerEpFaces || '') === ep);\n      } else if (payload.cabId) {\n        const esc = (window.CSS && CSS.escape) ? CSS.escape(String(payload.cabId)) : String(payload.cabId);\n        const cards = [...root.querySelectorAll(`.btk-ca-card[data-btk-planner-cab-id=\"${esc}\"]`)];\n        card = cards.find(c => !c.dataset.btkPlannerEpFaces) || cards[0];\n      } else if (payload.itemId) {\n        // Non-plannable line - match by its OWN item id. Matching by title was\n        // wrong whenever two lines share one: a worktop bought in two sizes\n        // (items 22 and 23) is two lines with the same title, so the first\n        // card always won and clicking 23 left 22 highlighted.\n        const esc = (window.CSS && CSS.escape) ? CSS.escape(String(payload.itemId)) : String(payload.itemId);\n        card = root.querySelector(`.btk-ca-card[data-btk-item-id=\"${esc}\"]`);\n      }\n      // No title fallback: two lines can share a title (one product in two\n      // sizes), so a title match highlights the wrong card. Without an item id\n      // nothing is highlighted, which is the correct failure.\n      if (card) card.classList.add('is-line-selected');\n    } catch (e) {}\n  }\n\n  // Reverse of clicking a basket line: given a clicked-in-3D cabinet, if the\n  // embedded basket is open, slide its line to the middle + open its details\n  // by replaying a click on that card (same selection path, forced fresh so\n  // it selects rather than toggling off).\n  function focusBasketLineForCab(cabId) {\n    try {\n      if (!basketEmbedPanel || basketEmbedPanel.hidden) return;\n      const esc = (window.CSS && CSS.escape) ? CSS.escape(String(cabId)) : String(cabId);\n      // A unit AND its owned panels/fillers all carry the same\n      // data-btk-planner-cab-id. Prefer the UNIT's own line (the card WITHOUT\n      // panel faces) so clicking a unit in 3D opens the unit, not its filler.\n      const cards = [...root.querySelectorAll(`.btk-ca-card[data-btk-planner-cab-id=\"${esc}\"]`)];\n      const card = cards.find(c => !c.dataset.btkPlannerEpFaces) || cards[0];\n      if (!card) return;\n      embedSelectedKey = null;\n      card.click();\n    } catch (e) {}\n  }\n\n  // Same reverse trip for a PANEL / FILLER / FEATURE clicked on the plan:\n  // find the card whose face list contains this exact key and replay a click\n  // on it. The key carries the part, so the feature row is found rather than\n  // the panel row that sits on the same side.\n  function focusBasketLineForFace(cabId, side) {\n    try {\n      if (!basketEmbedPanel || basketEmbedPanel.hidden) return;\n      const key = `${cabId}:${side}`;\n      const card = [...root.querySelectorAll('.btk-ca-card[data-btk-planner-ep-faces]')]\n        .find(c => (c.dataset.btkPlannerEpFaces || '').split(',').includes(key));\n      if (!card) return;\n      embedSelectedKey = null;      // force a select rather than a toggle-off\n      card.click();\n    } catch (e) {}\n  }\n\n  const lineMoney = new Intl.NumberFormat('en-GB', { style: 'currency', currency: context.currency || 'GBP' });\n  const handleFromUrl = (url) => {\n    const m = String(url || '').split('/products/')[1];\n    return m ? m.split(/[?#/]/)[0] : '';\n  };\n\n  // Featured image + thumbnail strip for a non-plannable product, shown\n  // over the 3D box.\n  function renderImageGallery(images, alt) {\n    if (!embedImageOverlayEl) return;\n    const imgs = (images || []).filter(Boolean);\n    if (!imgs.length) { embedImageOverlayEl.hidden = true; return; }\n    embedImageOverlayEl.innerHTML =\n      `<div class=\"btk-kp-gallery\">` +\n        `<img class=\"btk-kp-gallery-main\" src=\"${escForKp(imgs[0])}\" alt=\"${escForKp(alt || '')}\">` +\n        (imgs.length > 1\n          ? `<div class=\"btk-kp-gallery-thumbs\">` +\n              imgs.slice(0, 6).map((src, i) =>\n                `<img class=\"btk-kp-gallery-thumb${i === 0 ? ' is-active' : ''}\" src=\"${escForKp(src)}\" data-idx=\"${i}\" alt=\"\">`).join('') +\n            `</div>`\n          : '') +\n      `</div>`;\n    embedImageOverlayEl.hidden = false;\n    const main = embedImageOverlayEl.querySelector('.btk-kp-gallery-main');\n    embedImageOverlayEl.querySelectorAll('.btk-kp-gallery-thumb').forEach((t, i) => {\n      t.addEventListener('click', () => {\n        if (main) main.src = imgs[i];\n        embedImageOverlayEl.querySelectorAll('.btk-kp-gallery-thumb').forEach(x => x.classList.remove('is-active'));\n        t.classList.add('is-active');\n      });\n    });\n  }\n\n  // Cache of fetched, parsed product pages so re-selecting a line is instant.\n  const _lineDocCache = new Map();   // handle \u2192 parsed <html> document | null\n  async function fetchProductDoc(handle) {\n    if (!handle) return null;\n    if (_lineDocCache.has(handle)) return _lineDocCache.get(handle);\n    let doc = null;\n    try {\n      const html = await fetch('/products/' + encodeURIComponent(handle)).then(r => r.ok ? r.text() : null);\n      if (html) doc = new DOMParser().parseFromString(html, 'text/html');\n    } catch (e) {}\n    _lineDocCache.set(handle, doc);\n    return doc;\n  }\n  // Reuse the basket's OWN swatch + toggle components (btk-ca-*), so the\n  // detail panel matches the basket line (and the PDP) exactly - same fonts,\n  // swatch chips and Left/Right \u00B7 Flatpack/Assembled toggles. Read-only here.\n  function swatchChip(label, name, swatch) {\n    if (!name) return '';\n    const img = swatch\n      ? `<img class=\"btk-ca-swatch-img\" src=\"${escForKp(swatch)}\" alt=\"${escForKp(name)}\">`\n      : `<div class=\"btk-ca-swatch-img btk-ca-swatch-img--empty\"></div>`;\n    return `<div class=\"btk-kp-detail-opt\">` +\n      `<button class=\"btk-ca-swatch-btn\" style=\"cursor:default;\" disabled>${img}</button>` +\n      `<span class=\"btk-ca-swatch-label\">${escForKp(label)}</span>` +\n      `<span class=\"btk-ca-swatch-name\">${escForKp(name)}</span>` +\n    `</div>`;\n  }\n  function toggleChip(label, opts, active) {\n    const btns = opts.map(o =>\n      `<button class=\"btk-ca-toggle-opt ${o.value === active ? 'btk-ca-toggle-opt--active' : ''}\" disabled>${escForKp(o.label)}</button>`\n    ).join('');\n    return `<div class=\"btk-kp-detail-opt\">` +\n      `<span class=\"btk-ca-swatch-label\">${escForKp(label)}</span>` +\n      `<div class=\"btk-ca-toggle-wrap\" style=\"pointer-events:none;\">${btns}</div>` +\n    `</div>`;\n  }\n\n  // Details panel = the real product page's own blocks: its title, the\n  // line's chosen colours/options as pills, and the actual description /\n  // what's-included / care / delivery concertinas transplanted from the PDP\n  // (main.css + main.js style + hydrate them here). Falls back gracefully to\n  // the line's own data when the product page can't be fetched.\n  async function showLineDetails(p, plannable) {\n    if (!embedDetailsEl) return;\n    const myKey = embedSelectedKey;\n\n    // WORKTOP line: the item number, the title, and that board's cut list -\n    // nothing else. No product fetch, no image gallery, no options or specs,\n    // and the mini 2D/3D above stays exactly as it was.\n    if (String(p.group || '').toLowerCase() === 'worktops') {\n      const tp = String(p.title || '').split(' - ');\n      const eyebrow = tp.length > 1 ? tp[0].trim() : '';\n      const name    = tp.length > 1 ? tp.slice(1).join(' - ').trim() : (p.title || '');\n      // The generic title below turns the size into \"\u2026mm Wide x \u2026mm Deep\",\n      // which mangles a board size (\"23mmmm Wide\"); show it as supplied.\n      const size = String(p.size || '').trim();\n      const title =\n        `<span class=\"btk-ca-card-title\" style=\"display:block;\">` +\n          (eyebrow ? `<span class=\"btk-ca-card-title-style\">${escForKp(eyebrow)}</span>` : '') +\n          `<span class=\"btk-ca-card-title-unit\">${escForKp(name)}${size ? ' - ' + escForKp(size) : ''}</span>` +\n        `</span>`;\n      const num = p.num ? `<span class=\"btk-kp-detail-num\">${escForKp(String(p.num))}</span>` : '';\n      embedDetailsEl.innerHTML =\n        `<div class=\"btk-kp-product-detail\">` +\n          `<div class=\"btk-kp-detail-head\">` +\n            `<div class=\"btk-kp-detail-head-left\">${num}<div class=\"btk-kp-detail-head-title\">${title}</div></div>` +\n            // Right-hand slot of the head - where a unit shows its price.\n            `<div style=\"flex:0 0 auto;\">` +\n              `<button type=\"button\" class=\"btk-kp-action-btn btk-kp-action-btn--green btk-kp-action-btn--sm\" data-btk-kp-open-cutlist>` +\n                `<span class=\"btk-kp-action-btn-label\">${escForKp((window.BTKWorktopCutList && window.BTKWorktopCutList.label && window.BTKWorktopCutList.label()) || 'Cut List')}</span>` +\n              `</button>` +\n            `</div>` +\n          `</div>` +\n          lineCutListHTML(p) +\n          `<button type=\"button\" class=\"btk-kp-line-detail-back\" data-btk-kp-focus-close>Back to overview</button>` +\n        `</div>`;\n      embedDetailsEl.hidden = false;\n      if (embedAdvisoryEl) embedAdvisoryEl.hidden = true;\n      embedDetailsEl.querySelectorAll('[data-btk-kp-focus-close]').forEach(b => b.addEventListener('click', clearEmbedFocus));\n      bindCutListFocus(embedDetailsEl);\n      // Same entry point as the Cut List button in the basket's Worktops\n      // header, so both open the identical full-size popup.\n      embedDetailsEl.querySelector('[data-btk-kp-open-cutlist]')\n        ?.addEventListener('click', () => { try { window.BTKWorktopCutList?.open(); } catch (e) {} });\n      return;\n    }\n    embedDetailsEl.innerHTML = `<div class=\"btk-kp-product-detail\"><p class=\"btk-kp-product-loading\">Loading details\u2026</p></div>`;\n    embedDetailsEl.hidden = false;\n    if (embedAdvisoryEl) embedAdvisoryEl.hidden = true;\n\n    const handle = handleFromUrl(p.url);\n    const doc = await fetchProductDoc(handle);\n    if (embedSelectedKey !== myKey) return;   // selection changed mid-fetch\n\n    // Non-plannable products keep the image gallery (a plannable line already\n    // has the mini-3D as its visual).\n    if (!plannable && doc) {\n      const imgs = [...doc.querySelectorAll('.product-gallery__media img, .product__media img, .product-media img')]\n        .map(i => i.getAttribute('src')).filter(Boolean).slice(0, 6);\n      if (imgs.length) renderImageGallery(imgs, p.title);\n    }\n\n    // Name rendered EXACTLY like the basket line / listing card: a small\n    // style eyebrow + the unit name, width/depth trailing - SAME classes, so\n    // it's the same 2-part font style and size (not the huge full-width PDP\n    // <h1>). Built from THIS line's own title, so it's always the right\n    // product (a filler reads \"Tall Filler Panel\", never the fetched page's).\n    // Eyebrow = the STYLE name only; everything else (unit type + door +\n    // size) is the bold second line. The basket line sends it already split\n    // (titleParts in btk-cart-advanced.js, the card's own rule); otherwise\n    // fall back to the first hyphen.\n    const tparts = String(p.title || '').split(' - ');\n    let styleName = '', unitName = p.title || '';\n    if (typeof p.titleUnit === 'string' && p.titleUnit) { styleName = p.titleStyle || ''; unitName = p.titleUnit; }\n    else if (tparts.length > 1) { styleName = tparts[0].trim(); unitName = tparts.slice(1).join(' - ').trim(); }\n    const vparts = String(p.size || '').split('/').map(s => s.trim());\n    // Only real sizes read as \"mm Wide\" / \"mm Deep\" (Arden, 2026-10-11).\n    const _num = (v) => { const m = String(v || '').trim().match(/^(\\d+(?:\\.\\d+)?)\\s*(?:mm)?$/i); return m ? m[1] : ''; };\n    const w = _num(vparts[0]), d = _num(vparts[1]);\n    const dims = (w || d) ? ' - ' + (w ? w + 'mm Wide' : '') + (w && d ? ' x ' : '') + (d ? d + 'mm Deep' : '') : '';\n    const titleHtml =\n      `<span class=\"btk-ca-card-title\" style=\"display:block;\">` +\n        (styleName ? `<span class=\"btk-ca-card-title-style\">${escForKp(styleName)}</span>` : '') +\n        `<span class=\"btk-ca-card-title-unit\">${escForKp(unitName)}${escForKp(dims)}</span>` +\n      `</span>`;\n    const numBadge = p.num ? `<span class=\"btk-kp-detail-num\">${escForKp(String(p.num))}</span>` : '';\n\n    // Price as a right-hand column with before/after (like the listing).\n    const priceNum    = parseFloat(p.price);\n    const compareNum  = parseFloat(p.compareAt);\n    const originalNum = parseFloat(p.original);\n    const wasNum = (isFinite(compareNum) && compareNum > priceNum) ? compareNum\n                 : (isFinite(originalNum) && originalNum > priceNum) ? originalNum : null;\n    // Same markup + classes as the basket line's price column: \"Total Price\"\n    // label, the total, then \"Was \u2026\" struck-through BELOW it.\n    const priceCol =\n      `<div class=\"btk-kp-detail-price\">` +\n        `<span class=\"btk-ca-price-label\">Total Price</span>` +\n        (isFinite(priceNum) ? `<span class=\"btk-ca-price-total\">${lineMoney.format(priceNum)}</span>` : '') +\n        (wasNum ? `<span class=\"btk-ca-price-original\">Was <span class=\"btk-ca-price-was-value\">${lineMoney.format(wasNum)}</span></span>` : '') +\n      `</div>`;\n\n    // Hinge is CHANGEABLE from the panel (updates the cabinet + basket).\n    const hingeToggle = (p.hinge && p.cabId) ? (() => {\n      const btns = [['Left', 'Left'], ['Right', 'Right']].map(([v, l]) =>\n        `<button class=\"btk-ca-toggle-opt ${v === p.hinge ? 'btk-ca-toggle-opt--active' : ''}\"` +\n        ` data-btk-kp-set-hinge=\"${v}\" data-btk-kp-cab=\"${escForKp(String(p.cabId))}\">${l}</button>`).join('');\n      return `<div class=\"btk-kp-detail-opt\"><span class=\"btk-ca-swatch-label\">Hinge</span>` +\n             `<div class=\"btk-ca-toggle-wrap\">${btns}</div></div>`;\n    })() : '';\n\n    const options = [\n      swatchChip('Door', p.door, p.doorSwatch),\n      swatchChip('Carcase', p.carcase, p.carcaseSwatch),   // auto-hidden when no carcase colour\n      hingeToggle,\n      // Assembly is changed HERE now - the basket line only shows it\n      // (Arden, 2026-10-10).\n      (p.assembly && p.itemId) ? (() => {\n        // A flat pack delivery chosen in the basket, or a size only supplied\n        // flat packed, locks Assembled.\n        const _ca = window.BTKCartAdvanced;\n        const lockTitle = !_ca ? ''\n          : (typeof _ca.assemblyLockedFor === 'function') ? _ca.assemblyLockedFor(p.itemId)\n          : ((typeof _ca.assemblyLocked === 'function' && _ca.assemblyLocked()) ? (_ca.assemblyLockedTitle || '') : '');\n        const btns = [['Flatpack', 'Flatpack'], ['Fully Assembled', 'Assembled']].map(([v, l]) =>\n          (lockTitle && v !== 'Flatpack')\n            ? `<button class=\"btk-ca-toggle-opt\" disabled title=\"${escForKp(lockTitle)}\" style=\"opacity:0.45;cursor:not-allowed;\">${l}</button>`\n            : `<button class=\"btk-ca-toggle-opt ${/flat/i.test(p.assembly) === (v === 'Flatpack') ? 'btk-ca-toggle-opt--active' : ''}\"` +\n              ` data-btk-kp-set-assembly=\"${v}\" data-btk-kp-item=\"${escForKp(String(p.itemId))}\">${l}</button>`).join('');\n        return `<div class=\"btk-kp-detail-opt\"><span class=\"btk-ca-swatch-label\">Assembly</span>` +\n               `<div class=\"btk-ca-toggle-wrap\">${btns}</div></div>`;\n      })() : p.assembly ? toggleChip('Assembly', [{ value: 'Flatpack', label: 'Flatpack' }, { value: 'Fully Assembled', label: 'Assembled' }], p.assembly) : '',\n    ].filter(Boolean).join('');\n\n    // Transplant the real product-page concertinas (description, what's\n    // included, care, delivery).\n    let concertinas = '';\n    if (doc) {\n      const wanted = ['description', 'included', 'care', 'delivery'];\n      concertinas = [...doc.querySelectorAll('details-disclosure')]\n        .filter(el => {\n          const t = (el.querySelector('.disclosure__title')?.textContent || '').trim().toLowerCase();\n          return wanted.some(w => t.includes(w));\n        })\n        .map(el => el.outerHTML).join('');\n    }\n\n    const link = p.url\n      ? `<a class=\"btk-kp-product-link\" href=\"${escForKp(p.url)}\" target=\"_blank\" rel=\"noopener\">View full product page \u2197</a>` : '';\n    embedDetailsEl.innerHTML =\n      `<div class=\"btk-kp-product-detail\">` +\n        `<div class=\"btk-kp-detail-head\">` +\n          `<div class=\"btk-kp-detail-head-left\">${numBadge}<div class=\"btk-kp-detail-head-title\">${titleHtml}</div></div>` +\n          priceCol +\n        `</div>` +\n        (options  ? `<div class=\"btk-kp-detail-opts\">${options}</div>` : '') +\n        (concertinas ? `<div class=\"btk-kp-product-concertinas\">${concertinas}</div>` : '') +\n        link +\n        `<button type=\"button\" class=\"btk-kp-line-detail-back\" data-btk-kp-focus-close>Back to overview</button>` +\n      `</div>`;\n    embedDetailsEl.querySelectorAll('[data-btk-kp-focus-close]').forEach(b => b.addEventListener('click', clearEmbedFocus));\n    embedDetailsEl.querySelectorAll('[data-btk-kp-set-hinge]').forEach(btn => {\n      btn.addEventListener('click', () => {\n        const cabId = btn.getAttribute('data-btk-kp-cab');\n        const val   = btn.getAttribute('data-btk-kp-set-hinge');\n        if (!cabId) return;\n        btn.parentElement.querySelectorAll('.btk-ca-toggle-opt').forEach(b => b.classList.remove('btk-ca-toggle-opt--active'));\n        btn.classList.add('btk-ca-toggle-opt--active');\n        setPlannerLineHinge(cabId, val);\n      });\n    });\n    embedDetailsEl.querySelectorAll('[data-btk-kp-set-assembly]').forEach(btn => {\n      btn.addEventListener('click', () => {\n        const itemId = btn.getAttribute('data-btk-kp-item');\n        const val    = btn.getAttribute('data-btk-kp-set-assembly');\n        const api    = window.BTKCartAdvanced;\n        if (!itemId || !api || typeof api.setItemAttr !== 'function') return;\n        if (!api.setItemAttr(itemId, 'assembly', val)) return;\n        btn.parentElement.querySelectorAll('.btk-ca-toggle-opt').forEach(b => b.classList.remove('btk-ca-toggle-opt--active'));\n        btn.classList.add('btk-ca-toggle-opt--active');\n      });\n    });\n  }\n\n  // Flip a planner unit's hinge from the details panel: update the cabinet\n  // (3D/2D reflect it), then rebuild the basket so the line + quote follow.\n  function setPlannerLineHinge(cabId, val) {\n    try { handleUpdateCabinetHinge(cabId, String(val).toLowerCase()); } catch (e) {}\n    refreshQuoteLocally();\n  }\n\n  window.__btkPlannerLineSelected = (payload) => {\n    if (!payload) return;\n    const cabId = payload.cabId;\n    const epFaces = payload.epFaces ? String(payload.epFaces).split(',').filter(Boolean) : null;\n    // A vertical PROFILE line (\"cabId:rail-left\"): selects the PROFILE - its\n    // strip on the plan, its mesh in 3D - like a panel line selects its panel.\n    const _railM = (epFaces && epFaces.length) ? String(epFaces[0]).match(/^(.*):rail-(left|right)$/) : null;\n    const _railFace = _railM ? railOwnerFace(_railM[1], _railM[2]) : null;\n    const _cpM = (epFaces && epFaces.length) ? String(epFaces[0]).match(/^(.*):(left|right):cpost(-back)?$/) : null;\n    // A SINK line (q:sk:<unit>) or a TAP line on a sink unit (q:wi:tap:<tap>)\n    // selects that unit's sink + tap, not the unit (Arden, 2026-10-24).\n    const _lineId = String(payload.itemId || '');\n    let _sinkSetCab = null;\n    {\n      const _sk = _lineId.match(/^q:sk:(.+)$/);\n      const _tp = _lineId.match(/^q:wi:tap:(.+)$/);\n      if (_sk && cabinets.some(c => c.id === _sk[1])) _sinkSetCab = _sk[1];\n      else if (_tp) { const _h = sinkUnitForTap(_tp[1]); if (_h) _sinkSetCab = _h.id; }\n    }\n    const key = (epFaces && epFaces.length) ? ('ep:' + payload.epFaces)\n      : _sinkSetCab ? ('sink:' + _lineId)\n      : (cabId ? ('cab:' + cabId) : ('np:' + (payload.itemId || payload.url || '')));\n    if (embedSelectedKey === key) { clearEmbedFocus(); return; }   // toggle off\n    clearEmbedFocus();\n    embedSelectedKey = key;\n    setSelectedLineCard(payload);\n    const plannable = !!cabId || !!_sinkSetCab || !!(epFaces && epFaces.length);\n    const in2D = (viewMode === '2d');\n    if (epFaces && epFaces.length) {\n      if (in2D && _cpM) {\n        selectItem({ kind: 'cpost', cabinetId: _cpM[1], side: _cpM[2], pos: _cpM[3] ? 'back' : 'front' });\n      } else if (in2D && _railFace) {\n        selectItem({ kind: 'rail', cabinetId: _railFace.cabId, side: _railFace.side });\n      } else if (in2D) {\n        // 2D view: highlight the PANEL / FILLER itself on the plan (its own\n        // element, independent of the host unit - like the 3D framing does),\n        // and DON'T zoom - the whole room is already in view.\n        // Keep everything after the cab id - the side AND any part suffix\n        // ('left:feature'), so a feature row selects the post, not the panel.\n        const _bits = String(epFaces[0]).split(':');\n        const hostId = _bits.shift();\n        selectItem({ kind: 'end-panel', cabinetId: hostId, side: _bits.join(':') });\n      } else {\n        // Panel / filler line \u2192 highlight + frame the PANEL itself in the\n        // mini-3D, not the host unit it sits against.\n        try { handle3D?.focusOnEndPanel?.(epFaces); } catch (e) {}\n        // Float the panel's number over the focused slab (this path doesn't\n        // go through selectItem, so drive the badge directly).\n        try {\n          const map = (endPanelLayout && endPanelLayout.cabSideToNumber) || {};\n          let num = payload.num || null;\n          if (num == null && _railFace) num = railNumberOf(cabinets.find(c => c.id === _railFace.cabId), _railFace.side);\n          if (num == null && _cpM) num = cornerPostNumberOf(cabinets.find(c => c.id === _cpM[1]), _cpM[2], _cpM[3] ? 'back' : 'front');\n          if (num == null) { for (const f of epFaces) { if (map[f] != null) { num = map[f]; break; } } }\n          handle3D?.setSelectionBadge?.(num == null ? null : num);\n        } catch (e) {}\n      }\n    } else if (_sinkSetCab) {\n      selectItem({ kind: 'planner-sink', cabinetId: _sinkSetCab });\n      if (!in2D) { try { handle3D?.focusOnCabinet?.(_sinkSetCab); } catch (e) {} }\n    } else if (cabId) {\n      const cab = cabinets.find(c => String(c.id) === String(cabId));\n      if (cab) {\n        selectItem({ kind: 'cabinet', id: cab.id });\n        // Highlight only in 2D (no zoom - just show it on the plan); the 3D\n        // view still frames the camera on the unit.\n        if (!in2D) { try { handle3D?.focusOnCabinet?.(cab.id); } catch (e) {} }\n      }\n    } else if (payload.image && embedImageOverlayEl\n               && String(payload.group || '').toLowerCase() !== 'worktops') {\n      // Show the picker thumbnail immediately; the fetch upgrades it to\n      // the full product gallery. NOT for a worktop line: its visual is the\n      // cut list in the panel below, and the mini 2D/3D must stay visible.\n      const img = document.createElement('img');\n      img.src = payload.image;\n      img.alt = payload.title || '';\n      embedImageOverlayEl.replaceChildren(img);\n      embedImageOverlayEl.hidden = false;\n    }\n    showLineDetails(payload, plannable);\n    const x = root.querySelector('[data-btk-kp-focus-close]');\n    if (x) x.hidden = false;\n  };\n  root.querySelectorAll('[data-btk-kp-focus-close]').forEach(btn => {\n    btn.addEventListener('click', clearEmbedFocus);\n  });\n\n  // The basket's red X on a planner line excludes that unit from the\n  // quote (it stays in the 3D plan) and re-syncs the basket without it.\n  window.__btkPlannerExcludeFromQuote = (cabId) => {\n    if (cabId == null) return;\n    const cab = cabinets.find(c => String(c.id) === String(cabId));\n    if (!cab) return;\n    clearEmbedFocus();\n    setCabinetExcludeFromQuote(cab.id, true);\n    refreshQuoteLocally();\n  };\n\n  // The basket's Include / Exclude popup. Excluded units have no basket line,\n  // so the list comes from the PLAN: every cabinet that can be quoted (the\n  // same set buildItem turns into unit lines), included first in plan order.\n  window.__btkPlannerQuoteCabinets = () => (cabinets || [])\n    .filter(c => c && c.variantId && !c.endPanelUnit && !c.freestandingAppliance)\n    .map(c => {\n      const def  = findCabinet(c) || {};\n      const info = Catalogue.getVariantInfo(c.variantId);\n      return {\n        id:       c.id,\n        num:      c.excludeFromQuote ? null : (c.displayNumber != null ? c.displayNumber : null),\n        name:     (info && info.product && info.product.title) || def.name || c.code || 'Cabinet',\n        excluded: !!c.excludeFromQuote,\n      };\n    })\n    .sort((a, b) => (a.excluded - b.excluded) || ((a.num ?? 9e9) - (b.num ?? 9e9)));\n  // The other lines (see quoteExcludedLines): what is excluded, and set one.\n  window.__btkPlannerExcludedLines = () => Object.entries(quoteExcludedLines)\n    .map(([id, m]) => ({ id, name: (m && m.name) || 'Item', group: (m && m.group) || 'other' }));\n  window.__btkPlannerSetLineExcluded = (id, excluded, meta) => {\n    if (!id) return;\n    if (excluded) quoteExcludedLines = { ...quoteExcludedLines, [id]: { name: (meta && meta.name) || 'Item', group: (meta && meta.group) || 'other' } };\n    else { const next = { ...quoteExcludedLines }; delete next[id]; quoteExcludedLines = next; }\n    clearEmbedFocus();\n    // The numbering skips excluded lines, so re-number (rerender) before the\n    // basket is rebuilt: the plan, basket and order close up round the line.\n    rerender();\n    refreshQuoteLocally();\n    refreshHiddenPlanNumbers();\n    scheduleAutosave();\n  };\n  // FREE TAP OFFER (Arden, 2026-10-18): the basket's \"replace your tap\" puts\n  // the free tap in place of a tap on the plan - same spot, same way round,\n  // its product swapped - so it stays on the worktop in 2D/3D and in the plan's\n  // Taps. Keyed by the worktop item id (the line is q:wi:tap:<id>). False when\n  // the tap is not on the plan or the free tap is not one the planner has.\n  window.__btkPlannerSwapTap = (wiId, handle, freeGift) => {\n    const idx = (worktopItems || []).findIndex(w => w && w.id === wiId && w.kind === 'tap');\n    if (idx === -1) return false;\n    const entry = (getWorktopItemCatalogue().taps || []).find(t => t && t.handle === handle);\n    if (!entry) return false;\n    const old = worktopItems[idx];\n    const def = buildWorktopItemDefinition(entry, { id: old.id, x: old.x, y: old.y });\n    if (!def) return false;\n    // Same centre, whatever the new tap's footprint.\n    def.x = old.x + ((old.widthMm || 0) - (def.widthMm || 0)) / 2;\n    def.y = old.y + ((old.depthMm || 0) - (def.depthMm || 0)) / 2;\n    def.rotationDeg = old.rotationDeg || 0;\n    if (old.planLineNumber != null) def.planLineNumber = old.planLineNumber;\n    if (freeGift) def.freeGift = true;\n    const next = [...worktopItems];\n    next[idx] = def;\n    worktopItems = next;\n    rerender();\n    refreshQuoteLocally();\n    scheduleAutosave();\n    return true;\n  };\n  // The free tap stops being free (the units fell under the offer): the tap\n  // stays on the plan, at its price.\n  window.__btkPlannerSetTapGift = (wiId, on) => {\n    const idx = (worktopItems || []).findIndex(w => w && w.id === wiId && w.kind === 'tap');\n    if (idx === -1) return false;\n    const next = [...worktopItems];\n    next[idx] = { ...worktopItems[idx] };\n    if (on) next[idx].freeGift = true; else delete next[idx].freeGift;\n    worktopItems = next;\n    refreshQuoteLocally();\n    scheduleAutosave();\n    return true;\n  };\n  // Staff \"Make free\" (see quoteFreeLines): the basket asks planner-api for the\n  // code, then records it here, or clears it on Undo.\n  window.__btkPlannerFreeLine = (id) => (id && quoteFreeLines[id]) ? { ...quoteFreeLines[id] } : null;\n  window.__btkPlannerSetLineFree = (id, rec) => {\n    if (!id) return;\n    if (rec && rec.code) {\n      quoteFreeLines = { ...quoteFreeLines, [id]: {\n        code: String(rec.code), variantId: String(rec.variantId || ''), quantity: Number(rec.quantity || 1),\n        amount: rec.amount || null, title: rec.title || null, by: rec.by || null, at: new Date().toISOString(),\n        endsAt: rec.endsAt || null,\n      } };\n    } else { const next = { ...quoteFreeLines }; delete next[id]; quoteFreeLines = next; }\n    refreshQuoteLocally();\n    scheduleAutosave();\n  };\n  window.__btkPlannerSetExcluded = (cabId, excluded) => {\n    const cab = (cabinets || []).find(c => String(c.id) === String(cabId));\n    if (!cab) return;\n    clearEmbedFocus();\n    setCabinetExcludeFromQuote(cab.id, !!excluded);\n    refreshQuoteLocally();\n  };\n\n  // \u2500\u2500 Add other items: every simple product on the site \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n  // The basket's \"Add other items\" tile (Arden, 2026-10-08, for the sales\n  // team: a wrong-sized worktop board has to be swappable for the right one,\n  // and a showroom order got over the line without waiting for a fix). Every\n  // product type the shop sells is grouped into the left menu (the Splashbacks\n  // icon buttons); a group's products load when it is opened, ONE request per\n  // type and page, from templates/collection.kpextras.liquid - so every size /\n  // option is there, at the site's own discounted price. They go into the\n  // basket's Extras group and are never drawn or numbered on the plan.\n  // Doors, Panels & Accessories (Arden, 2026-10-15/16) is the one group read\n  // from a COLLECTION, not by type: the Add Units category of the same name,\n  // whose panels, trims and posts carry no product type. It holds ~2,800\n  // products across every style, so it loads ONE style at a time (the units\n  // listing's kitchen_style_handle filter, plus \"all\" for the shared carcase\n  // material items), opening on the plan's style. It used to read six\n  // collections in the section settings, 50 products each and only the first\n  // variant - so a worktop's other lengths could not be chosen at all.\n  const extrasPopup     = root.querySelector('[data-btk-kp-popup=\"extras-picker\"]');\n  const extrasBodyEl    = root.querySelector('[data-btk-kp-extras-body]');\n  const extrasSearchEl  = root.querySelector('[data-btk-kp-extras-search]');\n  const extrasSearchClr = root.querySelector('[data-btk-kp-extras-search-clear]');\n  const extrasMoney   = new Intl.NumberFormat('en-GB', { style: 'currency', currency: context.currency || 'GBP' });\n  const formatExtrasPrice = (cents) => extrasMoney.format((Number(cents) || 0) / 100);\n  const xEsc = (s) => String(s == null ? '' : s).replace(/[&<>\"]/g, ch =>\n    ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '\"': '&quot;' }[ch]));\n  // First match wins, so the narrower groups come first (Worktop Accessories\n  // are worktops; True Handleless Accessories are not handles). The door\n  // types are claimed by the collection group, which lists them itself, so\n  // they never land in Other Items; whole names only, so Kitchen Door\n  // Samples, Warming Drawers and the in-column fridges \"To suit 1245mm High\n  // Door\" stay in their own groups.\n  const EXTRAS_FRONT_TYPES = /^(doors|drawer fronts|framed doors|glazed doors)$/i;\n  const EXTRAS_GROUPS = [\n    { key: 'worktops',    label: 'Worktops',           re: /worktop/i },\n    { key: 'splashbacks', label: 'Splashbacks',        re: /splashback/i },\n    { key: 'th',          label: 'True Handleless',    re: /handleless|profile/i },\n    { key: 'handles',     label: 'Handles',            re: /handle/i },\n    { key: 'dpa',         label: 'Doors, Panels & Accessories', re: EXTRAS_FRONT_TYPES,\n      collection: 'kitchen-unit-doors-panels-accessories' },\n    { key: 'sinks',       label: 'Sinks & Taps',       re: /sink|tap/i },\n    { key: 'appliances',  label: 'Appliances',         re: /oven|hob|extract|fridge|freezer|dishwasher|wine|washer|dryer|microwave|warming|appliance/i },\n    { key: 'storage',     label: 'Storage & Fittings', re: /fitting|storage|pull ?out|cutlery|spice|waste|recycl|component|accessor/i },\n    { key: 'lighting',    label: 'Lighting',           re: /light/i },\n    { key: 'furniture',   label: 'Stools & Furniture', re: /stool|chair|table|furniture/i },\n    { key: 'samples',     label: 'Door Samples',       re: /sample/i },\n  ];\n  // A part from Doors, Panels & Accessories is made in the kitchen's colours, as\n  // the same part added from the website is (the listing gives it the style,\n  // door and carcase colour): the carcase-material boards (utg \"mfc-panel\" -\n  // shelves, plinth panels) in the carcase colour, everything else - doors,\n  // drawer fronts, end panels, plinth, cornice, fillers, posts - in the door\n  // colour. Stamped when it is added and again every time the basket is\n  // rebuilt, so a colour changed on the plan reaches it. Only for the plan's\n  // own style: a part picked in another style has no colour of the plan's to\n  // take, and is left as it is.\n  function extrasColourOf(p) {\n    const st = extrasCurrentStyle();\n    if (!st) return null;\n    return { style: st.id, kind: p && p.utg === 'mfc-panel' ? 'carcase' : 'door' };\n  }\n  // The plan's colour for a part of that range: the plan's own range as\n  // before; another range the plan has units in (a two-range plan, Sales\n  // line 104) takes its units' colour.\n  function planColourHandle(kind, styleId = kitchenStyleId) {\n    if (styleId === kitchenStyleId) {\n      const g = kind === 'carcase' ? globalCarcaseColourHandle : globalDoorColourHandle;\n      if (g) return g;\n    }\n    const key = kind === 'carcase' ? 'carcaseColourHandle' : 'doorColourHandle';\n    const c = (cabinets || []).find(x => x && x.kitchenStyleId === styleId && x[key]);\n    return c ? c[key] : null;\n  }\n  // An extra added before Add Other Items gave its parts the plan's colour\n  // (Arden, 2026-10-20): SO300016's four Ultimo doors, added on 17 Oct, reached\n  // Odoo with no colour while the parts added later had Cream Gloss. A part of\n  // the plan's own range - its title is \"<Range> - ...\", the range named as\n  // the catalogue names it, punctuation aside - is marked for the plan's door\n  // colour, which stampExtraColour then gives it. Nothing it can't place is\n  // touched (another range's part, or one already coloured).\n  const extrasNameKey = (v) => String(v || '').toLowerCase().replace(/[^a-z0-9]/g, '');\n  function backfillExtraColour(item) {\n    const a = item && item.attributes;\n    if (!a || !a.manualExtra || a.extraColour || a.doorColour || a.carcaseColour || !kitchenStyleId) return;\n    const st = (window.BTKKitchenCatalogue?.kitchenStyles || []).find(x => x && x.id === kitchenStyleId);\n    const t = String(item.productTitle || ''), i = t.indexOf(' - ');\n    if (!st || !st.name || i < 1 || extrasNameKey(t.slice(0, i)) !== extrasNameKey(st.name)) return;\n    a.style = kitchenStyleId;\n    a.extraColour = 'door';\n  }\n  function stampExtraColour(item) {\n    const a = item && item.attributes;\n    if (!a || !a.extraColour || !a.style) return;\n    // The plan's range, or any range the plan still has units in.\n    if (a.style !== kitchenStyleId && !(cabinets || []).some(c => c && c.kitchenStyleId === a.style)) return;\n    delete a.bespokeColour;\n    if (a.extraColour === 'carcase') {\n      a.carcaseColour = planColourHandle('carcase', a.style);\n      a.doorColour = null;\n      return;\n    }\n    a.carcaseColour = null;\n    const door = planColourHandle('door', a.style);\n    // An F&B / RAL paint: the range's own colour product, the paint named\n    // beside it - the same as a unit's line (see the BESPOKE PAINT pass).\n    const bp = door && Catalogue.getBespokePaint ? Catalogue.getBespokePaint(door) : null;\n    if (bp) { a.doorColour = bp.baseHandle; a.bespokeColour = { type: bp.type, value: bp.value, ...(bp.own && bp.hex ? { hex: bp.hex } : {}) }; }\n    else a.doorColour = door;\n  }\n\n  const EXTRAS_ICON = '<svg width=\"20\" height=\"20\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M21 8l-9-5-9 5 9 5 9-5z\"/><path d=\"M3 8v8l9 5 9-5V8\"/><path d=\"M12 13v8\"/></svg>';\n  const EXTRAS_CHEVRON = '<svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M9 18l6-6-6-6\"/></svg>';\n  const EXTRAS_FUNNEL = '<svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\"><path d=\"M3 5h18l-7 8v6l-4 2v-8z\"/></svg>';\n  const EXTRAS_CHEV_DOWN = '<svg width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M6 9l6 6 6-6\"/></svg>';\n\n  // Quartz and porcelain slabs are made to measure and installed, not sold as\n  // blanks (Sales bug sheet, 2026-11-05): the website hides their buy buttons\n  // by product type, so they are left out here by the same types. They reach\n  // a basket only as a worktop drawn on the plan (the bespoke band line).\n  const EXTRAS_NOT_SOLD = /^(quartz|porcelain) worktops$/i;\n  function extrasGroups() {\n    const types = (Array.isArray(window.BTKPlannerExtraTypes) ? window.BTKPlannerExtraTypes : [])\n      .map(t => String(t || '').trim()).filter(t => t && !EXTRAS_NOT_SOLD.test(t));\n    const out = EXTRAS_GROUPS.map(g => ({ ...g, types: [] }));\n    const other = { key: 'other', label: 'Other Items', types: [] };\n    for (const t of types) (out.find(g => g.re.test(t)) || other).types.push(t);\n    return [...out, other].filter(g => g.types.length || g.collection);\n  }\n\n  // url -> Promise<products>, every page. Kept for the page: a group (or a\n  // style) opened again is instant.\n  const extrasFetchCache = new Map();\n  function fetchExtrasPages(url) {\n    if (extrasFetchCache.has(url)) return extrasFetchCache.get(url);\n    const p = (async () => {\n      const out = [];\n      for (let page = 1, pages = 1; page <= pages && page <= 40; page++) {\n        const r = await fetch(url + '&page=' + page, { credentials: 'same-origin' });\n        if (!r.ok) throw new Error('HTTP ' + r.status);\n        const j = JSON.parse(await r.text());\n        pages = Number(j.pages) || 1;\n        for (const prod of (j.products || [])) out.push(prod);\n      }\n      return out;\n    })().catch((e) => {\n      console.warn('[BTK Kitchen Planner] other items: loading \"' + url + '\" failed', e);\n      extrasFetchCache.delete(url);   // try again next time the group opens\n      return [];\n    });\n    extrasFetchCache.set(url, p);\n    return p;\n  }\n\n  let extrasActive = null;          // the open group's key\n  const extrasLoaded = {};          // data key -> products (missing while loading)\n  const extrasLoading = new Set();\n  let extrasFacets = { type: '', brand: '' };\n  let extrasFilterOpen = false;\n  let extrasQuery = '';\n  const extrasPick = {};            // product id -> chosen variant id\n\n  // The collection group's style: a kitchen style id, null until the\n  // customer picks one (then the plan's own style is used).\n  let extrasStyleId = null;\n  const extrasStyles = () => (window.BTKKitchenCatalogue?.kitchenStyles || [])\n    .filter(st => st && st.id && st.name)\n    .sort((a, b) => a.name.localeCompare(b.name));\n  function extrasCurrentStyle() {\n    const list = extrasStyles();\n    return list.find(st => st.id === extrasStyleId)\n      || list.find(st => st.id === kitchenStyleId) || list[0] || null;\n  }\n  // Where a group's products live in extrasLoaded: per style for the\n  // collection group, as it loads one style at a time.\n  function extrasDataKey(g) {\n    if (!g || !g.collection) return g ? g.key : '';\n    const st = extrasCurrentStyle();\n    return g.key + ':' + (st ? st.id : '');\n  }\n  // Front sizes are authored \"296 / Yes\" (width / drilled for 35mm hinges).\n  // Drilling is not offered (Arden, 2026-10-18): the drilled sizes are dropped\n  // when the group loads (extrasNotDrilled), so a size reads as its width.\n  const extrasVariantLabel = (p, v) => {\n    const m = EXTRAS_FRONT_TYPES.test(p.type || '') ? /^(\\d+)(?: \\/ (Yes|No))?$/.exec(String(v.title || '')) : null;\n    if (!m) return v.title;\n    return m[1] + 'mm wide';\n  };\n  const extrasNotDrilled = (p, v) => !(EXTRAS_FRONT_TYPES.test(p.type || '') && / \\/ Yes$/.test(String(v.title || '')));\n\n  function loadExtrasGroup(g) {\n    const key = extrasDataKey(g);\n    if (!g || extrasLoaded[key] || extrasLoading.has(key)) return;\n    extrasLoading.add(key);\n    let urls;\n    if (g.collection) {\n      const st = extrasCurrentStyle();\n      const f = 'filter.p.m.custom.kitchen_style_handle=';\n      urls = ['/collections/' + encodeURIComponent(g.collection) + '?view=kpextras'\n        + (st ? '&' + f + encodeURIComponent(st.id) : '') + '&' + f + 'all'];\n    } else {\n      urls = g.types.map(t => '/collections/types?q=' + encodeURIComponent(t) + '&view=kpextras');\n    }\n    Promise.all(urls.map(fetchExtrasPages)).then(lists => {\n      // Only what can be bought: the cart refuses the rest. `kind` is what\n      // the Type filter shows: the product type, or for the panels, trims\n      // and posts (which have none) their Add Units group, e.g. End Panels,\n      // from the feed's utg tag. The tag is the group's SLUG (\"mfc-panel\" for\n      // Carcase MFC Panels), not its handle; the handle is a fallback.\n      const utgTitle = {};\n      for (const ug of (window.BTKKitchenCatalogue?.unitTypeGroups || [])) {\n        if (!ug || !ug.title) continue;\n        if (ug.id && !utgTitle[ug.id]) utgTitle[ug.id] = ug.title;\n        if (ug.slug) utgTitle[ug.slug] = ug.title;\n      }\n      extrasLoaded[key] = lists.flat()\n        .map(p => ({ ...p, kind: p.type || utgTitle[p.utg] || (g.collection ? 'Other' : ''),\n                     variants: (p.variants || []).filter(v => v.available && extrasNotDrilled(p, v)) }))\n        .filter(p => p.variants.length)\n        .sort((a, b) => String(a.kind).localeCompare(String(b.kind)) || String(a.title).localeCompare(String(b.title)));\n      extrasLoading.delete(key);\n      if (extrasDataKey(extrasGroups().find(x => x.key === extrasActive)) === key) renderExtras();\n    });\n  }\n\n  function extrasPriceHTML(cents) {\n    const vat = window.BTKVat;\n    const money = (vat && typeof vat.formatPrice === 'function')\n      ? vat.formatPrice(Math.round(Number(cents) || 0))\n      : formatExtrasPrice(cents);\n    return `<div class=\"product-info__price btk-kp-picker-price\"><div class=\"price\"><div class=\"price__default\">\n        <span class=\"price__current\"><span class=\"js-value\">${xEsc(money)}</span></span>\n      </div></div></div>`;\n  }\n  const extrasChosenVariant = (p) =>\n    p.variants.find(v => String(v.id) === String(extrasPick[p.id])) || p.variants[0];\n\n  function extrasFilterBar(rows) {\n    if (!rows.length) return '';\n    const chosen = rows.map(r => extrasFacets[r.key]).filter(Boolean);\n    return `<div class=\"btk-kp-cabinets-dimfilter-bar\">\n        <button type=\"button\" class=\"btk-kp-cabinets-dimfilter-btn${extrasFilterOpen ? ' is-open' : ''}${chosen.length ? ' has-selection' : ''}\"\n                data-btk-kp-extras-ftoggle aria-expanded=\"${extrasFilterOpen}\">\n          ${EXTRAS_FUNNEL}<span>${xEsc(chosen.length ? chosen.join(', ') : 'Filter')}</span>\n          <span class=\"btk-kp-cabinets-dimfilter-chevron\" aria-hidden=\"true\">${EXTRAS_CHEV_DOWN}</span>\n        </button>\n        <button type=\"button\" class=\"btk-kp-cabinets-dimfilter-reset\" data-btk-kp-extras-freset${chosen.length ? '' : ' hidden'}>Reset</button>\n      </div>\n      <div class=\"btk-kp-cabinets-dimfilter\"${extrasFilterOpen ? '' : ' hidden'}>\n        ${rows.map(r => `<div class=\"btk-kp-cabinets-pill-row btk-kp-cabinets-dimfilter-row\">\n            <div class=\"btk-kp-cabinets-pill-label\">${xEsc(r.label)}</div>\n            <div class=\"btk-kp-cabinets-pills\">${r.vals.map(v => `<button type=\"button\"\n                class=\"btk-kp-cabinets-pill${extrasFacets[r.key] === v ? ' is-active' : ''}\"\n                data-btk-kp-extras-facet=\"${r.key}\" data-facet-value=\"${xEsc(v)}\">${xEsc(v)}</button>`).join('')}</div>\n          </div>`).join('')}\n      </div>`;\n  }\n\n  function renderExtras() {\n    if (!extrasBodyEl) return;\n    const groups = extrasGroups();\n    if (!groups.length) {\n      extrasBodyEl.innerHTML = '<p class=\"btk-kp-panel-note\">No products could be listed. Please refresh the page and try again.</p>';\n      return;\n    }\n    if (!groups.some(g => g.key === extrasActive)) extrasActive = groups[0].key;\n    const g = groups.find(x => x.key === extrasActive);\n    loadExtrasGroup(g);\n    const tile = (gr) => `\n      <button type=\"button\" class=\"btk-kp-action-btn${gr.key === extrasActive ? ' is-active' : ''}\" data-btk-kp-extras-group=\"${gr.key}\">\n        <span class=\"btk-kp-action-btn-icon\" aria-hidden=\"true\">${EXTRAS_ICON}</span>\n        <span class=\"btk-kp-action-btn-label\">${xEsc(gr.label)}</span>\n        <span class=\"btk-kp-action-btn-arrow\" aria-hidden=\"true\">${EXTRAS_CHEVRON}</span>\n      </button>`;\n    const all = extrasLoaded[extrasDataKey(g)];\n    // The collection group's Style row lists every style and is never empty:\n    // its products are loaded for one style, so \"no style\" is not a choice.\n    const styleRows = [];\n    delete extrasFacets.style;\n    if (g.collection) {\n      const st = extrasCurrentStyle();\n      if (st) extrasFacets.style = st.name;\n      styleRows.push({ key: 'style', label: 'Style', vals: extrasStyles().map(x => x.name) });\n    }\n    let pane;\n    if (!all) {\n      pane = extrasFilterBar(styleRows) + '<p class=\"btk-kp-panel-note\">Loading\u2026</p>';\n    } else {\n      const rowsFor = (key, label, of) => {\n        const vals = [...new Set(all.map(of).filter(Boolean))].sort((a, b) => a.localeCompare(b));\n        return vals.length > 1 ? [{ key, label, vals }] : [];\n      };\n      const rows = [...styleRows, ...rowsFor('type', 'Type', p => p.kind),\n                    ...rowsFor('brand', 'Brand', p => p.vendor)];\n      const q = extrasQuery.trim().toLowerCase();\n      const cards = all.filter(p =>\n        (!extrasFacets.type  || p.kind   === extrasFacets.type) &&\n        (!extrasFacets.brand || p.vendor === extrasFacets.brand) &&\n        (!q || [p.title, p.vendor, ...p.variants.map(v => v.title + ' ' + (v.sku || ''))].join(' ').toLowerCase().includes(q)));\n      pane = extrasFilterBar(rows)\n        + `<p class=\"btk-kp-extras-count\">${cards.length} product${cards.length === 1 ? '' : 's'}</p>`\n        + (cards.length ? `<div class=\"btk-kp-wt-grid\">${cards.map(p => {\n            const v = extrasChosenVariant(p);\n            const img = v.image || p.image;\n            const sizes = p.variants.length > 1\n              ? `<select class=\"btk-kp-extras-variant\" data-btk-kp-extras-variant=\"${p.id}\" aria-label=\"Choose an option\">\n                   ${p.variants.map(o => `<option value=\"${o.id}\"${o.id === v.id ? ' selected' : ''}>${xEsc(extrasVariantLabel(p, o))}</option>`).join('')}\n                 </select>`\n              : (v.title ? `<div class=\"btk-kp-wt-tile-meta\">${xEsc(extrasVariantLabel(p, v))}</div>` : '');\n            return `<div class=\"btk-kp-wt-tile btk-kp-extras-tile\">\n                <div class=\"btk-kp-wt-tile-img\">${img ? `<img src=\"${xEsc(img)}\" alt=\"\" loading=\"lazy\">` : ''}</div>\n                <div class=\"btk-kp-wt-tile-body\">\n                  <div class=\"btk-kp-wt-tile-name\">${xEsc(p.title)}</div>\n                  ${p.vendor || v.sku ? `<div class=\"btk-kp-wt-tile-meta\">${xEsc([p.vendor, v.sku].filter(Boolean).join(' \u00B7 '))}</div>` : ''}\n                  ${sizes}\n                  ${extrasPriceHTML(v.price)}\n                </div>\n                <button type=\"button\" class=\"btk-kp-action-btn btk-kp-action-btn--green btk-kp-action-btn--sm\" data-btk-kp-extras-add=\"${p.id}\">\n                  <span class=\"btk-kp-btn-spinner\" aria-hidden=\"true\"></span>\n                  <span class=\"btk-kp-action-btn-label\">Add to basket</span>\n                </button>\n              </div>`;\n          }).join('')}</div>`\n          : `<p class=\"btk-kp-panel-note\">${all.length ? 'Nothing matches - try another word, or Reset the filters.' : 'There are no products in this group at the moment.'}</p>`);\n    }\n    extrasBodyEl.innerHTML = `\n      <div class=\"btk-kp-cabinets-shell btk-kp-extras\">\n        <aside class=\"btk-kp-cabinets-l1-col\">${groups.map(tile).join('')}</aside>\n        <section class=\"btk-kp-cabinets-right\">\n          <h3 class=\"btk-kp-cabinets-products-title\">${xEsc(g.label)}</h3>\n          <p class=\"btk-kp-cabinets-products-desc\">Added to your basket as an extra item. It is not drawn or numbered on your plan.</p>\n          ${pane}\n        </section>\n      </div>`;\n  }\n\n  function openExtrasPicker() {\n    if (!extrasPopup || !extrasBodyEl) return;\n    renderExtras();\n    extrasPopup.hidden = false;\n  }\n\n  if (extrasBodyEl) {\n    extrasBodyEl.addEventListener('click', async (e) => {\n      const grp = e.target.closest('[data-btk-kp-extras-group]');\n      if (grp) {\n        extrasActive = grp.dataset.btkKpExtrasGroup;\n        extrasFacets = { type: '', brand: '' };\n        renderExtras();\n        return;\n      }\n      if (e.target.closest('[data-btk-kp-extras-ftoggle]')) { extrasFilterOpen = !extrasFilterOpen; renderExtras(); return; }\n      if (e.target.closest('[data-btk-kp-extras-freset]')) {\n        extrasFacets = { type: '', brand: '' };\n        extrasStyleId = null;           // back to the plan's style\n        renderExtras();\n        return;\n      }\n      const facet = e.target.closest('[data-btk-kp-extras-facet]');\n      if (facet) {\n        const k = facet.dataset.btkKpExtrasFacet, v = facet.dataset.facetValue;\n        if (k === 'style') {\n          // Another style's products: a fresh load, and its own Type values.\n          const st = extrasStyles().find(x => x.name === v);\n          if (st) { extrasStyleId = st.id; extrasFacets.type = ''; }\n        } else {\n          extrasFacets[k] = extrasFacets[k] === v ? '' : v;\n        }\n        renderExtras();\n        return;\n      }\n      const add = e.target.closest('[data-btk-kp-extras-add]');\n      if (add && !add.disabled) {\n        const activeGroup = extrasGroups().find(x => x.key === extrasActive);\n        const p = (extrasLoaded[extrasDataKey(activeGroup)] || []).find(x => String(x.id) === add.dataset.btkKpExtrasAdd);\n        if (!p) return;\n        const v = extrasChosenVariant(p);\n        const label = add.querySelector('.btk-kp-action-btn-label');\n        add.disabled = true;\n        add.classList.add('is-saving');\n        if (label) label.textContent = 'Adding\u2026';\n        const ok = await addExtraToBasket({\n          variantId: v.id, productTitle: p.title, variantTitle: v.title || '',\n          price: v.price, compareAt: v.compareAtPrice || null, image: v.image || p.image || null, manual: true,\n          colour: (activeGroup && activeGroup.key === 'dpa') ? extrasColourOf(p) : null,\n        }, p.kind);\n        add.classList.remove('is-saving');\n        if (label) label.textContent = ok ? 'Added \u2713' : 'Could not add - try again';\n        setTimeout(() => { add.disabled = false; if (label) label.textContent = 'Add to basket'; }, 1600);\n      }\n    });\n    extrasBodyEl.addEventListener('change', (e) => {\n      const sel = e.target.closest('[data-btk-kp-extras-variant]');\n      if (!sel) return;\n      extrasPick[sel.dataset.btkKpExtrasVariant] = sel.value;\n      renderExtras();\n    });\n  }\n  if (extrasSearchEl) {\n    extrasSearchEl.addEventListener('input', () => {\n      extrasQuery = extrasSearchEl.value || '';\n      if (extrasSearchClr) extrasSearchClr.hidden = !extrasQuery;\n      renderExtras();\n    });\n  }\n  if (extrasSearchClr) {\n    extrasSearchClr.addEventListener('click', () => {\n      if (extrasSearchEl) extrasSearchEl.value = '';\n      extrasQuery = '';\n      extrasSearchClr.hidden = true;\n      renderExtras();\n    });\n  }\n\n  // Which Pricing-bar group a picker-added extra totals into, read off the\n  // source collection's title (the picker groups by collection). Anything we\n  // can't place falls to \"Other\", which is what that group is for.\n  function extrasQuoteGroup(title) {\n    const t = String(title || '').toLowerCase();\n    if (/worktop|splashback|upstand/.test(t)) return 'worktops';\n    if (/appliance|oven|hob|extractor|fridge|freezer|dishwasher|microwave|sink|tap/.test(t)) return 'appliances';\n    if (/handle|knob/.test(t)) return 'handles';\n    if (/plinth|cornice|pelmet|trim/.test(t)) return 'trims';\n    if (/end panel|panel|filler/.test(t)) return 'panels';\n    return 'other';\n  }\n\n  // Parts added with Add other items > Doors, Panels & Accessories in a range\n  // the units have just left move to the units' new range (Sales line 104):\n  // the same part (\"<Range> - 715mm High Door\") and size in that range's\n  // listing. A shared part (no range in its title - carcase boards) keeps its\n  // product and just takes the new range's colours. Returns the names of the\n  // parts the new range does not make, which are left as they were.\n  async function moveExtrasToStyle(fromStyles, toStyleId) {\n    const api = window.BTKBasketAPI;\n    if (!api || !fromStyles || !fromStyles.size || !toStyleId) return [];\n    const missed = [];\n    try {\n      const project = await api.getProject();\n      const basket = await planBasketIn(project);\n      const section = basket && (basket.sections || []).find(s => s.name === 'Extras');\n      const items = section ? (section.items || []).filter(it => it && it.attributes\n        && it.attributes.extraColour && fromStyles.has(it.attributes.style)) : [];\n      if (!items.length) return [];\n      const f = 'filter.p.m.custom.kitchen_style_handle=';\n      const products = await fetchExtrasPages('/collections/kitchen-unit-doors-panels-accessories?view=kpextras&'\n        + f + encodeURIComponent(toStyleId));\n      const styleOf = (id) => extrasStyles().find(st => st.id === id) || null;\n      const partOf = (title, st) => {\n        const s = String(title || ''), i = s.indexOf(' - ');\n        return (st && i > 0 && extrasNameKey(s.slice(0, i)) === extrasNameKey(st.name)) ? extrasNameKey(s.slice(i + 3)) : null;\n      };\n      const width = (vt) => (/^(\\d+)/.exec(String(vt || '')) || [])[1] || null;\n      const toStyle = styleOf(toStyleId);\n      for (const it of items) {\n        const a = it.attributes;\n        const part = partOf(it.productTitle, styleOf(a.style));\n        if (!part) { a.style = toStyleId; continue; }\n        const p = products.find(x => x && partOf(x.title, toStyle) === part);\n        const vs = p ? (p.variants || []).filter(v => v && v.available && extrasNotDrilled(p, v)) : [];\n        const v = vs.find(x => String(x.title || '') === String(it.variantTitle || ''))\n          || (width(it.variantTitle) && vs.find(x => width(x.title) === width(it.variantTitle)));\n        if (!v) {\n          missed.push(String(it.productTitle || 'Item') + (it.variantTitle ? ', ' + it.variantTitle : ''));\n          continue;\n        }\n        it.shopifyVariantId = String(v.id);\n        it.productTitle = p.title;\n        it.variantTitle = v.title || '';\n        it.price = (Number(v.price) / 100).toFixed(2);\n        const cmp = Number(v.compareAtPrice) || 0;\n        if (cmp > (Number(v.price) || 0)) it.compareAtPrice = (cmp / 100).toFixed(2); else delete it.compareAtPrice;\n        it.image = v.image || p.image || it.image || null;\n        a.style = toStyleId;\n      }\n      for (const it of items) stampExtraColour(it);\n      api.recalculateLineNumbers(basket);\n      await api.saveBasket(basket);\n      await api.syncToShopifyCart(basket.id);\n      window.BTKCartAdvanced?.reload?.();\n    } catch (e) {\n      console.error('[BTK Kitchen Planner] moving basket parts to the new range failed', e);\n    }\n    return missed;\n  }\n\n  async function addExtraToBasket(p, groupTitle) {\n    const api = window.BTKBasketAPI;\n    if (!api || !p || !p.variantId) return;\n    try {\n      if (window.BTKLoader) window.BTKLoader.show({ message: 'Adding to your basket\u2026' });\n      const project = await api.getProject();\n      let basket = await planBasketIn(project);\n      if (!basket) return false;\n      // Non-plannable items live in a dedicated, editable \"Extras\" group.\n      basket.sections = basket.sections || [];\n      let section = basket.sections.find(s => s.name === 'Extras');\n      if (!section) { section = api.createSection('Extras'); basket.sections.push(section); }\n      // p.qty: how many (default one). p.setQty: the quantity is what the plan\n      // needs (a supply-only upstand's lengths), so an Extras line already\n      // holding this variant is set to it rather than a second line added.\n      const qty = Math.max(1, Math.floor(Number(p.qty) || 1));\n      const had = p.setQty ? section.items.find(i => String(i.shopifyVariantId) === String(p.variantId)) : null;\n      if (had) {\n        had.quantity = qty;\n      } else {\n        const item = api.createItem(\n          String(p.variantId), p.productTitle || 'Item', p.variantTitle || '',\n          qty, (Number(p.price) / 100).toFixed(2)\n        );\n        item.image = p.image || null;   // shown when the line is selected\n        // Its was price, when the product has one (Arden, 2026-10-11).\n        { const _c = Number(p.compareAt) || 0; if (_c > (Number(p.price) || 0)) item.compareAtPrice = (_c / 100).toFixed(2); }\n        if (item.attributes) item.attributes.quoteGroup = extrasQuoteGroup(groupTitle);\n        // Added by hand with Add Other Items: the one kind of line the planner\n        // basket lets the customer delete, shown in its own Other Items group\n        // (btk-cart-advanced.js). Worktop accessories and supply-only\n        // splashbacks come in here too, but the plan chose those.\n        if (item.attributes && p.manual) item.attributes.manualExtra = true;\n        // A Doors, Panels & Accessories part: its range and the plan's colour\n        // (extrasColourOf). Bought several to a line, like the same part from\n        // the website (_btk_multi), so its quantity stays the customer's.\n        if (item.attributes && p.colour) {\n          item.attributes.style = p.colour.style;\n          item.attributes.extraColour = p.colour.kind;\n          item.attributes.multi = true;\n          stampExtraColour(item);\n        }\n        section.items.push(item);\n      }\n      api.recalculateLineNumbers(basket);\n      await api.saveBasket(basket);\n      // By id, so there is no whole-project PUT just to flag the basket, and\n      // nothing writes `isActive` onto a planner basket - which is /cart's\n      // notion of the current basket and must never be one of these. See\n      // flushCartForCheckout for the timings behind it.\n      await api.syncToShopifyCart(basket.id);\n      window.BTKCartAdvanced?.reload?.();\n      refreshExtraSinks();\n      return true;\n    } catch (e) {\n      console.error('[BTK Kitchen Planner] add extra failed', e);\n      return false;\n    } finally {\n      if (window.BTKLoader) window.BTKLoader.hide();\n    }\n  }\n\n  // \u2500\u2500 Convert Basket to Kitchen Plan \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n  // The /cart \"Convert Basket to Kitchen Plan\" button stashes a line payload\n  // in sessionStorage, creates a fresh planner basket, and lands us here with\n  // ?convert=1. We reconstruct each plannable line into a cabinet definition\n  // (the SAME getVariantInfo \u2192 buildCabinetDefinition path the picker uses),\n  // hold them as UNPLACED staged units for the drag-in tray (Phase 5), route\n  // non-plannable lines to the plan's Extras, and land on Room Setup.\n  let convertStagedUnits = [];   // [{ def, variantId, styleId, doorColour, carcaseColour, hinge, productTitle, image }]\n  let convertExtras      = [];   // non-plannable lines \u2192 the plan's Extras (persisted in Phase 5 via the planner's own save path)\n\n  function reconstructConvertUnit(line) {\n    try {\n      const variantId = Number(line.variantId);\n      if (!Number.isFinite(variantId)) return null;\n      const vInfo = Catalogue.getVariantInfo && Catalogue.getVariantInfo(variantId);\n      if (!vInfo || !vInfo.product || !vInfo.product.unitTypeId) return null;   // not a plannable unit\n      const ut = Catalogue.getUnitType && Catalogue.getUnitType(vInfo.product.unitTypeId);\n      if (!ut) return null;\n      const styleId = (line.style && line.style !== 'all' ? line.style : '') || vInfo.product.kitchenStyleId || '';\n      if (!styleId) return null;\n      const def = Catalogue.buildCabinetDefinition && Catalogue.buildCabinetDefinition({\n        unitTypeId: vInfo.product.unitTypeId, variantId, kitchenStyleId: styleId\n      });\n      if (!def || !def.widthMm) return null;\n      return {\n        def, variantId, styleId,\n        doorColour:    line.doorColour || null,\n        carcaseColour: line.carcaseColour || null,\n        hinge:         (line.hinge || '').toLowerCase() || null,\n        productTitle:  line.productTitle || def.name || '',\n        image:         line.image || null,\n        line   // the basket line, saved with the plan while the unit waits\n      };\n    } catch (e) { return null; }\n  }\n\n  // Preload the planning-style mood board from the converted basket: use the\n  // DOMINANT style + door + carcase colour across the placeable units as the\n  // buying style, so Style Setup opens already reflecting their kitchen.\n  function preloadMoodBoardFromConvert(staged, extras) {\n    try {\n      // Worktop + handle PRODUCTS bought in the basket land in the Extras; match\n      // them back to the catalogue so the mood board shows them too.\n      for (const ex of (extras || [])) {\n        if (!ex || ex.variantId == null) continue;\n        if (!buyingWorktops.length && Catalogue.getWorktopMaterialByVariant) {\n          const wm = Catalogue.getWorktopMaterialByVariant(ex.variantId);\n          if (wm) buyingWorktops = [{ handle: wm.handle, name: wm.title || wm.handle }];\n        }\n        if (!buyingHandles.length && Catalogue.getHandleByVariant) {\n          const hp = Catalogue.getHandleByVariant(ex.variantId);\n          if (hp) buyingHandles = [{ designId: hp.designId, designName: hp.designName, finishHandle: hp.finishHandle, finishName: hp.finishName }];\n        }\n        if (buyingWorktops.length && buyingHandles.length) break;\n      }\n      if (!staged || !staged.length) return;\n      // Distinct style|door|carcase combos across the placeable units, ordered\n      // by frequency - up to 3 become the plan's buying styles (issue: only the\n      // first was loading), and the DOMINANT one seeds the plan's global style +\n      // default colours.\n      const counts = {}, order = [];\n      for (const u of staged) {\n        const k = `${u.styleId || ''}|${u.doorColour || ''}|${u.carcaseColour || ''}`;\n        if (!(k in counts)) { counts[k] = 0; order.push(k); }\n        counts[k]++;\n      }\n      const combos = order\n        .map(k => { const p = k.split('|'); return { styleId: p[0], doorHandle: p[1] || null, carcaseHandle: p[2] || null, n: counts[k] }; })\n        .filter(c => c.styleId && Catalogue.getKitchenStyle && Catalogue.getKitchenStyle(c.styleId))\n        .sort((a, b) => b.n - a.n);\n      if (!combos.length) return;\n      const top = combos.slice(0, 3);\n      buyingStyles = top.map(c => ({ styleId: c.styleId, doorHandle: c.doorHandle, carcaseHandle: c.carcaseHandle }));\n      const dom = top[0];\n      kitchenStyleId = dom.styleId;\n      if (dom.doorHandle)    globalDoorColourHandle    = dom.doorHandle;\n      if (dom.carcaseHandle) globalCarcaseColourHandle = dom.carcaseHandle;\n      // NB: deliberately DON'T set journeyStarted/journeyMode or render here.\n      // A plan name is set on convert, so planHasContent() is true \u2192 opening\n      // Style Setup runs hydrateJourneyFromPlan(), which reliably renders the\n      // mood board from the state above (edit mode) and KEEPS these buyingStyles.\n    } catch (e) { console.error('[BTK Kitchen Planner] mood-board preload failed', e); }\n  }\n\n  async function processConvertPayload() {\n    let payload = null;\n    try { payload = JSON.parse(sessionStorage.getItem('btk_convert_payload') || 'null'); } catch (e) {}\n    if (!payload || !Array.isArray(payload.lines) || !payload.lines.length) {\n      if (window.BTKLoader) window.BTKLoader.hide();\n      return;\n    }\n    // Adopt the quote name from the trad basket as the plan name. The empty\n    // convert basket has no design, so the storage layer's load() returns null\n    // and can't restore the name on its own - set it directly here.\n    if (payload.planName) {\n      try { activePlanName = payload.planName; designControlsHandle.setPlanName(payload.planName); } catch (e) {}\n    }\n    // Keep the loading screen up and the planner home out of sight while the\n    // plan is made - the home showed for a few seconds first (Arden, 2026-10-11).\n    try {\n      if (window.BTKLoader) window.BTKLoader.show({ message: 'Creating your bedroom plan\u2026' });\n      hideWelcome();\n      const _h = root.querySelector('[data-btk-kp-home]'); if (_h) _h.hidden = true;\n    } catch (e) {}\n    // Load the products of EVERY style in the basket before rebuilding its\n    // units (Arden, 2026-10-11). The planner page only arrives with one\n    // style's products; a unit from any other style could not be found, so\n    // it went to Extras and the convert said it couldn't place anything.\n    const _styles = [...new Set(payload.lines.map(l => String(l.style || '').trim()).filter(x => x && x !== 'all'))];\n    await Promise.all(_styles.map(st => ensureStyleProducts(st).catch(e => console.warn('[BTK convert] style load failed', st, e))));\n    // Only now is the payload done with (a failed load above leaves it for a retry).\n    try { sessionStorage.removeItem('btk_convert_payload'); } catch (e) {}\n    const staged = [], extras = [];\n    for (const line of payload.lines) {\n      const built = reconstructConvertUnit(line);\n      if (built) {\n        const qty = Math.max(1, Number(line.quantity) || 1);\n        for (let n = 0; n < qty; n++) staged.push(built);\n      } else {\n        extras.push(line);\n      }\n    }\n    convertStagedUnits = staged;\n    convertExtras      = extras;   // persisted in Phase 5 when placement is committed\n    preloadMoodBoardFromConvert(staged, extras);   // seed the mood board (style + worktop/handle)\n    // Leave the Welcome landing page (the edit-plan / journey deep-links do this\n    // too) - setStep only controls the home OVERLAY, not the Welcome page.\n    hideWelcome();\n    // Land on Add Items, the units waiting in the tray (Arden, 2026-10-14):\n    // customers want to see their units in a plan, and may not have their\n    // room's measurements yet - Room Setup is there whenever they do.\n    // roomShapePrompted keeps the automatic room-shape popup away.\n    roomShapePrompted = true;\n    stepperHandle.setStep('add-units');\n    // Belt-and-suspenders: make sure the home overlay is hidden on this stage.\n    const _homeEl = root.querySelector('[data-btk-kp-home]');\n    if (_homeEl) _homeEl.hidden = true;\n    renderConvertTray();   // show the staging tray of units to place\n    if (window.BTKLoader) window.BTKLoader.hide();\n\n    // Name the plan first, in the planner's own Name Your Plan popup (Arden,\n    // 2026-10-14) - the basket's suggestion is filled in.\n    convertOwnBasketId = payload.plannerBasketId || null;\n    const chosenName = await askConvertPlanName(payload.planName || activePlanName || '');\n    if (chosenName) {\n      try { activePlanName = chosenName; designControlsHandle.setPlanName(chosenName); } catch (e) {}\n      // The plan name shown on the plan (\"Plan: ...\") and the Live Quote.\n      try { refreshLiveQuoteLabels(); basketDrawerHandle?.refresh?.(); } catch (e) {}\n      // The plan's basket was made in the basket page under the suggested\n      // name; give it the chosen one, so the save below goes into it rather\n      // than forking a new basket and leaving that one empty.\n      try {\n        const api = window.BTKBasketAPI;\n        const proj = api && await api.getProject();\n        const own = proj && (proj.baskets || []).find(x => x.id === convertOwnBasketId);\n        if (own && own.name !== chosenName && !(await otherPlansNamed(chosenName, null)).some(x => x.id !== own.id)) {\n          own.name = chosenName;\n          await api.saveBasket(own);\n        }\n      } catch (e) { console.warn('[BTK convert] plan rename failed', e); }\n    }\n\n    const uWord = staged.length === 1 ? 'unit' : 'units';\n    let msg = staged.length\n      ? `${staged.length} ${uWord} from your basket are ready to place. Drag each one into your room to build your plan.\\n\\nEnd panels, trims and fillers are added automatically as you lay units out, so your total price may change.`\n      : `We couldn't place any of your basket items in the layout.`;\n    if (extras.length) {\n      msg += `\\n\\n${extras.length} item${extras.length === 1 ? '' : 's'} (worktops, appliances, accessories or units we couldn't add to the layout) ${extras.length === 1 ? 'was' : 'were'} added to your plan's Extras.`;\n    }\n\n    try {\n      // Save the new plan straight away - its waiting units with it - and only\n      // then link the basket to it (Arden, 2026-10-11). Before, nothing was\n      // saved until a unit was placed, so a refresh lost the lot while the\n      // basket already said it had a plan.\n      (async () => {\n        try {\n          const saved = await planStore.saveAs(activePlanName, currentDesign());\n          if (!saved) throw new Error('plan not saved');\n          try { designControlsHandle.setSaveState?.('saved', `Saved \"${activePlanName}\"`); refreshLiveQuoteLabels(); } catch (e) {}\n          const api = window.BTKBasketAPI;\n          if (api && payload.sourceBasketId && payload.plannerBasketId && api.getProject) {\n            const project = await api.getProject();\n            const src = ((project && project.baskets) || []).find(b => b.id === payload.sourceBasketId);\n            if (src) {\n              // The items now live in the plan, so the basket they came from\n              // is emptied - only once the plan is safely saved (Arden,\n              // 2026-10-14). The basket page then links to this plan by name:\n              // the basket saveAs actually used (a name the customer chose to\n              // replace an older plan with is saved into that plan's basket).\n              let planBasketId = payload.plannerBasketId;\n              try { planBasketId = (await api.getActivePlannerBasketId()) || planBasketId; } catch (e) {}\n              src.convertedPlannerId = planBasketId;\n              src.sections = [];\n              src.items    = [];\n              if (api.recalculateLineNumbers) api.recalculateLineNumbers(src);\n              await api.saveBasket(src);\n              // The online cart may still hold that basket's lines; /cart\n              // would take them straight back into the basket. Empty it too\n              // - but only when it is that basket's cart.\n              try {\n                const cart = await (await fetch('/cart.js', { credentials: 'same-origin' })).json();\n                const cartBasket = cart && cart.attributes && cart.attributes._btk_basket_id;\n                if (cartBasket === src.id && api.syncToShopifyCart) await api.syncToShopifyCart(src.id);\n              } catch (e) { console.warn('[BTK convert] cart empty failed', e); }\n            }\n          }\n        } catch (e) { console.warn('[BTK convert] save / link failed', e); }\n      })();\n      window.BTKKPDialog.alert(msg, { title: 'Basket converted to a plan', locked: true });\n    } catch (e) {\n      console.log('[BTK Kitchen Planner] convert:', msg);\n    }\n  }\n\n  // Bring back the units a converted plan was still waiting to place (saved\n  // with the design as their basket lines). Their styles' products load first.\n  let _restoreConvertSeq = 0;\n  function restoreConvertStaged(lines) {\n    const seq = ++_restoreConvertSeq;\n    if (!lines.length) {\n      if (convertStagedUnits.length) { convertStagedUnits = []; renderConvertTray(); }\n      return;\n    }\n    const styles = [...new Set(lines.map(l => String((l && l.style) || '').trim()).filter(x => x && x !== 'all'))];\n    Promise.all(styles.map(st => ensureStyleProducts(st).catch(() => {}))).then(() => {\n      if (seq !== _restoreConvertSeq) return;   // a newer restore has run\n      const staged = [];\n      for (const line of lines) { const u = reconstructConvertUnit(line); if (u) staged.push(u); }\n      convertStagedUnits = staged;\n      renderConvertTray();\n    });\n  }\n\n  // ---- Convert staging tray: click a card to drop the unit on the plan ----\n  const convertTrayEl        = root.querySelector('[data-btk-kp-convert-tray]');\n  const convertListEl        = root.querySelector('[data-btk-kp-convert-list]');\n  const convertCountEl       = root.querySelector('[data-btk-kp-convert-count]');\n  const convertReopenEl      = root.querySelector('[data-btk-kp-convert-reopen]');\n  const convertReopenCountEl = root.querySelector('[data-btk-kp-convert-reopen-count]');\n  let   convertTrayDismissed = false;\n  let   convertDragIndex     = null;   // index being dragged from the tray onto the canvas\n  // Room Setup shows the EXPANDED tray ONLY on the first landing (after the auto\n  // room-shape popup is closed); it minimises as soon as the user clicks a Room\n  // Setup left-menu button or leaves the stage. Add Units always expands.\n  let   convertShowOnRoomSetup = false;\n\n  function updateConvertTrayVisibility(step) {\n    const s = step || currentStep;\n    const hasUnits = convertStagedUnits.length > 0;\n    const expandStage = (s === 'add-units') || (s === 'room-setup' && convertShowOnRoomSetup);\n    const showTray = hasUnits && expandStage && !convertTrayDismissed;\n    // Pill (minimised) shows whenever units remain but the tray isn't expanded.\n    const showPill = hasUnits && !showTray;\n    // Units are only placed on Add Units (Arden, 2026-10-11): elsewhere the tray\n    // is a preview - the cards don't drag or add, and the line says where to.\n    const canPlace = (s === 'add-units');\n    if (convertTrayEl) {\n      convertTrayEl.classList.toggle('is-locked', !canPlace);\n      convertTrayEl.querySelectorAll('[data-btk-kp-convert-place]').forEach(c => { c.draggable = canPlace; });\n      const hint = convertTrayEl.querySelector('[data-btk-kp-convert-hint]');\n      if (hint) hint.textContent = canPlace\n        ? 'click one to add it, then drag it into place'\n        : 'set up your room first, then place them on the Add Units stage';\n    }\n    if (convertTrayEl && showTray && convertTrayEl.hidden) {\n      convertTrayEl.classList.remove('is-sliding-out');\n      convertTrayEl.classList.add('is-sliding-in');\n      setTimeout(() => convertTrayEl.classList.remove('is-sliding-in'), 400);\n    }\n    if (convertTrayEl)   convertTrayEl.hidden   = !showTray;\n    if (convertReopenEl) convertReopenEl.hidden = !showPill;\n    if (convertReopenCountEl) convertReopenCountEl.textContent = String(convertStagedUnits.length);\n  }\n  // Slide the tray down to its pill (Arden, 2026-10-11) - after the convert\n  // message, so the user has seen it is there.\n  function slideConvertTrayDown() {\n    if (!convertTrayEl || convertTrayEl.hidden) { convertShowOnRoomSetup = false; updateConvertTrayVisibility(); return; }\n    convertTrayEl.classList.add('is-sliding-out');\n    setTimeout(() => {\n      convertShowOnRoomSetup = false;\n      updateConvertTrayVisibility();\n      convertTrayEl.classList.remove('is-sliding-out');\n    }, 380);\n  }\n  // Room Setup left-menu (Room Shape / Doors / Windows / Features / Gas) click\n  // means the user has moved on from placing units \u2192 minimise the tray. Popup\n  // clicks (room-shape etc.) don't count.\n  (function wireRoomSetupMinimise() {\n    const panel = root.querySelector('[data-btk-kp-panel=\"room-setup\"]');\n    if (!panel) return;\n    panel.addEventListener('click', (e) => {\n      if (e.target.closest('[data-btk-kp-popup]')) return;                 // ignore popup interactions\n      if (!e.target.closest('[data-btk-kp-open-popup], [data-btk-kp-hide-units]')) return;\n      if (convertShowOnRoomSetup) { convertShowOnRoomSetup = false; updateConvertTrayVisibility(); }\n    });\n  })();\n  // Render a colour-accurate 3D thumbnail for a staged unit into imgEl,\n  // upgrading over the flat cart photo. Best-effort + async; mirrors the\n  // line-items thumbnail cab build (incl. corner/diagonal/L-shape markers).\n  async function renderStagedThumbnail(u, imgEl) {\n    if (!imgEl || !u || !u.def) return;\n    // Cache per unit - the tray re-renders after every placement, and re-running\n    // the shared headless renderer each time is what made dragging feel laggy.\n    if (u._thumbUrl) { imgEl.src = u._thumbUrl; return; }\n    if (typeof window.btkRenderCabinetThumbnail !== 'function') return;\n    try {\n      const d = u.def;\n      const _shape = String((d.planner2D && d.planner2D.shape) || '').trim().toLowerCase();\n      let cornerUnit = null, diagonalCornerUnit = null, lShapeUnit = null;\n      let footprintWidthMm = d.widthMm, footprintDepthMm = d.depthMm;\n      if (_shape === 'corner-blank' || _shape === 'diagonal' || _shape === 'lshape') {\n        // The sizes the planner gives a placed unit - base 910 / 570, WALL 630 / 330\n        // (one helper for every thumbnail; see Catalogue.cornerThumbMarkers).\n        ({ cornerUnit, diagonalCornerUnit, lShapeUnit, footprintWidthMm, footprintDepthMm } = Catalogue.cornerThumbMarkers(d));\n      }\n      const cab = {\n        id: 'convert-thumb', type: 'cabinet',\n        unitTypeId: d.unitTypeId, variantId: d.variantId, kitchenStyleId: d.kitchenStyleId,\n        code: d.code, category: d.categoryHandle, planner2D: d.planner2D,\n        x: 0, y: 0, rotationDeg: 0,\n        widthMm: footprintWidthMm, depthMm: footprintDepthMm,\n        heightMm: (d.carcaseHeightMm || 720) + (d.plinthHeightMm || 0),\n        doorColourHandle:    u.doorColour || null,\n        carcaseColourHandle: u.carcaseColour || null,\n        cutoutSchema: d.cutoutSchema,\n        hingeSide: (u.hinge === 'left' || u.hinge === 'right') ? u.hinge : 'right',\n        drawerCount: d.drawerCount,\n        belfastSink: d.belfastSink, splayEnd: d.splayEnd, sinkBase: d.sinkBase,\n        cornerUnit, diagonalCornerUnit, lShapeUnit\n      };\n      const url = await window.btkRenderCabinetThumbnail(cab, { width: 220, height: 220 });\n      if (url) { u._thumbUrl = url; if (imgEl.isConnected) imgEl.src = url; }\n    } catch (e) {}\n  }\n  function renderConvertTray() {\n    if (!convertTrayEl || !convertListEl) return;\n    if (convertCountEl) convertCountEl.textContent = String(convertStagedUnits.length);\n    convertListEl.replaceChildren();\n    convertStagedUnits.forEach((u, i) => {\n      const card = document.createElement('button');\n      card.type = 'button';\n      card.className = 'btk-kp-convert-card';\n      card.draggable = (currentStep === 'add-units');   // drag onto the plan - Add Units only\n      card.dataset.btkKpConvertPlace = String(i);\n      const name = u.productTitle || (u.def && u.def.name) || 'Unit';\n      card.innerHTML =\n        `<img class=\"btk-kp-convert-card-img\" src=\"${u.image ? escForKp(u.image) : ''}\" alt=\"\" aria-hidden=\"true\">` +\n        `<span class=\"btk-kp-convert-card-name\">${escForKp(name)}</span>` +\n        `<span class=\"btk-kp-convert-card-add\">Add +</span>`;\n      convertListEl.appendChild(card);\n      renderStagedThumbnail(u, card.querySelector('.btk-kp-convert-card-img'));\n    });\n    updateConvertTrayVisibility();\n  }\n  function placeStagedUnit(index, dropMm) {\n    const u = convertStagedUnits[index];\n    if (!u || !u.def) return;\n    // Units only render on the placement stage - jump to Add Units so the unit\n    // the user just added actually appears (they may still be on Room Setup).\n    if (currentStep !== 'add-units') { try { stepperHandle.setStep('add-units'); } catch (e) {} }\n    let newId = null;\n    try { newId = addCabinet(u.def); } catch (e) { console.error('[BTK Kitchen Planner] place staged unit failed', e); }\n    // addCabinet uses the buying-style default colour - overlay THIS unit's own\n    // door/carcase colour + hinge from the basket line.\n    const cab = newId ? cabinets.find(c => c.id === newId) : null;\n    if (cab) {\n      if (u.doorColour)    cab.doorColourHandle    = u.doorColour;\n      if (u.carcaseColour) cab.carcaseColourHandle = u.carcaseColour;\n      if (u.hinge === 'left' || u.hinge === 'right') cab.hingeSide = u.hinge;\n      // Dragged onto the plan: drop it (roughly centred) where released.\n      if (dropMm && isFinite(dropMm.x) && isFinite(dropMm.y)) {\n        cab.x = Math.round(dropMm.x - (cab.widthMm || 600) / 2);\n        cab.y = Math.round(dropMm.y - (cab.depthMm || 600) / 2);\n      }\n      try { rerender(); } catch (e) {}\n    }\n    convertStagedUnits.splice(index, 1);\n    renderConvertTray();\n  }\n  if (convertListEl) {\n    convertListEl.addEventListener('click', (e) => {\n      const card = e.target.closest('[data-btk-kp-convert-place]');\n      if (!card) return;\n      // Units are placed on Add Units only: elsewhere point at the line saying so.\n      if (currentStep !== 'add-units') {\n        const hint = convertTrayEl && convertTrayEl.querySelector('[data-btk-kp-convert-hint]');\n        if (hint) { hint.classList.remove('is-flash'); void hint.offsetWidth; hint.classList.add('is-flash'); }\n        return;\n      }\n      placeStagedUnit(Number(card.dataset.btkKpConvertPlace));\n    });\n    // Drag a card onto the canvas to drop the unit where released.\n    convertListEl.addEventListener('dragstart', (e) => {\n      const card = e.target.closest('[data-btk-kp-convert-place]');\n      if (!card) return;\n      if (currentStep !== 'add-units') { e.preventDefault(); return; }\n      convertDragIndex = Number(card.dataset.btkKpConvertPlace);\n      try { e.dataTransfer.setData('text/plain', String(convertDragIndex)); e.dataTransfer.effectAllowed = 'copy'; } catch (_) {}\n      card.classList.add('is-dragging');\n    });\n    convertListEl.addEventListener('dragend', (e) => {\n      const card = e.target.closest('[data-btk-kp-convert-place]');\n      if (card) card.classList.remove('is-dragging');\n      convertDragIndex = null;   // the drop (fires first) has already consumed it\n    });\n  }\n  // Canvas drop target: dropping a tray card places that unit where released.\n  (function wireConvertDrop() {\n    const mainEl = document.getElementById('btk-kp-main');\n    if (!mainEl) return;\n    mainEl.addEventListener('dragover', (e) => {\n      if (convertDragIndex == null) return;\n      e.preventDefault();                                    // allow the drop\n      try { e.dataTransfer.dropEffect = 'copy'; } catch (_) {}\n    });\n    mainEl.addEventListener('drop', (e) => {\n      if (convertDragIndex == null) return;\n      e.preventDefault();\n      const idx = convertDragIndex;\n      convertDragIndex = null;\n      let mm = null;\n      try { mm = paintPointerToMm(e); } catch (_) {}          // screen \u2192 room mm (best-effort)\n      placeStagedUnit(idx, mm);\n    });\n  })();\n  root.querySelectorAll('[data-btk-kp-convert-done]').forEach(btn => {\n    btn.addEventListener('click', () => {\n      if (convertStagedUnits.length && window.BTKKPDialog && window.BTKKPDialog.confirm) {\n        window.BTKKPDialog.confirm(\n          `You still have ${convertStagedUnits.length} unit${convertStagedUnits.length === 1 ? '' : 's'} to place. Hide the tray for now? You can reopen it from the pill at the bottom.`,\n          { title: 'Units still to place', confirmText: 'Hide tray', cancelText: 'Keep placing' }\n        ).then((ok) => { if (ok) { convertTrayDismissed = true; updateConvertTrayVisibility(); } });\n      } else {\n        convertTrayDismissed = true;\n        updateConvertTrayVisibility();\n      }\n    });\n  });\n  root.querySelectorAll('[data-btk-kp-convert-reopen]').forEach(btn => {\n    btn.addEventListener('click', () => {\n      convertTrayDismissed = false;\n      if (currentStep === 'room-setup') convertShowOnRoomSetup = true;   // slide back up, here\n      // From a non-placement stage, jump to Add Units so the expanded tray shows.\n      if (currentStep !== 'room-setup' && currentStep !== 'add-units') {\n        try { stepperHandle.setStep('add-units'); } catch (e) {}\n      } else {\n        updateConvertTrayVisibility();\n      }\n    });\n  });\n  root.querySelectorAll('[data-btk-kp-convert-discard]').forEach(btn => {\n    btn.addEventListener('click', () => {\n      if (!convertStagedUnits.length) return;\n      const doDiscard = () => { convertStagedUnits = []; convertTrayDismissed = false; renderConvertTray(); };\n      if (window.BTKKPDialog && window.BTKKPDialog.confirm) {\n        window.BTKKPDialog.confirm(\n          'Are you sure you want to disregard the remaining units? They will be removed from your plan.',\n          { title: 'Discard remaining units', confirmText: 'Discard', cancelText: 'Keep them', danger: true }\n        ).then((ok) => { if (ok) doDiscard(); });\n      } else { doDiscard(); }\n    });\n  });\n\n  root.querySelectorAll('[data-btk-kp-basket-embed-additems]').forEach(btn => {\n    btn.addEventListener('click', openExtrasPicker);\n  });\n  if (extrasPopup) {\n    extrasPopup.addEventListener('click', e => {\n      if (e.target.closest('[data-btk-kp-popup-close]')) extrasPopup.hidden = true;\n    });\n  }\n\n  const sidebarTitleEl = root.querySelector('[data-btk-kp-sidebar-title]');\n  const sidebarIntroEl = root.querySelector('[data-btk-kp-sidebar-intro]');\n  // Short one-line intro that sits under the sidebar title and\n  // changes with the active stepper step. Keep these in sync with\n  // the {data-btk-kp-step=\"...\"} keys above; missing entries fall\n  // back to a blank line so the header doesn't collapse mid-swap.\n  const SIDEBAR_INTRO = {\n    'planner-home':  'Start a new plan, browse the guides, or get help from our team.',\n    'style-setup':   'Choose your style, colour, carcase, handles and worktops before you plan.',\n    'room-setup':    'Build the shape of your room before placing any units.',\n    'add-units':     'Drag base, wall and tall units onto the plan to lay out your bedroom.',\n    'style-colours': 'Choose your style, colour, handles, worktops and furniture.',\n    'checklist':     'Check and approve the key choices on your plan before you check out.',\n    'review-order':  'Review your full plan and pricing before placing the order.'\n  };\n  function updateSidebarTitle(step) {\n    if (sidebarTitleEl) {\n      const labelEl = root.querySelector(`[data-btk-kp-step=\"${step}\"] .btk-kp-step-label`);\n      if (labelEl) sidebarTitleEl.textContent = labelEl.textContent;\n    }\n    if (sidebarIntroEl) {\n      sidebarIntroEl.textContent = SIDEBAR_INTRO[step] || '';\n    }\n    // A stage's own header action (Room Setup's Start New Room) shows only on it.\n    root.querySelectorAll('[data-btk-kp-header-action]').forEach(b => {\n      b.hidden = b.dataset.btkKpHeaderAction !== step;\n    });\n  }\n\n  // Default view mode per stage - switches the 2D/3D toggle when the\n  // user clicks a stepper button. Stage 3 (Change Style & Colours)\n  // and Stage 4 (Finishing Touches) read better in 3D because the\n  // user is mostly judging visual impact; the rest stay in 2D for\n  // measurement / layout work.\n  const STEP_DEFAULT_VIEW = {\n    'room-setup':   '2d',\n    'add-units':    '2d',\n    'style-colours':'3d',\n    'review-order': '2d'\n  };\n  // ---- stage-change stopwatch (?btktime=1 only) --------------------------\n  //\n  // A stage change is several jobs in a row - covering or revealing the\n  // canvas, switching 2D/3D, redrawing the plan - and \"it takes 3 to 6\n  // seconds\" does not say which one. These marks split it up, and the run ends\n  // AFTER the browser has painted, so what is timed is what the customer\n  // waits for rather than when our own code returned (Arden, 2026-09-30).\n  //\n  // Inert without ?btktime=1: BTKKPTiming.start no-ops, so mark and show do\n  // nothing either. Add ?btktime=1 to the planner URL, change stage, and the\n  // timings come up in a dialog.\n  //\n  // The marks above only cover OUR code. When the wait turns out to be after\n  // it - \"waited for other work: 3928ms\" - these two say what that work was:\n  // every task over 50ms the browser ran in the window, and anything it\n  // fetched. Between them they name the culprit rather than narrowing it\n  // (Arden, 2026-09-30).\n  let stageT0 = 0;\n  let stageLongTasks = [];\n  let stageFrames = [];\n  let stageObserver = null;\n  let stageFrameObserver = null;\n  const stageWatchStart = () => {\n    try {\n      stageT0 = performance.now();\n      stageLongTasks = [];\n      stageFrames = [];\n      if (stageObserver) { try { stageObserver.disconnect(); } catch (e) {} }\n      if (stageFrameObserver) { try { stageFrameObserver.disconnect(); } catch (e) {} }\n      if (typeof PerformanceObserver !== 'function') return;\n      stageObserver = new PerformanceObserver((list) => {\n        for (const e of list.getEntries()) stageLongTasks.push(e);\n      });\n      stageObserver.observe({ entryTypes: ['longtask'] });\n      // A long task only says \"4275ms of script\". A long ANIMATION frame says\n      // WHICH script: every entry carries scripts[] with the source file, the\n      // function name and the character position. That is the difference\n      // between narrowing a slowdown and naming it.\n      try {\n        stageFrameObserver = new PerformanceObserver((list) => {\n          for (const e of list.getEntries()) stageFrames.push(e);\n        });\n        stageFrameObserver.observe({ type: 'long-animation-frame', buffered: false });\n      } catch (e) { stageFrameObserver = null; }\n    } catch (e) { stageObserver = null; }\n  };\n  const stageWatchReport = () => {\n    try {\n      if (stageObserver) { try { stageObserver.disconnect(); } catch (e) {} stageObserver = null; }\n      if (stageFrameObserver) { try { stageFrameObserver.disconnect(); } catch (e) {} stageFrameObserver = null; }\n      for (const f of stageFrames.slice(0, 4)) {\n        window.BTKKPTiming.mark('   frame ' + Math.round(f.duration) + 'ms at '\n          + Math.round(f.startTime - stageT0) + 'ms'\n          + (f.blockingDuration ? ' (blocking ' + Math.round(f.blockingDuration) + 'ms)' : ''));\n        const scripts = (f.scripts || []).slice().sort((a, b) => b.duration - a.duration);\n        for (const sc of scripts.slice(0, 6)) {\n          const file = String(sc.sourceURL || '').split('/').pop().split('?')[0] || 'inline';\n          const fn = sc.sourceFunctionName || sc.invoker || '(anon)';\n          window.BTKKPTiming.mark('      ' + Math.round(sc.duration) + 'ms  ' + fn\n            + '  ' + file + (sc.sourceCharPosition >= 0 ? '@' + sc.sourceCharPosition : '')\n            + (sc.forcedStyleAndLayoutDuration > 20\n                ? ' [layout ' + Math.round(sc.forcedStyleAndLayoutDuration) + 'ms]' : ''));\n        }\n      }\n      for (const e of stageLongTasks.slice(0, 12)) {\n        const at = Math.round(e.startTime - stageT0);\n        const who = (e.attribution && e.attribution[0] && (e.attribution[0].containerName\n          || e.attribution[0].containerSrc || e.attribution[0].name)) || 'script';\n        window.BTKKPTiming.mark('   busy ' + Math.round(e.duration) + 'ms at ' + at + 'ms (' + who + ')');\n      }\n      // Anything fetched during the wait: a module, a picture, an API call.\n      const res = performance.getEntriesByType('resource')\n        .filter(r => r.startTime >= stageT0 - 5 && r.duration >= 40)\n        .sort((a, b) => b.duration - a.duration)\n        .slice(0, 8);\n      for (const r of res) {\n        const name = String(r.name).split('/').pop().split('?')[0];\n        window.BTKKPTiming.mark('   fetched ' + name + ' ' + Math.round(r.duration) + 'ms'\n          + (r.transferSize ? ' (' + Math.round(r.transferSize / 1024) + 'kB)' : ''));\n      }\n    } catch (e) {}\n  };\n  const stageTime = {\n    start: (step) => {\n      try {\n        if (!window.BTKKPTiming) return;\n        window.BTKKPTiming.start('stage change -> ' + step);\n        stageWatchStart();\n      } catch (e) {}\n    },\n    mark:  (label) => { try { window.BTKKPTiming && window.BTKKPTiming.mark(label); } catch (e) {} },\n    done:  (step) => {\n      try {\n        if (!window.BTKKPTiming) return;\n        // A Plan Online run owns the list (BTKKPTiming above): one line, and\n        // none of this stopwatch's own frame and download report.\n        if (planNavOpen()) {\n          window.BTKKPTiming.mark('stage ' + step + ' set');\n          if (stageObserver) { try { stageObserver.disconnect(); } catch (e) {} stageObserver = null; }\n          if (stageFrameObserver) { try { stageFrameObserver.disconnect(); } catch (e) {} stageFrameObserver = null; }\n          return;\n        }\n        // Two frames: the first is scheduled before this paint, the second\n        // runs after it. Anything still loading (a 3D scene, a picture) lands\n        // later and is deliberately not counted here.\n        requestAnimationFrame(() => {\n          // Everything queued ahead of this frame has now run. If the time\n          // lands HERE it is other work (a module loading, pictures being\n          // built); if it lands on 'painted' it is the browser's own layout\n          // and paint (Arden, 2026-09-30).\n          try { window.BTKKPTiming.mark('waited for other work'); } catch (e) {}\n          requestAnimationFrame(() => {\n            try {\n              window.BTKKPTiming.mark('painted');\n              // The long-animation-frame entry describing THIS frame is not\n              // delivered until the frame has finished, so reading it here\n              // found scripts[] empty every time. The marks are already\n              // timestamped, so showing the panel a moment later costs\n              // nothing and the attribution arrives (Arden, 2026-09-30).\n              setTimeout(() => {\n                try {\n                  stageWatchReport();\n                  window.BTKKPTiming.show('Stage change: ' + step);\n                } catch (e) {}\n              }, 600);\n            } catch (e) {}\n          });\n        });\n      } catch (e) {}\n    },\n  };\n\n  // Move to a stage with a given view instead of the stage's own default.\n  let stageViewOverride = null;\n  function goToStage(step, view) {\n    stageViewOverride = view || null;\n    try { stepperHandle.setStep(step); }\n    finally { stageViewOverride = null; }\n  }\n  let homeReady = false;   // gate the saved-plans render until setup completes (avoids init-time TDZ)\n  stepperHandle = initStepper(root, {\n    initialStep: 'planner-home',\n    onChange: (step) => {\n      stageTime.start(step);\n      currentStep = step;\n      wallMenuReturn = false;   // a new stage starts at its own menu\n      syncUnitsOverlay();      // Room Setup only - see the note on the toggle\n      if (planFeatureArmed) setPlanFeatureArmed(null);   // leaving the stage ends corner mode\n      // A wall section or opening can only be worked on in Room Setup, so a\n      // selection of one does not survive leaving it.\n      if (step !== 'room-setup' && selectedItem &&\n          (selectedItem.kind === 'wall' || selectedItem.kind === 'opening')) {\n        selectItem(null);\n      }\n      // Clicking a planner stage while the basket is open returns to it. Guard\n      // the teardown so a hiccup can't abort the rest of onChange and leave the\n      // basket / raw canvas showing.\n      if (basketEmbedPanel && !basketEmbedPanel.hidden) {\n        try { closeBasketEmbed(); }\n        catch (e) { console.warn('[BTK KP] basket close failed', e); if (basketEmbedPanel) basketEmbedPanel.hidden = true; }\n      }\n      // Planner Home AND Style Setup cover the canvas with their own right-pane\n      // content (the process guide / the guided journey); every other stage\n      // shows the planner. applyStageCanvasState sets the overlay + viewport.\n      applyStageCanvasState(step);\n      stageTime.mark('canvas shown or covered');\n      // Style Setup = the guided journey. Reveal its right pane (and start it\n      // the first time this stage is opened).\n      if (step === 'style-setup') enterStyleSetup();\n      if (step === 'style-setup') stageTime.mark('style setup opened');\n      // Planner Home: land on the default New Plan view (the two cards). Coming\n      // from Style Setup / the basket otherwise leaves the journey 'start' panel\n      // showing (or none at all). Header How-To / Get-Help links run AFTER this\n      // and re-point to their own panel, so this doesn't fight them.\n      if (step === 'planner-home') {\n        // Default view = 'home' (the two start cards); light its sidebar button.\n        root.querySelectorAll('[data-btk-kp-home-view]').forEach(t => t.classList.toggle('is-active', t.dataset.btkKpHomeView === 'home'));\n        root.querySelectorAll('[data-btk-kp-home-panel]').forEach(p => { p.hidden = p.dataset.btkKpHomePanel !== 'home'; });\n        syncRoomShapeCard();\n      }\n      // Checklist: its own page in the home overlay, checked against the plan\n      // as it is now.\n      if (step === 'checklist') {\n        root.querySelectorAll('[data-btk-kp-home-panel]').forEach(p => { p.hidden = p.dataset.btkKpHomePanel !== 'checklist'; });\n        renderChecklist();\n        try { ensurePreviews(); } catch (e) { /* the door photos are a nicety */ }\n      }\n      // Refresh the always-visible left-menu saved-plans list when Home opens.\n      if (step === 'planner-home' && homeReady) renderHomeSavedPlans();\n      // Leaving Planner Home clears the How To Guides / Get Help highlight.\n      if (step !== 'planner-home') {\n        root.querySelector('[data-btk-kp-howto-home]')?.classList.remove('is-active');\n        root.querySelector('[data-btk-kp-header-gethelp]')?.classList.remove('is-active');\n      }\n      updateSidebarTitle(step);\n      stageTime.mark('left menu + title');\n      // Leaving Room Setup ends the one-time \"expanded on first landing\" window.\n      if (step !== 'room-setup') convertShowOnRoomSetup = false;\n      // Convert staging tray: expanded on Add Units (+ the first Room Setup\n      // landing); minimised to the pill everywhere else.\n      if (typeof updateConvertTrayVisibility === 'function') updateConvertTrayVisibility(step);\n      if (selectedItem) selectItem(null);\n      // A jump between Add Items and Customise keeps the view it came from\n      // (see goToStage); an ordinary stage change takes the stage default.\n      const wanted = stageViewOverride || STEP_DEFAULT_VIEW[step];\n      if (wanted) setViewMode(wanted);\n      if (wanted) stageTime.mark('view set to ' + wanted);\n      // Authoritative final pass: setViewMode short-circuits when the mode is\n      // unchanged, and some flows toggle the viewport's display directly\n      // (basket embed, report/thumbnail capture), leaving it out of sync.\n      // Re-asserting here (after the view default) keeps Home/Style Setup\n      // covered and canvas stages showing the right 2D/3D view.\n      applyStageCanvasState(step);\n      // \"Hide units\" only applies on Room Setup - re-evaluate on every nav.\n      if (typeof applyHideUnits === 'function') applyHideUnits();\n      // EVERY stage change renders. What can be clicked and dragged on the\n      // plan is decided while it is being drawn - wall sections and openings\n      // are wired live only on Room Setup, units only away from it - so a\n      // stage change that does not render leaves the previous stage's\n      // permissions sitting on the plan. That is how doors and windows stayed\n      // live after moving on to Add Units, and how the walls were dead on\n      // arriving at Room Setup until something else happened to render.\n      // STEP_DEFAULT_VIEW lists exactly the stages that show the plan, so the\n      // two can never disagree about which those are. Home and Style Setup\n      // have no canvas up - rendering into one that is not there is how a grid\n      // gets built at the wrong size - and this also fires once during init,\n      // where there is nothing to render yet.\n      if (STEP_DEFAULT_VIEW[step]) {\n        try { rerender(); } catch (e) { console.error('[BTK KP] stage render', e); }\n        stageTime.mark('plan redrawn');\n      }\n      // Whatever else this stage does below, the clock stops when the browser\n      // has painted.\n      stageTime.done(step);\n      // Not during start-up: the plan (and its styles) is still being restored.\n      if (step === 'add-units' && bootRestoreSettled && needsPlanningStyle()) requestAnimationFrame(askForPlanningStyle);\n      // Room Setup nudge: open the Room Shape popup ONCE to steer someone\n      // planning their first room into setting its shape before anything else.\n      // It is deliberately narrow, because it used to arrive on arrival at the\n      // stage for anyone whose room was still the default - so a customer who\n      // keeps the standard rectangle met it every time they came back to the\n      // room, with their units already in:\n      //   - only while the room is untouched (as before), AND\n      //   - only while the plan is EMPTY. Units on the plan (or a saved plan\n      //     open) means the user is editing a kitchen, not starting one, and\n      //     'start a new room' is then the last thing to put in front of them.\n      //   - only the FIRST time, remembered per browser (ROOM_SHAPE_PROMPT_KEY).\n      // The Room Shape button is still there whenever they do want it.\n      if (step === 'room-setup' && !roomShapePrompted) {\n        let isDefaultRoom = false;\n        try { isDefaultRoom = JSON.stringify(roomConfig) === JSON.stringify(freshRoomConfig()); } catch (e) {}\n        const planStarted = !!(cabinets && cabinets.length) || !!activePlanName;\n        const rsPopup = root.querySelector('[data-btk-kp-popup=\"room-shape\"]');\n        if (isDefaultRoom && !planStarted && rsPopup && rsPopup.hidden) {\n          roomShapePrompted = true;\n          try { localStorage.setItem(ROOM_SHAPE_PROMPT_KEY, '1'); } catch (e) {}\n          rsPopup.hidden = false;   // the MutationObserver lights the Room Shape button\n          if (roomShapeHandle) requestAnimationFrame(() => requestAnimationFrame(() => roomShapeHandle.refresh()));\n          if (typeof pulseCeilingCard === 'function') pulseCeilingCard();\n        }\n      }\n      // Intro on Room Setup - shows EVERY time the stage loads until the user\n      // ticks \"Don't show this again\" (persisted), regardless of what's chosen.\n      // Intro on Style Setup - shows EVERY time the stage loads until the user\n      // ticks \"Don't show this again\" (persisted).\n      if (step === 'style-setup' && !styleIntroDone\n          && !document.querySelector('.btk-kp-dialog-overlay')) {\n        openStyleIntro();\n      }\n    }\n  });\n\n  // Planner Home - the left-menu tiles don't open popups; each swaps the\n  // right-hand content between the [data-btk-kp-home-panel] views.\n  const homeSavedEmpty = root.querySelector('[data-btk-kp-home-saved-empty]');\n\n  // Versions of one plan belong together in a listing: newest set first, and\n  // inside a set the versions in order. A plan with no versions is a set of\n  // one, so nothing needs a special case downstream.\n  function groupPlanVersions(plans) {\n    const sets = new Map();\n    for (const p of plans) {\n      const key = p.versionOf || p.name;\n      if (!sets.has(key)) sets.set(key, { base: key, plans: [] });\n      sets.get(key).plans.push(p);\n    }\n    for (const set of sets.values()) {\n      set.plans.sort((a, b) => String(a.name).localeCompare(String(b.name), 'en', { numeric: true }));\n      set.savedAt = set.plans.reduce((t, p) => (String(p.savedAt || '') > t ? String(p.savedAt || '') : t), '');\n    }\n    return [...sets.values()].sort((a, b) => b.savedAt.localeCompare(a.savedAt));\n  }\n\n  // The part of a version's name that distinguishes it from its siblings: what\n  // follows \"<base> - \", or the whole name when it doesn't start that way.\n  function versionLabel(p) {\n    if (!p.versionOf) return '';\n    const name = String(p.name || '');\n    const base = String(p.versionOf);\n    if (!name.startsWith(base)) return name;\n    const m = /^\\s*-\\s*(.+)$/.exec(name.slice(base.length));\n    return m ? m[1] : name;\n  }\n\n  const ICON_PENCIL = `<svg viewBox=\"0 0 24 24\" width=\"15\" height=\"15\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\"><path d=\"M12 20h9\"/><path d=\"M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z\"/></svg>`;\n\n  // Rename ONE saved plan. A version stays in its set whatever it is called:\n  // versionOf ties them together, so the new name is used as given. Renaming\n  // the set itself is separate.\n  async function renameSavedPlan(p, after) {\n    const isVersion = !!p.versionOf;\n    const current   = isVersion ? (versionLabel(p) || p.name) : p.name;\n    const next = await window.BTKKPDialog.prompt(\n      isVersion ? `Rename this version of \"${p.versionOf}\":` : 'Rename this plan:',\n      { title: 'Rename', defaultValue: current, confirmText: 'Rename' });\n    const trimmed = String(next || '').trim();\n    if (!trimmed || trimmed === current) return;\n\n    const newName = trimmed;\n    if (await refuseBoughtPlanName(newName)) return;\n    const plans = await planStore.listPlans();\n    if (plans.some(x => x.name === newName && x.name !== p.name)) {\n      await window.BTKKPDialog.alert(`A plan called \"${newName}\" already exists.`, { title: 'Name in use' });\n      return;\n    }\n    if (typeof planStore.renamePlan !== 'function') return;\n    await planStore.renamePlan(p.name, newName);\n    // The plan on screen is the one being renamed - keep the header in step.\n    if (activePlanName === p.name) {\n      activePlanName = newName;\n      designControlsHandle.setPlanName(newName);\n      refreshLiveQuoteLabels();\n    }\n    if (after) after();\n  }\n\n  // Rename a whole version SET: names built on the base take the new base, ones\n  // the user typed stay as they are, and versionOf is restamped so they all stay\n  // tied together.\n  function renamedInSet(p, base) {\n    if (!p.versionOf) return base;\n    const label = versionLabel(p);\n    return label === p.name ? p.name : `${base} - ${label}`;\n  }\n  async function renameVersionSet(set, after) {\n    const next = await window.BTKKPDialog.prompt('Rename this plan and all its versions:',\n      { title: 'Rename plan', defaultValue: set.base, confirmText: 'Rename' });\n    const base = String(next || '').trim();\n    if (!base || base === set.base) return;\n    if (typeof planStore.renamePlan !== 'function') return;\n\n    const plans = await planStore.listPlans();\n    const names = new Set(set.plans.map(x => x.name));\n    for (const p of set.plans) {\n      const newName = renamedInSet(p, base);\n      if (await refuseBoughtPlanName(newName)) return;\n      if (plans.some(x => x.name === newName && !names.has(x.name))) {\n        await window.BTKKPDialog.alert(`A plan called \"${newName}\" already exists.`, { title: 'Name in use' });\n        return;\n      }\n    }\n    for (const p of set.plans) {\n      const newName = renamedInSet(p, base);\n      await planStore.renamePlan(p.name, newName, { versionOf: p.versionOf ? base : null });\n      if (activePlanName === p.name) {\n        activePlanName = newName;\n        if (p.versionOf) activePlanVersionOf = base;\n        designControlsHandle.setPlanName(newName);\n        refreshLiveQuoteLabels();\n      }\n    }\n    if (after) after();\n  }\n\n  // Renders the saved plans as a card gallery (with the 3D snapshot thumbnail)\n  // into the \"Saved Plans\" right-pane view. Opening a card loads that plan and\n  // drops the user into the planner; delete removes it.\n  // Draw the plan as it was bought. Failure is explicit: a blank planner with\n  // no explanation would look like their kitchen had been lost.\n  // View-only: the plan and the camera, nothing else. The bought-plan styling\n  // (is-ordered-view) hides the editing chrome; is-viewonly also hides the left\n  // menu and lets the canvas through the phone card (btk-kitchen-planner-base.css).\n  // The only controls are 2D/3D and Close, which goes back to the Plans tab.\n  function setupViewOnly() {\n    root.classList.add('is-ordered-view', 'is-viewonly');\n    const toggle = root.querySelector('[data-btk-kp-view-toggle]:not(.btk-kp-mini-view-toggle)');\n    if (!toggle || root.querySelector('[data-btk-kp-viewonly-close]')) return;\n    const close = document.createElement('button');\n    close.type = 'button';\n    close.className = 'btk-kp-action-btn btk-kp-action-btn--light btk-kp-action-btn--sm btk-kp-viewonly-close';\n    close.setAttribute('data-btk-kp-viewonly-close', '');\n    close.setAttribute('data-btk-kp-ordered-close', '');   // let through the lock\n    close.title = 'Close and return to your plans';\n    close.innerHTML = '<span class=\"btk-kp-action-btn-icon\" aria-hidden=\"true\"><svg viewBox=\"0 0 24 24\" width=\"16\" height=\"16\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2.2\" stroke-linecap=\"round\"><path d=\"M6 6l12 12M18 6L6 18\"/></svg></span>'\n      + '<span class=\"btk-kp-action-btn-label\">Close</span>';\n    close.addEventListener('click', () => { window.location.href = '/pages/my-account?tab=plans'; });\n    toggle.insertAdjacentElement('afterend', close);\n  }\n\n  async function openOrderedPlan() {\n    root.classList.add('is-ordered-view');\n    // The greeting goes up at once, with its Close, so there is a way out\n    // even while the plan loads (or if it never does).\n    renderOrderedBar(null, null, false, true);\n    try {\n      const api = window.BTKBasketAPI;\n      const snap = api && typeof api.getOrderedBasket === 'function'\n        ? await api.getOrderedBasket(_bootOrdered) : null;\n      const basket = snap && snap.basket;\n      // Through the same schema upgrade as every other load: an order placed\n      // on an older room format must still draw correctly.\n      const design = basket && normaliseLoadedPayload(basket.plannerDesign);\n      if (!design || !design.design) throw new Error('no design on the ordered basket');\n      await loadNamedPlan(basket.name || 'Your bedroom', design);\n      // Off the Welcome page and onto the plan, as opening a saved plan does.\n      // The stepper is hidden here, so without this the customer could never\n      // get past the Home cards to their kitchen.\n      hideWelcome();\n      roomShapePrompted = true;\n      stepperHandle.setStep('add-units');\n      // Worktop Quote (Sales line 108): staff always; a customer only when\n      // the order had no worktop in it.\n      renderOrderedBar(snap.orderRef, basket.name, false, false,\n        { worktopQuote: isStaffOrderedView() || !orderHadWorktops(basket),\n          // Its plan number (Sales sheet line 109), as on the order in Odoo.\n          planRef: basket.ref || (window.BTKBasketAPI && window.BTKBasketAPI.basketRef\n            ? window.BTKBasketAPI.basketRef(_bootOrdered) : '') || '' });\n      // Freeze it once the load has rendered: from here on, pushUndoSnapshot\n      // puts back any change at all.\n      requestAnimationFrame(() => { orderedFrozen = undoSnapshot(); });\n      renderWorktopToFollowPanel(snap, basket);\n    } catch (e) {\n      console.error('[BTK planner] the ordered plan could not be opened', e);\n      try { hideWelcome(); stepperHandle.setStep('add-units'); } catch (_) {}\n      renderOrderedBar(null, null, true);\n    }\n  }\n\n  // The greeting, in the left column, in the planner's own type. Close (back to\n  // the Orders list the viewer was opened from) sits under Download Plan, in\n  // every state: the black top bars are hidden here, so it is the way out.\n  function renderOrderedBar(orderRef, planName, failed, loading, opts) {\n    const host = root.querySelector('.btk-kp-sidebar-scroll') || root;\n    let bar = root.querySelector('[data-btk-kp-ordered-bar]');\n    if (!bar) {\n      bar = document.createElement('div');\n      bar.className = 'btk-kp-ordered-greet';\n      bar.setAttribute('data-btk-kp-ordered-bar', '');\n      host.prepend(bar);\n    }\n    // Staff opened it from the Odoo sales order (View 3D Plan): it is the\n    // customer's kitchen, not theirs, and Close goes back to that order.\n    const staffView = isStaffOrderedView();\n    // With the top bars hidden, Close is the way out, so the failure has it too.\n    const closeBtn = `\n      <button type=\"button\" class=\"btk-kp-action-btn btk-kp-action-btn--light btk-kp-action-btn--sm btk-kp-ordered-close\"\n              data-btk-kp-ordered-close title=\"${staffView ? 'Close and return to the order in Odoo' : 'Close and return to your orders'}\">\n        <span class=\"btk-kp-action-btn-icon\" aria-hidden=\"true\"><svg viewBox=\"0 0 24 24\" width=\"16\" height=\"16\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2.2\" stroke-linecap=\"round\"><path d=\"M6 6l12 12M18 6L6 18\"/></svg></span>\n        <span class=\"btk-kp-action-btn-label\">Close</span>\n      </button>`;\n    if (failed || loading) {\n      bar.innerHTML = '<div class=\"btk-kp-sidebar-title\">' + (staffView ? 'Ordered Kitchen' : 'Your Ordered Bedroom') + '</div>'\n        + '<p class=\"btk-kp-cabinets-products-desc\">' + (failed\n          ? 'We could not open this plan just now. Please try again, or contact us and we will send it over.'\n          : 'Opening your bedroom\u2026') + '</p>' + closeBtn;\n      bar.querySelector('[data-btk-kp-ordered-close]').addEventListener('click', closeOrderedView);\n      return;\n    }\n    // The order as the customer knows it: \"#BETKIT-1060\", not the internal\n    // \"Online Order #BETKIT-1060\" label a lock may carry.\n    const ref = String(orderRef || '').replace(/^Online Order\\s*/i, '').trim();\n    bar.innerHTML = `\n      <div class=\"btk-kp-sidebar-title\">${staffView ? 'Ordered Kitchen' : 'Your Ordered Bedroom'}</div>\n      <p class=\"btk-kp-cabinets-products-desc\">\n        <strong>${escForKp(planName || 'Your bedroom')}</strong>${(opts && opts.planRef) ? `<br>Plan ${escForKp(opts.planRef)}` : ''}${ref ? `<br>Order ${escForKp(ref)}` : ''}\n      </p>\n      <p class=\"btk-kp-cabinets-products-desc\">\n        ${staffView ? \"The customer's kitchen exactly as they ordered it.\" : 'This is your bedroom exactly as you ordered it.'} Click any unit to see its details.\n      </p>\n      ${(opts && opts.worktopQuote) ? `<button type=\"button\" class=\"btk-kp-action-btn btk-kp-action-btn--green btk-kp-action-btn--sm\"\n              data-btk-kp-ordered-wtq title=\"Quote worktops for this bedroom as an extra order\">\n        <span class=\"btk-kp-action-btn-label\">Worktop Quote</span>\n      </button>` : ''}\n      <button type=\"button\" class=\"btk-kp-action-btn btk-kp-action-btn--sm btk-kp-ordered-download\"\n              data-btk-kp-ordered-manual hidden>\n        <span class=\"btk-kp-action-btn-icon\" aria-hidden=\"true\"><svg viewBox=\"0 0 24 24\" width=\"16\" height=\"16\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M4 19.5V5a2 2 0 0 1 2-2h13v16H6a2 2 0 0 0-2 2\"/><path d=\"M8 7h7M8 11h5\"/></svg></span>\n        <span class=\"btk-kp-action-btn-label\">Bedroom Manual</span>\n      </button>\n      ${staffView ? '<p class=\"btk-kp-cabinets-products-desc\" data-btk-kp-ordered-manual-note hidden></p>' : ''}${closeBtn}`;\n    bar.querySelector('[data-btk-kp-ordered-close]').addEventListener('click', closeOrderedView);\n    // Worktop Quote (Sales line 108): this order's linked worktop copy.\n    bar.querySelector('[data-btk-kp-ordered-wtq]')?.addEventListener('click', () => {\n      window.location.href = window.location.pathname + '?worktopquote=' + encodeURIComponent(_bootOrdered);\n    });\n    // No Download Plan here any more: the Kitchen Manual below is the printable\n    // record of the kitchen (Arden, 2026-10-27).\n    // My Kitchen Manual: shown to a customer once it is released, and to\n    // staff always (to write, check and approve it).\n    bar.querySelector('[data-btk-kp-ordered-manual]').addEventListener('click', () => {\n      kitchenManualAction();\n    });\n    refreshKitchenManualStatus();\n  }\n\n  function openPurchasedPlans() {\n    window.location.href = '/pages/my-account?tab=orders';\n  }\n\n  // \u2500\u2500 Worktop Quote (Sales line 108, Arden 2026-11-11) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n  // Worktops sold AFTER the kitchen: a linked copy of the bought plan, named\n  // \"<plan> - Worktops (<order>)\", that carries design.worktopQuote = { ordered:\n  // <bought basket id>, orderRef, sourceName }. On that copy everything the\n  // customer bought is fixed - units, sinks, taps, hobs, appliances - and only\n  // Customise > Worktops (material, edges, corners, upstands and splashbacks)\n  // works. Its basket holds the worktop lines only and is linked to the\n  // original order (Order Extras), so it checks out as \"Extras for SO...\" and\n  // the cut-outs, radius corners and templating are priced from the units as\n  // bought. Opened from the bought plan's Worktop Quote button\n  // (?worktopquote=<bought basket id>); one copy per order, reopened after.\n  function isWorktopQuote() { return !!(worktopQuote && worktopQuote.ordered); }\n\n  // Did this bought basket include a worktop? Its Worktops section, less the\n  // automatic kits (excluded lines never reach the bought basket).\n  function orderHadWorktops(basket) {\n    return ((basket && basket.sections) || []).some(s => ((s && s.items) || []).some(it =>\n      it && it.attributes && it.attributes.quoteGroup === 'worktops' && !it.attributes.autoItem));\n  }\n\n  // The worktop job's lines, the same charges the basket's Worktops section is\n  // built from: boards or the bespoke band, upstands, splashbacks, cut-outs,\n  // and the automatic worktop kits.\n  function worktopQuoteTotals() {\n    let sale = 0, compare = 0, count = 0;\n    try {\n      for (const ch of (computeWorktopCharges() || [])) {\n        const v = ch.variant || {};\n        const q = ch.qty || 1;\n        sale += (v.priceCents || 0) * q;\n        compare += Math.max(v.compareAtCents || 0, v.priceCents || 0) * q;\n        count++;\n      }\n      for (const ch of (computeAutoItemCharges() || []).filter(c => c && c.group === 'worktops')) {\n        const p = ch.product || {};\n        const q = ch.qty || 1;\n        sale += (p.priceCents || 0) * q;\n        compare += Math.max(p.compareAtCents || 0, p.priceCents || 0) * q;\n        count++;\n      }\n    } catch (e) { /* a plan still loading prices */ }\n    return { saleGbp: sale / 100, compareGbp: compare / 100, count };\n  }\n\n  // What the top bar's price box shows: the units, or on a Worktop Quote the\n  // worktop job alone.\n  function headPriceState() {\n    if (isWorktopQuote()) {\n      const t = worktopQuoteTotals();\n      return { saleGbp: t.saleGbp, compareGbp: t.compareGbp, cabinetCount: t.count, pending: planPricesPending() };\n    }\n    return { saleGbp: computeUnitsTotal(), compareGbp: computeUnitsCompareTotal(), cabinetCount: cabinets.length, pending: planPricesPending() };\n  }\n\n  // buildQuote, on a Worktop Quote: only the Worktops section, and the link to\n  // the order it is for (the same basket.extras setBasketExtras writes, which\n  // the cart sync carries to checkout and the import as _btk_extras).\n  function applyWorktopQuoteToBasket(basket) {\n    basket.sections = (basket.sections || []).filter(s => s && s.id === 'q:s:worktops');\n    // A staff test copy (?worktopquote=PLN...) has no order behind it.\n    if (worktopQuote && worktopQuote.test) { delete basket.extras; return; }\n    const l = worktopQuoteLink;\n    if (l && l.token && l.order) {\n      basket.extras = { token: l.token, orderId: l.order.id, number: l.order.number || '',\n                        deliveryDate: l.order.delivery_date || null };\n    }\n  }\n\n  // The order link is signed for 30 days, so it is fetched fresh each time the\n  // copy opens rather than kept with the plan.\n  async function refreshWorktopQuoteLink() {\n    const id = worktopQuote && worktopQuote.ordered;\n    if (!id || worktopQuote.test || worktopQuoteLinkFor === id) return;\n    worktopQuoteLinkFor = id;\n    try {\n      const api = window.BTKBasketAPI;\n      const link = api && typeof api.orderExtrasLinkForPlan === 'function' ? await api.orderExtrasLinkForPlan(id) : null;\n      worktopQuoteLink = (link && link.token && link.order) ? link : null;\n    } catch (e) {\n      worktopQuoteLink = null;\n      console.warn('[BTK worktop quote] the order link could not be fetched', e);\n    }\n    if (worktopQuoteLink) scheduleBasketResync();\n  }\n\n  // Put the screen in (or out of) Worktop Quote mode for the plan now open.\n  function syncWorktopQuoteMode() {\n    if (!root) return;\n    const on = isWorktopQuote();\n    if (on && !worktopQuoteStyleAdded) {\n      worktopQuoteStyleAdded = true;\n      const st = document.createElement('style');\n      st.textContent =\n        '.is-worktop-quote .btk-kp-step:not([data-btk-kp-step=\"style-colours\"]):not(.btk-kp-step--quote){display:none!important}'\n        + '.is-worktop-quote [data-btk-kp-panel=\"style-colours\"] [data-btk-kp-open-popup]:not([data-btk-kp-open-popup=\"worktop\"]){display:none!important}'\n        + '.btk-kp-wtq{margin:0 0 16px;padding:14px 16px;border:1px solid #d9d9d9;border-radius:8px;background:#fff}'\n        + '.btk-kp-wtq .btk-kp-cabinets-products-desc{margin:6px 0 0}';\n      document.head.appendChild(st);\n    }\n    if (on) installWorktopQuoteLock();\n    root.classList.toggle('is-worktop-quote', on);\n    window.__btkKpDragLocked = on || !!_bootOrdered || !!_bootViewOnly\n      || !!(_bootLive.session && _bootLive.role === 'viewer');\n    const label = root.querySelector('[data-btk-kp-quote-label]');\n    if (label) {\n      if (!label.dataset.btkKpQuoteLabelDefault) label.dataset.btkKpQuoteLabelDefault = label.textContent;\n      label.textContent = on ? 'Worktop Price' : label.dataset.btkKpQuoteLabelDefault;\n    }\n    let box = root.querySelector('[data-btk-kp-wtq]');\n    if (!on) { if (box) box.remove(); return; }\n    if (!box) {\n      const panel = root.querySelector('[data-btk-kp-panel=\"style-colours\"]');\n      if (panel) {\n        box = document.createElement('div');\n        box.className = 'btk-kp-wtq';\n        box.setAttribute('data-btk-kp-wtq', '');\n        panel.prepend(box);\n      }\n    }\n    if (box) {\n      const esc = (s) => String(s == null ? '' : s).replace(/[&<>\"']/g,\n        (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '\"': '&quot;', \"'\": '&#39;' }[c]));\n      const ref = String(worktopQuote.orderRef || '').replace(/^Online Order\\s*/i, '').trim();\n      box.innerHTML = '<div class=\"btk-kp-sidebar-title\">Worktop Quote</div>'\n        + '<p class=\"btk-kp-cabinets-products-desc\">For <strong>' + esc(worktopQuote.sourceName || 'the bedroom')\n        + '</strong>' + (ref ? ', order ' + esc(ref) : '') + '.</p>'\n        + '<p class=\"btk-kp-cabinets-products-desc\">The units, sinks and hobs are as ordered and cannot be changed here. '\n        + 'Choose the worktop, its edges, upstands and splashbacks in Worktops below; '\n        + 'the price button at the top right opens the worktop order.</p>'\n        + (worktopQuote.test ? '<p class=\"btk-kp-cabinets-products-desc\"><strong>Test only \u2013 not linked to an order.</strong> '\n          + 'Made from a saved plan to try the screen; it cannot be checked out.</p>' : '');\n    }\n    refreshWorktopQuoteLink();\n  }\n\n  // Everything but the worktop is fixed: stopped at the window in the capture\n  // phase, as the bought-plan viewer does, so no unit, sink or hob control can\n  // be reached. Installed the first time a Worktop Quote opens; it only acts\n  // while one is open.\n  function installWorktopQuoteLock() {\n  if (worktopQuoteLocked) return;\n  worktopQuoteLocked = true;\n  const WTQ_ALLOW = '.btk-kp-dialog-overlay, #btk-staff-banner, [data-btk-kp-wtq], '\n    + '[data-btk-kp-popup=\"worktop\"], [data-btk-kp-popup=\"worktop-cutlist\"], '\n    + '[data-btk-kp-open-popup=\"worktop\"], [data-btk-kp-step=\"style-colours\"], '\n    + '[data-btk-kp-proceed-checkout], [data-btk-kp-basket-embed], '\n    + '[data-btk-kp-save], [data-btk-kp-save-split], [data-btk-kp-view-toggle], '\n    + '[data-btk-kp-hide-units-toggle], [data-btk-kp-popup-close], .btk-kp-popup-close, '\n    + '[data-btk-kp-close-selection], .btk-kp-panel-close, [data-btk-kp-modal-close], '\n    + '.btk-kp-panel-iconbtn--close, [data-btk-kp-basket-embed-close], '\n    // The basket's own popups (Rename Quote and the rest) open outside the\n    // basket panel, so their buttons were swallowed: a worktop quote could not\n    // be renamed (sales sheet row 134). The basket itself is allowed above.\n    + '#btk-popup-overlay';\n  const WTQ_CONTROL = 'button, input, select, textarea, label, a[href], '\n    + '[role=\"button\"], [role=\"tab\"], [role=\"checkbox\"], [role=\"switch\"], [contenteditable]';\n  {\n    const wtqAllowed = (t) => !!(t && t.closest && t.closest(WTQ_ALLOW));\n    const wtqBlock = (e) => {\n      if (!isWorktopQuote()) return;\n      const t = e.target;\n      if (!t || !t.closest || wtqAllowed(t)) return;\n      if (!t.closest(WTQ_CONTROL)) return;\n      if (!t.closest('.btk-kp-app, [class*=\"btk-kp-\"]')) return;\n      e.stopImmediatePropagation();\n      if (e.cancelable) e.preventDefault();\n    };\n    ['pointerdown', 'mousedown', 'touchstart', 'click', 'dblclick',\n      'input', 'change', 'drop', 'paste', 'submit'].forEach((ev) =>\n      window.addEventListener(ev, wtqBlock, { capture: true, passive: false }));\n    ['contextmenu', 'dragstart'].forEach((ev) => window.addEventListener(ev, (e) => {\n      if (!isWorktopQuote() || wtqAllowed(e.target)) return;\n      e.stopImmediatePropagation();\n      if (e.cancelable) e.preventDefault();\n    }, { capture: true, passive: false }));\n    // Delete, the arrow nudges and the shortcuts reach nothing; typing in the\n    // worktop popup's own boxes still does.\n    ['keydown', 'keyup', 'keypress'].forEach((ev) => window.addEventListener(ev, (e) => {\n      if (!isWorktopQuote() || wtqAllowed(e.target) || e.key === 'Escape') return;\n      e.stopImmediatePropagation();\n    }, { capture: true }));\n    // No checkout without the order link: a staff test copy has no order, and a\n    // real copy whose link did not load would go through as an unlinked order.\n    ['pointerdown', 'click'].forEach((ev) => window.addEventListener(ev, (e) => {\n      if (!(isWorktopQuote() && (worktopQuote.test || !worktopQuoteLink))) return;\n      const t = e.target;\n      if (!t || !t.closest || !t.closest('[data-action=\"checkout\"]')) return;\n      e.stopImmediatePropagation();\n      if (e.cancelable) e.preventDefault();\n      if (ev === 'click' && window.BTKKPDialog) {\n        window.BTKKPDialog.alert(worktopQuote.test\n          ? 'This is a test worktop quote made from a saved plan, with no order behind it, so it cannot be checked out.'\n          : 'We could not link this worktop to your order just now. Please refresh the page and try again, or call us on 01934 813 201.',\n          { title: worktopQuote.test ? 'Test Only' : 'Not Linked to Your Order' });\n      }\n    }, { capture: true, passive: false }));\n  }\n  }\n\n  // ?worktopquote=<bought basket id>: open this order's Worktop Quote, making\n  // the linked copy the first time. Resolves true when it is on screen.\n  async function openWorktopQuote(orderedId) {\n    const api = window.BTKBasketAPI;\n    // STAFF TEST (?worktopquote=PLN100123): the same copy made from one of the\n    // customer's SAVED plans, as if it had been bought, so the screen can be\n    // tried without placing an order. No order link, and checkout is blocked.\n    // Read loosely: \"PLN100123\", \"pln100123\", \"#PLN 100123\", \"PLN-100123\".\n    const refM = /(PLN|BSK)[\\s#-]*(\\d{3,})/i.exec(String(orderedId || ''));\n    const testRef = refM ? (refM[1] + refM[2]).toUpperCase() : '';\n    if (testRef && !isStaffOrderedView()) {\n      await window.BTKKPDialog.alert('A test worktop quote can only be opened by our team.', { title: 'Staff Only' });\n      return false;\n    }\n    const key = testRef ? 'test:' + testRef : orderedId;\n    // Already made: reopen it (one per order).\n    try {\n      const proj = await api.getProject();\n      const mine = ((proj && proj.baskets) || []).find(b => {\n        const d = b && b.source === 'planner' && b.plannerDesign && b.plannerDesign.design;\n        return d && d.worktopQuote && d.worktopQuote.ordered === key;\n      });\n      const pid = mine && mine.plannerDesign.design.plannerPlanId;\n      if (pid && await loadLinkedPlan(pid, null, { backgroundSave: true })) return true;\n    } catch (e) { /* make a new one below */ }\n    if (testRef) {\n      let src = null;\n      try {\n        const proj = await api.getProject();\n        src = ((proj && proj.baskets) || []).find(b => b && String(b.ref || '').toUpperCase() === testRef && b.plannerDesign) || null;\n      } catch (e) { src = null; }\n      const tp = src && normaliseLoadedPayload(src.plannerDesign);\n      if (!tp || !tp.design) {\n        await window.BTKKPDialog.alert('Plan ' + testRef + ' was not found among this customer\\'s plans.', { title: 'Plan Not Found' });\n        return false;\n      }\n      const tName = (src.name || 'Bedroom') + ' - Worktops (test)';\n      const { plannerPlanId: _tid, versionOf: _tvo, ...tDesign } = tp.design;\n      tDesign.worktopQuote = { ordered: key, orderRef: '', sourceName: (src.name || 'Bedroom') + ' (' + testRef + ')', test: true };\n      tDesign.quoteExcludedLines = {};\n      tDesign.quoteFreeLines = {};\n      await loadNamedPlan(tName, { ...tp, versionOf: null, design: tDesign }, { noSlotSave: true });\n      await planStore.saveAs(tName, currentDesign());\n      return true;\n    }\n    const snap = api && typeof api.getOrderedBasket === 'function' ? await api.getOrderedBasket(orderedId) : null;\n    const basket = snap && snap.basket;\n    const payload = basket && normaliseLoadedPayload(basket.plannerDesign);\n    if (!payload || !payload.design) {\n      await window.BTKKPDialog.alert('The ordered bedroom \"' + orderedId + '\" could not be found, so the worktop quote could not be started.',\n        { title: 'Order Not Found' });\n      return false;\n    }\n    const ref = String(snap.orderRef || '').replace(/^Online Order\\s*/i, '').trim();\n    // A customer whose order already had a worktop changes it through us.\n    if (!isStaffOrderedView() && orderHadWorktops(basket)) {\n      await window.BTKKPDialog.alert('Your order already includes worktops. To change or upgrade them, '\n        + 'please call us on 01934 813 201 and we will arrange it for you.', { title: 'Worktops Already Ordered' });\n      return false;\n    }\n    const sourceName = basket.name || 'Bedroom';\n    const name = sourceName + ' - Worktops' + (ref ? ' (' + ref + ')' : '');\n    // A copy, not the bought plan: no plan id (the save mints a fresh one), not\n    // a version of anything, and nothing carried from the bought basket's quote.\n    const { plannerPlanId: _oldId, versionOf: _vo, ...design } = payload.design;\n    design.worktopQuote = { ordered: orderedId, orderRef: snap.orderRef || '', sourceName };\n    design.quoteExcludedLines = {};\n    design.quoteFreeLines = {};\n    await loadNamedPlan(name, { ...payload, versionOf: null, design }, { noSlotSave: true });\n    const saved = await planStore.saveAs(name, currentDesign());\n    if (!saved) {\n      await window.BTKKPDialog.alert('The worktop quote is open but could not be saved. '\n        + 'Press Save to try again before leaving.', { title: 'Not Saved', danger: true });\n    }\n    return true;\n  }\n\n  // \u2500\u2500 Worktop to Follow (Arden, 2026-11-06) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n  // The customer ordered this kitchen without its made-to-measure worktop (the\n  // basket's Order Kitchen Now, Worktop to Follow). Staff, on the bought plan,\n  // enter the price as they would in the Worktops popup and send the worktop to\n  // the customer's basket as Extras for this order: the plan stays as bought.\n  // The price box takes EX VAT, as the Worktops popup's do, and the job is\n  // priced through the same bands (computeWorktopCharges) with that quote.\n  const wtfGBP = (n) => '\u00A3' + Number(n || 0).toLocaleString('en-GB', { minimumFractionDigits: 2, maximumFractionDigits: 2 });\n  function worktopToFollowCharges(priceGbpIncVat) {\n    const saved = worktopBespoke;\n    try {\n      const job = bespokeJob(mergeCornerRuns(buildWorktops() || []));\n      if (!job || !job.priceRequest) return { job, charges: [] };\n      worktopBespoke = normaliseBespokeOptions(job.poa\n        ? { ...saved, poaQuote: { key: job.requestKey, priceGbp: priceGbpIncVat } }\n        : { ...saved, quoted: { area: job.templating.area, priceGbp: priceGbpIncVat } });\n      return { job, charges: computeWorktopCharges().filter(ch => ch.bespoke === 'band') };\n    } catch (e) {\n      console.warn('[BTK worktop to follow] could not price the worktop', e);\n      return { job: null, charges: [] };\n    } finally {\n      worktopBespoke = saved;\n    }\n  }\n  function renderWorktopToFollowPanel(snap, basket) {\n    const pr = basket && basket.priceRequest;\n    const later = !!(pr && pr.deferredKey && pr.deferredKey === pr.key && pr.requestedAt);\n    const bar = root.querySelector('[data-btk-kp-ordered-bar]');\n    if (!later || !bar || !isStaffOrderedView()) return;\n    const ref = String((snap && snap.orderRef) || '').replace(/^Online Order\\s*/i, '').trim();\n    const box = document.createElement('div');\n    box.className = 'btk-kp-wtf';\n    box.innerHTML = `\n      <div class=\"btk-kp-sidebar-title\">Worktop to Follow</div>\n      <p class=\"btk-kp-cabinets-products-desc\">\n        <strong>${escForKp(pr.title || 'Made-to-measure worktop')}</strong>${pr.detail ? '<br>' + escForKp(pr.detail) : ''}<br>\n        Not in this order: the customer is buying it separately.\n      </p>\n      <label class=\"btk-kp-wtf-label\" for=\"btk-kp-wtf-price\">${pr.poa\n        ? 'Price for the whole worktop (supply, manufacture, template &amp; install), ex VAT'\n        : 'Templating &amp; fitting for ' + escForKp(pr.area || 'the area') + ', ex VAT'}</label>\n      <div class=\"btk-kp-wtf-row\">\n        <span class=\"btk-kp-wtf-pound\">\u00A3</span>\n        <input id=\"btk-kp-wtf-price\" class=\"btk-kp-wtf-input\" type=\"number\" min=\"0\" step=\"0.01\" inputmode=\"decimal\" data-btk-kp-wtf-price>\n      </div>\n      <p class=\"btk-kp-wtf-total\" data-btk-kp-wtf-total></p>\n      <button type=\"button\" class=\"btk-kp-action-btn btk-kp-action-btn--green btk-kp-action-btn--sm\" data-btk-kp-wtf-send disabled>\n        <span class=\"btk-kp-action-btn-label\">Send Worktop to Customer's Basket</span>\n      </button>\n      <p class=\"btk-kp-cabinets-products-desc\" data-btk-kp-wtf-msg hidden></p>`;\n    const close = bar.querySelector('[data-btk-kp-ordered-close]');\n    bar.insertBefore(box, close || null);\n    const input = box.querySelector('[data-btk-kp-wtf-price]');\n    const totalEl = box.querySelector('[data-btk-kp-wtf-total]');\n    const send = box.querySelector('[data-btk-kp-wtf-send]');\n    const msg = box.querySelector('[data-btk-kp-wtf-msg]');\n    const say = (t) => { msg.hidden = !t; msg.textContent = t || ''; };\n    let current = null;\n    const price = () => {\n      const ex = Number(input.value);\n      current = null;\n      if (!(ex > 0)) { totalEl.textContent = ''; send.disabled = true; return; }\n      const inc = Math.round(ex * 1.2 * 100) / 100;\n      const { charges } = worktopToFollowCharges(inc);\n      const cents = charges.reduce((n, ch) => n + (ch.variant.priceCents || 0) * (ch.qty || 1), 0);\n      if (!charges.length || !cents) { totalEl.textContent = 'This worktop cannot be priced here - check the Worktops popup.'; send.disabled = true; return; }\n      current = { charges, cents };\n      totalEl.textContent = 'Worktop order: ' + wtfGBP(cents / 100) + ' inc VAT';\n      send.disabled = false;\n    };\n    input.addEventListener('input', price);\n    send.addEventListener('click', async () => {\n      if (!current || send.disabled) return;\n      const api = window.BTKBasketAPI;\n      send.disabled = true; say('Sending\u2026');\n      try {\n        const link = await api.orderExtrasLinkForPlan(_bootOrdered);\n        if (!link || !link.token) throw new Error('no extras link');\n        const number = (link.order && link.order.number) || ref || 'your order';\n        const b = await api.startOrderExtras(link);\n        b.name = 'Worktop for ' + number;\n        const forText = 'For your bedroom plan \"' + (basket.name || 'Your bedroom') + '\", order ' + number;\n        b.items = (b.items || []).concat(current.charges.map(ch => {\n          const v = ch.variant;\n          const item = api.createItem(String(v.variantId), v.name || 'Worktop', ch.label || '', ch.qty || 1,\n            ((v.priceCents || 0) / 100).toFixed(2));\n          item.attributes.quoteGroup = 'worktops';\n          item.attributes.installedOnly = true;\n          item.attributes.worktopDetail = ch.detail || ch.label || '';\n          item.attributes.worktopSpec = (ch.spec && ch.spec.length) ? ch.spec.join('\\n') : null;\n          item.attributes.notes = forText;\n          { const wm = Catalogue.getWorktopMaterial?.(ch.handle || v.materialHandle); item.image = (wm && wm.swatchUrl) || null; }\n          return item;\n        }));\n        if (typeof api.recalculateLineNumbers === 'function') api.recalculateLineNumbers(b);\n        await api.saveBasket(b);\n        await api.syncToShopifyCart(b.id).catch(() => {});\n        say('Sent: \"' + b.name + '\" (' + wtfGBP(current.cents / 100) + ' inc VAT) is now in the customer\\'s basket. Reply on their price request ticket to let them know.');\n      } catch (e) {\n        console.error('[BTK worktop to follow] send failed', e);\n        send.disabled = false;\n        say('That did not send. Please try again.');\n      }\n    });\n  }\n\n  function isStaffOrderedView() {\n    const api = window.BTKBasketAPI;\n    return !!(api && typeof api.isStaffMode === 'function' && api.isStaffMode());\n  }\n\n  // The viewer's Close. A customer goes back to their Orders list; staff, who\n  // came from the Odoo sales order, go back there through Back to Odoo (which\n  // also leaves staff mode) - not into the customer's own account pages.\n  function closeOrderedView() {\n    const api = window.BTKBasketAPI;\n    if (isStaffOrderedView() && api && typeof api.backToOdoo === 'function') {\n      api.backToOdoo();\n      return;\n    }\n    openPurchasedPlans();\n  }\n\n  let homeOpenBusy = false;   // a saved plan is being opened from its card\n  async function renderHomeSavedPlans() {\n    const cardsEl = root.querySelector('[data-btk-kp-home-saved-cards]');\n    if (!cardsEl) return;\n    const plans = await planStore.listPlans();\n    cardsEl.replaceChildren();\n    if (homeSavedEmpty) homeSavedEmpty.hidden = plans.length > 0;\n    if (!plans.length) return;\n    for (const set of groupPlanVersions(plans)) {\n      // A versioned set is boxed, with the ORIGINAL plan's name as the box's\n      // title and its versions inside. A heading alone left them looking like\n      // separate plans that happened to sort next to each other.\n      const isSet = set.plans.length > 1 || !!set.plans[0].versionOf;\n      let target = cardsEl;\n      if (isSet) {\n        const box = document.createElement('section');\n        box.className = 'btk-kp-savedplan-set';\n        box.innerHTML = `\n          <header class=\"btk-kp-savedplan-set-head\">\n            <span class=\"btk-kp-savedplan-set-name\"></span>\n            <span class=\"btk-kp-savedplan-set-count\"></span>\n            <button type=\"button\" class=\"btk-kp-savedplan-rename\" data-action=\"rename-set\"\n                    title=\"Rename this plan and all its versions\" aria-label=\"Rename plan\">${ICON_PENCIL}</button>\n          </header>\n          <div class=\"btk-kp-savedplan-set-cards\"></div>`;\n        box.querySelector('.btk-kp-savedplan-set-name').textContent = set.base;\n        box.querySelector('.btk-kp-savedplan-set-count').textContent =\n          `${set.plans.length} version${set.plans.length === 1 ? '' : 's'}`;\n        box.querySelector('[data-action=\"rename-set\"]').addEventListener('click',\n          () => renameVersionSet(set, renderHomeSavedPlans));\n        cardsEl.appendChild(box);\n        target = box.querySelector('.btk-kp-savedplan-set-cards');\n      }\n      for (const p of set.plans) {\n      const priceStr = (typeof p.total === 'number' && p.total > 0)\n        ? ((window.BTKVat && window.BTKVat.formatPrice)\n            ? window.BTKVat.formatPrice(Math.round(p.total * 100))\n            : ('\u00A3' + Math.round(p.total).toLocaleString('en-GB')))\n        : '';\n      // The thumbnail is stored with the plan, and staff open customers' plans,\n      // so only an image data URL or an https URL is shown, set as an attribute\n      // rather than written into markup (same rule as btk-account.js).\n      const safeThumb = typeof p.thumbnail === 'string'\n        && /^(data:image\\/(png|jpe?g|webp);base64,|https:\\/\\/)/i.test(p.thumbnail) ? p.thumbnail : '';\n      const card = document.createElement('div');\n      card.className = 'btk-kp-savedplan-card';\n      card.innerHTML = `\n        <div class=\"btk-kp-savedplan-card-img\">\n          ${safeThumb ? '' : '<span class=\"btk-kp-savedplan-card-noimg\">No preview yet</span>'}\n        </div>\n        <div class=\"btk-kp-savedplan-card-body\">\n          <div class=\"btk-kp-savedplan-card-namerow\">\n            <div class=\"btk-kp-savedplan-card-name\"></div>\n            <button type=\"button\" class=\"btk-kp-savedplan-rename\" data-action=\"rename\"\n                    title=\"Rename\" aria-label=\"Rename\">${ICON_PENCIL}</button>\n          </div>\n          <div class=\"btk-kp-savedplan-card-meta\">\n            <span class=\"btk-kp-savedplan-card-time\"></span>\n            ${priceStr ? `<span class=\"btk-kp-savedplan-card-price\">${priceStr}</span>` : ''}\n          </div>\n          <div class=\"btk-kp-savedplan-card-actions\">\n            <button type=\"button\" class=\"btk-kp-action-btn btk-kp-action-btn--green btk-kp-action-btn--sm\" data-action=\"load\">\n              <span class=\"btk-kp-btn-spinner\" aria-hidden=\"true\"></span>\n              <span class=\"btk-kp-action-btn-label\">Open</span>\n            </button>\n            <button type=\"button\" class=\"btk-kp-header-button btk-kp-header-button-danger\" data-action=\"delete\" title=\"Delete plan\">Delete</button>\n          </div>\n        </div>`;\n      if (safeThumb) {\n        const img = document.createElement('img');\n        img.alt = ''; img.loading = 'lazy'; img.src = safeThumb;\n        card.querySelector('.btk-kp-savedplan-card-img').appendChild(img);\n      }\n      card.querySelector('.btk-kp-savedplan-card-name').textContent = versionLabel(p) || p.name;\n      card.querySelector('.btk-kp-savedplan-card-time').textContent = p.savedAt ? `Saved ${formatTime(p.savedAt)}` : '';\n      card.querySelector('[data-action=\"rename\"]').addEventListener('click',\n        () => renameSavedPlan(p, renderHomeSavedPlans));\n      card.querySelector('[data-action=\"load\"]').addEventListener('click', async (e) => {\n        // Opening takes a moment, so the button says so (spinner + \"Opening\u2026\")\n        // and a second click - on this plan or another - is ignored until it\n        // has finished, rather than starting a second load over the first.\n        if (homeOpenBusy) return;\n        homeOpenBusy = true;\n        const btn = e.currentTarget;\n        const label = btn.querySelector('.btk-kp-action-btn-label');\n        btn.disabled = true;\n        btn.classList.add('is-saving');\n        btn.setAttribute('aria-busy', 'true');\n        if (label) label.textContent = 'Opening\u2026';\n        try {\n          await loadNamedPlan(p.name);\n          // A saved plan already HAS its room, so Room Setup is the wrong place\n          // to arrive - and its nudge would open the Room Shape popup on top of\n          // someone's finished kitchen. Same idiom as the ?plan= deep link.\n          roomShapePrompted = true;\n          stepperHandle.setStep('add-units');\n        } finally {\n          homeOpenBusy = false;\n          btn.disabled = false;\n          btn.classList.remove('is-saving');\n          btn.setAttribute('aria-busy', 'false');\n          if (label) label.textContent = 'Open';\n        }\n      });\n      card.querySelector('[data-action=\"delete\"]').addEventListener('click', async () => {\n        if (!(await window.BTKKPDialog.confirm(`Delete \"${p.name}\"? This can\u2019t be undone.`, { title: 'Delete plan?', confirmText: 'Delete', danger: true }))) return;\n        await deleteNamedPlan(p.name);\n        renderHomeSavedPlans();   // refresh in place\n      });\n      target.appendChild(card);\n      }\n    }\n  }\n  // Populate the left-menu saved list now (initial step is Planner Home) and\n  // let onChange refresh it on subsequent visits.\n  homeReady = true;\n  renderHomeSavedPlans();\n\n  // Highlight the matching header item (Planner Home / How To Guides / Get\n  // Help) for the content currently showing.\n  // Highlight the matching nav items for the content currently showing \u2014\n  // both the header buttons AND the Planner Home left-menu tiles/links.\n  // which: 'home' | 'start' | 'open-saved-plan' | 'how-to' | 'get-help'\n  function setHeaderActive(which) {\n    const homeCtx = which !== 'how-to' && which !== 'get-help';   // Planner Home context\n    root.querySelector('[data-btk-kp-step=\"planner-home\"]')?.classList.toggle('is-active', homeCtx);\n    root.querySelector('[data-btk-kp-howto-home]')?.classList.toggle('is-active', which === 'how-to');\n    root.querySelector('[data-btk-kp-header-gethelp]')?.classList.toggle('is-active', which === 'get-help');\n    // Left-menu \"How To Guides\" link + the tile/link home-views.\n    root.querySelector('[data-btk-kp-howto-toggle]')?.classList.toggle('is-active', which === 'how-to');\n    root.querySelectorAll('[data-btk-kp-home-view]').forEach(t => {\n      t.classList.toggle('is-active', t.dataset.btkKpHomeView === which);\n    });\n  }\n\n  root.addEventListener('click', (e) => {\n    const tile = e.target.closest('[data-btk-kp-home-view]');\n    if (!tile || !root.contains(tile)) return;\n    hideWelcome();   // a card on the welcome page drops the user into the planner\n    const view = tile.dataset.btkKpHomeView;\n    // \"Start New Plan\" opens the dedicated Style Setup stage (guided journey);\n    // startGuidedJourney switches stages + reveals its right pane itself. Do NOT\n    // call setHeaderActive here - it re-lights the New Plan stepper button\n    // (homeCtx), which would leave BOTH New Plan and Style Setup active.\n    // Both reset the plan THE MOMENT they are clicked (see resetToNewPlan);\n    // the journey opens straight away and the reset lands alongside it.\n    // Start New Empty Plan: the plan is named first (name popup); its Save\n    // opens the mood board and resets the plan. Closing the popup changes nothing.\n    if (view === 'start') {\n      if (startBtnBusy) return;   // already loading the last one\n      npStart('Choose Room Shape clicked');\n      openJourneyNamePopup({ mode: 'new' });\n      requestAnimationFrame(() => npMark('name popup on screen'));\n      return;\n    }\n    // The room-shape card. \"Use Current Room Shape\" (a plan is loaded) keeps\n    // the room on screen; \"Use Previous Room Shape\" first offers the rooms of\n    // the saved plans to pick from. Either way the name comes next.\n    if (view === 'start-from-room') {\n      if (planHasContent()) openJourneyNamePopup({ mode: 'room', room: null });\n      else openPreviousRoomPicker();\n      return;\n    }\n    // The other home-views (process guide, saved plans) live on Planner Home,\n    // so make sure we're on it (a welcome card can be clicked from any stage).\n    if (currentStep !== 'planner-home') stepperHandle.setStep('planner-home');\n    root.querySelectorAll('[data-btk-kp-home-panel]').forEach(p => {\n      p.hidden = p.dataset.btkKpHomePanel !== view;\n    });\n    if (view === 'open-saved-plan') renderHomeSavedPlans();\n    if (view === 'home') syncRoomShapeCard();\n    setHeaderActive(view);\n  });\n\n  // ---- Full-width Welcome page ----------------------------------------\n  // Shows on load; the red brand button (data-btk-kp-welcome-toggle) reopens\n  // it. Navigating into any stage, or using a welcome card, dismisses it.\n  const welcomeEl = root.querySelector('[data-btk-kp-welcome]');\n  const welcomeToggleBtn = root.querySelector('[data-btk-kp-welcome-toggle]');\n  // The brand button lights up (is-active) whenever the Welcome page is open.\n  function syncWelcomeBtn() {\n    const open = !!(welcomeEl && !welcomeEl.hidden);\n    if (welcomeToggleBtn) welcomeToggleBtn.classList.toggle('is-active', open);\n    // While Welcome is open, no planner stage should look active.\n    root.classList.toggle('btk-kp-welcome-open', open);\n  }\n  function hideWelcome()   { if (welcomeEl) welcomeEl.hidden = true;  syncWelcomeBtn(); }\n  function toggleWelcome() { if (welcomeEl) welcomeEl.hidden = !welcomeEl.hidden; syncWelcomeBtn(); }\n  welcomeToggleBtn?.addEventListener('click', toggleWelcome);\n  root.querySelectorAll('[data-btk-kp-step]').forEach(b => b.addEventListener('click', hideWelcome));\n  // ALL of them - there is one on the welcome page itself and there may be\n  // others elsewhere; binding only the first left the rest opening the request\n  // form behind a welcome page that stayed up.\n  root.querySelectorAll('[data-btk-kp-request-plan]').forEach(b => b.addEventListener('click', hideWelcome));\n  // The header basket/price button too: it is not a stage button, so the\n  // basket used to open UNDER the welcome page and nothing seemed to happen.\n  root.querySelectorAll('[data-btk-kp-proceed-checkout]').forEach(b => b.addEventListener('click', hideWelcome));\n  syncWelcomeBtn();   // welcome shows on load \u2192 brand starts active\n\n  // ---- \"Start New Plan\" guided journey --------------------------------\n  // A stepped flow inside the Planner Home right pane: pick a kitchen\n  // style + door colour, then a carcase colour, then name the plan \u2014\n  // then apply it and drop the user into Room Setup.\n  const journeyEl = root.querySelector('[data-btk-kp-journey]');\n  const journey   = { styleId: null, doorHandle: null, doorName: '', carcaseHandle: null, carcaseName: '', railHandle: null, railName: '',\n                      handleDesignId: null, handleFinishHandle: null, handleFinishName: '', handleName: '', worktopHandle: null, worktopName: '' };\n  // True once the guided journey has been rendered this session. Opening the\n  // Style Setup stage starts a fresh journey the first time; after that,\n  // re-opening the stage keeps whatever progress was made.\n  let journeyStarted = false;\n  // 'new'  = Start New Plan \u2192 finishing creates a fresh blank plan.\n  // 'edit' = Style Setup opened on an existing / loaded plan \u2192 finishing (or\n  //          skipping) applies the choices to that plan and KEEPS its units.\n  let journeyMode = 'new';\n  // When true, a NEW plan keeps the CURRENT room shape/walls instead of\n  // resetting to the default room (\"New Plan from Current Room Shape\").\n  let journeyKeepRoom = false;\n  // Which buying-style set the mood board is currently showing (0-based).\n  // The board renders one scene per style set (up to J_STYLE_MAX); \u2039 / \u203A nav\n  // steps this. Only the cabinet/door/carcase changes per set - worktop,\n  // handle, wall + floor are the plan's shared applied choices.\n  let moodBoardIndex = 0;\n  // Set true while a mood-board nav re-render runs so renderJourneyName\n  // doesn't yank focus back to the plan-name input on every \u2039 / \u203A click.\n  let mbSuppressNameFocus = false;\n  // Prefer the tile matching a saved value (restore), else the first tile.\n  function jPickTile(grid, attr, value) {\n    let match = null;\n    if (value != null) grid.querySelectorAll('[' + attr + ']').forEach(t => { if (t.getAttribute(attr) === value) match = t; });\n    return match || grid.querySelector('[' + attr + ']');\n  }\n  const jEsc = (s) => String(s == null ? '' : s).replace(/[&<>\"]/g, ch =>\n    ({ '&':'&amp;','<':'&lt;','>':'&gt;','\"':'&quot;' }[ch]));\n  const jSwatch = (c) => c.swatchUrl\n    ? `background-image:url(${c.swatchUrl});background-size:cover;background-position:center;`\n    : (c.hex ? `background:${c.hex};` : 'background:#ddd;');\n\n  // ---- Left-menu setup stepper (auto-ticks) ---------------------------\n  // Shown while the journey runs (Start button + saved list hide). Handled\n  // styles pick handles; True-Handleless pick a rail profile (the 'rail'\n  // internal step) - the label + wiring auto-switch. The Handles-for-handled\n  // and Worktops pickers arrive in Phase 2, so those stages show muted.\n  const journeyNav = root.querySelector('[data-btk-kp-journey-nav]');\n  const isHandleless = () => !!(Catalogue.isStyleTrueRail && Catalogue.isStyleTrueRail(journey.styleId));\n  // The setup stepper is the Style Setup STAGE now (its own sidebar panel),\n  // not an overlay on Planner Home. \"Showing\" the journey means switching to\n  // that stage; leaving it happens via setStep to another stage.\n  // Style Setup is no longer a stage (Arden, 2026-10-07) - there is no button\n  // for it and nothing switches to it. The journey still runs underneath (it\n  // is what names and resets a new plan), finishing straight away; the mood\n  // board code stays to move to the website later.\n  function showJourneyNav(on) {}\n  // Entering the Style Setup stage: reveal the guided-journey right pane and,\n  // the first time, start a fresh journey. Called from onChange('style-setup').\n  function enterStyleSetup() {\n    const homeEl = root.querySelector('[data-btk-kp-home]');\n    if (homeEl) homeEl.hidden = false;\n    root.querySelectorAll('[data-btk-kp-home-panel]').forEach(p => { p.hidden = p.dataset.btkKpHomePanel !== 'start'; });\n    if (!journeyStarted) {\n      // \u26A0 WAIT FOR THE BOOT RESTORE BEFORE JUDGING THE PLAN EMPTY.\n      // planHasContent() reads `cabinets` and `activePlanName`, both filled\n      // asynchronously at boot, so until the restore settles an EXISTING plan\n      // looks like an empty planner. Deciding here took the 'genuinely empty'\n      // branch, which starts a journey -> resetToNewPlan -> planStore.save of\n      // an empty design -> getWorkingBasket creates a fresh 'Unsaved Plan'\n      // basket. On EVERY refresh. Arden ended up with a list full of empty\n      // plans (2026-09-26).\n      if (!bootRestoreSettled) { pendingStyleSetupEntry = true; return; }\n      // Returning with an in-progress / loaded plan \u2192 restore choices and let\n      // the user continue; a genuinely empty planner starts a fresh journey.\n      if (planHasContent()) hydrateJourneyFromPlan();\n      else startGuidedJourney();\n    } else {\n      // Already mid-journey: make sure a step is actually visible. Returning to\n      // Style Setup (e.g. from the basket) can leave the 'start' panel shown\n      // but every journey step hidden \u2192 a blank white pane. Land on the\n      // overview if nothing's showing.\n      const anyStep = journeyEl && Array.from(journeyEl.querySelectorAll('[data-btk-kp-journey-step]')).some(s => !s.hidden);\n      if (!anyStep) { renderJourneyName(); showJourneyStep('name'); }\n    }\n  }\n  function updateJourneyNav(internalStep) {\n    if (!journeyNav) return;\n    const handleless = isHandleless();\n    // internal 'rail' step maps onto the 'handles' nav stage.\n    const active = internalStep === 'rail' ? 'handles' : internalStep;\n    const done = {\n      style:    buyingStyles.length > 0,   // ticks as soon as a card exists\n      handles:  handleless ? buyingRails.length > 0 : HANDLE_GROUP_KEYS.some(k => handleGroups[k] && handleGroups[k].designId),\n      worktops: !!worktopMaterialHandle,\n      wall:     wallChosen,\n      floor:    floorChosen,\n      name:     !!activePlanName\n    };\n    // Red count badge = qty set for the stage (each can be 1-3 now).\n    const counts = {\n      style:    buyingStyles.length,\n      handles:  handleless ? buyingRails.length : HANDLE_GROUP_KEYS.filter(k => handleGroups[k] && handleGroups[k].designId).length,\n      worktops: worktopMaterialHandle ? 1 : 0,\n      name:     0\n    };\n    journeyNav.querySelectorAll('[data-btk-kp-jnav]').forEach(item => {\n      const stage = item.dataset.btkKpJnav;\n      item.classList.toggle('is-active', stage === active);\n      // Tick stays even while the stage is active, as long as it's done.\n      item.classList.toggle('is-done', !!done[stage]);\n      item.classList.toggle('is-upcoming', false);\n      let badge = item.querySelector('[data-btk-kp-jnav-count]');\n      const n = counts[stage] || 0;\n      if (n > 0) {\n        if (!badge) {\n          badge = document.createElement('span');\n          badge.className = 'btk-kp-jnav-count';\n          badge.setAttribute('data-btk-kp-jnav-count', '');\n          item.appendChild(badge);\n        }\n        badge.textContent = String(n);\n        badge.hidden = false;\n      } else if (badge) {\n        badge.hidden = true;\n      }\n    });\n    const hLabel = journeyNav.querySelector('[data-btk-kp-jnav-handles-label]');\n    if (hLabel) hLabel.textContent = handleless ? 'Profiles' : 'Handles';\n  }\n  // Navigate to any setup stage (used by the left-menu nav AND the mood-board\n  // hotspots). Every stage is optional + editable any time - no prerequisites.\n  function gotoJourneyStage(stage) {\n    if (stage === 'name') { renderJourneyName(); showJourneyStep('name'); }\n    else if (stage === 'style') { renderJourneyStyles(); showJourneyStep('style'); }\n    else if (stage === 'handles') {\n      if (isHandleless()) { optEnter(OPT.rails); showJourneyStep('rail'); }\n      else { optEnter(OPT.handles); showJourneyStep('handles'); }\n    }\n    else if (stage === 'worktops') { optEnter(OPT.worktops); showJourneyStep('worktops'); }\n    else if (stage === 'wall')  { renderJourneyWall();  showJourneyStep('wall'); }\n    else if (stage === 'floor') { renderJourneyFloor(); showJourneyStep('floor'); }\n  }\n  // Wall + floor colour pickers - reuse the Finishing palette (WALL_COLOURS)\n  // and the metaobject floor list; clicking a swatch applies it immediately\n  // via the same handlers Finishing uses, and the mood board reflects it.\n  // ---- Wall & Floor popup (Customise) ---------------------------------------\n  // Their home on the mood board went with that tab, so Customise opens them,\n  // together (Arden, 2026-10-12): the popup's left menu is Wall Colour and\n  // Floor Colour - the planner's one left-menu design, as Splashbacks - each\n  // with what it is set to under its name, and the chosen one's options\n  // beside it. A pick paints the room and is saved with the plan; the popup\n  // stays open, so both can be set in one go.\n  //   Wall  - the eight wall colours, then any Farrow & Ball paint: the same\n  //           dropdown the chimney breast (cooker alcove) uses in Room Setup.\n  //           A paint is stored as its own wall colour handle,\n  //           \"fb:<hex>:<number>:<name>\" (getWallColour reads it).\n  //   Floor - the floor cards from the old Floor Colours popup: smaller\n  //           tiles, each with rotate 90\u00B0 and a size slider for its texture.\n  let wallFloorTab = 'wall';\n  // Feature Wall (Arden, 2026-10-13): step 1 is the room plan - pick walls and\n  // pillar sides - then Choose Feature Colour slides the colours in; Confirm\n  // applies the one picked there.\n  let fwSelected = [];   // surface keys: \"<wallNo>\" or \"<pillarId>:<side>\"\n  let fwStep = 'walls';  // 'walls' | 'colour'\n  let fwStaged = null;   // { colourHandle } | { patternId } picked on the colour step\n  let fwSlideIn = false; // play the slide once, as the colour step opens\n  const WF_ICON_FEATURE = '<svg width=\"20\" height=\"20\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><rect x=\"3\" y=\"4\" width=\"18\" height=\"16\" rx=\"1\"/><line x1=\"3\" y1=\"9.3\" x2=\"21\" y2=\"9.3\"/><line x1=\"3\" y1=\"14.6\" x2=\"21\" y2=\"14.6\"/><line x1=\"9\" y1=\"4\" x2=\"9\" y2=\"9.3\"/><line x1=\"15\" y1=\"9.3\" x2=\"15\" y2=\"14.6\"/><line x1=\"9\" y1=\"14.6\" x2=\"9\" y2=\"20\"/></svg>';\n  // The sections you can pick: each wall's sections as the plan lists them\n  // (wallSegments) - a pillar or corner block standing on a wall is its own\n  // section - with doors and windows folded into the stretch they sit in, as\n  // they are painted with it. A wall in one piece keeps its plain number as\n  // its key, so older plans still find it.\n  function fwSurfaces() {\n    const walls = getWalls(room);\n    const labels = deriveWallLabels(walls);\n    const out = [];\n    walls.forEach((w, wi) => {\n      if (!(w.lengthMm > 1)) return;\n      let segs = [];\n      try { segs = (wallSegments(wi) || []).slice().sort((p, q) => p.fromMm - q.fromMm); } catch (_) { segs = []; }\n      const runs = [];\n      for (const sg of segs) {\n        if (!(sg.toMm - sg.fromMm > 0)) continue;\n        if (sg.kind === 'feature') { runs.push({ feature: true, id: sg.id, seg: sg, fromMm: sg.fromMm, toMm: sg.toMm }); continue; }\n        const last = runs[runs.length - 1];\n        if (last && !last.feature && Math.abs(last.toMm - sg.fromMm) < 1) last.toMm = sg.toMm;\n        else runs.push({ feature: false, fromMm: sg.fromMm, toMm: sg.toMm });\n      }\n      if (!runs.length) runs.push({ feature: false, fromMm: 0, toMm: w.lengthMm });\n      const dir = { x: (w.to.x - w.from.x) / w.lengthMm, y: (w.to.y - w.from.y) / w.lengthMm };\n      const letter = labels[wi] || String(wi + 1);\n      const one = runs.length === 1;\n      let g = 0;\n      runs.forEach((r, n) => {\n        const key = one ? String(wi) : (r.feature ? `${wi}:f:${r.id}` : `${wi}:g${g++}`);\n        out.push({\n          key, wallIndex: wi, fromMm: r.fromMm, toMm: r.toMm, dir,\n          featureId: r.feature ? r.id : null,\n          seg: r.feature ? r.seg : { kind: 'gap', key, fromMm: r.fromMm, toMm: r.toMm },\n          badge: one ? letter : letter + (n + 1),\n          label: one ? `Wall ${letter}` : `Wall ${letter}${n + 1}`\n        });\n      });\n    });\n    return out;\n  }\n  function fwSummary() {\n    const n = Object.keys(featureWalls || {}).length;\n    return n ? `${n} wall${n > 1 ? 's' : ''}` : 'None';\n  }\n  // The chosen feature, if every selected wall has the same one.\n  function fwCommon() {\n    if (!fwSelected.length) return null;\n    const first = JSON.stringify(featureWalls[fwSelected[0]] || null);\n    return fwSelected.every(i => JSON.stringify(featureWalls[i] || null) === first) ? (featureWalls[fwSelected[0]] || null) : null;\n  }\n  function fwDrawPlan(body) {\n    const wrap = body.querySelector('[data-btk-kp-fw-plan]');\n    if (!wrap) return;\n    wrap.replaceChildren();\n    const items = ((getRoomConfig() || {}).perimeterItems || []).filter(it => it && it.type !== 'cooker-alcove');\n    const grid = renderGrid(wrap, room, { wallOpenings: [], perimeterItems: items, dimStackPx: 36 });\n    if (items.some(it => it.cornerCut) || items.some(it => !it.cornerCut && !it.pillarCorner)) {\n      renderFeatures(grid.el, items, grid.pxPerMm, room, { forceMiniDims: true, noMiniDimIds: new Set(items.map(it => it.id)) });\n    }\n    grid.el.querySelectorAll('.btk-kp-feature, [data-feature-id]').forEach(el => { el.style.pointerEvents = 'none'; });\n    const walls = getWalls(room);\n    renderWallDimensions(grid.el, room, grid.pxPerMm, {\n      wallOpenings: [], perimeterItems: [], cabinets: [], wallLabels: deriveWallLabels(walls)\n    });\n    const px = grid.pxPerMm;\n    const NS = 'http://www.w3.org/2000/svg';\n    const svg = document.createElementNS(NS, 'svg');\n    svg.setAttribute('class', 'btk-kp-fw-svg');\n    svg.style.cssText = 'position:absolute;inset:0;width:100%;height:100%;overflow:visible;pointer-events:none;z-index:30';\n    const defs = document.createElementNS(NS, 'defs');\n    svg.appendChild(defs);\n    let patN = 0;\n    const fillFor = (v) => {\n      if (!v) return null;\n      if (v.colourHandle) return getWallColour(v.colourHandle).hex;\n      const p = v.patternId && wallPatternList.find(x => x.id === v.patternId);\n      if (!p) return null;\n      const id = 'btk-kp-fw-pat-' + (patN++);\n      const pat = document.createElementNS(NS, 'pattern');\n      pat.setAttribute('id', id);\n      pat.setAttribute('patternUnits', 'userSpaceOnUse');\n      pat.setAttribute('width', '28'); pat.setAttribute('height', '28');\n      const img = document.createElementNS(NS, 'image');\n      img.setAttribute('href', p.swatchUrl || p.textureUrl);\n      img.setAttribute('width', '28'); img.setAttribute('height', '28');\n      img.setAttribute('preserveAspectRatio', 'xMidYMid slice');\n      pat.appendChild(img);\n      defs.appendChild(pat);\n      return 'url(#' + id + ')';\n    };\n    const badges = [];\n    fwSurfaces().forEach(sf => {\n      const pts = segmentPoints(sf.wallIndex, sf.seg, px);\n      if (!pts) return;\n      const sel = fwSelected.includes(sf.key);\n      const fill = fillFor(featureWalls[sf.key]);\n      const poly = document.createElementNS(NS, 'polygon');\n      poly.setAttribute('points', pts);\n      poly.setAttribute('class', 'btk-kp-fw-sec' + (sel ? ' is-selected' : '') + (fill ? ' is-feature' : ''));\n      // Picked = the plan's black selection; a feature shows its colour.\n      poly.setAttribute('fill', sel ? '#111111' : (fill || 'transparent'));\n      poly.setAttribute('data-btk-kp-fw-wall', sf.key);\n      const t = document.createElementNS(NS, 'title');\n      t.textContent = sf.label;\n      poly.appendChild(t);\n      svg.appendChild(poly);\n      const xy = pts.split(' ').map(p => p.split(',').map(Number));\n      const cx = xy.reduce((a, p) => a + p[0], 0) / xy.length;\n      const cy = xy.reduce((a, p) => a + p[1], 0) / xy.length;\n      badges.push({ cx, cy, text: sf.badge });\n    });\n    // Badges last, so they sit over every band; clicks pass through them.\n    for (const b of badges) {\n      const g = document.createElementNS(NS, 'g');\n      g.style.pointerEvents = 'none';\n      const c = document.createElementNS(NS, 'circle');\n      c.setAttribute('cx', b.cx); c.setAttribute('cy', b.cy); c.setAttribute('r', b.text.length > 1 ? 12 : 10);\n      c.setAttribute('class', 'btk-kp-wall-hit-badge');\n      const tx = document.createElementNS(NS, 'text');\n      tx.setAttribute('x', b.cx); tx.setAttribute('y', b.cy);\n      tx.setAttribute('text-anchor', 'middle'); tx.setAttribute('dominant-baseline', 'central');\n      tx.setAttribute('class', 'btk-kp-wall-hit-num');\n      tx.textContent = b.text;\n      g.appendChild(c); g.appendChild(tx);\n      svg.appendChild(g);\n    }\n    grid.el.appendChild(svg);\n  }\n  function fwPaneHTML() {\n    const surfaces = fwSurfaces();\n    fwSelected = fwSelected.filter(k => surfaces.some(x => x.key === k));   // a redrawn room may have lost some\n    if (!fwSelected.length) { fwStep = 'walls'; fwStaged = null; }\n    const picked = fwSelected.map(k => surfaces.find(x => x.key === k).label).join(', ');\n    if (fwStep === 'colour') {\n      const active = fwStaged || fwCommon();\n      const groups = new Map();\n      for (const p of wallPatternList) {\n        const k = p.category || 'Pattern';\n        if (!groups.has(k)) groups.set(k, []);\n        groups.get(k).push(p);\n      }\n      const patternCard = (p) => `\n        <button type=\"button\" class=\"btk-kp-fw-pattern${active && active.patternId === p.id ? ' is-active' : ''}\" data-btk-kp-fw-pattern=\"${jEsc(p.id)}\" title=\"${jEsc(p.name)}\">\n          <span class=\"btk-kp-fw-pattern-img\" style=\"background-image:url(${p.swatchUrl || p.textureUrl})\"></span>\n          <span class=\"btk-kp-fw-pattern-name\">${jEsc(p.name)}</span>\n        </button>`;\n      const activeColour = active && active.colourHandle ? active.colourHandle : null;\n      const slide = fwSlideIn;\n      fwSlideIn = false;\n      return `\n        <div class=\"btk-kp-fw-colour-step${slide ? ' is-sliding' : ''}\">\n          <button type=\"button\" class=\"btk-kp-fw-back\" data-btk-kp-fw-back>&lsaquo; Back to walls</button>\n          <h3 class=\"btk-kp-cabinets-products-title\">Choose feature colour</h3>\n          <p class=\"btk-kp-cabinets-products-desc\">For ${jEsc(picked)}. Pick a pattern or a paint colour, then Confirm.</p>\n          ${wallPatternList.length ? `\n          <div class=\"btk-kp-bbbp-title btk-kp-wf-col-title\">Patterns</div>\n          ${[...groups].map(([k, list]) => `\n            ${groups.size > 1 ? `<div class=\"btk-kp-fw-group\">${jEsc(k)}</div>` : ''}\n            <div class=\"btk-kp-fw-patterns\">${list.map(patternCard).join('')}</div>`).join('')}` : ''}\n          <div class=\"btk-kp-wf-wall btk-kp-fw-colours\">\n            <div>\n              <div class=\"btk-kp-bbbp-title btk-kp-wf-col-title\">Quick Colours</div>\n              <div class=\"btk-kp-wf-wall-grid\">${(WALL_COLOURS || []).map(c => wallFloorSwatch('data-btk-kp-fw-colour', c.handle,\n                c.label || c.handle, `background:${c.hex || '#ccc'}`, c.handle === activeColour)).join('')}</div>\n            </div>\n            <div>\n              <div class=\"btk-kp-bbbp-title btk-kp-wf-col-title\">Farrow &amp; Ball</div>\n              ${wfFbPanelHTML('data-btk-kp-fw-colour', activeColour)}\n            </div>\n          </div>\n        </div>`;\n    }\n    const hasFeature = fwSelected.some(k => featureWalls[k]);\n    return `\n        <h3 class=\"btk-kp-cabinets-products-title\">Choose a feature wall</h3>\n        <p class=\"btk-kp-cabinets-products-desc\">Click the walls you want as a feature - a pillar or corner block is its own section - then choose its colour or a pattern such as brick, stone or cladding.</p>\n        <div class=\"btk-kp-fw-walls\">\n          <div class=\"btk-kp-rs-preview btk-kp-fw-plan\" data-btk-kp-fw-plan></div>\n          <div class=\"btk-kp-fw-side\">\n            <div class=\"btk-kp-fw-side-title\">Chosen</div>\n            <div class=\"btk-kp-fw-picked\">${picked ? jEsc(picked) : 'Nothing yet - click a wall on the plan.'}</div>\n            <button type=\"button\" class=\"btk-kp-action-btn btk-kp-action-btn--green btk-kp-fw-next\" data-btk-kp-fw-next${fwSelected.length ? '' : ' disabled'}>\n              <span class=\"btk-kp-action-btn-label\">Choose Feature Colour</span>\n              <span class=\"btk-kp-action-btn-icon\" aria-hidden=\"true\"><svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M9 18l6-6-6-6\"/></svg></span>\n            </button>\n            ${hasFeature ? '<button type=\"button\" class=\"btk-kp-fw-clear\" data-btk-kp-fw-clear>Back to main wall colour</button>' : ''}\n          </div>\n        </div>`;\n  }\n\n  const WF_ICON_WALL  = '<svg width=\"20\" height=\"20\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><rect x=\"3\" y=\"3\" width=\"15\" height=\"6\" rx=\"1\"/><path d=\"M18 6h2v5h-8v3\"/><rect x=\"10\" y=\"14\" width=\"4\" height=\"7\" rx=\"1\"/></svg>';\n  const WF_ICON_FLOOR = '<svg width=\"20\" height=\"20\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><rect x=\"3\" y=\"3\" width=\"18\" height=\"18\" rx=\"1\"/><line x1=\"3\" y1=\"9\" x2=\"21\" y2=\"9\"/><line x1=\"3\" y1=\"15\" x2=\"21\" y2=\"15\"/><line x1=\"10\" y1=\"3\" x2=\"10\" y2=\"9\"/><line x1=\"15\" y1=\"9\" x2=\"15\" y2=\"15\"/><line x1=\"8\" y1=\"15\" x2=\"8\" y2=\"21\"/></svg>';\n  const WF_CHEVRON    = '<svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M9 18l6-6-6-6\"/></svg>';\n\n  // Farrow & Ball palette, loaded the first time the Wall pane needs it.\n  let wfFbGroups = null;        // null: not loaded; []: failed\n  let wfFbLoading = false;\n  function wfLoadFb() {\n    if (wfFbGroups || wfFbLoading) return;\n    wfFbLoading = true;\n    const url = (window.BTK_KP_ASSETS && window.BTK_KP_ASSETS.farrowBallJson) || '/assets/btk-farrow-ball.json';\n    fetch(url).then(r => r.json()).then(j => { wfFbGroups = Array.isArray(j && j.groups) ? j.groups : []; })\n      .catch(() => { wfFbGroups = []; })\n      .finally(() => { wfFbLoading = false; renderWallFloorPopup(); });\n  }\n  const wfFbHandle = (c) => `fb:${c.hex}:${c.number}:${c.name}`;\n\n  function wallFloorSwatch(attr, handle, name, dot, active) {\n    return `\n      <button type=\"button\" class=\"btk-kp-journey-swatch${active ? ' is-active' : ''}\" ${attr}=\"${jEsc(handle)}\" title=\"${jEsc(name)}\">\n        <span class=\"btk-kp-journey-swatch-dot\" style=\"${dot}\"></span>\n        <span class=\"btk-kp-journey-swatch-name\">${jEsc(name)}</span>\n      </button>`;\n  }\n  // The Farrow & Ball panel beside the quick colours (Arden, 2026-10-12): a\n  // title, the search box and the whole palette listed below it - always open,\n  // not a dropdown. The same rows and look as the chimney breast's picker\n  // (selection panel, alcoveFbPickerHTML).\n  function wfFbPanelHTML(attr = 'data-btk-kp-wall-pick', activeHandle = wallColourHandle) {\n    if (!wfFbGroups) { wfLoadFb(); return '<p class=\"btk-kp-panel-note\">Loading Farrow &amp; Ball palette\u2026</p>'; }\n    if (!wfFbGroups.length) return '<p class=\"btk-kp-panel-note\">The Farrow &amp; Ball palette could not be loaded.</p>';\n    const row = (c) => {\n      const h = wfFbHandle(c);\n      return `<button type=\"button\" class=\"btk-kp-fb-row ${h === activeHandle ? 'is-active' : ''}\" ${attr}=\"${jEsc(h)}\"\n          data-wf-fb-text=\"${jEsc((c.name + ' ' + c.number).toLowerCase())}\" title=\"${jEsc(c.name)} (No. ${jEsc(String(c.number))})\">\n          <span class=\"btk-kp-fb-row-chip\" style=\"background:${c.hex}\"></span>\n          <span class=\"btk-kp-fb-row-name\">${jEsc(c.name)}</span>\n          <span class=\"btk-kp-fb-row-num\">${jEsc(String(c.number))}</span>\n        </button>`;\n    };\n    return `\n      <div class=\"btk-kp-wf-fb\" data-wf-fb-picker>\n        <div class=\"btk-kp-fb-search\">\n          <svg class=\"btk-kp-fb-search-icon\" viewBox=\"0 0 24 24\" width=\"14\" height=\"14\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\"><circle cx=\"11\" cy=\"11\" r=\"7\"/><path d=\"M21 21l-4.35-4.35\"/></svg>\n          <input type=\"search\" class=\"btk-kp-fb-search-input\" data-wf-fb-search placeholder=\"Search by name or number\u2026\" autocomplete=\"off\" spellcheck=\"false\">\n        </div>\n        <div class=\"btk-kp-fb-results btk-kp-wf-fb-results\" data-wf-fb-results>${wfFbGroups.map(g => `\n          <div class=\"btk-kp-fb-group\" data-wf-fb-group>\n            <div class=\"btk-kp-fb-group-name\">${jEsc(g.name)}</div>\n            <div class=\"btk-kp-fb-rows\">${(g.colours || []).map(row).join('')}</div>\n          </div>`).join('')}\n          <p class=\"btk-kp-fb-empty\" data-wf-fb-empty hidden>No colours match.</p>\n        </div>\n      </div>`;\n  }\n  // F&B search: rows by name or number, empty groups hidden.\n  function wfFilterFb(input) {\n    const q = input.value.trim().toLowerCase();\n    const picker = input.closest('[data-wf-fb-picker]');\n    if (!picker) return;\n    let shown = 0;\n    picker.querySelectorAll('[data-wf-fb-group]').forEach(g => {\n      let n = 0;\n      g.querySelectorAll('[data-wf-fb-text]').forEach(r => {\n        const ok = !q || r.dataset.wfFbText.includes(q);\n        r.style.display = ok ? '' : 'none'; if (ok) n++;\n      });\n      g.style.display = n === 0 ? 'none' : ''; shown += n;\n    });\n    const empty = picker.querySelector('[data-wf-fb-empty]');\n    if (empty) empty.hidden = shown > 0;\n  }\n  // One floor card, as the old Floor Colours popup drew it (ui-room-shape\n  // buildFloorCard): the texture shown at its rotation and size, a tick when\n  // chosen, rotate 90\u00B0 and a size slider.\n  function wfFloorCard(c) {\n    const st = getFloorSettings(c.handle);\n    const active = c.handle === floorColourHandle;\n    const img = c.swatchUrl || c.textureUrl;\n    const tex = img\n      ? `background-image:url(${img});background-size:${(st.zoom || 1) * 50}%;transform:rotate(${st.rotationDeg || 0}deg);`\n      : `background:${c.hex || '#ddd'};`;\n    return `\n      <div class=\"btk-kp-floor-card${active ? ' is-active' : ''}\">\n        <button type=\"button\" class=\"btk-kp-floor-swatch\" data-btk-kp-floor-pick=\"${jEsc(c.handle)}\" title=\"${jEsc(c.name || c.handle)}\">\n          <span class=\"btk-kp-floor-swatch-tex\" style=\"${tex}\"></span>\n        </button>\n        <span class=\"btk-kp-floor-card-tick\" aria-hidden=\"true\"><svg viewBox=\"0 0 24 24\" width=\"13\" height=\"13\" fill=\"none\" stroke=\"#fff\" stroke-width=\"3.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M20 6L9 17l-5-5\"/></svg></span>\n        <div class=\"btk-kp-floor-card-name\">${jEsc(c.name || c.label || c.handle)}</div>\n        <div class=\"btk-kp-floor-card-ctrls\">\n          <button type=\"button\" class=\"btk-kp-floor-ctrl-btn\" data-wf-floor-rotate=\"${jEsc(c.handle)}\" title=\"Rotate texture 90\u00B0 (now ${st.rotationDeg || 0}\u00B0)\" aria-label=\"Rotate texture 90\u00B0\"><svg viewBox=\"0 0 24 24\" width=\"15\" height=\"15\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M21 2v6h-6\"/><path d=\"M3 12a9 9 0 0 1 15-6.7L21 8\"/></svg></button>\n          <input type=\"range\" class=\"btk-kp-floor-zoom\" min=\"50\" max=\"250\" step=\"10\" value=\"${Math.round((st.zoom || 1) * 100)}\" data-wf-floor-zoom=\"${jEsc(c.handle)}\" title=\"Floor size\" aria-label=\"Floor size\">\n        </div>\n      </div>`;\n  }\n  function renderWallFloorPopup(popup) {\n    const body = (popup || root).querySelector('[data-btk-kp-wallfloor-body]');\n    if (!body) return;\n    // The F&B search and where its list was scrolled to survive a redraw - a\n    // pick redraws the pane, and the list jumping back to the top lost the place.\n    const _fbList = body.querySelector('[data-wf-fb-results]');\n    const _fbScroll = _fbList ? _fbList.scrollTop : 0;\n    const _fbQuery = (body.querySelector('[data-wf-fb-search]') || {}).value || '';\n    const wall  = getWallColour(wallColourHandle);\n    const floor = (floorColourList || []).find(c => c.handle === floorColourHandle);\n    const tile = (key, icon, label, summary) => `\n      <button type=\"button\" class=\"btk-kp-action-btn${wallFloorTab === key ? ' is-active' : ''}\" data-btk-kp-wf-tab=\"${key}\">\n        <span class=\"btk-kp-action-btn-icon\" aria-hidden=\"true\">${icon}</span>\n        <span class=\"btk-kp-action-btn-label\">${label}\n          <span class=\"btk-kp-splash-tile-summary\">${jEsc(summary || '')}</span>\n        </span>\n        <span class=\"btk-kp-action-btn-arrow\" aria-hidden=\"true\">${WF_CHEVRON}</span>\n      </button>`;\n    let pane;\n    if (wallFloorTab === 'feature') {\n      pane = fwPaneHTML();\n    } else if (wallFloorTab === 'floor') {\n      const groups = new Map();\n      for (const c of (floorColourList || [])) {\n        const k = c.category || 'wooden';\n        if (!groups.has(k)) groups.set(k, []);\n        groups.get(k).push(c);\n      }\n      const title = k => k.charAt(0).toUpperCase() + k.slice(1);\n      pane = `\n        <h3 class=\"btk-kp-cabinets-products-title\">Choose your floor</h3>\n        <p class=\"btk-kp-cabinets-products-desc\">The floor shown in the 3D view and on your plan report - it is there to help you picture the room, not something we supply. Turn a floor with the rotate button, and use its slider to make the pattern bigger or smaller.</p>\n        ${[...groups].map(([k, list]) => `\n          ${groups.size > 1 ? `<div class=\"btk-kp-bbbp-title btk-kp-wf-group-title\">${jEsc(title(k))}</div>` : ''}\n          <div class=\"btk-kp-floor-grid\">${list.map(wfFloorCard).join('')}</div>`).join('')}`;\n    } else {\n      // Two columns (Arden, 2026-10-12): the sixteen quick colours four across\n      // on the left, the Farrow & Ball panel on the right.\n      pane = `\n        <h3 class=\"btk-kp-cabinets-products-title\">Choose your wall colour</h3>\n        <p class=\"btk-kp-cabinets-products-desc\">The colour your walls are painted in the 3D view and on your plan report - it is there to help you picture the room, not something we supply. Pick a quick colour, or any Farrow &amp; Ball paint.</p>\n        <div class=\"btk-kp-wf-wall\">\n          <div>\n            <div class=\"btk-kp-bbbp-title btk-kp-wf-col-title\">Quick Colours</div>\n            <div class=\"btk-kp-wf-wall-grid\">${(WALL_COLOURS || []).map(c => wallFloorSwatch('data-btk-kp-wall-pick', c.handle,\n              c.label || c.handle, `background:${c.hex || '#ccc'}`, c.handle === wallColourHandle)).join('')}</div>\n          </div>\n          <div>\n            <div class=\"btk-kp-bbbp-title btk-kp-wf-col-title\">Farrow &amp; Ball</div>\n            ${wfFbPanelHTML()}\n          </div>\n        </div>`;\n    }\n    body.innerHTML = `\n      <div class=\"btk-kp-cabinets-shell\">\n        <aside class=\"btk-kp-cabinets-l1-col\">\n          ${tile('wall',  WF_ICON_WALL,  'Wall Colour',  wall ? (wall.label || wall.handle) : '')}\n          ${tile('feature', WF_ICON_FEATURE, 'Feature Wall', fwSummary())}\n          ${tile('floor', WF_ICON_FLOOR, 'Floor Colour', floor ? (floor.name || floor.label || floor.handle) : '')}\n        </aside>\n        <section class=\"btk-kp-cabinets-right\">${pane}</section>\n      </div>\n      <div class=\"btk-kp-ep-apply-row btk-kp-confirm-row\">\n        <button type=\"button\" class=\"btk-kp-action-btn btk-kp-action-btn--green btk-kp-action-btn--sm\" ${wallFloorTab === 'feature'\n          ? `data-btk-kp-fw-confirm${fwStep === 'colour' && fwStaged ? '' : ' disabled'}` : 'data-btk-kp-popup-close'}>\n          <span class=\"btk-kp-action-btn-icon\" aria-hidden=\"true\"><svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><polyline points=\"20 6 9 17 4 12\"/></svg></span>\n          <span class=\"btk-kp-action-btn-label\">Confirm</span>\n        </button>\n      </div>`;\n    // The Confirm strip (Arden, 2026-10-13) only closes: wall and floor picks\n    // apply as they are made, like the other popups' Confirm rows.\n    if (wallFloorTab === 'feature') {\n      try { fwDrawPlan(body); } catch (err) { console.error('[BTK feature wall plan]', err); }\n    }\n    const _s = body.querySelector('[data-wf-fb-search]');\n    if (_s && _fbQuery) { _s.value = _fbQuery; wfFilterFb(_s); }\n    const _l = body.querySelector('[data-wf-fb-results]');\n    if (_l) _l.scrollTop = _fbScroll;\n  }\n  root.addEventListener('click', (e) => {\n    if (!e.target.closest('[data-btk-kp-wallfloor-body]')) return;\n    const tab = e.target.closest('[data-btk-kp-wf-tab]');\n    if (tab) { wallFloorTab = tab.dataset.btkKpWfTab; renderWallFloorPopup(); return; }\n    // The F&B dropdown opens and closes in place.\n    const fbToggle = e.target.closest('[data-wf-fb-toggle]');\n    if (fbToggle) {\n      const dd = fbToggle.parentElement.querySelector('[data-wf-fb-dropdown]');\n      if (dd) {\n        dd.hidden = !dd.hidden;\n        fbToggle.setAttribute('aria-expanded', String(!dd.hidden));\n        const s = dd.querySelector('[data-wf-fb-search]');\n        if (!dd.hidden && s) requestAnimationFrame(() => s.focus());\n      }\n      return;\n    }\n    if (e.target.closest('[data-wf-fb-search]')) return;\n    // Feature Wall.\n    const fwWall = e.target.closest('[data-btk-kp-fw-wall]');\n    if (fwWall) {\n      const k = fwWall.getAttribute('data-btk-kp-fw-wall');\n      fwSelected = fwSelected.includes(k) ? fwSelected.filter(x => x !== k) : [...fwSelected, k];\n      renderWallFloorPopup(); return;\n    }\n    if (e.target.closest('[data-btk-kp-fw-next]') && fwSelected.length) {\n      fwStep = 'colour'; fwStaged = null; fwSlideIn = true;\n      renderWallFloorPopup(); return;\n    }\n    if (e.target.closest('[data-btk-kp-fw-back]')) {\n      fwStep = 'walls'; fwStaged = null;\n      renderWallFloorPopup(); return;\n    }\n    const fwColour = e.target.closest('[data-btk-kp-fw-colour]');\n    const fwPattern = !fwColour && e.target.closest('[data-btk-kp-fw-pattern]');\n    if ((fwColour || fwPattern) && fwSelected.length) {\n      fwStaged = fwColour ? { colourHandle: fwColour.getAttribute('data-btk-kp-fw-colour') }\n                          : { patternId: fwPattern.getAttribute('data-btk-kp-fw-pattern') };\n      renderWallFloorPopup(); return;\n    }\n    const fwConfirm = e.target.closest('[data-btk-kp-fw-confirm]');\n    if (fwConfirm) {\n      if (!fwStaged || !fwSelected.length) return;\n      featureWalls = { ...featureWalls };\n      for (const k of fwSelected) featureWalls[k] = fwStaged;\n      fwSelected = []; fwStep = 'walls'; fwStaged = null;\n      applyFeatureWallsTo3D(); scheduleAutosave();\n      const pop = fwConfirm.closest('[data-btk-kp-popup]');\n      if (pop) pop.hidden = true;\n      renderWallFloorPopup(); return;\n    }\n    if (e.target.closest('[data-btk-kp-fw-clear]')) {\n      featureWalls = { ...featureWalls };\n      for (const i of fwSelected) delete featureWalls[i];\n      applyFeatureWallsTo3D(); scheduleAutosave(); renderWallFloorPopup(); return;\n    }\n    const rot = e.target.closest('[data-wf-floor-rotate]');\n    if (rot) { handleRotateFloor(rot.dataset.wfFloorRotate); scheduleAutosave(); renderWallFloorPopup(); return; }\n    const wall = e.target.closest('[data-btk-kp-wall-pick]');\n    const floor = !wall && e.target.closest('[data-btk-kp-floor-pick]');\n    if (!wall && !floor) return;\n    if (wall) handleSetWallColour(wall.dataset.btkKpWallPick);\n    else handleSetFloorColour(floor.dataset.btkKpFloorPick);\n    scheduleAutosave();\n    // A wall colour is one choice, so picking it closes the popup (Arden,\n    // 2026-10-12). A floor stays open: its rotate and size are set after.\n    if (wall) {\n      const pop = wall.closest('[data-btk-kp-popup]');\n      if (pop) { pop.hidden = true; return; }\n    }\n    renderWallFloorPopup();\n  });\n  root.addEventListener('input', (e) => {\n    const s = e.target.closest('[data-wf-fb-search]');\n    if (s) { wfFilterFb(s); return; }\n    // Floor size slider: live while dragging, without redrawing the slider.\n    const z = e.target.closest('[data-wf-floor-zoom]');\n    if (!z) return;\n    const pct = parseInt(z.value, 10) || 100;\n    handleSetFloorZoom(z.dataset.wfFloorZoom, pct / 100);\n    const card = z.closest('.btk-kp-floor-card');\n    if (card) {\n      card.parentElement.parentElement.querySelectorAll('.btk-kp-floor-card.is-active').forEach(el => el.classList.remove('is-active'));\n      card.classList.add('is-active');\n      const tex = card.querySelector('.btk-kp-floor-swatch-tex');\n      if (tex) tex.style.backgroundSize = ((pct / 100) * 50) + '%';\n    }\n  });\n  root.addEventListener('change', (e) => {\n    if (e.target.closest('[data-wf-floor-zoom]')) { scheduleAutosave(); renderWallFloorPopup(); }\n  });\n\n  function renderJourneyWall() {\n    const grid = journeyEl && journeyEl.querySelector('[data-btk-kp-journey-wall]');\n    if (!grid) return;\n    grid.innerHTML = (WALL_COLOURS || []).map(c => `\n      <button type=\"button\" class=\"btk-kp-journey-swatch${c.handle === wallColourHandle ? ' is-active' : ''}\"\n              data-btk-kp-journey-wall-swatch=\"${jEsc(c.handle)}\" title=\"${jEsc(c.label || c.handle)}\">\n        <span class=\"btk-kp-journey-swatch-dot\" style=\"background:${c.hex || '#ccc'}\"></span>\n        <span class=\"btk-kp-journey-swatch-name\">${jEsc(c.label || c.handle)}</span>\n      </button>`).join('');\n  }\n  function renderJourneyFloor() {\n    const grid = journeyEl && journeyEl.querySelector('[data-btk-kp-journey-floor]');\n    if (!grid) return;\n    grid.innerHTML = (floorColourList || []).map(c => {\n      const img = c.textureUrl || c.swatchUrl;\n      const dot = img ? `background-image:url(${img});background-size:cover;background-position:center;` : `background:${c.hex || '#ccc'};`;\n      const nm  = c.name || c.label || c.handle;\n      return `\n      <button type=\"button\" class=\"btk-kp-journey-swatch${c.handle === floorColourHandle ? ' is-active' : ''}\"\n              data-btk-kp-journey-floor-swatch=\"${jEsc(c.handle)}\" title=\"${jEsc(nm)}\">\n        <span class=\"btk-kp-journey-swatch-dot\" style=\"${dot}\"></span>\n        <span class=\"btk-kp-journey-swatch-name\">${jEsc(nm)}</span>\n      </button>`;\n    }).join('');\n  }\n  if (journeyNav) {\n    journeyNav.querySelectorAll('[data-btk-kp-jnav]').forEach(item => {\n      item.addEventListener('click', () => {\n        if (item.classList.contains('is-upcoming')) return;\n        gotoJourneyStage(item.dataset.btkKpJnav);\n      });\n    });\n  }\n  // The note under the mood board offers the same trip as the left menu's first\n  // item. It needs its own binding: the handler above is scoped to the NAV, so\n  // a data-btk-kp-jnav anywhere else would look wired and do nothing.\n  root.querySelectorAll('[data-btk-kp-goto-style]').forEach(b => {\n    b.addEventListener('click', () => gotoJourneyStage('style'));\n  });\n\n  // The mood board ('name') is the page and stays up; every other step is a\n  // picker that opens over it in the setup popup.\n  function showJourneyStep(step) {\n    if (!journeyEl) return;\n    // Inside the function, not a const beside it: no TDZ if a stage change\n    // during init reaches here first.\n    const JOURNEY_POPUP_TITLES = {\n      style: 'Cabinet & Door', carcase: 'Carcase Colour', rail: 'Handleless Profile',\n      handles: 'Handles', worktops: 'Worktops', wall: 'Wall Colour', floor: 'Floor Colour'\n    };\n    const inPopup = step !== 'name';\n    journeyEl.querySelectorAll('[data-btk-kp-journey-step]').forEach(s => {\n      const k = s.dataset.btkKpJourneyStep;\n      s.hidden = k === 'name' ? false : k !== step;\n    });\n    const pop = journeyEl.querySelector('[data-btk-kp-journey-popup]');\n    if (pop) {\n      const wasOpen = !pop.hidden;\n      pop.hidden = !inPopup;\n      const title = pop.querySelector('[data-btk-kp-journey-popup-title]');\n      if (inPopup && title) title.textContent = JOURNEY_POPUP_TITLES[step] || 'Style Setup';\n      if (inPopup && !wasOpen) pop.querySelector('[data-btk-kp-journey-popup-body]')?.scrollTo?.(0, 0);\n    }\n    updateJourneyNav(step);\n  }\n  // Closing the setup popup (X / backdrop) does what that step's own \"Back to\n  // Mood Board\" button does - the style step applies the active style on its\n  // way out - or, for a step without one, just returns to the board.\n  function closeJourneyPopup() {\n    const pop = journeyEl && journeyEl.querySelector('[data-btk-kp-journey-popup]');\n    if (!pop || pop.hidden) return;\n    const open = pop.querySelector('[data-btk-kp-journey-step]:not([hidden])');\n    const back = open && open.querySelector('.btk-kp-style-help-action button');\n    if (back) back.click();\n    else gotoJourneyStage('name');\n  }\n\n  // ---- First Step (Style Setup intro) ---------------------------------\n  // The mid-size popup in the shell (data-btk-kp-style-intro): text, the mood\n  // board picture, \"Don't show this again\" + Got It. Any way of closing it\n  // honours the tick, as the old dialog did. Looked up on each call, so it is\n  // safe whenever the stage change that opens it runs.\n  function openStyleIntro() {\n    const pop = root.querySelector('[data-btk-kp-style-intro]');\n    if (!pop || !pop.hidden) return;\n    const box = pop.querySelector('[data-btk-kp-style-intro-dontshow]');\n    if (box) box.checked = false;\n    pop.hidden = false;\n    if (!pop.dataset.wired) {\n      pop.dataset.wired = '1';\n      const close = () => {\n        pop.hidden = true;\n        const tick = pop.querySelector('[data-btk-kp-style-intro-dontshow]');\n        if (tick && tick.checked) {\n          styleIntroDone = true;\n          try { localStorage.setItem('btk_kp_style_intro_seen_v2', '1'); } catch (e) {}\n        }\n      };\n      pop.addEventListener('click', (e) => {\n        if (e.target.closest('[data-btk-kp-style-intro-close]')) { close(); return; }\n        if (!e.target.closest('[data-btk-kp-style-intro-ok]')) return;\n        close();\n        // Style Setup opened straight from the stepper, on a new plan nobody\n        // has named yet (Start New Plan names it first): Got It goes on to the\n        // name popup, whose Save names the plan and stays on the mood board.\n        if (currentStep === 'style-setup' && journeyStarted\n            && journeyMode === 'new' && !journeyPlanName()) {\n          openJourneyNamePopup({ mode: 'rename' });\n        }\n      });\n    }\n    const ok = pop.querySelector('[data-btk-kp-style-intro-ok]');\n    if (ok) requestAnimationFrame(() => ok.focus());\n  }\n\n  // ---- The name popup ------------------------------------------------\n  // One small popup names the plan, whichever way in:\n  //   'new'     Start New Empty Plan  -> name, then the new plan's mood board\n  //   'room'    a room shape choice   -> name, then the mood board in that room\n  //   'finish'  Start Planning with no name yet -> name, then on to the plan\n  //   'rename'  Edit beside the name on the mood board\n  // Nothing is reset or started until Save, so closing it changes nothing.\n  // It lives on .btk-kp-home, outside the journey, so it is wired here.\n  let namePopupMode = 'finish';\n  let namePopupRoom = null;     // 'room': the room to keep (null = the one on screen)\n  let journeyReplaceName = '';  // a name the user agreed may replace a saved plan\n  const namePopupEl = root.querySelector('[data-btk-kp-journey-name-popup]');\n  const nameInputEl = namePopupEl && namePopupEl.querySelector('[data-btk-kp-journey-name]');\n\n  // A new plan's name is saved: Room Shape opens AT ONCE, over the Start\n  // page, with \"Loading\u2026\" across it until the new plan is set up (a few\n  // seconds - see resetToNewPlan) and Room Setup is behind it. Then\n  // finishGuidedJourney opens it properly and the cover comes off. Closing is\n  // ignored while it loads (Arden, 2026-10-07).\n  let startBtnBusy = false;\n  function setRoomShapeLoading(on) {\n    startBtnBusy = on;\n    const popup = root.querySelector('[data-btk-kp-popup=\"room-shape\"]');\n    if (!popup) return;\n    const body = popup.querySelector('.btk-kp-rs-body');\n    if (body && !body.querySelector('.btk-kp-rs-loading')) {\n      body.insertAdjacentHTML('beforeend', '<div class=\"btk-kp-rs-loading\" role=\"status\"><span class=\"btk-kp-rs-loading-spin\" aria-hidden=\"true\"></span><span>Loading\u2026</span></div>');\n    }\n    if (on) { if (popup.parentElement !== root) root.appendChild(popup); popup.hidden = false; }\n    popup.classList.toggle('is-loading', on);\n  }\n  // Finished, it takes the cover off itself once Room Shape is opened for\n  // real; the finally is for the ways it can stop short (a dialog, no style).\n  function finishBehindRoomShapeLoading() {\n    setRoomShapeLoading(true);\n    return finishGuidedJourney().finally(() => requestAnimationFrame(() => {\n      if (!startBtnBusy) return;\n      setRoomShapeLoading(false);\n      if (currentStep !== 'room-setup' || document.querySelector('.btk-kp-dialog-overlay')) {\n        const p = root.querySelector('[data-btk-kp-popup=\"room-shape\"]');\n        if (p) p.hidden = true;\n      }\n    }));\n  }\n  function openJourneyNamePopup(opts) {\n    namePopupMode = (opts && opts.mode) || 'finish';\n    namePopupRoom = (opts && opts.room) || null;\n    if (!namePopupEl) { if (namePopupMode === 'finish') finishGuidedJourney(); return; }\n    // A new plan starts unnamed; finishing / renaming starts from its name.\n    if (namePopupMode === 'new' || namePopupMode === 'room') {\n      if (nameInputEl) nameInputEl.value = '';\n      journeyReplaceName = '';   // a Replace agreed for an earlier plan is not for this one\n    }\n    namePopupEl.hidden = false;\n    if (nameInputEl) setTimeout(() => { nameInputEl.focus(); if (nameInputEl.select) nameInputEl.select(); }, 40);\n  }\n  function closeJourneyNamePopup() {\n    if (namePopupEl) namePopupEl.hidden = true;\n  }\n  // 'convert': Convert Basket to Kitchen Plan names its plan here too. The\n  // popup lives in the Start page, which is hidden during a convert, so it\n  // is lifted to the root while it is up and put back after. Resolves with\n  // the name; the X keeps the suggested name, so the convert always goes on.\n  let convertNameDone = null;\n  let convertOwnBasketId = null;   // the convert's own plan basket: its name is not a clash\n  let convertNameHome = null;\n  function askConvertPlanName(suggested) {\n    return new Promise(resolve => {\n      if (!namePopupEl) { resolve(suggested); return; }\n      convertNameDone = resolve;\n      convertNameHome = namePopupEl.parentElement;\n      if (convertNameHome !== root) root.appendChild(namePopupEl);\n      namePopupMode = 'convert';\n      journeyReplaceName = '';\n      setJourneyNameInput(suggested || '');\n      namePopupEl.hidden = false;\n      if (nameInputEl) setTimeout(() => { nameInputEl.focus(); if (nameInputEl.select) nameInputEl.select(); }, 40);\n    });\n  }\n  function finishConvertName(name) {\n    closeJourneyNamePopup();\n    if (convertNameHome && namePopupEl.parentElement !== convertNameHome) convertNameHome.appendChild(namePopupEl);\n    const done = convertNameDone;\n    convertNameDone = null; convertNameHome = null; namePopupMode = 'finish';\n    if (done) done(name);\n  }\n  function journeyPlanName() {\n    return nameInputEl ? (nameInputEl.value || '').trim() : '';\n  }\n  function setJourneyNameInput(v) {\n    if (nameInputEl) nameInputEl.value = v || '';\n  }\n  // A new plan's name clashing with a saved plan is asked about HERE, while the\n  // popup is still up to take another name. Nothing is deleted yet: Replace is\n  // remembered and carried out when the plan is really saved (Start Planning).\n  async function nameIsFreeOrReplace(name) {\n    if (await refuseBoughtPlanName(name)) return false;\n    if (journeyMode === 'edit' && namePopupMode !== 'new' && namePopupMode !== 'room') return true;\n    if (name === journeyReplaceName) return true;\n    const clash = (await otherPlansNamed(name, null))\n      .filter(b => !(namePopupMode === 'convert' && b.id === convertOwnBasketId));\n    if (!clash.length) return true;\n    const ok = await window.BTKKPDialog.confirm(\n      `A saved plan called \"${name}\" already exists.\\n\\nReplace it with this new plan, or choose another name?`,\n      { title: 'Plan name already used', confirmText: 'Replace it', cancelText: 'Choose another name', danger: true }\n    );\n    if (ok) journeyReplaceName = name;\n    return ok;\n  }\n  async function saveJourneyName() {\n    const name = journeyPlanName();\n    if (!name) { if (nameInputEl) nameInputEl.focus(); return; }\n    npMark('name entered, Save pressed');\n    const nameFree = await nameIsFreeOrReplace(name);\n    npMark('name checked against saved plans');\n    if (!nameFree) {\n      if (nameInputEl) { nameInputEl.focus(); if (nameInputEl.select) nameInputEl.select(); }\n      return;\n    }\n    const mode = namePopupMode;\n    if (mode === 'convert') { finishConvertName(name); return; }\n    if (mode === 'finish') {\n      // A brand-new plan (the website's Start Planning, Arden 2026-10-07):\n      // Room Shape opens at once with Loading over it, as Choose Room Shape's\n      // does. Editing a plan's setup goes on as before.\n      if (journeyMode !== 'edit' && journeyNeedsReset && !journeyKeepRoom) finishBehindRoomShapeLoading();\n      else finishGuidedJourney();   // it closes the popup\n      return;\n    }\n    closeJourneyNamePopup();\n    if (mode === 'new' || mode === 'room') {\n      // What the New Plan cards did on click, now that the plan has a name:\n      // open the journey and reset the plan alongside it (see resetToNewPlan).\n      const keepRoom = mode === 'room';\n      const room = namePopupRoom;\n      const agreed = journeyReplaceName;   // startGuidedJourney clears it\n      startGuidedJourney(keepRoom ? { keepRoom: true, resetDone: true } : { resetDone: true });\n      journeyReplaceName = agreed;\n      // The empty-plan save goes into the journey-save queue rather than being\n      // waited for: it took 25s for a large account, and Room Shape waited on it.\n      newPlanReset = resetToNewPlan(keepRoom ? { keepRoom: true, room, backgroundSave: true } : { backgroundSave: true });\n      setJourneyNameInput(name);   // startGuidedJourney cleared it\n      // No Style Setup stage any more: named, the new plan goes straight on to\n      // Room Setup (what Start Planning on the mood board did).\n      finishBehindRoomShapeLoading();\n      return;\n    }\n    renderJourneyName();\n  }\n  if (namePopupEl) {\n    namePopupEl.addEventListener('click', (e) => {\n      if (e.target.closest('[data-btk-kp-journey-name-close]')) {\n        // A convert can't stop here: its units are already staged. Closing\n        // keeps the name in the box (or the suggestion) and carries on.\n        if (namePopupMode === 'convert') {\n          finishConvertName(journeyPlanName() || activePlanName || 'My Bedroom Plan');\n          return;\n        }\n        autosaveHeldForLinkedNewPlan = false;   // the old plan is back in use\n        closeJourneyNamePopup();\n        return;\n      }\n      if (e.target.closest('[data-btk-kp-journey-name-save]')) saveJourneyName();\n    });\n    if (nameInputEl) nameInputEl.addEventListener('keydown', (e) => {\n      if (e.key !== 'Enter') return;\n      e.preventDefault();\n      saveJourneyName();   // Enter = Save\n    });\n  }\n\n  // ---- Use Previous Room Shape --------------------------------------------\n  // The saved plans' rooms, three to a row: walls, doors and windows only.\n  // Picking one names the new plan (name popup, 'room') and carries on.\n  const prevRoomPopupEl = root.querySelector('[data-btk-kp-prevroom-popup]');\n  const prevRoomGridEl  = prevRoomPopupEl && prevRoomPopupEl.querySelector('[data-btk-kp-prevroom-grid]');\n  // It lived inside the Start page overlay, which is hidden on every other\n  // stage - so opened from Room Setup's Room Shape popup it could not be seen.\n  // It moves to the root beside the hoisted Room Shape popup (see\n  // hoistPopupsToRoot), and its CSS puts it one layer above, so Use Existing\n  // Room opens it on top of Room Shape rather than behind it.\n  if (prevRoomPopupEl && prevRoomPopupEl.parentElement !== root) root.appendChild(prevRoomPopupEl);\n  // 'new': the picked room starts a new plan (name popup next).\n  // 'apply': Room Shape's Use Existing Room - it becomes this plan's room.\n  let prevRoomMode = 'new';\n  let prevRoomChoices = [];\n\n  // A small copy of the 2D plan's look for a room: page-grey surround, the\n  // white floor with its 100mm / 1m grid, 100mm grey wall bands with dark\n  // edges, pillars and internal walls drawn the same way (opening into the\n  // wall they stand against), the cooker alcove, windows (white pane, blue\n  // glass line) and doors (gap, jambs, leaf and dashed swing). No units, no\n  // dimensions. Colours are the 2D plan's (2d-grid / 2d-openings / base.css).\n  let roomThumbSeq = 0;\n  function roomThumbSVG(rc) {\n    let rm;\n    try { rm = buildRoomPolygon(rc); } catch (e) { return ''; }\n    const verts = (rm && rm.vertices) || [];\n    if (verts.length < 3) return '';\n    const T = 100;                                   // wall band, mm\n    const bb = getBoundingBox(rm);\n    const span = Math.max(bb.widthMm, bb.heightMm, 1);\n    const lw = Math.max(12, span * 0.0045);          // dark edge line\n    const pad = T + span * 0.05;\n    const r = (n) => Math.round(n);\n    const vb = [bb.minX - pad, bb.minY - pad, bb.widthMm + pad * 2, bb.heightMm + pad * 2].map(r).join(' ');\n    const id = 'btkRt' + (++roomThumbSeq);\n    const pts = verts.map(v => `${r(v.x)},${r(v.y)}`).join(' ');\n    const cx = verts.reduce((a, v) => a + v.x, 0) / verts.length;\n    const cy = verts.reduce((a, v) => a + v.y, 0) / verts.length;\n    const BG = '#f5f5f5', BAND = '#d8d8d8', EDGE = '#333';\n    let out = '';\n    // Surround, then the wall band: a stroke of twice the band on the floor\n    // outline, whose inner half the floor then covers.\n    out += `<rect x=\"${r(bb.minX - pad)}\" y=\"${r(bb.minY - pad)}\" width=\"${r(bb.widthMm + pad * 2)}\" height=\"${r(bb.heightMm + pad * 2)}\" fill=\"${BG}\"/>`;\n    out += `<polygon points=\"${pts}\" fill=\"none\" stroke=\"${EDGE}\" stroke-width=\"${r(T * 2 + lw * 2)}\" stroke-linejoin=\"miter\"/>`;\n    out += `<polygon points=\"${pts}\" fill=\"none\" stroke=\"${BAND}\" stroke-width=\"${r(T * 2)}\" stroke-linejoin=\"miter\"/>`;\n    out += `<polygon points=\"${pts}\" fill=\"#fff\"/>`;\n    out += `<polygon points=\"${pts}\" fill=\"url(#${id}g)\"/>`;\n    out += `<polygon points=\"${pts}\" fill=\"none\" stroke=\"${EDGE}\" stroke-width=\"${r(lw)}\" stroke-linejoin=\"miter\"/>`;\n\n    // Features. Rectangular pillars / internal walls get the wall's double\n    // line; a side flush with the room's edge opens into the wall band.\n    const EPS = 5;\n    for (const it of (rc.perimeterItems || [])) {\n      if (!it || !(it.widthMm > 0) || !(it.depthMm > 0)) continue;\n      const rot = ((Math.round(it.rotationDeg || 0) % 360) + 360) % 360;\n      const quarter = rot % 90 === 0;\n      const turned = rot === 90 || rot === 270;\n      const w = turned ? it.depthMm : it.widthMm, d = turned ? it.widthMm : it.depthMm;\n      const icx = it.x + it.widthMm / 2, icy = it.y + it.depthMm / 2;\n      const x0 = icx - w / 2, y0 = icy - d / 2, x1 = x0 + w, y1 = y0 + d;\n      const rotAttr = quarter ? '' : ` transform=\"rotate(${rot} ${r(icx)} ${r(icy)})\"`;\n      if (it.type === 'column' && it.cornerCut) {\n        const pv = getPentagonVerticesWorld(it).map(p => `${r(p.x)},${r(p.y)}`).join(' ');\n        out += `<polygon points=\"${pv}\" fill=\"${BAND}\" stroke=\"${EDGE}\" stroke-width=\"${r(lw)}\" stroke-linejoin=\"miter\"${rotAttr}/>`;\n      } else if (it.type === 'column') {\n        const fT = quarter && y0 <= bb.minY + EPS, fB = quarter && y1 >= bb.maxY - EPS;\n        const fL = quarter && x0 <= bb.minX + EPS, fR = quarter && x1 >= bb.maxX - EPS;\n        // Grey body, reaching through the band on a flush side.\n        const X0 = fL ? x0 - T : x0, X1 = fR ? x1 + T : x1, Y0 = fT ? y0 - T : y0, Y1 = fB ? y1 + T : y1;\n        out += `<rect x=\"${r(X0)}\" y=\"${r(Y0)}\" width=\"${r(X1 - X0)}\" height=\"${r(Y1 - Y0)}\" fill=\"${BAND}\"${rotAttr}/>`;\n        // Its hollow middle, open to the outside on a flush side.\n        const iw = w - 2 * T, id2 = d - 2 * T;\n        if (iw > 0 && id2 > 0) {\n          const ix0 = fL ? x0 - T - lw : x0 + T, ix1 = fR ? x1 + T + lw : x1 - T;\n          const iy0 = fT ? y0 - T - lw : y0 + T, iy1 = fB ? y1 + T + lw : y1 - T;\n          out += `<rect x=\"${r(ix0)}\" y=\"${r(iy0)}\" width=\"${r(ix1 - ix0)}\" height=\"${r(iy1 - iy0)}\" fill=\"${BG}\"${rotAttr}/>`;\n          const L = (ax, ay, bx, by) => `<line x1=\"${r(ax)}\" y1=\"${r(ay)}\" x2=\"${r(bx)}\" y2=\"${r(by)}\" stroke=\"${EDGE}\" stroke-width=\"${r(lw)}\" stroke-linecap=\"square\"${rotAttr}/>`;\n          // inner lines on the sides that stay closed\n          if (!fT) out += L(ix0, y0 + T, ix1, y0 + T);\n          if (!fB) out += L(ix0, y1 - T, ix1, y1 - T);\n          if (!fL) out += L(x0 + T, iy0, x0 + T, iy1);\n          if (!fR) out += L(x1 - T, iy0, x1 - T, iy1);\n        }\n        // outer lines on the sides that face the room\n        const L2 = (ax, ay, bx, by) => `<line x1=\"${r(ax)}\" y1=\"${r(ay)}\" x2=\"${r(bx)}\" y2=\"${r(by)}\" stroke=\"${EDGE}\" stroke-width=\"${r(lw)}\" stroke-linecap=\"square\"${rotAttr}/>`;\n        if (!fT) out += L2(X0, y0, X1, y0);\n        if (!fB) out += L2(X0, y1, X1, y1);\n        if (!fL) out += L2(x0, Y0, x0, Y1);\n        if (!fR) out += L2(x1, Y0, x1, Y1);\n      } else if (it.type === 'cooker-alcove') {\n        const lc = it.leftColumnMm || 0, rcw = it.rightColumnMm || 0;\n        out += `<g${rotAttr}>` +\n          `<rect x=\"${r(x0)}\" y=\"${r(y0)}\" width=\"${r(w)}\" height=\"${r(d)}\" fill=\"#fff\" stroke=\"#b5b5b5\" stroke-width=\"${r(lw * 0.8)}\"/>` +\n          (lc > 0 ? `<rect x=\"${r(x0)}\" y=\"${r(y0)}\" width=\"${r(lc)}\" height=\"${r(d)}\" fill=\"#ebebeb\"/>` : '') +\n          (rcw > 0 ? `<rect x=\"${r(x1 - rcw)}\" y=\"${r(y0)}\" width=\"${r(rcw)}\" height=\"${r(d)}\" fill=\"#ebebeb\"/>` : '') +\n          `<text x=\"${r(icx)}\" y=\"${r(icy)}\" text-anchor=\"middle\" dominant-baseline=\"central\" fill=\"#999\" font-family=\"sans-serif\" font-size=\"${r(Math.min(d * 0.45, span * 0.035))}\" letter-spacing=\"${r(span * 0.002)}\">Alcove</text>` +\n          `</g>`;\n      } else if (it.type === 'free-block') {\n        out += `<rect x=\"${r(x0)}\" y=\"${r(y0)}\" width=\"${r(w)}\" height=\"${r(d)}\" fill=\"#e6e6e6\" stroke=\"${EDGE}\" stroke-width=\"${r(lw * 0.8)}\"${rotAttr}/>`;\n      }\n    }\n\n    // Doors and windows, on the walls of the outline.\n    const walls = getWalls(rm);\n    for (const op of (rc.wallOpenings || [])) {\n      const wl = walls[op.wallIndex];\n      if (!wl || !wl.lengthMm || op.floating) continue;\n      const ux = (wl.to.x - wl.from.x) / wl.lengthMm, uy = (wl.to.y - wl.from.y) / wl.lengthMm;\n      let nx = -uy, ny = ux;                          // inward: towards the room's middle\n      const off = Math.max(0, op.offsetMm || 0), len = Math.max(0, op.widthMm || 0);\n      const ax = wl.from.x + ux * off, ay = wl.from.y + uy * off;\n      if ((cx - ax) * nx + (cy - ay) * ny < 0) { nx = -nx; ny = -ny; }\n      const bx = ax + ux * len, by = ay + uy * len;\n      // the stretch of wall band the opening occupies (outward by T)\n      const quad = (sx, sy, ex, ey, depth) => { const q = depth || T; return `${r(sx)},${r(sy)} ${r(ex)},${r(ey)} ${r(ex - nx * q)},${r(ey - ny * q)} ${r(sx - nx * q)},${r(sy - ny * q)}`; };\n      if (op.type === 'door') {\n        // the gap goes clean through, past the band's outer edge line too\n        out += `<polygon points=\"${quad(ax, ay, bx, by, T + lw * 2)}\" fill=\"${BG}\" stroke=\"${BG}\" stroke-width=\"${r(lw * 1.2)}\"/>`;\n        // and the floor's edge line across the doorway goes too\n        out += `<line x1=\"${r(ax + nx * lw * 0.4)}\" y1=\"${r(ay + ny * lw * 0.4)}\" x2=\"${r(bx + nx * lw * 0.4)}\" y2=\"${r(by + ny * lw * 0.4)}\" stroke=\"#fff\" stroke-width=\"${r(lw * 1.6)}\"/>`;\n        const J = Math.min(30, len / 4);\n        out += `<polygon points=\"${quad(ax, ay, ax + ux * J, ay + uy * J)}\" fill=\"#c8c8c8\" stroke=\"${EDGE}\" stroke-width=\"${r(lw * 0.6)}\"/>`;\n        out += `<polygon points=\"${quad(bx - ux * J, by - uy * J, bx, by)}\" fill=\"#c8c8c8\" stroke=\"${EDGE}\" stroke-width=\"${r(lw * 0.6)}\"/>`;\n        const hingeAtEnd = op.hingeEnd === 'end';\n        const hx = hingeAtEnd ? bx : ax, hy = hingeAtEnd ? by : ay;       // hinge\n        const ox = hingeAtEnd ? ax : bx, oy = hingeAtEnd ? ay : by;       // closing jamb\n        const s = op.swing === 'out' ? -1 : 1;\n        const tx = hx + nx * len * s, ty = hy + ny * len * s;             // open leaf tip\n        const cross = (tx - hx) * (oy - hy) - (ty - hy) * (ox - hx);\n        out += `<line x1=\"${r(hx)}\" y1=\"${r(hy)}\" x2=\"${r(tx)}\" y2=\"${r(ty)}\" stroke=\"#444\" stroke-width=\"${r(lw)}\"/>`;\n        out += `<path d=\"M ${r(tx)} ${r(ty)} A ${r(len)} ${r(len)} 0 0 ${cross > 0 ? 1 : 0} ${r(ox)} ${r(oy)}\" fill=\"none\" stroke=\"#888\" stroke-width=\"${r(lw * 0.7)}\" stroke-dasharray=\"${r(lw * 3)} ${r(lw * 2)}\"/>`;\n      } else {\n        out += `<polygon points=\"${quad(ax, ay, bx, by)}\" fill=\"#fff\" stroke=\"${EDGE}\" stroke-width=\"${r(lw * 0.7)}\"/>`;\n        const mx = -nx * T / 2, my = -ny * T / 2;\n        out += `<line x1=\"${r(ax + mx)}\" y1=\"${r(ay + my)}\" x2=\"${r(bx + mx)}\" y2=\"${r(by + my)}\" stroke=\"#2a7fff\" stroke-width=\"${r(lw * 1.4)}\"/>`;\n      }\n    }\n\n    const minor = r(Math.max(4, span * 0.0012)), major = r(Math.max(6, span * 0.002));\n    const defs = `<defs>` +\n      `<pattern id=\"${id}m\" width=\"100\" height=\"100\" patternUnits=\"userSpaceOnUse\" x=\"${r(bb.minX)}\" y=\"${r(bb.minY)}\">` +\n        `<path d=\"M 100 0 L 0 0 0 100\" fill=\"none\" stroke=\"#efefef\" stroke-width=\"${minor}\"/></pattern>` +\n      `<pattern id=\"${id}g\" width=\"1000\" height=\"1000\" patternUnits=\"userSpaceOnUse\" x=\"${r(bb.minX)}\" y=\"${r(bb.minY)}\">` +\n        `<rect width=\"1000\" height=\"1000\" fill=\"url(#${id}m)\"/>` +\n        `<path d=\"M 1000 0 L 0 0 0 1000\" fill=\"none\" stroke=\"#dfdfdf\" stroke-width=\"${major}\"/></pattern>` +\n      `</defs>`;\n    return `<svg viewBox=\"${vb}\" xmlns=\"http://www.w3.org/2000/svg\" aria-hidden=\"true\" preserveAspectRatio=\"xMidYMid meet\">` +\n           defs + out + `</svg>`;\n  }\n  // The same room in several plans (versions, copies) is one choice: keyed on\n  // the outline and its openings, the newest plan's name kept.\n  function roomKey(rc) {\n    try {\n      const rm = buildRoomPolygon(rc);\n      const v = (rm.vertices || []).map(p => [Math.round(p.x), Math.round(p.y)]);\n      const o = (rc.wallOpenings || []).map(op => [op.type, op.wallIndex, Math.round(op.offsetMm || 0), Math.round(op.widthMm || 0)]);\n      return JSON.stringify([v, o]);\n    } catch (e) { return null; }\n  }\n  async function openPreviousRoomPicker(mode) {\n    prevRoomMode = mode === 'apply' ? 'apply' : 'new';\n    if (!prevRoomPopupEl || !prevRoomGridEl) {\n      if (prevRoomMode === 'new') openJourneyNamePopup({ mode: 'room', room: previousPlanRoom });\n      return;\n    }\n    prevRoomGridEl.innerHTML = '<p class=\"btk-kp-popup-empty\">Loading your rooms...</p>';\n    prevRoomPopupEl.hidden = false;\n    let plans = [];\n    try { plans = await planStore.listPlans(); } catch (e) { /* none */ }\n    const seen = new Set();\n    prevRoomChoices = [];\n    for (const p of plans) {                 // newest first\n      if (!p.roomConfig) continue;\n      const k = roomKey(p.roomConfig);\n      if (!k || seen.has(k)) continue;\n      seen.add(k);\n      prevRoomChoices.push({ name: p.name, roomConfig: p.roomConfig });\n    }\n    if (!prevRoomChoices.length) {\n      prevRoomGridEl.innerHTML = '<p class=\"btk-kp-popup-empty\">None of your saved plans has a room yet.</p>';\n      return;\n    }\n    prevRoomGridEl.innerHTML = prevRoomChoices.map((c, i) => `\n      <button type=\"button\" class=\"btk-kp-rs-starter btk-kp-prevroom-card\" data-btk-kp-prevroom-pick=\"${i}\">\n        <span class=\"btk-kp-rs-starter-art\">${roomThumbSVG(c.roomConfig)}</span>\n        <span class=\"btk-kp-prevroom-name\">${jEsc(c.name)}</span>\n      </button>`).join('');\n  }\n  if (prevRoomPopupEl) {\n    prevRoomPopupEl.addEventListener('click', (e) => {\n      if (e.target.closest('[data-btk-kp-prevroom-close]')) { prevRoomPopupEl.hidden = true; return; }\n      const pick = e.target.closest('[data-btk-kp-prevroom-pick]');\n      if (!pick) return;\n      const c = prevRoomChoices[parseInt(pick.dataset.btkKpPrevroomPick, 10)];\n      if (!c) return;\n      prevRoomPopupEl.hidden = true;\n      if (prevRoomMode === 'apply') {\n        handleUseExistingRoom(c.roomConfig);\n        const rsPopup = root.querySelector('[data-btk-kp-popup=\"room-shape\"]');\n        if (rsPopup) rsPopup.hidden = true;\n        return;\n      }\n      openJourneyNamePopup({ mode: 'room', room: JSON.parse(JSON.stringify(c.roomConfig)) });\n    });\n  }\n\n  // Shared green icon-button markup (check + label + chevron), matching the\n  // Select buttons used elsewhere in the planner.\n  const J_ICON_CHECK   = '<svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><polyline points=\"20 6 9 17 4 12\"/></svg>';\n  const J_ICON_CHEVRON = '<svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M9 18l6-6-6-6\"/></svg>';\n  const jGreenBtn = (label, attrs, extraClass) =>\n    `<button type=\"button\" class=\"btk-kp-action-btn btk-kp-action-btn--green btk-kp-action-btn--sm${extraClass ? ' ' + extraClass : ''}\" ${attrs}>` +\n      `<span class=\"btk-kp-action-btn-icon\" aria-hidden=\"true\">${J_ICON_CHECK}</span>` +\n      `<span class=\"btk-kp-action-btn-label\">${label}</span>` +\n      `<span class=\"btk-kp-action-btn-arrow\" aria-hidden=\"true\">${J_ICON_CHEVRON}</span>` +\n    `</button>`;\n\n  // Mirrors the \"Change Colours\" modal's card (see btk-kitchen-planner-ui-cabinets.js):\n  // hero image + colour name that update when a swatch is clicked, swatches\n  // clamped to two rows with a +N expander, and a Select button.\n  const J_SWATCH_CLAMP = 10;   // 5-col swatch grid \u2192 2 full rows = 10 cells\n  function jBuildStyleCard(style, selectLabel) {\n    const styleId = style.id;\n    // An F&B range is painted in a colour the customer names: its card offers\n    // no swatches (the range's one \"Farrow & Ball Colour\" is not a colour to\n    // pick), and its green button chooses the paint (Arden, 2026-10-10).\n    const bespoke = !!(Catalogue.isBespokePaintStyle && Catalogue.isBespokePaintStyle(styleId));\n    const colours = bespoke ? [] : ((Catalogue.getDoorColoursForStyle && Catalogue.getDoorColoursForStyle(styleId)) || []);\n    const activeDoor = (colours[0] && colours[0].handle) || null;\n    // An F&B card keeps its photo: the range's own colour's.\n    const heroDoor = bespoke\n      ? ((((Catalogue.getDoorColoursForStyle && Catalogue.getDoorColoursForStyle(styleId)) || []).find(c => !c.bespoke)) || {}).handle || null\n      : activeDoor;\n    const heroImg = heroDoor && Catalogue.getHeroPreviewUrl ? (Catalogue.getHeroPreviewUrl(styleId, heroDoor) || '') : '';\n    const activeColourName = bespoke ? 'Any Farrow & Ball or RAL colour'\n      : ((colours.find(c => c.handle === activeDoor) || {}).name || '');\n    const overflowing  = colours.length > J_SWATCH_CLAMP;\n    const visibleCount = overflowing ? (J_SWATCH_CLAMP - 1) : colours.length;\n    const overflowN    = overflowing ? colours.length - visibleCount : 0;\n    const swItem = (c, hidden) => `\n      <div class=\"btk-kp-style-card-swatch-item${hidden ? ' is-hidden' : ''}\">\n        <button type=\"button\" class=\"btk-kp-style-card-swatch ${c.handle === activeDoor ? 'is-active' : ''}\"\n                data-btk-kp-card-swatch=\"${jEsc(c.handle)}\" data-btk-kp-card-swatch-name=\"${jEsc(c.name || c.handle)}\"\n                title=\"${jEsc(c.name || c.handle)}\" style=\"${jSwatch(c)}\"></button>\n        <span class=\"btk-kp-style-card-swatch-name\">${jEsc(c.name || c.handle)}</span>\n      </div>`;\n    // Two faces on a sliding track: pick door colour, then \"Confirm & Select\n    // Carcase\" slides to the carcase picker (carcase is exclusive to the\n    // style+colour), then \"Add to Plan\" adds the full buying style.\n    return `\n      <article class=\"btk-kp-style-card\" data-btk-kp-card-style=\"${jEsc(styleId)}\" data-face=\"door\">\n        <div class=\"btk-kp-style-card-track\">\n          <div class=\"btk-kp-style-card-face btk-kp-style-card-face--door\">\n            <div class=\"btk-kp-style-card-image\">\n              <img class=\"btk-kp-style-card-hero\" data-btk-kp-card-hero src=\"${heroImg}\" alt=\"\" ${heroImg ? '' : 'hidden'}>\n            </div>\n            <div class=\"btk-kp-style-card-meta\">\n              <div class=\"btk-kp-style-card-title\">${jEsc(style.name || styleId)}</div>\n              <div class=\"btk-kp-style-card-colour\" data-btk-kp-card-colour-name>${jEsc(activeColourName)}</div>\n            </div>\n            <div class=\"btk-kp-style-card-swatches\">\n              ${colours.slice(0, visibleCount).map(c => swItem(c, false)).join('')}\n              ${overflowing ? `<button type=\"button\" class=\"btk-kp-style-card-more\" data-btk-kp-card-more aria-label=\"Show all colours\">+${overflowN}</button>` : ''}\n              ${colours.slice(visibleCount).map(c => swItem(c, true)).join('')}\n            </div>\n            <div class=\"btk-kp-style-card-actions\">\n              ${bespoke\n                ? jGreenBtn('Choose Custom Colour', 'data-btk-kp-card-paint', 'btk-kp-style-card-select')\n                : jGreenBtn('Confirm &amp; Select Carcase', 'data-btk-kp-card-tocarcase', 'btk-kp-style-card-select')}\n            </div>\n          </div>\n          <div class=\"btk-kp-style-card-face btk-kp-style-card-face--carcase\">\n            <!-- Two columns on the carcase step (is-carcase-focus): the picture and a\n                 card of the choices on the left, the carcase colours on the right.\n                 On a card in the list the columns fall away (display: contents). -->\n            <div class=\"btk-kp-cf-left\">\n              <div class=\"btk-kp-style-card-carcase-preview\" data-btk-kp-card-overlay></div>\n              <div class=\"btk-kp-cf-info\">\n                <div class=\"btk-kp-style-card-meta btk-kp-style-card-focus-meta\">\n                  <div class=\"btk-kp-style-card-title\">${jEsc(style.name || styleId)}</div>\n                  <div class=\"btk-kp-cf-label\">Door colour</div>\n                  <div class=\"btk-kp-style-card-colour\" data-btk-kp-card-focus-door></div>\n                </div>\n                <div class=\"btk-kp-style-card-meta btk-kp-cf-carcase-meta\">\n                  <div class=\"btk-kp-style-card-title\">Carcase colour</div>\n                  <div class=\"btk-kp-style-card-colour\" data-btk-kp-card-carcase-name></div>\n                </div>\n              </div>\n            </div>\n            <div class=\"btk-kp-cf-right\">\n              <h3 class=\"btk-kp-cf-title\">Choose a Carcase Colour</h3>\n              <div class=\"btk-kp-style-card-carcases\" data-btk-kp-card-carcases></div>\n              <div class=\"btk-kp-style-card-actions btk-kp-style-card-actions--carcase\">\n                <button type=\"button\" class=\"btk-kp-style-card-back\" data-btk-kp-card-back aria-label=\"Back to colour\">&larr; Colour</button>\n                ${jGreenBtn(selectLabel || 'Add to Plan', 'data-btk-kp-card-select', 'btk-kp-style-card-select')}\n              </div>\n            </div>\n          </div>\n        </div>\n      </article>`;\n  }\n\n  // Carcase tile + door/carcase overlay for the style card's second face.\n  function jCardCarcaseTile(c, family, active) {\n    const url = family && Catalogue.getCarcasePreviewUrl ? (Catalogue.getCarcasePreviewUrl(family, c.handle) || '') : '';\n    return `<button type=\"button\" class=\"btk-kp-carcase-tile${active ? ' is-active' : ''}\"\n              data-btk-kp-card-carcase=\"${jEsc(c.handle)}\" data-btk-kp-card-carcase-name=\"${jEsc(c.name || c.handle)}\">\n        <div class=\"btk-kp-carcase-tile-img\" style=\"${url ? '' : jSwatch(c)}\">${url ? `<img src=\"${url}\" alt=\"\">` : ''}</div>\n        <div class=\"btk-kp-carcase-tile-name\">${jEsc(c.name || c.handle)}</div>\n      </button>`;\n  }\n  function jCardOverlayHtml(styleId, doorHandle, family, carcaseHandle) {\n    const { doorImg, carcaseImg } = unitPicture(styleId, doorHandle, carcaseHandle,\n      doorHandle && Catalogue.getDoorPreviewUrl ? (Catalogue.getDoorPreviewUrl(styleId, doorHandle) || '') : '',\n      family && carcaseHandle && Catalogue.getCarcasePreviewUrl ? (Catalogue.getCarcasePreviewUrl(family, carcaseHandle) || '') : '');\n    const inner = (carcaseImg ? `<img class=\"btk-kp-journey-preview-carcase\" src=\"${carcaseImg}\" alt=\"\">` : '')\n      + (doorImg ? `<img class=\"btk-kp-journey-preview-door\" src=\"${doorImg}\" alt=\"\">` : '')\n      + ((!carcaseImg && !doorImg) ? '<span class=\"btk-kp-journey-preview-empty\">Preview</span>' : '');\n    return `<div class=\"btk-kp-journey-preview\">${inner}</div>`;\n  }\n  // Populate a style card's carcase face (tiles + overlay), defaulting to the\n  // first carcase. Lazy - the face is empty until the user flips to it.\n  function renderCardCarcase(card, styleId, doorHandle) {\n    const ks      = Catalogue.getKitchenStyle && Catalogue.getKitchenStyle(styleId);\n    const family  = ks && ks.carcaseFamilyHandle;\n    const colours = (Catalogue.getCarcaseColoursForStyle && Catalogue.getCarcaseColoursForStyle(styleId)) || [];\n    const carcasesEl = card.querySelector('[data-btk-kp-card-carcases]');\n    const overlayEl  = card.querySelector('[data-btk-kp-card-overlay]');\n    const nameEl     = card.querySelector('[data-btk-kp-card-carcase-name]');\n    const first = colours[0] || null;\n    if (carcasesEl) carcasesEl.innerHTML = colours.map((c, i) => jCardCarcaseTile(c, family, i === 0)).join('') || '<p class=\"btk-kp-home-lead\">No carcase options for this style.</p>';\n    if (overlayEl)  overlayEl.innerHTML  = jCardOverlayHtml(styleId, doorHandle, family, first ? first.handle : null);\n    if (nameEl)     nameEl.textContent   = first ? (first.name || first.handle) : '';\n  }\n\n  // The two-faced kitchen-style card (door colours, then the carcase) is\n  // shared by the journey's style list and the Customise > Door & Carcase\n  // popup, so both behave the same. Handles every click inside a card list -\n  // the filter pills, a swatch, +N more, the flip to the carcase face, a\n  // carcase tile and Back - and hands the card's green button to onSelect.\n  // Returns true when it handled the click.\n  // The CARCASE step takes over the whole list (Arden, 2026-10-10): the other\n  // ranges, the filter pills and the card's own colour face go, and the chosen\n  // range's carcase choice fills the space - instead of one card sliding over\n  // with every other range still beside it. Back brings the list back.\n  function styleCardFocus(card, on) {\n    if (!card) return;\n    const host = card.closest('[data-btk-kp-style-cards]');\n    if (host) host.classList.toggle('is-carcase-step', !!on);\n    card.classList.toggle('is-carcase-focus', !!on);\n    if (on) {\n      // The door colour chosen on the first step, beside the range's name.\n      const door = card.querySelector('[data-btk-kp-card-focus-door]');\n      const picked = card.querySelector('[data-btk-kp-card-colour-name]');\n      if (door) door.textContent = picked ? picked.textContent : '';\n      const body = card.closest('.btk-kp-popup-body') || card.closest('[data-btk-kp-journey-styles]');\n      if (body) body.scrollTop = 0;\n    }\n  }\n  function handleStyleCardClick(e, onSelect) {\n    const host = e.target.closest('[data-btk-kp-journey-styles], [data-btk-kp-style-cards]') || journeyEl;\n    // Filter pills - show/hide cards by the style's filterGroupKeys.\n    const pill = e.target.closest('[data-btk-kp-journey-pill]');\n    if (pill) {\n      const filter = pill.dataset.btkKpJourneyPill || null;\n      host.querySelectorAll('[data-btk-kp-journey-pill]').forEach(p => p.classList.toggle('is-active', p === pill));\n      applyStyleCardFilters(host);\n      return true;\n    }\n    // Swatch click \u2192 swap this card's hero image + colour name (preview only).\n    const sw = e.target.closest('[data-btk-kp-card-swatch]');\n    if (sw) {\n      const card    = sw.closest('[data-btk-kp-card-style]');\n      const styleId = card.dataset.btkKpCardStyle;\n      const handle  = sw.dataset.btkKpCardSwatch;\n      const hero    = card.querySelector('[data-btk-kp-card-hero]');\n      const heroUrl = Catalogue.getHeroPreviewUrl ? (Catalogue.getHeroPreviewUrl(styleId, handle) || '') : '';\n      if (hero) { if (heroUrl) { hero.src = heroUrl; hero.hidden = false; } else { hero.hidden = true; } }\n      card.querySelectorAll('[data-btk-kp-card-swatch]').forEach(b => b.classList.remove('is-active'));\n      sw.classList.add('is-active');\n      const nameEl = card.querySelector('[data-btk-kp-card-colour-name]');\n      if (nameEl) nameEl.textContent = sw.dataset.btkKpCardSwatchName || '';\n      return true;\n    }\n    // An F&B range: the green button chooses the paint (F&B or RAL), and the\n    // card moves on with it as the door colour - to its carcase, or, with the\n    // one carcase the range comes in, straight to its green button's job\n    // (Use as Active Style: Add Units follows) (Arden, 2026-10-10).\n    const paintBtn = e.target.closest('[data-btk-kp-card-paint]');\n    if (paintBtn) {\n      const card = paintBtn.closest('[data-btk-kp-card-style]');\n      const styleId = card.dataset.btkKpCardStyle;\n      openPaintPicker({ styleId, current: card.dataset.cardDoor || null, onPick: (entry) => {\n        card.dataset.cardDoor = entry.handle;\n        const nameEl = card.querySelector('[data-btk-kp-card-colour-name]');\n        if (nameEl) nameEl.textContent = entry.name || '';\n        renderCardCarcase(card, styleId, entry.handle);\n        const tiles = card.querySelectorAll('[data-btk-kp-card-carcase]');\n        if (tiles.length === 1 && onSelect) {\n          onSelect(styleId, entry.handle, tiles[0].dataset.btkKpCardCarcase, card);\n          return;\n        }\n        card.dataset.face = 'carcase';\n        styleCardFocus(card, true);\n      } });\n      return true;\n    }\n    // +N more \u2192 reveal the clamped swatches in place.\n    const moreBtn = e.target.closest('[data-btk-kp-card-more]');\n    if (moreBtn) {\n      const card = moreBtn.closest('[data-btk-kp-card-style]');\n      card.querySelectorAll('.btk-kp-style-card-swatch-item.is-hidden').forEach(it => it.classList.remove('is-hidden'));\n      moreBtn.remove();\n      return true;\n    }\n    // \"Confirm & Select Carcase\" \u2192 remember the chosen door, populate the\n    // card's carcase face and slide to it.\n    const toCarcase = e.target.closest('[data-btk-kp-card-tocarcase]');\n    if (toCarcase) {\n      const card = toCarcase.closest('[data-btk-kp-card-style]');\n      const styleId = card.dataset.btkKpCardStyle;\n      const activeSw = card.querySelector('[data-btk-kp-card-swatch].is-active') || card.querySelector('[data-btk-kp-card-swatch]');\n      const doorHandle = activeSw ? activeSw.dataset.btkKpCardSwatch : null;\n      card.dataset.cardDoor = doorHandle || '';\n      renderCardCarcase(card, styleId, doorHandle);\n      card.dataset.face = 'carcase';\n      styleCardFocus(card, true);\n      return true;\n    }\n    // Carcase tile on the card \u2192 select it + refresh the overlay preview.\n    const cardCarc = e.target.closest('[data-btk-kp-card-carcase]');\n    if (cardCarc) {\n      const card = cardCarc.closest('[data-btk-kp-card-style]');\n      const styleId = card.dataset.btkKpCardStyle;\n      const ks = Catalogue.getKitchenStyle && Catalogue.getKitchenStyle(styleId);\n      const family = ks && ks.carcaseFamilyHandle;\n      card.querySelectorAll('[data-btk-kp-card-carcase]').forEach(t => t.classList.toggle('is-active', t === cardCarc));\n      const overlayEl = card.querySelector('[data-btk-kp-card-overlay]');\n      if (overlayEl) overlayEl.innerHTML = jCardOverlayHtml(styleId, card.dataset.cardDoor || null, family, cardCarc.dataset.btkKpCardCarcase);\n      const nameEl = card.querySelector('[data-btk-kp-card-carcase-name]');\n      if (nameEl) nameEl.textContent = cardCarc.dataset.btkKpCardCarcaseName || '';\n      return true;\n    }\n    // Back \u2192 slide the card back to the colour face.\n    const cardBack = e.target.closest('[data-btk-kp-card-back]');\n    if (cardBack) {\n      const card = cardBack.closest('[data-btk-kp-card-style]');\n      card.dataset.face = 'door';\n      styleCardFocus(card, false);\n      return;\n    }\n    // \"Add to Plan\" \u2192 add this style + door + chosen carcase as a buying\n    // style (up to 3). Doesn't advance; the user confirms below.\n    const selBtn = e.target.closest('[data-btk-kp-card-select]');\n    if (selBtn) {\n      const card = selBtn.closest('[data-btk-kp-card-style]');\n      const styleId = card.dataset.btkKpCardStyle;\n      const doorHandle = card.dataset.cardDoor || null;\n      const carcTile = card.querySelector('[data-btk-kp-card-carcase].is-active') || card.querySelector('[data-btk-kp-card-carcase]');\n      const carcaseHandle = carcTile ? carcTile.dataset.btkKpCardCarcase : null;\n      if (onSelect) onSelect(styleId, doorHandle, carcaseHandle, card);\n      return true;\n    }\n    return false;\n  }\n\n  // The journey's own use of the card: the style joins the plan's buying\n  // styles (up to three).\n  function journeyAddStyleCard(styleId, doorHandle, carcaseHandle, card) {\n    if (buyingStyles.length >= J_STYLE_MAX) return;\n    // Skip an exact duplicate (same style + door + carcase).\n    if (!buyingStyles.some(st => st.styleId === styleId && st.doorHandle === doorHandle && st.carcaseHandle === carcaseHandle)) {\n      buyingStyles.push({ styleId, doorHandle, carcaseHandle });\n    }\n    card.dataset.face = 'door';   // reset for next use\n    closeStylePicker();           // style saved \u2192 collapse the list\n    renderJourneyStyleSlots();\n    updateStyleConfirmState();\n    updateJourneyNav('style');    // refresh the left-menu tick + count\n  }\n\n  // Draw the kitchen-style list (filter pills + cards) into any container and\n  // wire it up once. `onSelect` gets the style, door and carcase the customer\n  // built on the card.\n  // ---- Paint picker popup (F&B ranges' style cards) -----------------------\n  // Farrow & Ball or RAL, a search, and the palette as swatches - the same\n  // picker Door & Carcase shows for an F&B range (ui-style-colours), here as a\n  // popup over the style cards. Picking registers the paint as a door colour\n  // (Catalogue.registerBespokePaint) and hands it back (Arden, 2026-10-10).\n  const PAINT_SOURCES = [\n    { kind: 'fab', label: 'Farrow & Ball', asset: 'farrowBallJson' },\n    { kind: 'ral', label: 'RAL',           asset: 'ralJson' }\n  ];\n  const paintPal = { fab: null, ral: null };   // null = loading; [] = failed\n  let paintPalLoad = null;\n  function loadPaintPalettes() {\n    if (!paintPalLoad) paintPalLoad = Promise.all(PAINT_SOURCES.map(async (src) => {\n      try {\n        const url = window.BTK_KP_ASSETS && window.BTK_KP_ASSETS[src.asset];\n        if (!url) throw new Error('no URL');\n        const j = await (await fetch(url)).json();\n        paintPal[src.kind] = Array.isArray(j && j.groups) ? j.groups : [];\n      } catch (_) { paintPal[src.kind] = []; }\n    }));\n    return paintPalLoad;\n  }\n  const paintPick = { kind: 'fab', query: '', styleId: null, current: null, onPick: null };\n  let paintPopupEl = null;\n  function paintGridHTML() {\n    const groups = paintPal[paintPick.kind];\n    if (groups == null) return '<p class=\"btk-kp-cabinets-products-desc\">Loading colours\u2026</p>';\n    if (!groups.length) return '<p class=\"btk-kp-cabinets-products-desc\">The colour list could not be loaded. Refresh the page to try again.</p>';\n    const q = paintPick.query.trim().toLowerCase().replace(/^ral\\s*/, '');\n    const out = [];\n    const paintKindIsFab = paintPick.kind === 'fab';\n    const own = paintKindIsFab && Catalogue.getOwnPaints ? Catalogue.getOwnPaints() : [];\n    if (own.length && !q) out.push(`<div class=\"btk-kp-paint-group\">\n          <div class=\"btk-kp-paint-group-title\">Your colours</div>\n          <div class=\"btk-kp-style-card-swatches btk-kp-dc-swatches\">${own.map(c => {\n            const on = Catalogue.bespokePaintHandle && Catalogue.bespokePaintHandle('fab', c.code) === paintPick.current;\n            const label = c.name + (/^own-/.test(c.code) ? '' : ' No.' + c.code);\n            return `<span class=\"btk-kp-style-card-swatch-item\">\n                <button type=\"button\" class=\"btk-kp-style-card-swatch${on ? ' is-active' : ''}\" data-btk-kp-paint-pick=\"${jEsc('fab|' + c.code)}\"\n                        title=\"${jEsc(label)}\" aria-pressed=\"${!!on}\" style=\"background-color:${jEsc(c.hex)}\"></button>\n                <span class=\"btk-kp-style-card-swatch-name\">${jEsc(label)}</span>\n              </span>`;\n          }).join('')}</div>\n        </div>`);\n    for (const g of groups) {\n      const cols = (g.colours || []).filter(c => !q\n        || String(c.name || '').toLowerCase().includes(q) || String(c.number || '').toLowerCase().includes(q));\n      if (!cols.length) continue;\n      out.push(`<div class=\"btk-kp-paint-group\">\n          <div class=\"btk-kp-paint-group-title\">${jEsc(g.name)}</div>\n          <div class=\"btk-kp-style-card-swatches btk-kp-dc-swatches\">${cols.map(c => {\n            const h = Catalogue.bespokePaintHandle ? Catalogue.bespokePaintHandle(paintPick.kind, c.number) : '';\n            const on = h && h === paintPick.current;\n            const label = paintPick.kind === 'fab' ? `${c.name} No.${c.number}` : `RAL ${c.number} ${c.name}`;\n            return `<span class=\"btk-kp-style-card-swatch-item\">\n                <button type=\"button\" class=\"btk-kp-style-card-swatch${on ? ' is-active' : ''}\" data-btk-kp-paint-pick=\"${jEsc(paintPick.kind + '|' + c.number)}\"\n                        title=\"${jEsc(label)}\" aria-pressed=\"${!!on}\" style=\"background-color:${jEsc(c.hex)}\"></button>\n                <span class=\"btk-kp-style-card-swatch-name\">${jEsc(label)}</span>\n              </span>`;\n          }).join('')}</div>\n        </div>`);\n    }\n    return out.length ? out.join('') : '<p class=\"btk-kp-cabinets-products-desc\">No colours match that search.</p>';\n  }\n  function renderPaintPopup() {\n    const body = paintPopupEl && paintPopupEl.querySelector('[data-btk-kp-paint-body]');\n    if (!body) return;\n    body.innerHTML = `\n      <p class=\"btk-kp-cabinets-products-desc\">This range is painted in the colour you choose: any Farrow &amp; Ball colour, or a RAL colour.</p>\n      <div class=\"btk-kp-seg-toggle btk-kp-seg-toggle--dark btk-kp-seg-toggle--equal btk-kp-paint-tabs\" role=\"group\" aria-label=\"Paint colours\">\n        ${PAINT_SOURCES.map(k => `<button type=\"button\" class=\"btk-kp-seg-toggle-btn ${paintPick.kind === k.kind ? 'is-active' : ''}\" data-btk-kp-paint-src=\"${k.kind}\">${jEsc(k.label)}</button>`).join('')}\n      </div>\n      <input type=\"search\" class=\"btk-kp-paint-search\" data-btk-kp-paint-q value=\"${jEsc(paintPick.query)}\"\n             placeholder=\"${paintPick.kind === 'fab' ? 'Search by name or number, e.g. Hague Blue or 30' : 'Search by RAL number or name, e.g. 7016'}\"\n             aria-label=\"Search paint colours\" autocomplete=\"off\" spellcheck=\"false\">\n      <div class=\"btk-kp-paint-grid\" data-btk-kp-paint-list>${paintGridHTML()}</div>${paintPick.kind === 'fab' ? `\n      <div class=\"btk-kp-paint-own\" data-btk-kp-paint-own>\n        <div class=\"btk-kp-paint-group-title\">Add your own Farrow &amp; Ball colour</div>\n        <p class=\"btk-kp-cabinets-products-desc\">Not in the list? Enter its name and number, and pick a colour close to it to show it on your plan.</p>\n        <div class=\"btk-kp-paint-own-row\">\n          <input type=\"text\" class=\"btk-kp-paint-own-name\" data-btk-kp-paint-own-name maxlength=\"80\" placeholder=\"Name, e.g. Deep Reddish Brown\" aria-label=\"Colour name\" autocomplete=\"off\" spellcheck=\"false\">\n          <input type=\"text\" class=\"btk-kp-paint-own-no\" data-btk-kp-paint-own-no maxlength=\"12\" placeholder=\"No., e.g. W101\" aria-label=\"Colour number\" autocomplete=\"off\" spellcheck=\"false\">\n          <input type=\"color\" class=\"btk-kp-paint-own-hex\" data-btk-kp-paint-own-hex value=\"#8c8c8c\" aria-label=\"Colour to show it in\" title=\"Colour to show it in\">\n          <button type=\"button\" class=\"btk-kp-action-btn btk-kp-action-btn--green btk-kp-action-btn--sm\" data-btk-kp-paint-own-add><span class=\"btk-kp-action-btn-label\">Add colour</span></button>\n        </div>\n        <p class=\"btk-kp-paint-own-msg\" data-btk-kp-paint-own-msg hidden></p>\n      </div>` : ''}`;\n  }\n  function paintPopup() {\n    if (paintPopupEl && document.body.contains(paintPopupEl)) return paintPopupEl;\n    const host = document.querySelector('.btk-kp-app') || document.body;\n    const el = document.createElement('div');\n    el.className = 'btk-kp-popup btk-kp-popup--wide btk-kp-paint-popup';\n    el.setAttribute('data-btk-kp-popup', 'paint-picker');\n    el.hidden = true;\n    el.innerHTML = `\n      <div class=\"btk-kp-popup-backdrop\" data-btk-kp-paint-close></div>\n      <div class=\"btk-kp-popup-panel\" role=\"dialog\" aria-labelledby=\"btk-kp-paint-title\">\n        <header class=\"btk-kp-popup-head\">\n          <h2 id=\"btk-kp-paint-title\">Choose Your Paint Colour</h2>\n          <button type=\"button\" class=\"btk-kp-popup-close\" data-btk-kp-paint-close aria-label=\"Close\">&times;</button>\n        </header>\n        <div class=\"btk-kp-popup-body\" data-btk-kp-paint-body></div>\n      </div>`;\n    el.addEventListener('click', (e) => {\n      if (e.target.closest('[data-btk-kp-paint-close]')) { el.hidden = true; return; }\n      const src = e.target.closest('[data-btk-kp-paint-src]');\n      if (src) { paintPick.kind = src.dataset.btkKpPaintSrc; paintPick.query = ''; renderPaintPopup(); return; }\n      const base = ((Catalogue.getDoorColoursForStyle && Catalogue.getDoorColoursForStyle(paintPick.styleId)) || []).find(x => !x.bespoke);\n      // Add your own Farrow & Ball colour (Catalogue.ownFabPaint).\n      const ownAdd = e.target.closest('[data-btk-kp-paint-own-add]');\n      let entry = null;\n      if (ownAdd) {\n        const box = ownAdd.closest('[data-btk-kp-paint-own]');\n        const val = sel => (box && box.querySelector(sel) || {}).value || '';\n        const p = Catalogue.ownFabPaint ? Catalogue.ownFabPaint({ name: val('[data-btk-kp-paint-own-name]'), number: val('[data-btk-kp-paint-own-no]'), hex: val('[data-btk-kp-paint-own-hex]') }, paintPal.fab) : null;\n        const msg = box && box.querySelector('[data-btk-kp-paint-own-msg]');\n        if (!p || p.error) { if (msg) { msg.textContent = (p && p.error) || 'That colour could not be added.'; msg.hidden = false; } return; }\n        entry = Catalogue.registerBespokePaint ? Catalogue.registerBespokePaint({ ...p, baseHandle: base && base.handle }) : null;\n      } else {\n        const pk = e.target.closest('[data-btk-kp-paint-pick]');\n        if (!pk) return;\n        const [kind, code] = pk.dataset.btkKpPaintPick.split('|');\n        let c = null;\n        for (const g of (paintPal[kind] || [])) { c = (g.colours || []).find(x => String(x.number) === String(code)); if (c) break; }\n        // Not in the list: one of the plan's own colours (Your colours).\n        const own = !c && kind === 'fab' && Catalogue.getOwnPaints ? Catalogue.getOwnPaints().find(p => String(p.code) === String(code)) : null;\n        entry = !Catalogue.registerBespokePaint ? null\n          : c ? Catalogue.registerBespokePaint({ kind, code, name: c.name, hex: c.hex, baseHandle: base && base.handle })\n          : own ? Catalogue.registerBespokePaint({ ...own, baseHandle: base && base.handle }) : null;\n      }\n      if (!entry) return;\n      paintPick.query = '';\n      el.hidden = true;\n      if (typeof paintPick.onPick === 'function') paintPick.onPick(entry);\n    });\n    el.addEventListener('input', (e) => {\n      const q = e.target.closest && e.target.closest('[data-btk-kp-paint-q]');\n      if (!q) return;\n      paintPick.query = q.value || '';\n      const list = el.querySelector('[data-btk-kp-paint-list]');\n      if (list) list.innerHTML = paintGridHTML();   // the grid only, so the search keeps its focus\n    });\n    host.appendChild(el);\n    paintPopupEl = el;\n    return el;\n  }\n  function openPaintPicker({ styleId, current, onPick }) {\n    Object.assign(paintPick, { styleId, current: current || null, onPick, query: '' });\n    const cur = Catalogue.getBespokePaint ? Catalogue.getBespokePaint(current) : null;\n    if (cur) paintPick.kind = cur.type;\n    const el = paintPopup();\n    renderPaintPopup();\n    el.hidden = false;\n    loadPaintPalettes().then(() => { if (!el.hidden) renderPaintPopup(); });\n  }\n\n  // The style list's two filters together (Arden, 2026-10-12): the group pill\n  // and the search typed in a popup's top bar (host._btkStyleQuery). Search\n  // matches the style's name, its groups (Shaker, J Pull...) and its door\n  // colours, every word typed, so \"shaker sage\" finds a Shaker style in Sage.\n  function applyStyleCardFilters(host) {\n    if (!host) return;\n    const pill = host.querySelector('[data-btk-kp-journey-pill].is-active');\n    const filter = (pill && pill.dataset.btkKpJourneyPill) || null;\n    const words = String(host._btkStyleQuery || '').toLowerCase().split(/\\s+/).filter(Boolean);\n    const groups = (Catalogue.getKitchenFilterGroups && Catalogue.getKitchenFilterGroups()) || [];\n    let shown = 0;\n    host.querySelectorAll('[data-btk-kp-card-style]').forEach(card => {\n      const id = card.dataset.btkKpCardStyle;\n      const ks = Catalogue.getKitchenStyle && Catalogue.getKitchenStyle(id);\n      const keys = (ks && ks.filterGroupKeys) || [];\n      let ok = !filter || keys.includes(filter);\n      if (ok && words.length) {\n        const hay = [ (ks && ks.name) || id,\n          ...groups.filter(g => keys.includes(g.key)).map(g => g.title),\n          ...((Catalogue.getDoorColoursForStyle && Catalogue.getDoorColoursForStyle(id)) || []).map(c => c.name || '')\n        ].join(' ').toLowerCase();\n        ok = words.every(w => hay.includes(w));\n      }\n      card.style.display = ok ? '' : 'none';\n      if (ok) shown++;\n    });\n    const empty = host.querySelector('[data-btk-kp-style-empty]');\n    if (empty) empty.hidden = shown > 0;\n  }\n\n  function renderStyleCardsInto(container, { selectLabel, onSelect } = {}) {\n    if (!container) return;\n    const styles = ((Catalogue.getKitchenStyles && Catalogue.getKitchenStyles()) || []).filter(st => st.doorGeometry);\n    const filterGroups = (Catalogue.getKitchenFilterGroups && Catalogue.getKitchenFilterGroups()) || [];\n    container.setAttribute('data-btk-kp-style-cards', '');\n    container.classList.remove('is-carcase-step');   // a fresh list starts on the styles\n    container.innerHTML = `\n      ${filterGroups.length ? `\n        <div class=\"btk-kp-styles-modal-pills\" role=\"group\" aria-label=\"Filter by style group\">\n          <button type=\"button\" class=\"btk-kp-styles-modal-pill is-active\" data-btk-kp-journey-pill=\"\">All</button>\n          ${filterGroups.map(g => `<button type=\"button\" class=\"btk-kp-styles-modal-pill\" data-btk-kp-journey-pill=\"${jEsc(g.key)}\">${jEsc(g.title)}</button>`).join('')}\n        </div>` : ''}\n      <div class=\"btk-kp-styles-modal-grid\">\n        ${styles.map(st => jBuildStyleCard(st, selectLabel)).join('') || '<p class=\"btk-kp-home-lead\">No bedroom styles available yet.</p>'}\n      </div>\n      <p class=\"btk-kp-home-lead\" data-btk-kp-style-empty hidden>No bedroom styles match your search.</p>`;\n    container._btkStyleQuery = '';   // a fresh list starts unsearched\n    // For a popup in another module (Door & Carcase) to run its search through.\n    container._btkApplyFilters = () => applyStyleCardFilters(container);\n    applyStyleCardFilters(container);\n    // The handler reads the CURRENT callback, so a re-render never stacks\n    // listeners or calls a stale one.\n    container._btkStyleCardsPick = onSelect || null;\n    if (!container._btkStyleCardsBound) {\n      container._btkStyleCardsBound = true;\n      container.addEventListener('click', (ev) => {\n        handleStyleCardClick(ev, (styleId, doorHandle, carcaseHandle, card) => {\n          if (container._btkStyleCardsPick) container._btkStyleCardsPick(styleId, doorHandle, carcaseHandle, card);\n        });\n      });\n    }\n  }\n\n  function renderJourneyStyles() {\n    const container = journeyEl && journeyEl.querySelector('[data-btk-kp-journey-styles]');\n    if (!container) return;\n    renderStyleCardsInto(container, { selectLabel: 'Add to Plan', onSelect: journeyAddStyleCard });\n    renderJourneyStyleSlots();\n    // The style list only shows when there's nothing chosen yet; once a style\n    // is added it collapses to the slot cards until the user clicks \"Add\".\n    stylePickerOpen = (buyingStyles.length === 0);\n    updateStylePicker();\n    updateStyleConfirmState();\n  }\n\n  // ---- Style-picker (kitchen-style list) show/hide --------------------\n  let stylePickerOpen = false;\n  function updateStylePicker() {\n    const list  = journeyEl && journeyEl.querySelector('[data-btk-kp-journey-styles]');\n    const title = journeyEl && journeyEl.querySelector('[data-btk-kp-journey-styles-title]');\n    if (list)  list.hidden  = !stylePickerOpen;\n    if (title) title.hidden = !stylePickerOpen;\n  }\n  function openStylePicker() {\n    stylePickerOpen = true;\n    updateStylePicker();\n    const anchor = journeyEl && (journeyEl.querySelector('[data-btk-kp-journey-styles-title]') || journeyEl.querySelector('[data-btk-kp-journey-styles]'));\n    if (anchor && anchor.scrollIntoView) requestAnimationFrame(() => anchor.scrollIntoView({ behavior: 'smooth', block: 'start' }));\n  }\n  function closeStylePicker() { stylePickerOpen = false; updateStylePicker(); }\n\n  // ---- Style Setup: selected buying/planning styles (up to 3) --------\n  // Renders the chosen styles as .bku-bs-card cards (the same look as the\n  // Add Units switch-styles drawer) with an \"Add\" placeholder, from the\n  // plan-persisted `buyingStyles` array. Card #0 is the active/main style.\n  const J_STYLE_MAX = 3;\n  const J_ORDINALS = ['Main', '2nd', '3rd'];\n  // Resolve door hex + a text-contrast colour for a card tint.\n  function jDoorHex(styleId, doorHandle) {\n    const cols = (Catalogue.getDoorColoursForStyle && Catalogue.getDoorColoursForStyle(styleId)) || [];\n    const c = cols.find(x => x.handle === doorHandle);\n    return (c && c.hex) ? c.hex : null;\n  }\n  function jBuyingStyleCard(bs, index) {\n    const ks       = Catalogue.getKitchenStyle && Catalogue.getKitchenStyle(bs.styleId);\n    const name     = (ks && ks.name) || bs.styleId || '';\n    const parts    = name.trim().split(' ');\n    const nameHtml = `<span style=\"font-weight:800;\">${jEsc(parts[0] || '')}</span>` + (parts.length > 1 ? `<span style=\"font-weight:300;\"> ${jEsc(parts.slice(1).join(' '))}</span>` : '');\n    const doorCols = (Catalogue.getDoorColoursForStyle && Catalogue.getDoorColoursForStyle(bs.styleId)) || [];\n    const doorC    = doorCols.find(c => c.handle === bs.doorHandle) || null;\n    const carcCols = (Catalogue.getCarcaseColoursForStyle && Catalogue.getCarcaseColoursForStyle(bs.styleId)) || [];\n    const carcC    = carcCols.find(c => c.handle === bs.carcaseHandle) || null;\n    const family   = ks && ks.carcaseFamilyHandle;\n    const doorHex  = jDoorHex(bs.styleId, bs.doorHandle);\n    const _jp = unitPicture(bs.styleId, bs.doorHandle, bs.carcaseHandle,\n      (bs.doorHandle && Catalogue.getDoorPreviewUrl) ? (Catalogue.getDoorPreviewUrl(bs.styleId, bs.doorHandle) || '') : '',\n      (family && bs.carcaseHandle && Catalogue.getCarcasePreviewUrl) ? (Catalogue.getCarcasePreviewUrl(family, bs.carcaseHandle) || '') : '');\n    const doorUrl = _jp.doorImg, carcaseUrl = _jp.carcaseImg;\n    const isActive = index === 0;\n    const carcDot = (carcC && carcC.swatchUrl) ? `background-image:url(${carcC.swatchUrl});background-size:cover;` : (carcC && carcC.hex ? `background:${carcC.hex};` : 'background:#e6e6e6;');\n    // Laid out to echo the mood board's cabinet element: name across the top,\n    // the unit standing on the left facing the way it faces on the board, and\n    // the two choices as pills stacked beside it. No door tint - the unit\n    // carries the colour.\n    return `\n      <div class=\"bku-bs-card bku-bs-card--jstyle ${isActive ? 'bku-bs-card--active' : 'bku-bs-card--alt'}\" data-btk-kp-style-slot=\"${index}\">\n        ${isActive ? '<div class=\"bku-bs-card__tick\"><span class=\"bku-bs-card__tick-mark\" aria-hidden=\"true\">\u2713</span>Active Planning Style</div>' : ''}\n        <div class=\"btk-kp-jstyle-head\">\n          ${isActive ? '' : `<span class=\"bku-bs-card__status\">${jEsc(J_ORDINALS[index] || '')} Style</span>`}\n          <div class=\"bku-bs-card__name\">${nameHtml}</div>\n        </div>\n        <div class=\"btk-kp-jstyle-body\">\n          <div class=\"bku-bs-card__images\">\n            ${carcaseUrl ? `<img class=\"bku-bs-card__img bku-bs-card__img--carcase\" src=\"${carcaseUrl}\" alt=\"\">` : ''}\n            ${doorUrl ? `<img class=\"bku-bs-card__img bku-bs-card__img--door\" src=\"${doorUrl}\" alt=\"\">` : ''}\n          </div>\n          <div class=\"btk-kp-jstyle-side\">\n            <div class=\"bku-bs-card__chip\">\n              <span class=\"bku-bs-chip__dot\" style=\"${doorHex ? `background:${doorHex};` : (doorC && doorC.swatchUrl ? `background-image:url(${doorC.swatchUrl});background-size:cover;` : 'background:#e6e6e6;')}\"></span>\n              <div class=\"bku-bs-chip__text\"><span class=\"bku-bs-chip__label\">Door</span><span class=\"bku-bs-chip__value\">${jEsc(doorC ? (doorC.name || bs.doorHandle) : (bs.doorHandle || '-'))}</span></div>\n            </div>\n            <div class=\"bku-bs-card__chip\">\n              <span class=\"bku-bs-chip__dot\" style=\"${carcDot}\"></span>\n              <div class=\"bku-bs-chip__text\"><span class=\"bku-bs-chip__label\">Carcase</span><span class=\"bku-bs-chip__value\">${jEsc(carcC ? (carcC.name || bs.carcaseHandle) : 'Default')}</span></div>\n            </div>\n          </div>\n        </div>\n        <div class=\"btk-kp-journey-style-card-links\">\n          ${isActive ? '' : `<button type=\"button\" class=\"bku-bs-card__switch-link\" data-btk-kp-journey-style-makefirst=\"${index}\">Set as main</button>`}\n          <button type=\"button\" class=\"bku-bs-card__switch-link\" data-btk-kp-journey-style-remove=\"${index}\">Remove</button>\n        </div>\n      </div>`;\n  }\n  function renderJourneyStyleSlots() {\n    const wrap = journeyEl && journeyEl.querySelector('[data-btk-kp-journey-style-slots]');\n    if (!wrap) return;\n    // Nothing chosen yet \u2192 no slot row (just the style list shows).\n    if (!buyingStyles.length) { wrap.innerHTML = ''; return; }\n    let html = buyingStyles.slice(0, J_STYLE_MAX).map((bs, i) => jBuyingStyleCard(bs, i)).join('');\n    // Fill the remaining slots (up to 3) with clickable \"Add\" blanks.\n    for (let i = buyingStyles.length; i < J_STYLE_MAX; i++) {\n      html += `\n        <button type=\"button\" class=\"bku-bs-card bku-bs-card--placeholder\" data-btk-kp-journey-style-add>\n          <span class=\"bku-bs-card__plus\">+</span>\n          <span class=\"bku-bs-card__placeholder-label\">Add ${jEsc(J_ORDINALS[i] || '')} style</span>\n        </button>`;\n    }\n    wrap.innerHTML = html;\n  }\n  // The old Done button was disabled until a style existed. Its replacement is\n  // \"Back to Mood Board\" in the note below the list, which is always available -\n  // so there is nothing to gate here any more.\n  function updateStyleConfirmState() {}\n\n  // ---- Generic multi-option stages (handles / worktops / rails) -------\n  // Same \"pick from a list, then it becomes a card + Add another\" pattern as\n  // the style step. Each config owns its array (getArr, mutated in place), its\n  // picker/slots/confirm selectors, a card renderer, the picker (re)builder,\n  // and what Confirm applies + advances to.\n  function jOptCardShell(o) {\n    const isActive = o.index === 0;\n    return `\n      <div class=\"bku-bs-card ${isActive ? 'bku-bs-card--active' : 'bku-bs-card--alt'}\">\n        ${isActive ? `<div class=\"bku-bs-card__tick\"><span class=\"bku-bs-card__tick-mark\" aria-hidden=\"true\">\u2713</span>Active ${jEsc(o.noun)}</div>` : ''}\n        <div class=\"bku-bs-card__top\">\n          <div class=\"bku-bs-card__info\">\n            ${isActive ? '' : `<span class=\"bku-bs-card__status\">${jEsc(J_ORDINALS[o.index] || '')} ${jEsc(o.noun)}</span>`}\n            <div class=\"bku-bs-card__name\"><span style=\"font-weight:800;\">${jEsc(o.title)}</span></div>\n            ${o.sub ? `<div class=\"bku-bs-card__chips\"><div class=\"bku-bs-card__chip\" style=\"background:#fff;\"><div class=\"bku-bs-chip__text\"><span class=\"bku-bs-chip__label\">${jEsc(o.subLabel || '')}</span><span class=\"bku-bs-chip__value\">${jEsc(o.sub)}</span></div></div></div>` : ''}\n            <div class=\"btk-kp-journey-style-card-links\">\n              ${isActive ? '' : `<button type=\"button\" class=\"bku-bs-card__switch-link\" data-btk-kp-opt-makefirst=\"${o.cfg}\" data-i=\"${o.index}\">Set as main</button>`}\n              <button type=\"button\" class=\"bku-bs-card__switch-link\" data-btk-kp-opt-remove=\"${o.cfg}\" data-i=\"${o.index}\">Remove</button>\n            </div>\n          </div>\n          ${o.imgHtml ? `<div class=\"bku-bs-card__images\" style=\"background:#fff;\">${o.imgHtml}</div>` : ''}\n        </div>\n      </div>`;\n  }\n  function jHandleOptionCard(it, i) {\n    const designs = (Catalogue.getHandleDesigns && Catalogue.getHandleDesigns()) || [];\n    const d = designs.find(x => x.id === it.designId);\n    const name = it.designName || (d && d.name) || it.designId;\n    const imgUrl = handleImageFor(it.designId, it.finishHandle);\n    const img = imgUrl ? `<img src=\"${jEsc(imgUrl)}\" alt=\"\" style=\"width:100%;height:100%;object-fit:contain;\">` : '';\n    const fins = (Catalogue.getHandleFinishesForDesign && Catalogue.getHandleFinishesForDesign(it.designId)) || [];\n    const fin = fins.find(f => f.handle === it.finishHandle);\n    const finName = it.finishName || (fin && fin.name) || it.finishHandle || '';\n    return jOptCardShell({ index: i, cfg: 'handles', noun: 'Handle', title: name, subLabel: 'Finish', sub: finName, imgHtml: img });\n  }\n  function jWorktopOptionCard(it, i) {\n    const m = Catalogue.getWorktopMaterial && Catalogue.getWorktopMaterial(it.handle);\n    const name = it.name || (m && m.title) || it.handle;\n    const img = (m && m.swatchUrl) ? `<img src=\"${jEsc(m.swatchUrl)}\" alt=\"\" style=\"width:100%;height:100%;object-fit:cover;\">` : '';\n    return jOptCardShell({ index: i, cfg: 'worktops', noun: 'Worktop', title: name, subLabel: 'Material', sub: (m && m.type) || '', imgHtml: img });\n  }\n  function jRailOptionCard(it, i) {\n    const f = Catalogue.getRailFinish && Catalogue.getRailFinish(it.handle);\n    const name = it.name || (f && f.name) || it.handle;\n    const img = (f && f.swatchUrl) ? `<img src=\"${f.swatchUrl}\" alt=\"\" style=\"width:100%;height:100%;object-fit:cover;\">` : `<div style=\"width:100%;height:100%;${f ? jSwatch(f) : 'background:#ddd;'}\"></div>`;\n    return jOptCardShell({ index: i, cfg: 'rails', noun: 'Profile', title: name, subLabel: 'Profile', sub: 'Handleless rail', imgHtml: img });\n  }\n  const OPT = {\n    handles: {\n      cfg: 'handles', noun: 'handle', navStep: 'handles',\n      // The tiles ARE the stage, not a picker shown until something is picked.\n      alwaysRender: true,\n      slots: '[data-btk-kp-journey-handle-slots]', picker: '[data-btk-kp-journey-handle-picker]', confirm: '[data-btk-kp-journey-handle-confirm]',\n      getArr: () => buyingHandles, card: jHandleOptionCard, key: (it) => it.designId + ':' + (it.finishHandle || ''),\n      render: () => renderJourneyHandleGroups(),\n      apply: () => { syncJourneyHandleFromGroups(); renderJourneyName(); showJourneyStep('name'); }\n    },\n    worktops: {\n      cfg: 'worktops', noun: 'worktop', navStep: 'worktops',\n      // The tile IS the stage, not a picker shown until something is picked.\n      alwaysRender: true,\n      slots: '[data-btk-kp-journey-worktop-slots]', picker: '[data-btk-kp-journey-worktop-picker]', confirm: '[data-btk-kp-journey-worktop-confirm]',\n      getArr: () => buyingWorktops, card: jWorktopOptionCard, key: (it) => it.handle,\n      render: () => renderJourneyWorktopTile(),\n      apply: () => { syncJourneyWorktopFromPlan(); renderJourneyName(); showJourneyStep('name'); }\n    },\n    rails: {\n      cfg: 'rails', noun: 'profile', navStep: 'rail',\n      slots: '[data-btk-kp-journey-rail-slots]', picker: '[data-btk-kp-journey-rail-picker]', confirm: '[data-btk-kp-journey-rail-confirm]',\n      getArr: () => buyingRails, card: jRailOptionCard, key: (it) => it.handle,\n      render: () => renderJourneyRails(),\n      apply: () => {\n        const r = buyingRails[0];\n        journey.railHandle = r.handle; journey.railName = r.name || '';\n        renderJourneyName(); showJourneyStep('name');\n      }\n    }\n  };\n  function optRenderSlots(c) {\n    const wrap = journeyEl && journeyEl.querySelector(c.slots);\n    if (!wrap) return;\n    const arr = c.getArr();\n    if (!arr.length) { wrap.innerHTML = ''; return; }\n    let html = arr.slice(0, 3).map((it, i) => c.card(it, i)).join('');\n    for (let i = arr.length; i < 3; i++) {\n      html += `<button type=\"button\" class=\"bku-bs-card bku-bs-card--placeholder\" data-btk-kp-opt-add=\"${c.cfg}\"><span class=\"bku-bs-card__plus\">+</span><span class=\"bku-bs-card__placeholder-label\">Add ${jEsc(J_ORDINALS[i] || '')} ${jEsc(c.noun)}</span></button>`;\n    }\n    wrap.innerHTML = html;\n  }\n  // Nothing to gate: the Done button this disabled is now \"Back to Mood Board\",\n  // which is always available. Kept as a no-op so the call sites read the same.\n  function optUpdateConfirm(c) {}\n  function optSetPicker(c, open) {\n    const p = journeyEl && journeyEl.querySelector(c.picker);\n    if (p) p.hidden = !open;\n  }\n  function optOpenPicker(c) {\n    optSetPicker(c, true);\n    c.render();\n    const p = journeyEl && journeyEl.querySelector(c.picker);\n    if (p && p.scrollIntoView) requestAnimationFrame(() => p.scrollIntoView({ behavior: 'smooth', block: 'start' }));\n  }\n  // Entering a stage: show the slot cards if any chosen, else open the picker.\n  function optEnter(c) {\n    optRenderSlots(c);\n    optUpdateConfirm(c);\n    const has = c.getArr().length > 0;\n    optSetPicker(c, !has);\n    if (!has || c.alwaysRender) c.render();\n  }\n  function optAdd(c, item) {\n    const arr = c.getArr();\n    if (arr.length >= 3) return;\n    if (!arr.some(x => c.key(x) === c.key(item))) arr.push(item);\n    optSetPicker(c, false);          // chosen \u2192 collapse the picker\n    optRenderSlots(c);\n    optUpdateConfirm(c);\n    updateJourneyNav(c.navStep);\n  }\n  function optRemove(c, i) {\n    const arr = c.getArr();\n    if (i >= 0 && i < arr.length) arr.splice(i, 1);\n    optRenderSlots(c);\n    optUpdateConfirm(c);\n    if (!arr.length) optOpenPicker(c);\n    updateJourneyNav(c.navStep);\n  }\n  function optMakeFirst(c, i) {\n    const arr = c.getArr();\n    if (i > 0 && i < arr.length) { const [x] = arr.splice(i, 1); arr.unshift(x); }\n    optRenderSlots(c);\n    updateJourneyNav(c.navStep);\n  }\n  function optConfirm(c) {\n    // apply() ends by returning to the board; with nothing chosen there is\n    // nothing to apply, but \"Back to Mood Board\" still means what it says.\n    if (c.getArr().length) { c.apply(); return; }\n    renderJourneyName(); showJourneyStep('name');\n  }\n\n  function renderJourneyCarcases() {\n    const grid = journeyEl && journeyEl.querySelector('[data-btk-kp-journey-carcases]');\n    if (!grid) return;\n    const ks      = Catalogue.getKitchenStyle && Catalogue.getKitchenStyle(journey.styleId);\n    const family  = ks && ks.carcaseFamilyHandle;\n    const colours = (Catalogue.getCarcaseColoursForStyle && Catalogue.getCarcaseColoursForStyle(journey.styleId)) || [];\n    if (!colours.length) {\n      // No carcase choice for this style - skip the carcase step.\n      journey.carcaseHandle = null;\n      journey.carcaseName   = '';\n      advanceAfterCarcase();\n      return;\n    }\n    grid.innerHTML = colours.map(c => {\n      const url = family && Catalogue.getCarcasePreviewUrl ? (Catalogue.getCarcasePreviewUrl(family, c.handle) || '') : '';\n      return `\n        <button type=\"button\" class=\"btk-kp-carcase-tile\"\n                data-btk-kp-journey-carcase=\"${jEsc(c.handle)}\"\n                data-btk-kp-journey-carcase-name=\"${jEsc(c.name || c.handle)}\">\n          <div class=\"btk-kp-carcase-tile-img\" style=\"${url ? '' : jSwatch(c)}\">${url ? `<img src=\"${url}\" alt=\"\">` : ''}</div>\n          <div class=\"btk-kp-carcase-tile-name\">${jEsc(c.name || c.handle)}</div>\n        </button>`;\n    }).join('');\n    // Open the current carcase (when restoring a plan), else the first.\n    const firstTile = jPickTile(grid, 'data-btk-kp-journey-carcase', journey.carcaseHandle);\n    if (firstTile) {\n      firstTile.classList.add('is-active');\n      renderJourneyCarcaseDetail(firstTile.dataset.btkKpJourneyCarcase, firstTile.dataset.btkKpJourneyCarcaseName || '');\n    }\n  }\n\n  // Right-hand detail panel for a chosen carcase: big image, title, a\n  // (placeholder) description, and the Select button. Description text\n  // will come from a metaobject later.\n  function renderJourneyCarcaseDetail(handle, name) {\n    const detail = journeyEl && journeyEl.querySelector('[data-btk-kp-journey-carcase-detail]');\n    if (!detail) return;\n    const ks     = Catalogue.getKitchenStyle && Catalogue.getKitchenStyle(journey.styleId);\n    const family = ks && ks.carcaseFamilyHandle;\n    // Door-over-carcase overlay (1000mm Highline Base look) - the chosen door\n    // with this carcase, same composite as the plan-name step.\n    const { doorImg, carcaseImg } = unitPicture(journey.styleId, journey.doorHandle, handle,\n      journey.doorHandle && Catalogue.getDoorPreviewUrl ? (Catalogue.getDoorPreviewUrl(journey.styleId, journey.doorHandle) || '') : '',\n      family && Catalogue.getCarcasePreviewUrl ? (Catalogue.getCarcasePreviewUrl(family, handle) || '') : '');\n    detail.innerHTML = `\n      <div class=\"btk-kp-journey-detail-body\">\n        <div class=\"btk-kp-journey-preview btk-kp-journey-detail-preview\">\n          ${carcaseImg ? `<img class=\"btk-kp-journey-preview-carcase\" src=\"${carcaseImg}\" alt=\"\">` : ''}\n          ${doorImg ? `<img class=\"btk-kp-journey-preview-door\" src=\"${doorImg}\" alt=\"\">` : ''}\n          ${(!carcaseImg && !doorImg) ? '<span class=\"btk-kp-journey-preview-empty\">Preview</span>' : ''}\n        </div>\n        <div class=\"btk-kp-journey-detail-meta\">\n          <h3 class=\"btk-kp-journey-detail-title\">${jEsc(name)}</h3>\n          <p class=\"btk-kp-journey-detail-text\">A quality carcase in ${jEsc(name)}. Placeholder description - full carcase details will be added from a metaobject.</p>\n          ${jGreenBtn('Select', `data-btk-kp-journey-carcase-select data-handle=\"${jEsc(handle)}\" data-name=\"${jEsc(name)}\"`, 'btk-kp-journey-detail-select')}\n        </div>\n      </div>`;\n  }\n\n  // ---- DEV: mood-board layout tool -------------------------------------\n  // Makes every mood-board element + label (all EXCEPT the wall/floor\n  // background images) drag-to-position, so a layout can be nudged by hand\n  // and the resulting coordinates read off the console for hard-coding.\n  // Console usage:\n  //   btkMoodDragOn()   - enable dragging (re-renders the board)\n  //   ...drag pieces...  (each drop logs its selector + left/top)\n  //   btkMoodDump()     - print a paste-ready CSS block of every change\n  //   btkMoodDragOff()  - turn the tool off\n  // Positions are expressed as left/top % of each element's containing box\n  // (items/zones \u2192 the board; a tag \u2192 its own item), matching how the real\n  // CSS positions them. Existing transforms (rotate/centre) are preserved.\n  const MB_DRAG_SELECTORS = [\n    '.btk-kp-mb-zone--wall',\n    '.btk-kp-mb-zone--floor',\n    '.btk-kp-mb-worktop',\n    '.btk-kp-mb-cabinet',\n    '.btk-kp-mb-handle',\n    '.btk-kp-mb-worktop .btk-kp-mb-tag',\n    '.btk-kp-mb-cabinet .btk-kp-mb-tag',\n    '.btk-kp-mb-handle .btk-kp-mb-tag'\n  ];\n  function mbEnableDrag(board) {\n    // With the multi-set carousel there are several `.btk-kp-mb` cards - drag\n    // the one that's currently in view.\n    const cards = board.querySelectorAll('.btk-kp-mb');\n    const mb = cards[moodBoardIndex] || cards[0];\n    if (!mb) return;\n    window.__btkMoodDragPos = window.__btkMoodDragPos || {};\n    const store = window.__btkMoodDragPos;\n    MB_DRAG_SELECTORS.forEach(sel => {\n      const el = mb.querySelector(sel);\n      if (!el) return;\n      const parent = el.offsetParent || mb;\n      // Measure the CURRENT rendered offset BEFORE we touch anchors.\n      const l0 = el.offsetLeft, t0 = el.offsetTop;\n      const pw0 = parent.clientWidth || 1, ph0 = parent.clientHeight || 1;\n      el.style.position = 'absolute';\n      el.style.right = 'auto';\n      el.style.bottom = 'auto';\n      el.style.margin = '0';\n      if (store[sel]) {\n        el.style.left = store[sel].left;\n        el.style.top  = store[sel].top;\n      } else {\n        el.style.left = (l0 / pw0 * 100).toFixed(2) + '%';\n        el.style.top  = (t0 / ph0 * 100).toFixed(2) + '%';\n      }\n      el.style.cursor = 'move';\n      el.style.outline = '1px dashed rgba(45,122,58,.9)';\n      el.style.outlineOffset = '1px';\n      let dragging = false, moved = false, sx = 0, sy = 0, sL = 0, sT = 0, pw = 1, ph = 1;\n      el.addEventListener('pointerdown', (e) => {\n        dragging = true; moved = false;\n        const p = el.offsetParent || mb;\n        pw = p.clientWidth || 1; ph = p.clientHeight || 1;\n        sx = e.clientX; sy = e.clientY; sL = el.offsetLeft; sT = el.offsetTop;\n        try { el.setPointerCapture(e.pointerId); } catch (err) {}\n        e.preventDefault(); e.stopPropagation();\n      });\n      el.addEventListener('pointermove', (e) => {\n        if (!dragging) return;\n        const dx = e.clientX - sx, dy = e.clientY - sy;\n        if (Math.abs(dx) > 2 || Math.abs(dy) > 2) moved = true;\n        el.style.left = ((sL + dx) / pw * 100).toFixed(2) + '%';\n        el.style.top  = ((sT + dy) / ph * 100).toFixed(2) + '%';\n      });\n      const end = (e) => {\n        if (!dragging) return;\n        dragging = false;\n        try { el.releasePointerCapture(e.pointerId); } catch (err) {}\n        if (moved) {\n          store[sel] = { left: el.style.left, top: el.style.top };\n          console.log('[MoodBoard] ' + sel + '  \u2192  left: ' + el.style.left + '; top: ' + el.style.top + ';');\n        }\n      };\n      el.addEventListener('pointerup', end);\n      el.addEventListener('pointercancel', end);\n      // Suppress the button's navigate-click after an actual drag.\n      el.addEventListener('click', (e) => { if (moved) { e.preventDefault(); e.stopPropagation(); } }, true);\n    });\n  }\n  if (typeof window !== 'undefined') {\n    window.btkMoodDragOn  = () => { window.__btkMoodDrag = true;  renderJourneyName(); console.log('[MoodBoard] drag ON - drag any element/label, then call btkMoodDump()'); };\n    window.btkMoodDragOff = () => { window.__btkMoodDrag = false; renderJourneyName(); console.log('[MoodBoard] drag OFF'); };\n    window.btkMoodDump = () => {\n      const store = window.__btkMoodDragPos || {};\n      const keys = Object.keys(store);\n      if (!keys.length) { console.log('[MoodBoard] nothing moved yet'); return; }\n      let css = '/* Mood board positions */\\n';\n      keys.forEach(sel => { css += sel + ' { left: ' + store[sel].left + '; top: ' + store[sel].top + '; right: auto; bottom: auto; }\\n'; });\n      console.log(css);\n    };\n  }\n\n  // Build ONE mood-board scene (the `.btk-kp-mb` card) for a given buying-style\n  // set { styleId, doorHandle, carcaseHandle }. The cabinet/door/carcase come\n  // from the set; worktop, handle, wall + floor are the plan's shared applied\n  // choices (from `journey`). Kept self-contained per card so worktop/handle\n  // can later be linked per style set (just read set.* instead of journey.*).\n  function mbSceneHTML(set) {\n    set = set || {};\n    const mbKs       = Catalogue.getKitchenStyle ? Catalogue.getKitchenStyle(set.styleId) : null;\n    const family     = mbKs && mbKs.carcaseFamilyHandle;\n    const { doorImg, carcaseImg } = unitPicture(set.styleId, set.doorHandle, set.carcaseHandle,\n      set.doorHandle && Catalogue.getDoorPreviewUrl ? (Catalogue.getDoorPreviewUrl(set.styleId, set.doorHandle) || '') : '',\n      family && set.carcaseHandle && Catalogue.getCarcasePreviewUrl ? (Catalogue.getCarcasePreviewUrl(family, set.carcaseHandle) || '') : '');\n    const wm = journey.worktopHandle && Catalogue.getWorktopMaterial ? Catalogue.getWorktopMaterial(journey.worktopHandle) : null;\n    const wImg = (wm && wm.swatchUrl) ? wm.swatchUrl : '';\n    const hSys = (Catalogue.handleSystem && Catalogue.handleSystem(set.styleId || journey.styleId)) || 'standard';\n    let hImg = '', hTag = 'Handle', hNote = '';\n    if (hSys === 'true-rail') {\n      const rf = journey.railHandle && Catalogue.getRailFinish ? Catalogue.getRailFinish(journey.railHandle) : null;\n      hImg = (rf && rf.swatchUrl) ? rf.swatchUrl : ''; hTag = 'Profile';\n    } else if (hSys === 'j-pull') {\n      // The handle is part of the door, so there is nothing to pick and no\n      // image to show - the tile says so instead.\n      hTag = 'Handle';\n      hNote = 'Integrated handle - built into the door.';\n    } else {\n      hImg = handleImageFor(journey.handleDesignId, journey.handleFinishHandle);\n    }\n    const wall  = (typeof getWallColour === 'function') ? getWallColour(wallColourHandle) : null;\n    const wallStyle  = wall ? (wall.swatchUrl ? `background-image:url(${wall.swatchUrl})` : `background:${wall.hex || '#ece7df'}`) : 'background:#ece7df';\n    const floor = (typeof resolveFloorColour === 'function') ? resolveFloorColour(floorColourHandle) : null;\n    const floorSrc = floor ? (floor.textureUrl || floor.swatchUrl) : '';\n    const floorStyle = floor ? (floorSrc ? `background-image:url(${floorSrc})` : `background:${floor.hex || '#cbb79b'}`) : 'background:#cbb79b';\n    const cabInner = (doorImg || carcaseImg)\n      ? `${carcaseImg ? `<img class=\"btk-kp-journey-preview-carcase\" src=\"${carcaseImg}\" alt=\"\">` : ''}${doorImg ? `<img class=\"btk-kp-journey-preview-door\" src=\"${doorImg}\" alt=\"\">` : ''}`\n      : '<span class=\"btk-kp-mb-ph\">Cabinet &amp; Door</span>';\n    const wtInner = wImg ? `<img src=\"${jEsc(wImg)}\" alt=\"\">` : '<span class=\"btk-kp-mb-ph\">Worktop</span>';\n    const hInner  = hNote ? `<span class=\"btk-kp-mb-note\">${jEsc(hNote)}</span>`\n                          : (hImg ? `<img src=\"${jEsc(hImg)}\" alt=\"\">` : `<span class=\"btk-kp-mb-ph\">${jEsc(hTag)}</span>`);\n    return `\n        <div class=\"btk-kp-mb\">\n          <div class=\"btk-kp-mb-wall\" style=\"${wallStyle}\"></div>\n          <div class=\"btk-kp-mb-floor\" style=\"${floorStyle}\"></div>\n          <button type=\"button\" class=\"btk-kp-mb-zone btk-kp-mb-zone--wall\" data-btk-kp-mood-goto=\"wall\" aria-label=\"Choose wall colour\"><span class=\"btk-kp-mb-tag\">Wall</span></button>\n          <button type=\"button\" class=\"btk-kp-mb-zone btk-kp-mb-zone--floor\" data-btk-kp-mood-goto=\"floor\" aria-label=\"Choose floor colour\"><span class=\"btk-kp-mb-tag\">Floor</span></button>\n          <button type=\"button\" class=\"btk-kp-mb-item btk-kp-mb-worktop${wImg ? '' : ' is-empty'}\" data-btk-kp-mood-goto=\"worktops\" aria-label=\"Choose worktop\">\n            <div class=\"btk-kp-mb-item-img\">${wtInner}</div>\n            <span class=\"btk-kp-mb-tag\">Worktop</span>\n          </button>\n          <button type=\"button\" class=\"btk-kp-mb-item btk-kp-mb-cabinet${(doorImg || carcaseImg) ? '' : ' is-empty'}\" data-btk-kp-mood-goto=\"style\" aria-label=\"Choose style, colour &amp; carcase\">\n            <div class=\"btk-kp-mb-cabinet-img\">${cabInner}</div>\n            <span class=\"btk-kp-mb-tag\">Cabinet &amp; Door</span>\n          </button>\n          ${hNote\n            ? `<div class=\"btk-kp-mb-item btk-kp-mb-handle btk-kp-mb-handle--fixed\">\n            <div class=\"btk-kp-mb-item-img\">${hInner}</div>\n            <span class=\"btk-kp-mb-tag\">${jEsc(hTag)}</span>\n          </div>`\n            : `<button type=\"button\" class=\"btk-kp-mb-item btk-kp-mb-handle${hImg ? '' : ' is-empty'}\" data-btk-kp-mood-goto=\"handles\" aria-label=\"Choose ${jEsc(hTag.toLowerCase())}\">\n            <div class=\"btk-kp-mb-item-img\">${hInner}</div>\n            <span class=\"btk-kp-mb-tag\">${jEsc(hTag)}</span>\n          </button>`}\n        </div>`;\n  }\n\n  // Heading above the mood board: the active buying style (index 0) reads\n  // \"Active Planning Style\"; alternates read \"2nd / 3rd Planning Style\".\n  function mbPlanningStyleTitle(idx) {\n    const ord = ['Active', '2nd', '3rd', '4th', '5th'][idx] || `${idx + 1}th`;\n    return `${ord} Planning Style`;\n  }\n  function updatePlanningStyleTitle() {\n    const el = journeyEl && journeyEl.querySelector('[data-btk-kp-planning-style-title]');\n    if (el) el.textContent = mbPlanningStyleTitle(moodBoardIndex);\n  }\n\n  // Slide the mood-board carousel by `dir` (-1 / +1), wrapping around. Only\n  // moves the track + updates the nav label - no full re-render, so the CSS\n  // transform transition animates the slide.\n  function slideMoodBoard(dir) {\n    const track = journeyEl && journeyEl.querySelector('[data-btk-kp-mb-track]');\n    if (!track) return;\n    const n = track.children.length;\n    if (n <= 1) return;\n    moodBoardIndex = (moodBoardIndex + dir + n) % n;\n    track.style.transform = `translateX(-${moodBoardIndex * 100}%)`;\n    const nameEl  = journeyEl.querySelector('[data-btk-kp-mb-nav-name]');\n    const badgeEl = journeyEl.querySelector('[data-btk-kp-mb-active]');\n    const countEl = journeyEl.querySelector('[data-btk-kp-mb-nav] .btk-kp-mb-nav-count');\n    const activeKs = Catalogue.getKitchenStyle ? Catalogue.getKitchenStyle((buyingStyles[moodBoardIndex] || {}).styleId) : null;\n    if (nameEl)  nameEl.textContent  = (activeKs && activeKs.name) || (buyingStyles[moodBoardIndex] || {}).styleId || 'Style';\n    if (badgeEl) badgeEl.hidden = (moodBoardIndex !== 0);   // buyingStyles[0] = the active/applied style\n    if (countEl) countEl.textContent = `${moodBoardIndex + 1} / ${n}`;\n    updatePlanningStyleTitle();\n    if (window.__btkMoodDrag) mbEnableDrag(journeyEl.querySelector('[data-btk-kp-journey-moodboard]'));\n  }\n\n  function renderJourneyName() {\n    if (!journeyEl) return;\n    syncJourneyFromOptions();   // reflect the chosen style/handles/worktops (if any)\n    const ks = Catalogue.getKitchenStyle && Catalogue.getKitchenStyle(journey.styleId);\n    const styleName = (ks && ks.name) || journey.styleId || '';\n    // Update the primary action label for new vs editing an existing plan.\n    // Editing always applies the ACTIVE planning style (buyingStyles[0]), so\n    // the label says so regardless of which style set the carousel is showing.\n    const labelEl = journeyEl.querySelector('[data-btk-kp-journey-finish-label]');\n    if (labelEl) labelEl.textContent = (journeyMode === 'edit') ? 'Update Plan to Active Style' : 'Start Planning';\n    // ---- Mood board: a composed scene. Wall colour (top 75%) + floor (bottom\n    // 25%); the cabinet/door stands on the floor, the worktop sits upper-left,\n    // the handle overlaps lower-right. Each product is clickable \u2192 its stage. ----\n    const board = journeyEl.querySelector('[data-btk-kp-journey-moodboard]');\n    if (board) {\n      // One mood board per buying-style set (up to J_STYLE_MAX). With >1 set\n      // the boards become a horizontal carousel of separate cards that SLIDE\n      // between sets (\u2039 / \u203A nav). Each card is a self-contained scene, so\n      // worktop/handle can later be linked per style set. For now only the\n      // cabinet/door/carcase changes per card - worktop, handle, wall + floor\n      // are the shared applied choices (from `journey`). See mbSceneHTML.\n      const mbSets = buyingStyles.length\n        ? buyingStyles.slice(0, J_STYLE_MAX)\n        : [{ styleId: journey.styleId, doorHandle: journey.doorHandle, carcaseHandle: journey.carcaseHandle }];\n      if (moodBoardIndex >= mbSets.length) moodBoardIndex = 0;\n      if (moodBoardIndex < 0) moodBoardIndex = mbSets.length - 1;\n      if (mbSets.length > 1) {\n        const activeKs   = Catalogue.getKitchenStyle ? Catalogue.getKitchenStyle((mbSets[moodBoardIndex] || {}).styleId) : null;\n        const activeName = (activeKs && activeKs.name) || (mbSets[moodBoardIndex] || {}).styleId || 'Style';\n        board.innerHTML = `\n        <div class=\"btk-kp-mb-viewport\">\n          <div class=\"btk-kp-mb-track\" data-btk-kp-mb-track style=\"transform:translateX(-${moodBoardIndex * 100}%)\">\n            ${mbSets.map(s => `<div class=\"btk-kp-mb-slide\">${mbSceneHTML(s)}</div>`).join('')}\n          </div>\n        </div>\n        <div class=\"btk-kp-mb-nav\" data-btk-kp-mb-nav>\n          <button type=\"button\" class=\"btk-kp-mb-nav-btn\" data-btk-kp-mood-prev aria-label=\"Previous style set\">\n            <svg xmlns=\"http://www.w3.org/2000/svg\" width=\"18\" height=\"18\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2.4\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><polyline points=\"15 18 9 12 15 6\"/></svg>\n          </button>\n          <span class=\"btk-kp-mb-nav-label\">\n            <strong><span data-btk-kp-mb-nav-name>${jEsc(activeName)}</span><span class=\"btk-kp-mb-active-badge\" data-btk-kp-mb-active${moodBoardIndex === 0 ? '' : ' hidden'}>Active</span></strong>\n            <span class=\"btk-kp-mb-nav-count\">${moodBoardIndex + 1} / ${mbSets.length}</span>\n          </span>\n          <button type=\"button\" class=\"btk-kp-mb-nav-btn\" data-btk-kp-mood-next aria-label=\"Next style set\">\n            <svg xmlns=\"http://www.w3.org/2000/svg\" width=\"18\" height=\"18\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2.4\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><polyline points=\"9 18 15 12 9 6\"/></svg>\n          </button>\n        </div>`;\n      } else {\n        board.innerHTML = mbSceneHTML(mbSets[0] || {});\n      }\n      updatePlanningStyleTitle();\n      if (window.__btkMoodDrag) mbEnableDrag(board);\n    }\n    // The plan's name above Start Planning, once it has one (named before the\n    // mood board, or the loaded plan's). The box itself is in the name popup.\n    const pnWrap = journeyEl.querySelector('[data-btk-kp-journey-planname]');\n    if (pnWrap) {\n      const pn = journeyPlanName();\n      pnWrap.hidden = !pn;\n      const pnText = pnWrap.querySelector('[data-btk-kp-journey-planname-text]');\n      if (pnText) pnText.textContent = pn;\n    }\n    // \"Skip for now\" only shows while something's still unset - once every\n    // option (style, handles/profile, worktops, wall, floor) is chosen there's\n    // nothing left to skip, so hide it.\n    const skipBtn = journeyEl.querySelector('[data-btk-kp-journey-skip]');\n    if (skipBtn) {\n      const allSet = buyingStyles.length > 0\n        && (isHandleless() ? buyingRails.length > 0 : buyingHandles.length > 0)\n        && buyingWorktops.length > 0\n        && wallChosen && floorChosen;\n      // Editing a loaded plan: no \"Skip\" - you're updating, not starting fresh.\n      skipBtn.hidden = allSet || journeyMode === 'edit';\n    }\n    // Live selections summary below the Start Planning button.\n    const summaryEl = journeyEl.querySelector('[data-btk-kp-journey-summary]');\n    if (summaryEl) {\n      const handleless = isHandleless();\n      const handleVal = handleless\n        ? (journey.railName || '')\n        : [journey.handleName, journey.handleFinishName].filter(Boolean).join(' \u00B7 ');\n      const rows = [\n        ['Bedroom style',  styleName],\n        ['Colour',         journey.doorName],\n        ['Carcase colour', journey.carcaseName],\n        ['Worktop',        journey.worktopName],\n        [handleless ? 'Rail profile' : 'Handles', handleVal]\n      ];\n      summaryEl.innerHTML =\n        '<h4 class=\"btk-kp-journey-summary-title\">Your selections</h4>' +\n        '<dl class=\"btk-kp-journey-summary-list\">' +\n        rows.map(([label, val]) =>\n          '<div class=\"btk-kp-journey-summary-row\">' +\n            '<dt>' + jEsc(label) + '</dt>' +\n            '<dd' + (val ? '' : ' class=\"is-empty\"') + '>' + (val ? jEsc(val) : 'Not chosen yet') + '</dd>' +\n          '</div>').join('') +\n        '</dl>';\n    }\n  }\n\n  // After a carcase is chosen: True Handleless ranges pick a rail profile\n  // colour next; everything else goes straight to naming.\n  function advanceAfterCarcase() {\n    if (isHandleless()) {\n      const fins = (Catalogue.getRailFinishes && Catalogue.getRailFinishes()) || [];\n      if (!fins.length) { advanceToWorktops(); return; }\n      optEnter(OPT.rails);\n      showJourneyStep('rail');\n    } else {\n      advanceToHandles();\n    }\n  }\n  // After handles (or the rail step for handleless) \u2192 worktops \u2192 name. Steps\n  // with nothing authored are skipped so the flow never dead-ends.\n  function advanceToHandles() {\n    const designs = (Catalogue.getHandleDesigns && Catalogue.getHandleDesigns()) || [];\n    if (!designs.length) { advanceToWorktops(); return; }\n    optEnter(OPT.handles);\n    showJourneyStep('handles');\n  }\n  function advanceToWorktops() {\n    const mats = rangeWorktopMaterials();\n    if (!mats.length) { renderJourneyName(); showJourneyStep('name'); return; }\n    optEnter(OPT.worktops);\n    showJourneyStep('worktops');\n  }\n\n  // ---- Journey: Handles picker (handled styles) ----------------------\n  // Resolve a handle image the SAME way Customise (ui-finishes) does: prefer the\n  // matched handle PRODUCT's featured photo for the finish, then the design's\n  // own imageUrl. Many designs have no imageUrl - the image is on the products.\n  function handleImageFor(designId, finishHandle) {\n    if (!designId) return '';\n    if (finishHandle && Catalogue.getHandleProduct) {\n      const sizes = (Catalogue.getHandleSizesForDesign && Catalogue.getHandleSizesForDesign(designId)) || [];\n      // A design with no sizes listed is matched on a sizeless product.\n      for (const sz of (sizes.length ? sizes : [null])) {\n        const p = Catalogue.getHandleProduct(designId, finishHandle, sz);\n        if (p && p.featuredImageUrl) return p.featuredImageUrl;\n      }\n    }\n    const d = ((Catalogue.getHandleDesigns && Catalogue.getHandleDesigns()) || []).find(x => x.id === designId);\n    return (d && d.imageUrl) || '';\n  }\n  // ---- Style Setup: handles, by position group ------------------------\n  // The stage edits the PLAN's five handle groups - the same state Customise\n  // edits - rather than a journey-only list, and hands the choosing to the\n  // same popup. A tile is the opener: `data-btk-kp-open-popup=\"handles\"` is\n  // what finishes.js listens for, and the group rides along so the popup opens\n  // on the type that was clicked.\n  const J_HGROUP_FALLBACK = [\n    { key: 'base',        label: 'Base Unit Doors' },\n    { key: 'wall',        label: 'Wall Unit Doors' },\n    { key: 'tall',        label: 'Tall Unit Doors' },\n    { key: 'drawers',     label: 'Standard Drawers' },\n    { key: 'pan-drawers', label: 'Pan Drawers' }\n  ];\n  // Same label -> key rule the popup uses: 'pan' before 'drawer', so \"Pan\n  // Drawers\" cannot fall into Drawers.\n  function jHGroupKey(label) {\n    const l = String(label || '').toLowerCase();\n    if (l.includes('wall')) return 'wall';\n    if (l.includes('tall')) return 'tall';\n    if (l.includes('pan')) return 'pan-drawers';\n    if (l.includes('drawer')) return 'drawers';\n    return 'base';\n  }\n  function jHandleGroupsUI() {\n    const sections = (Catalogue.getHandleGroupSections && Catalogue.getHandleGroupSections()) || [];\n    if (!sections.length) return J_HGROUP_FALLBACK.map(g => ({ ...g, iconUrl: null }));\n    return sections.map(x => ({ key: jHGroupKey(x.label), label: x.label, iconUrl: x.iconUrl || null }));\n  }\n  function jHandleNames(g) {\n    if (!g || !g.designId) return null;\n    const d = ((Catalogue.getHandleDesigns && Catalogue.getHandleDesigns()) || []).find(x => x.id === g.designId);\n    const fins = (Catalogue.getHandleFinishesForDesign && Catalogue.getHandleFinishesForDesign(g.designId)) || [];\n    const f = fins.find(x => x.handle === g.finishHandle);\n    return {\n      designId: g.designId, designName: (d && d.name) || g.designId,\n      finishHandle: g.finishHandle || null, finishName: (f && (f.name || f.handle)) || ''\n    };\n  }\n  // Five tiles is a lot to meet first; most kitchens want ONE handle anyway.\n  // So the stage opens on a single tile that sets every unit type at once, and\n  // a toggle above it swaps to the per-type row. Not persisted - it is a way\n  // of looking at the choice, not part of the plan - but a plan that already\n  // holds different handles per type opens on Per Unit Type, because hiding\n  // that behind one tile would misrepresent it.\n  let journeyHandleMode = null;   // 'all' | 'per'; null until the user picks\n  // All Units is the default however the plan is set: one handle is what most\n  // kitchens want, and the toggle is right there for the rest. A plan that\n  // already holds different handles per type still opens here showing the base\n  // units' handle - nothing is changed until a pick is committed.\n  function jHandleModeNow() { return journeyHandleMode || 'all'; }\n  function jHandleToggleHTML(mode) {\n    const opt = (v, label) => `\n      <button type=\"button\" class=\"btk-kp-seg-toggle-btn${mode === v ? ' is-active' : ''}\"\n              data-btk-kp-journey-handle-mode=\"${v}\" aria-pressed=\"${mode === v}\">${label}</button>`;\n    return `\n      <div class=\"btk-kp-seg-row btk-kp-hmode\">\n        <span class=\"btk-kp-seg-row-label\">Handle Selector:</span>\n        <div class=\"btk-kp-seg-toggle btk-kp-seg-toggle--dark btk-kp-seg-toggle--equal\" role=\"group\" aria-label=\"Choose handles for all units or per unit type\">\n          ${opt('all', 'All Units')}${opt('per', 'Per Unit Type')}\n        </div>\n      </div>`;\n  }\n  // The green Change button on a handle card. The whole card is the opener (a\n  // <button>), so this is drawn as a span in the button style - a button\n  // inside a button is not valid HTML (Arden, 2026-10-08).\n  function jHandleChangeBtn() {\n    return `<span class=\"btk-kp-action-btn btk-kp-action-btn--green btk-kp-action-btn--sm btk-kp-hgroup-change\" aria-hidden=\"true\">\n      <span class=\"btk-kp-action-btn-icon\"><svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2.2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\"><path d=\"M12 20h9\"/><path d=\"M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z\"/></svg></span>\n      <span class=\"btk-kp-action-btn-label\">Change</span>\n    </span>`;\n  }\n  // The handle selector is drawn in two places: the Style Setup page, and the\n  // first screen of the Handles popup opened from Customise. One renderer, so\n  // the two are the same thing, not a copy that drifts.\n  function renderJourneyHandleGroups() {\n    renderHandleSelector(journeyEl && journeyEl.querySelector('[data-btk-kp-journey-handle-groups]'));\n    renderHandleSelector(document.querySelector('[data-btk-kp-popup=\"handles\"] [data-btk-kp-handle-selector]'));\n  }\n  function renderHandleSelector(wrap) {\n    if (!wrap) return;\n    const designs = (Catalogue.getHandleDesigns && Catalogue.getHandleDesigns()) || [];\n    if (!designs.length) {\n      wrap.innerHTML = '<p class=\"btk-kp-home-lead\">No handle designs in the catalogue yet.</p>';\n      return;\n    }\n    const mode = jHandleModeNow();\n    if (mode === 'all') {\n      // The whole kitchen, shown as whatever the base units hold.\n      const set = jHandleNames(handleGroups.base);\n      const img = set ? handleImageFor(set.designId, set.finishHandle) : '';\n      // Full width: picture on the left, what is chosen on the right, and under\n      // it the one thing the user cannot see from the picture - which way the\n      // handle is fitted. Title + note reuse the picker's own type\n      // (.btk-kp-picker-title) and the panel note style (.btk-kp-popup-intro).\n      wrap.innerHTML = jHandleToggleHTML(mode) + `\n        <button type=\"button\" class=\"btk-kp-hgroup btk-kp-hgroup--all\"\n                data-btk-kp-open-popup=\"handles\" data-btk-kp-handle-group=\"all\"\n                aria-label=\"Choose the handle for every unit\">\n          <span class=\"btk-kp-hgroup-img\">${img ? `<img src=\"${jEsc(img)}\" alt=\"\">` : '<span class=\"btk-kp-hgroup-empty\">Not chosen</span>'}</span>\n          <span class=\"btk-kp-hgroup-body\">\n            ${set ? '<span class=\"bku-bs-card__tick\"><span class=\"bku-bs-card__tick-mark\" aria-hidden=\"true\">\u2713</span>Active Planning Style</span>' : ''}\n            <span class=\"product-title h5 btk-kp-picker-title\">${set ? jEsc(set.designName) : 'Choose a handle'}</span>\n            <span class=\"btk-kp-hgroup-fin\">${set && set.finishName ? jEsc(set.finishName) : ''}</span>\n            <span class=\"btk-kp-hgroup-note-title\">How these are fitted</span>\n            <span class=\"btk-kp-popup-intro\">Upright on doors and across on drawers, the way handles are normally fitted. Switch to Per Unit Type if you want something different on the drawers.</span>\n          </span>\n          ${jHandleChangeBtn()}\n        </button>`;\n      return;\n    }\n    wrap.innerHTML = jHandleToggleHTML(mode) + '<div class=\"btk-kp-hgroup-row\">' + jHandleGroupsUI().map(g => {\n      const set  = jHandleNames(handleGroups[g.key]);\n      const img  = set ? handleImageFor(set.designId, set.finishHandle) : '';\n      const icon = g.iconUrl || '';\n      return `\n        <button type=\"button\" class=\"btk-kp-hgroup${set ? ' is-set' : ''}\"\n                data-btk-kp-open-popup=\"handles\" data-btk-kp-handle-group=\"${jEsc(g.key)}\"\n                aria-label=\"Choose the handle for ${jEsc(g.label)}\">\n          <span class=\"btk-kp-hgroup-head\">\n            ${icon ? `<span class=\"btk-kp-hgroup-icon\"><img src=\"${jEsc(icon)}\" alt=\"\"></span>` : ''}\n            <span class=\"btk-kp-hgroup-label\">${jEsc(g.label)}</span>\n          </span>\n          <span class=\"btk-kp-hgroup-img\">${img ? `<img src=\"${jEsc(img)}\" alt=\"\">` : '<span class=\"btk-kp-hgroup-empty\">Not chosen</span>'}</span>\n          <span class=\"btk-kp-hgroup-name\">${set ? jEsc(set.designName) : 'Choose a handle'}</span>\n          <span class=\"btk-kp-hgroup-fin\">${set && set.finishName ? jEsc(set.finishName) : ''}</span>\n          ${jHandleChangeBtn()}\n        </button>`;\n    }).join('') + '</div>';\n  }\n  // The mood board and the plan summary show ONE handle; with five groups that\n  // is the first one set, in reading order. Keeps `journey.handle*` and\n  // `buyingHandles` - which the board, the summary and the saved plan all read\n  // - as a reflection of the groups rather than a second source of truth.\n  function syncJourneyHandleFromGroups() {\n    const key = HANDLE_GROUP_KEYS.find(k => handleGroups[k] && handleGroups[k].designId);\n    const set = key ? jHandleNames(handleGroups[key]) : null;\n    if (!set) {\n      journey.handleDesignId = null; journey.handleName = '';\n      journey.handleFinishHandle = null; journey.handleFinishName = '';\n      buyingHandles = [];\n      return;\n    }\n    journey.handleDesignId     = set.designId;\n    journey.handleName         = set.designName;\n    journey.handleFinishHandle = set.finishHandle;\n    journey.handleFinishName   = set.finishName;\n    buyingHandles = [{ designId: set.designId, designName: set.designName,\n                       finishHandle: set.finishHandle, finishName: set.finishName }];\n  }\n  // ---- Style Setup: worktops ------------------------------------------\n  // A worktop is ONE material across the kitchen (see worktopMaterialForSlab),\n  // so there is nothing to split per unit type - one tile, opening the same\n  // picker Customise uses.\n  function renderJourneyWorktopTile() {\n    const wrap = journeyEl && journeyEl.querySelector('[data-btk-kp-journey-worktop-tile]');\n    if (!wrap) return;\n    const mats = rangeWorktopMaterials();\n    if (!mats.length) {\n      wrap.innerHTML = '<p class=\"btk-kp-home-lead\">No worktop materials in the catalogue yet.</p>';\n      return;\n    }\n    const cur = worktopMaterialHandle || journey.worktopHandle || null;\n    const m   = cur && Catalogue.getWorktopMaterial ? Catalogue.getWorktopMaterial(cur) : null;\n    const img = (m && m.swatchUrl) ? m.swatchUrl : '';\n    wrap.innerHTML = `\n      <button type=\"button\" class=\"btk-kp-hgroup btk-kp-hgroup--all\"\n              data-btk-kp-open-popup=\"worktop\" data-btk-kp-worktop-pick\n              aria-label=\"Choose your worktop material\">\n        <span class=\"btk-kp-hgroup-img\">${img ? `<img src=\"${jEsc(img)}\" alt=\"\">` : '<span class=\"btk-kp-hgroup-empty\">Not chosen</span>'}</span>\n        <span class=\"btk-kp-hgroup-body\">\n          ${m ? '<span class=\"bku-bs-card__tick\"><span class=\"bku-bs-card__tick-mark\" aria-hidden=\"true\">\\u2713</span>Active Planning Style</span>' : ''}\n          <span class=\"product-title h5 btk-kp-picker-title\">${m ? jEsc(m.title || cur) : 'Choose a worktop'}</span>\n          <span class=\"btk-kp-hgroup-fin\">${m ? jEsc([m.range || m.type, m.thicknessMm ? m.thicknessMm + 'mm' : ''].filter(Boolean).join(' \u00B7 ')) : ''}</span>\n          ${jWorktopFromPrice(m)}\n          <span class=\"btk-kp-hgroup-note-title\">Where it goes</span>\n          <span class=\"btk-kp-popup-intro\">Every worktop in the plan is drawn and priced in this material. Edge profiles, upstands and splashbacks are chosen in Customise.</span>\n        </span>\n      </button>`;\n  }\n  // \"From\" price - the cheapest board this material is sold as, in the theme's\n  // own price markup (the same block the handle cards use).\n  function jWorktopFromPrice(m) {\n    const cents = m && (m.variants || []).filter(v => v.available !== false)\n      .map(v => v.priceCents).filter(c => typeof c === 'number' && c > 0);\n    if (!cents || !cents.length) return '';\n    return `<span class=\"product-info__price btk-kp-picker-price\"><span class=\"price\"><span class=\"price__default\">\n      <span class=\"price__current\">From <span class=\"js-value\">\u00A3${(Math.min(...cents) / 100).toFixed(2)}</span></span>\n    </span></span></span>`;\n  }\n  // The board and the summary read `journey.worktopHandle`; the plan itself\n  // holds `worktopMaterialHandle`. Mirror one onto the other so a pick made in\n  // the popup - from either stage - reaches both.\n  function syncJourneyWorktopFromPlan() {\n    const h = worktopMaterialHandle || null;\n    const m = (h && Catalogue.getWorktopMaterial) ? Catalogue.getWorktopMaterial(h) : null;\n    journey.worktopHandle = h;\n    journey.worktopName   = m ? (m.title || h) : '';\n    buyingWorktops = h ? [{ handle: h, name: journey.worktopName }] : [];\n  }\n  function renderJourneyRails() {\n    const grid = journeyEl && journeyEl.querySelector('[data-btk-kp-journey-rails]');\n    if (!grid) return;\n    const finishes = (Catalogue.getRailFinishes && Catalogue.getRailFinishes()) || [];\n    if (!finishes.length) {\n      // No rail palette authored - skip to naming.\n      journey.railHandle = null; journey.railName = '';\n      renderJourneyName();\n      showJourneyStep('name');\n      return;\n    }\n    grid.innerHTML = finishes.map(f => `\n      <button type=\"button\" class=\"btk-kp-carcase-tile\"\n              data-btk-kp-journey-rail=\"${jEsc(f.handle)}\"\n              data-btk-kp-journey-rail-name=\"${jEsc(f.name || f.handle)}\">\n        <div class=\"btk-kp-carcase-tile-img\" style=\"${jSwatch(f)}\">${f.swatchUrl ? `<img src=\"${f.swatchUrl}\" alt=\"\">` : ''}</div>\n        <div class=\"btk-kp-carcase-tile-name\">${jEsc(f.name || f.handle)}</div>\n      </button>`).join('');\n    const first = jPickTile(grid, 'data-btk-kp-journey-rail', journey.railHandle);\n    if (first) {\n      first.classList.add('is-active');\n      renderJourneyRailDetail(first.dataset.btkKpJourneyRail, first.dataset.btkKpJourneyRailName || '');\n    }\n  }\n\n  // Rail detail: a big profile-colour swatch (real profile images land in\n  // the metaobject later), title, description and the green Select button.\n  function renderJourneyRailDetail(handle, name) {\n    const detail = journeyEl && journeyEl.querySelector('[data-btk-kp-journey-rail-detail]');\n    if (!detail) return;\n    const finish = Catalogue.getRailFinish && Catalogue.getRailFinish(handle);\n    const swatchCss = finish ? jSwatch(finish) : 'background:#ddd;';\n    const img = finish && finish.swatchUrl ? `<img src=\"${finish.swatchUrl}\" alt=\"\">` : '';\n    detail.innerHTML = `\n      <div class=\"btk-kp-journey-detail-body\">\n        <div class=\"btk-kp-journey-detail-preview btk-kp-journey-detail-swatch\" style=\"${img ? '' : swatchCss}\">${img}</div>\n        <div class=\"btk-kp-journey-detail-meta\">\n          <h3 class=\"btk-kp-journey-detail-title\">${jEsc(name)}</h3>\n          <p class=\"btk-kp-journey-detail-text\">Aluminium handleless rail profile in ${jEsc(name)}. Placeholder description - profile colour images and details will be added from a metaobject.</p>\n          ${jGreenBtn('Add to Plan', `data-btk-kp-journey-rail-select data-handle=\"${jEsc(handle)}\" data-name=\"${jEsc(name)}\"`, 'btk-kp-journey-detail-select')}\n        </div>\n      </div>`;\n  }\n\n  // Start a brand-new plan NOW. Planner Home's \"Start new empty plan\" and\n  // \"Use Current Room Shape\" run this the moment they are clicked: units (so the\n  // price and the unit count) to zero, the plan's basket to a fresh empty one,\n  // the name cleared. It used to happen only at the END of Style Setup, which\n  // was too late - the old units, price and basket showed all the way through,\n  // and Skip kept the old plan's name. keepRoom keeps the room shape + walls.\n  //\n  // ORDER MATTERS: the store lets go of the old plan's basket BEFORE the plan\n  // is emptied, or an autosave could write the empty plan over the old one.\n  let newPlanReset = null;        // the card's reset, still in flight\n  let journeyNeedsReset = false;  // started some other way: reset at its exit\n  // `room` (with keepRoom) = keep THAT room instead of the one on screen.\n  // ?btktime=1 marks for the Choose Room Shape path (Arden, 2026-10-07: the\n  // Room Shape popup takes 10-15s to appear). Its OWN list, timed from the\n  // click: the shared BTKKPTiming list is restarted by the stage change on the\n  // way, which wiped the marks before it. Inert without the flag.\n  // The website's Start Planning link uses it too (npStartFromPageLoad), timed\n  // from the moment the page began to load.\n  let npT0 = 0;\n  let npTitle = 'Choose Room Shape timings';\n  const npList = [];\n  // ?btktime=1 also sticks for THIS TAB (sessionStorage) until ?btktime=0 or\n  // the tab is closed, so the website's own Start Planning link - which cannot\n  // carry the flag - is timed too. It was localStorage, which kept the timings\n  // popping up in normal use, days later (Arden, 2026-10-08).\n  try { localStorage.removeItem('btk_kp_btktime'); } catch (_) {}\n  const npOn = () => {\n    try {\n      const v = new URLSearchParams(window.location.search).get('btktime');\n      if (v === '1') { try { sessionStorage.setItem('btk_kp_btktime', '1'); } catch (_) {} return true; }\n      if (v === '0') { try { sessionStorage.removeItem('btk_kp_btktime'); } catch (_) {} return false; }\n      return sessionStorage.getItem('btk_kp_btktime') === '1';\n    } catch (_) { return false; }\n  };\n  const npStart = (label) => {\n    if (!npOn()) return;\n    npT0 = performance.now();\n    npTitle = 'Choose Room Shape timings';\n    npList.length = 0;\n    npList.push(label + ': 0ms');\n  };\n  const npMark = (label) => { if (npT0) npList.push(label + ': ' + Math.round(performance.now() - npT0) + 'ms'); };\n  const npShow = () => {\n    if (!npT0) return;\n    npT0 = 0;\n    try { window.BTKKPDialog && window.BTKKPDialog.alert(npList.join(String.fromCharCode(10)), { title: npTitle }); } catch (_) {}\n  };\n  async function resetToNewPlan({ keepRoom = false, room = null, backgroundSave = false } = {}) {\n    // Finish the OLD plan's saving first: wait for an autosave already running,\n    // and run one still waiting on its timer now, while the old plan is still\n    // on screen. One landing after clear() pointed the working slot back at the\n    // old plan, and the new plan's empty first save then went into it - how\n    // plans were wiped on New Plan (Julian, 2026-09-29). The storage layer now\n    // refuses that anyway (mayOverwrite); this keeps the pointer honest too.\n    autosaveHeldForLinkedNewPlan = false;\n    npMark('reset: started' + (autosaveRunning ? ' (an autosave was running)' : ''));\n    for (let i = 0; autosaveRunning && i < 100; i++) await new Promise((r) => setTimeout(r, 100));\n    npMark('reset: no autosave running');\n    if (autosaveTimer) { clearTimeout(autosaveTimer); await runAutosave(); npMark('reset: pending autosave saved'); }\n    // backgroundSave: clearing the old plan joins the save queue too, ahead of\n    // the new plan's first save (below), instead of being waited for. It is\n    // one whole-project upload to say no plan is open - 3.7s on Arden's\n    // account (?btktime=1, 2026-10-07). The queue keeps the order: nothing\n    // that saves (autosave, Start Planning's save, Save / Save As) runs until\n    // the clear and the first save are done, so nothing lands in the old plan.\n    if (!backgroundSave) {\n      try { await planStore.clear(); } catch (e) { /* non-fatal */ }\n      npMark('reset: old plan cleared');\n    }\n    plannerPlanId = null;\n    // Style Setup's choices belong to the new plan's journey. Given no styles,\n    // applyState seeds them from the planner's current style - the OLD plan's -\n    // which put the previous style back into the Kitchen Style step. Keep what\n    // the journey holds: empty, or anything picked since the card was clicked.\n    const journeyPicks = { styles: buyingStyles, handles: buyingHandles, worktops: buyingWorktops, rails: buyingRails };\n    // ...and the F&B / RAL paints those picks use (applyState forgets paints).\n    const keepPaints = (Catalogue.getBespokePaints ? Catalogue.getBespokePaints() : []).filter(p =>\n      (journeyPicks.styles || []).some(s => s && Catalogue.bespokePaintHandle && s.doorHandle === Catalogue.bespokePaintHandle(p.kind, p.code)));\n    applyState({\n      roomConfig: keepRoom ? JSON.parse(JSON.stringify(room || roomConfig)) : freshRoomConfig(),\n      cabinets: []\n    });\n    buyingStyles   = journeyPicks.styles;\n    buyingHandles  = journeyPicks.handles;\n    buyingWorktops = journeyPicks.worktops;\n    buyingRails    = journeyPicks.rails;\n    for (const p of keepPaints) { try { Catalogue.registerBespokePaint?.(p); } catch (_) {} }\n    // Nor the old plan's door and carcase colours (Arden, 2026-10-10): with no\n    // units and none saved, applyState kept the last plan's, and new units\n    // took them. The new plan's own style picks, if any yet, give them.\n    globalDoorColourHandle    = (journeyPicks.styles[0] && journeyPicks.styles[0].doorHandle) || null;\n    globalCarcaseColourHandle = (journeyPicks.styles[0] && journeyPicks.styles[0].carcaseHandle) || null;\n    planThumb = null;   // fresh plan: no preview until viewed in 3D + saved\n    takePlanPrice(null);\n    activePlanName = null;\n    designControlsHandle.setPlanName(null);\n    // Units staged from a converted basket belonged to the old plan.\n    convertStagedUnits = [];\n    renderConvertTray();\n    // A new plan has its own history. Undo snapshots carry the plan's id and\n    // units, so stepping back would have brought the old plan straight back.\n    undoStack.length = 0;\n    redoStack.length = 0;\n    undoLast = undoSnapshot();\n    syncUndoButtons();\n    // Its own empty basket straight away (an unsaved draft; naming the plan\n    // promotes it), so the basket shows THIS plan instead of falling back to\n    // the last planner basket.\n    npMark('reset: new plan set up on screen');\n    // backgroundSave (Choose Room Shape, Arden 2026-10-07): the empty plan's\n    // first save sends the customer's whole project to the planner API - 25s\n    // for an account of ~100 plans - and Room Setup / Room Shape waited for it.\n    // Now it joins the journey-save queue (journeySaveInFlight) and the reset\n    // returns at once. The queue keeps the order safe: the save that names the\n    // plan (saveJourneyPlanInBackground) waits for it, and so does autosave\n    // (awaitJourneySave), so nothing can overtake it into the wrong basket.\n    const firstSave = async (design) => {\n      try { await planStore.save(design); } catch (e) { /* non-fatal */ }\n      npMark('reset: new empty plan saved to the server');\n      refreshLiveQuoteLabels();\n      basketDrawerHandle?.refresh?.();\n    };\n    if (backgroundSave) {\n      const design = currentDesign();\n      const prev = journeySaveInFlight;\n      const run = (async () => {\n        if (prev) { try { await prev; } catch (e) {} }\n        try { await planStore.clear(); } catch (e) { /* non-fatal */ }\n        npMark('reset: old plan cleared (in the background)');\n        await firstSave(design);\n      })();\n      journeySaveInFlight = run;\n      run.finally(() => { if (journeySaveInFlight === run) journeySaveInFlight = null; });\n      return;\n    }\n    await firstSave(currentDesign());\n  }\n\n  function startGuidedJourney(opts) {\n    journey.styleId = journey.doorHandle = journey.carcaseHandle = journey.railHandle = null;\n    journey.doorName = journey.carcaseName = journey.railName = '';\n    journey.handleDesignId = journey.handleFinishHandle = journey.worktopHandle = null;\n    journey.handleName = journey.handleFinishName = journey.worktopName = '';\n    // Start New Plan = a clean slate: no style/handles/worktops carried over.\n    // (The storefront \"Plan Online\" deep-link presets buyingStyles itself after\n    // calling this, so it still lands with the website's chosen style.)\n    buyingStyles = []; buyingHandles = []; buyingWorktops = []; buyingRails = [];\n    wallChosen = false; floorChosen = false;\n    journeyKeepRoom = !!(opts && opts.keepRoom);\n    // Planner Home's cards reset the plan as they are clicked (resetDone);\n    // any other way in (a storefront link, the Style Setup stage) resets at\n    // the journey's exit, as before.\n    journeyNeedsReset = !(opts && opts.resetDone);\n    journeyStarted = true;   // so re-entering Style Setup keeps this journey\n    journeyMode = 'new';     // finishing this journey creates a fresh blank plan\n    setJourneyNameInput('');  // a new plan starts unnamed\n    journeyReplaceName = '';  // and with no Replace agreed\n    showJourneyNav(true);    // switch to the Style Setup stage\n    // Fast path: Start Planning \u2192 name \u2192 Room Setup. Style/handles/worktops\n    // are optional and editable any time from the mood board.\n    renderJourneyName();\n    showJourneyStep('name');\n  }\n\n  // Is there a plan worth continuing (rather than starting a fresh journey)?\n  function planHasContent() {\n    return (Array.isArray(cabinets) && cabinets.length > 0) || !!activePlanName;\n  }\n\n  // New Plan's room-shape card:\n  //   plan loaded       -> \"Use Current Room Shape\": keeps that plan's room.\n  //   none, but saved   -> \"Use Previous Room Shape\": the newest saved plan's\n  //                        room (previousPlanRoom).\n  //   no saved plans    -> the card is not shown: a first-time planner has no\n  //                        room to keep.\n  // The label is right straight away; showing / hiding waits for the list.\n  async function syncRoomShapeCard() {\n    const btn = root.querySelector('[data-btk-kp-home-view=\"start-from-room\"]');\n    if (!btn) return;\n    const card = btn.closest('.btk-kp-home-card');\n    const loaded = planHasContent();\n    const label = btn.querySelector('[data-btk-kp-room-shape-label]');\n    if (label) label.textContent = loaded ? 'Use Current Room Shape' : 'Use Previous Room Shape';\n    const seq = ++roomShapeSyncSeq;\n    let plans = [];\n    try { plans = await planStore.listPlans(); } catch (e) { /* treat as none */ }\n    if (seq !== roomShapeSyncSeq) return;   // a newer sync has run\n    previousPlanRoom = (plans.find(p => p.roomConfig) || {}).roomConfig || null;\n    const show = loaded || !!previousPlanRoom;\n    if (card) card.hidden = !show;\n  }\n\n  // Rebuild the journey state from the CURRENTLY-LOADED plan so returning to\n  // Style Setup shows what's already been chosen (stages tick, pickers land on\n  // the current selection) and the user can carry on rather than start over.\n  // Display names aren't stored on the plan, so resolve them from the Catalogue.\n  function hydrateJourneyFromPlan() {\n    journey.styleId       = kitchenStyleId || null;\n    journey.doorHandle    = globalDoorColourHandle || null;\n    journey.carcaseHandle = globalCarcaseColourHandle || null;\n    journey.railHandle    = railFinishHandle || null;\n    const baseGroup = handleGroups && handleGroups.base;\n    journey.handleDesignId     = (baseGroup && baseGroup.designId)     || null;\n    journey.handleFinishHandle = (baseGroup && baseGroup.finishHandle) || null;\n    journey.worktopHandle      = worktopMaterialHandle || null;\n    // Names (not persisted) - resolve from the catalogue lists.\n    const doors = (journey.styleId && Catalogue.getDoorColoursForStyle) ? (Catalogue.getDoorColoursForStyle(journey.styleId) || []) : [];\n    journey.doorName = (doors.find(d => d.handle === journey.doorHandle) || {}).name || '';\n    const carcases = (journey.styleId && Catalogue.getCarcaseColoursForStyle) ? (Catalogue.getCarcaseColoursForStyle(journey.styleId) || []) : [];\n    journey.carcaseName = (carcases.find(c => c.handle === journey.carcaseHandle) || {}).name || '';\n    const rail = (journey.railHandle && Catalogue.getRailFinish) ? Catalogue.getRailFinish(journey.railHandle) : null;\n    journey.railName = rail ? (rail.name || journey.railHandle) : '';\n    const hDesign = (journey.handleDesignId && Catalogue.getHandleDesigns) ? (Catalogue.getHandleDesigns() || []).find(d => d.id === journey.handleDesignId) : null;\n    journey.handleName = hDesign ? (hDesign.name || journey.handleDesignId) : '';\n    const hFins = (journey.handleDesignId && Catalogue.getHandleFinishesForDesign) ? (Catalogue.getHandleFinishesForDesign(journey.handleDesignId) || []) : [];\n    journey.handleFinishName = (hFins.find(f => f.handle === journey.handleFinishHandle) || {}).name || '';\n    const wt = (journey.worktopHandle && Catalogue.getWorktopMaterial) ? Catalogue.getWorktopMaterial(journey.worktopHandle) : null;\n    journey.worktopName = wt ? (wt.title || journey.worktopHandle) : '';\n    // A loaded plan with a non-default wall/floor means it was chosen \u2192 tick.\n    wallChosen  = !!wallColourHandle  && wallColourHandle  !== DEFAULT_WALL_COLOUR_HANDLE;\n    floorChosen = !!floorColourHandle && floorColourHandle !== DEFAULT_FLOOR_COLOUR_HANDLE;\n    // buyingStyles is restored by applyState on load; seed the active style if\n    // the loaded plan predates the multi-style set.\n    if (!buyingStyles.length && journey.styleId) {\n      buyingStyles = [{ styleId: journey.styleId, doorHandle: journey.doorHandle, carcaseHandle: journey.carcaseHandle }];\n    }\n    journeyStarted = true;\n    journeyMode = 'edit';    // finishing applies to the existing plan (keeps units)\n    setJourneyNameInput(activePlanName || '');\n    renderJourneyName();\n    showJourneyStep('name');   // land on the mood board; options open from it\n  }\n\n  // ---- Skip the setup \u2192 straight to Add Items -------------------------\n  // A friendly confirm, then start a fresh plan with whatever's been chosen so\n  // far and drop the user on the Add Items stage. Skip links live in the\n  // left-menu stepper and under each stage in the right pane.\n  async function handleSkipJourney() {\n    var ok = true;\n    if (window.BTKKPDialog && window.BTKKPDialog.confirm) {\n      ok = await window.BTKKPDialog.confirm(\n        \"The planner's at its best with your style, colours, handles and worktops chosen - but no worries if you'd rather dive straight in. You can set all of these any time inside the planner.\",\n        { title: 'Skip setup?', confirmText: 'Skip & Start Planning' }\n      );\n    }\n    if (ok) skipJourney();\n  }\n  async function skipJourney() {\n    if (journeyMode === 'edit') {\n      // Existing plan - \"skip\" just drops back into planning; nothing wiped or\n      // re-applied (the plan already carries its style/handles/worktop).\n      journeyStarted = false;\n      stepperHandle.setStep('add-units');\n      return;\n    }\n    syncJourneyFromOptions();\n    const snap = { styles: buyingStyles.slice(), handles: buyingHandles.slice(), worktops: buyingWorktops.slice(), rails: buyingRails.slice() };   // survive the new-plan reset\n    // The new plan was reset when its card was clicked; otherwise reset now.\n    if (newPlanReset) { try { await newPlanReset; } catch (e) {} newPlanReset = null; }\n    if (journeyNeedsReset) await resetToNewPlan({ keepRoom: journeyKeepRoom });\n    journeyNeedsReset = false;\n    // Apply whatever the customer chose before skipping.\n    if (journey.styleId)       applyDeepLinkStyle(journey.styleId, journey.doorHandle, journey.carcaseHandle);\n    if (journey.railHandle)    handleSetRailFinish(journey.railHandle);\n    if (journey.handleDesignId) handleSetGlobalHandle({ designId: journey.handleDesignId, finishHandle: journey.handleFinishHandle });\n    if (journey.worktopHandle) handleSetWorktopMaterial(journey.worktopHandle);\n    commitJourneyBuyingStyles(snap);   // persist any styles chosen so far\n    refreshLiveQuoteLabels();\n    journeyStarted = false;   // journey consumed; next open starts fresh\n    stepperHandle.setStep('add-units');\n  }\n  // Delegated: covers the static left-menu / style-step skip AND the skip\n  // rendered dynamically under each detail-panel Select.\n  root.addEventListener('click', function (e) {\n    if (e.target.closest('[data-btk-kp-journey-skip]')) { e.preventDefault(); handleSkipJourney(); }\n  });\n\n  // Seed the buying-style set FROM the shared session store (styles the user\n  // picked on the kitchen listing / detail pages). Used when starting a NEW\n  // plan so listing-page browsing carries into Style Setup. A LOADED plan\n  // leads instead (its own buyingStyles win + get pushed back to session).\n  // Active first, then alternates, deduped, capped at 3.\n  function seedBuyingStylesFromSession() {\n    const out = [];\n    const add = (c) => {\n      if (!c || !c.style || out.length >= 3) return;\n      if (out.some(s => s.styleId === c.style && s.doorHandle === (c.colour || null))) return;\n      out.push({ styleId: c.style, doorHandle: c.colour || null, carcaseHandle: c.carcase || null });\n    };\n    try { add(JSON.parse(sessionStorage.getItem('btk_kitchen_context') || 'null')); } catch (_) {}\n    try { (JSON.parse(sessionStorage.getItem('btk_comparison_styles') || '[]') || []).forEach(add); } catch (_) {}\n    return out;\n  }\n\n  // Build a buying-style session ctx (the shape btk_kitchen_context /\n  // btk_comparison_styles use) from a buyingStyles entry.\n  function buyingStyleCtx(bs) {\n    const ks = Catalogue.getKitchenStyle?.(bs.styleId);\n    const doorColour = lookupColourInList(Catalogue.getDoorColoursForStyle?.(bs.styleId), bs.doorHandle);\n    return {\n      style:      bs.styleId,\n      styleName:  ks?.name || bs.styleId,\n      colour:     bs.doorHandle || '',\n      colourName: doorColour?.name || '',\n      carcase:    bs.carcaseHandle || 'white'\n    };\n  }\n  // Push the full Style Setup set to the SHARED buying-style session store so\n  // the kitchen-style pages AND the planner's Add-Units \"switch style\" bar all\n  // reflect it: [0] = active (btk_kitchen_context), the rest = alternates\n  // (btk_comparison_styles), plus the slot keys + cart mirror + change event.\n  function syncBuyingStylesToSession() {\n    // A plan with no planning style yet (a new plan - Arden, 2026-10-07) clears\n    // the shared store, so the Add Units bar, the kitchen pages and the cart\n    // stop showing the last plan's style.\n    if (!buyingStyles.length) {\n      for (const k of ['btk_kitchen_context', 'btk_comparison_styles', 'btk_style_slots']) {\n        try { sessionStorage.removeItem(k); } catch (_) {}\n      }\n      try {\n        fetch('/cart/update.js', {\n          method: 'POST', headers: { 'Content-Type': 'application/json' },\n          body: JSON.stringify({ attributes: {\n            kitchen_style: '', kitchen_style_name: '', kitchen_colour: '',\n            kitchen_carcase_colour: '', kitchen_comparison_styles: ''\n          }})\n        });\n      } catch (_) {}\n      try { document.dispatchEvent(new CustomEvent('btk:style-changed', { detail: null })); } catch (_) {}\n      return;\n    }\n    const active = buyingStyleCtx(buyingStyles[0]);\n    const alts   = buyingStyles.slice(1).map(buyingStyleCtx);\n    try { sessionStorage.setItem('btk_kitchen_context', JSON.stringify(active)); } catch (_) {}\n    try { sessionStorage.setItem('btk_comparison_styles', JSON.stringify(alts)); } catch (_) {}\n    reconcileBuyingStyleSlots();\n    try {\n      fetch('/cart/update.js', {\n        method: 'POST', headers: { 'Content-Type': 'application/json' },\n        body: JSON.stringify({ attributes: {\n          kitchen_style:            active.style,\n          kitchen_style_name:       active.styleName || '',\n          kitchen_colour:           active.colour,\n          kitchen_carcase_colour:   active.carcase,\n          // Persist the alternates to cart too (cart is shared across tabs, so\n          // the full set survives a new browser tab / session - not just the\n          // active). Empty string clears it.\n          kitchen_comparison_styles: alts.length ? JSON.stringify(alts) : ''\n        }})\n      });\n    } catch (_) {}\n    try { document.dispatchEvent(new CustomEvent('btk:style-changed', { detail: active })); } catch (_) {}\n  }\n\n  // Sync the persisted buying-style set to the journey's final main-style\n  // selection (door + carcase chosen in later steps). `snapshot` guards the set\n  // against applyState() rebuilding it during a new-plan reset.\n  // Ensure journey.* holds the applied (first) option, even if the user added\n  // via a picker then jumped ahead by the left-menu nav instead of Confirm.\n  function syncJourneyFromOptions() {\n    // journey.* mirrors the MAIN (first) of each option set. Always overwrite -\n    // if the user removes / re-orders (Set as main) a style, the mood board must\n    // reflect the new [0], not keep the previously-set value.\n    const s = buyingStyles[0];\n    journey.styleId       = s ? s.styleId : null;\n    journey.doorHandle    = s ? s.doorHandle : null;\n    journey.carcaseHandle = s ? s.carcaseHandle : null;\n    const doors = (journey.styleId && Catalogue.getDoorColoursForStyle) ? (Catalogue.getDoorColoursForStyle(journey.styleId) || []) : [];\n    journey.doorName = (doors.find(d => d.handle === journey.doorHandle) || {}).name || '';\n    const carcs = (journey.styleId && Catalogue.getCarcaseColoursForStyle) ? (Catalogue.getCarcaseColoursForStyle(journey.styleId) || []) : [];\n    journey.carcaseName = (carcs.find(c => c.handle === journey.carcaseHandle) || {}).name || '';\n    const h = buyingHandles[0];\n    journey.handleDesignId     = h ? h.designId : null;\n    journey.handleName         = h ? (h.designName || '') : '';\n    journey.handleFinishHandle = h ? h.finishHandle : null;\n    journey.handleFinishName   = h ? (h.finishName || '') : '';\n    const w = buyingWorktops[0];\n    journey.worktopHandle = w ? w.handle : null;\n    journey.worktopName   = w ? (w.name || '') : '';\n    const r = buyingRails[0];\n    journey.railHandle = r ? r.handle : null;\n    journey.railName   = r ? (r.name || '') : '';\n  }\n\n  function commitJourneyBuyingStyles(snap) {\n    snap = snap || {};\n    // Styles - [0] synced to the journey's final main selection.\n    let s = (snap.styles || buyingStyles).slice();\n    if (s.length && journey.styleId) s[0] = { styleId: journey.styleId, doorHandle: journey.doorHandle, carcaseHandle: journey.carcaseHandle };\n    else if (!s.length && journey.styleId) s = [{ styleId: journey.styleId, doorHandle: journey.doorHandle, carcaseHandle: journey.carcaseHandle }];\n    buyingStyles = s.filter(x => x && x.styleId);\n    // Handles / worktops / rails - [0] synced to the applied journey value.\n    let h = (snap.handles || buyingHandles).slice();\n    if (h.length && journey.handleDesignId) h[0] = { designId: journey.handleDesignId, designName: journey.handleName || '', finishHandle: journey.handleFinishHandle, finishName: journey.handleFinishName || '' };\n    buyingHandles = h.filter(x => x && x.designId);\n    let w = (snap.worktops || buyingWorktops).slice();\n    if (w.length && journey.worktopHandle) w[0] = { handle: journey.worktopHandle, name: journey.worktopName || '' };\n    buyingWorktops = w.filter(x => x && x.handle);\n    let r = (snap.rails || buyingRails).slice();\n    if (r.length && journey.railHandle) r[0] = { handle: journey.railHandle, name: journey.railName || '' };\n    buyingRails = r.filter(x => x && x.handle);\n    syncBuyingStylesToSession();   // reflect on the kitchen pages + planner bar\n  }\n\n  // START PLANNING SAVES IN THE BACKGROUND. It used to wait for a picture of\n  // the plan (a raster of the view, for a plan that is still empty) and a\n  // whole-project upload before Room Setup could appear - 3 to 5 seconds on a\n  // button that should feel instant (Arden, 2026-09-29). The screen moves on\n  // at once; the save follows. Anything else that saves waits for it\n  // (awaitJourneySave), so a quick autosave cannot race it into a second copy\n  // of the plan. A failure still shows, via btk:project-save-failed.\n  function saveJourneyPlanInBackground(name, withThumb) {\n    // Behind any save already queued - the new plan's empty first save above -\n    // so this one, which names the plan, always lands second.\n    const prev = journeySaveInFlight;\n    const run = (async () => {\n      if (prev) { try { await prev; } catch (e) {} }\n      try {\n        const design = withThumb ? await currentDesignWithThumb() : currentDesign();\n        // The name the customer gave the plan here (Edit Plan Setup can change it).\n        await planStore.saveAs(name, design, { rename: true });\n      } catch (err) { console.warn('[BTK Kitchen Planner] Journey save failed', err); }\n    })();\n    journeySaveInFlight = run;\n    run.finally(() => { if (journeySaveInFlight === run) journeySaveInFlight = null; });\n    return run;\n  }\n  async function awaitJourneySave() {\n    const p = journeySaveInFlight;\n    if (p) { try { await p; } catch (e) {} }\n  }\n\n  async function finishGuidedJourney() {\n    const name = journeyPlanName();\n    if (!name) { openJourneyNamePopup({ mode: 'finish' }); return; }\n    // A new plan must not take over a saved plan that already has this name.\n    // Agreed to already in the name popup -> remove the other plan now, without\n    // asking twice; otherwise ask here (confirmPlanNameFree).\n    if (journeyMode !== 'edit') {\n      if (name === journeyReplaceName) {\n        await removeOtherPlansNamed(name, plannerPlanId);\n        journeyReplaceName = '';   // used up\n      } else if (window.BTKKPDialog && window.BTKKPDialog.confirm && !(await confirmPlanNameFree(name))) {\n        openJourneyNamePopup({ mode: 'finish' });\n        return;\n      }\n      npMark('finish: name checked again');\n    }\n    // The plan always applies the ACTIVE planning style (buyingStyles[0]). If\n    // the carousel is parked on a 2nd/3rd style, warn that only the active one\n    // is used before proceeding.\n    if (moodBoardIndex >= 1 && buyingStyles.length > 1 && window.BTKKPDialog && window.BTKKPDialog.confirm) {\n      const ok = await window.BTKKPDialog.confirm(\n        'Your plan is updated using your ACTIVE planning style only. The alternate style you\\'re viewing here isn\\'t applied - set it as active first if you want to use it.',\n        { title: 'Active style is applied', confirmText: 'Update to active style', cancelText: 'Cancel' }\n      );\n      if (!ok) return;\n    }\n    closeJourneyNamePopup();   // the name is accepted: on to the plan\n    syncJourneyFromOptions();\n    // Name-first flow: a style isn't required to start planning. A NEW plan\n    // starts with no planning style at all - the last plan's was carried over\n    // here before (Arden, 2026-10-07) - and is asked for one before its first\n    // unit (styleGated). Editing a plan still falls back to its current style.\n    if (!journey.styleId && journeyMode === 'edit') {\n      journey.styleId       = kitchenStyleId || null;\n      journey.doorHandle    = globalDoorColourHandle;\n      journey.carcaseHandle = globalCarcaseColourHandle;\n    }\n    if (!journey.styleId && journeyMode === 'edit') return;   // safety: no default available\n    const snap = { styles: buyingStyles.slice(), handles: buyingHandles.slice(), worktops: buyingWorktops.slice(), rails: buyingRails.slice() };   // survive a new-plan reset\n    if (journeyMode === 'edit') {\n      // Editing an existing plan: apply the (possibly changed) setup and KEEP\n      // every unit. Restyle the whole plan so existing cabinets follow the\n      // style/colour; rail, handles and worktop are plan-wide.\n      applyRestyleToWholePlan(journey.styleId, journey.doorHandle, journey.carcaseHandle);\n      if (journey.railHandle) handleSetRailFinish(journey.railHandle);\n      if (journey.handleDesignId) handleSetGlobalHandle({ designId: journey.handleDesignId, finishHandle: journey.handleFinishHandle });\n      if (journey.worktopHandle) handleSetWorktopMaterial(journey.worktopHandle);\n      commitJourneyBuyingStyles(snap);\n      activePlanName = name;\n      designControlsHandle.setPlanName(name);\n      refreshLiveQuoteLabels();\n      journeyStarted = false;\n      stepperHandle.setStep('add-units');   // back to planning, units intact\n      // Saved behind the screen change (this plan has units, so it gets its\n      // picture) - see saveJourneyPlanInBackground.\n      saveJourneyPlanInBackground(name, true).then(() => basketDrawerHandle?.refresh?.());\n      return;\n    }\n    // Start a BRAND-NEW blank plan - don't carry over / rename any plan that\n    // happened to be loaded. (Same reset handleClear does, minus the prompt.)\n    // The new plan was reset when its card was clicked; otherwise reset now\n    // (\"New Plan from Current Room Shape\" keeps the room either way).\n    if (newPlanReset) { try { await newPlanReset; } catch (e) {} newPlanReset = null; }\n    npMark('finish: waited for the reset');\n    // backgroundSave: the empty plan's upload joins the save queue rather than\n    // being waited for - 14s of the website Start Planning's wait (?btktime=1,\n    // Arden 2026-10-07). See resetToNewPlan.\n    if (journeyNeedsReset) await resetToNewPlan({ keepRoom: journeyKeepRoom, backgroundSave: true });\n    journeyNeedsReset = false;\n    // Apply the chosen style + door + carcase as the new plan's defaults\n    // (none chosen: the plan has no planning style yet).\n    if (journey.styleId) applyDeepLinkStyle(journey.styleId, journey.doorHandle, journey.carcaseHandle);\n    npMark('finish: style applied');\n    // True Handleless: apply the chosen rail profile colour too.\n    if (journey.railHandle) handleSetRailFinish(journey.railHandle);\n    // Handled styles: apply the chosen handle design + finish across all groups.\n    if (journey.handleDesignId) handleSetGlobalHandle({ designId: journey.handleDesignId, finishHandle: journey.handleFinishHandle });\n    // Apply the chosen plan-wide worktop material.\n    if (journey.worktopHandle) handleSetWorktopMaterial(journey.worktopHandle);\n    commitJourneyBuyingStyles(snap);   // persist the multi-style set\n    activePlanName = name;\n    designControlsHandle.setPlanName(name);\n    refreshLiveQuoteLabels();\n    journeyStarted = false;   // journey consumed; next open starts fresh\n    stepperHandle.setStep('room-setup');\n    npMark('Room Setup on screen');\n    // Saved behind the screen change, with no picture: a brand-new plan is\n    // empty, and it gets one on its first real save.\n    saveJourneyPlanInBackground(name, false).then(() => basketDrawerHandle?.refresh?.());\n    // A brand-new room: straight into Room Shape (and, once a shape is in,\n    // Room Height - see onShapeCommitted). Opened through the Start New Room\n    // button so it behaves exactly as that does. Not when the plan kept the\n    // current room (\"New Plan from Current Room Shape\") - that room is set.\n    if (!journeyKeepRoom) {\n      requestAnimationFrame(() => {\n        if (document.querySelector('.btk-kp-dialog-overlay')) return;\n        root.querySelector('[data-btk-kp-room-shape-opener]')?.click();\n        if (startBtnBusy) setRoomShapeLoading(false);   // opened over the Start page while it loaded\n        // ?btktime=1: once the Room Shape popup has painted, show the timings.\n        requestAnimationFrame(() => requestAnimationFrame(() => {\n          npMark('Room Shape popup on screen');\n          // After the stage-change timing popup (shown ~0.6s after the stage\n          // change), so this one sits on top of it.\n          setTimeout(npShow, 1500);\n        }));\n      });\n    }\n  }\n\n  if (journeyEl) {\n    journeyEl.addEventListener('click', (e) => {\n      // Mood-board \u2039 / \u203A nav \u2192 slide the carousel between buying-style sets.\n      if (e.target.closest('[data-btk-kp-mood-prev]')) { slideMoodBoard(-1); return; }\n      if (e.target.closest('[data-btk-kp-mood-next]')) { slideMoodBoard(1); return; }\n      // Mood-board hotspot \u2192 jump to that item's setup stage.\n      const moodGoto = e.target.closest('[data-btk-kp-mood-goto]');\n      if (moodGoto) { gotoJourneyStage(moodGoto.dataset.btkKpMoodGoto); return; }\n      // Setup popup X / backdrop, and the name popup's.\n      if (e.target.closest('[data-btk-kp-journey-popup-close]')) { closeJourneyPopup(); return; }\n      if (e.target.closest('[data-btk-kp-journey-name-edit]')) { openJourneyNamePopup({ mode: 'rename' }); return; }\n      // Handle Selector toggle \u2192 one tile for the lot, or one per unit type.\n      const hMode = e.target.closest('[data-btk-kp-journey-handle-mode]');\n      if (hMode) {\n        journeyHandleMode = hMode.dataset.btkKpJourneyHandleMode;\n        renderJourneyHandleGroups();\n        return;\n      }\n      // Wall / floor colour swatch \u2192 apply immediately, then drop back to the\n      // Planning Style Overview (like the other options - choose & return).\n      const wallSw = e.target.closest('[data-btk-kp-journey-wall-swatch]');\n      if (wallSw) { wallChosen = true; handleSetWallColour(wallSw.dataset.btkKpJourneyWallSwatch); renderJourneyName(); showJourneyStep('name'); return; }\n      const floorSw = e.target.closest('[data-btk-kp-journey-floor-swatch]');\n      if (floorSw) { floorChosen = true; handleSetFloorColour(floorSw.dataset.btkKpJourneyFloorSwatch); renderJourneyName(); showJourneyStep('name'); return; }\n      // \"Add Nth style\" blank \u2192 open the kitchen-style list and scroll to it.\n      const addSlot = e.target.closest('[data-btk-kp-journey-style-add]');\n      if (addSlot) { openStylePicker(); return; }\n      // Remove a buying-style slot.\n      const remBtn = e.target.closest('[data-btk-kp-journey-style-remove]');\n      if (remBtn) {\n        const i = parseInt(remBtn.dataset.btkKpJourneyStyleRemove, 10);\n        if (i >= 0 && i < buyingStyles.length) buyingStyles.splice(i, 1);\n        renderJourneyStyleSlots();\n        if (!buyingStyles.length) openStylePicker();   // back to the empty state\n        updateStyleConfirmState();\n        updateJourneyNav('style');\n        syncBuyingStylesToSession();   // live: reflect on kitchen pages + planner bar\n        return;\n      }\n      // Promote a slot to the MAIN (active) style.\n      const mkFirst = e.target.closest('[data-btk-kp-journey-style-makefirst]');\n      if (mkFirst) {\n        const i = parseInt(mkFirst.dataset.btkKpJourneyStyleMakefirst, 10);\n        if (i > 0 && i < buyingStyles.length) { const [s] = buyingStyles.splice(i, 1); buyingStyles.unshift(s); }\n        renderJourneyStyleSlots();\n        updateStyleConfirmState();\n        updateJourneyNav('style');\n        syncBuyingStylesToSession();   // live: reflect on kitchen pages + planner bar\n        return;\n      }\n      // \"Back to Mood Board\" - applies the ACTIVE style on the way out, which\n      // is what the old Done button did. Nothing chosen yet is not an error:\n      // there is simply nothing to apply, and the trip back still stands.\n      const styleConfirm = e.target.closest('[data-btk-kp-journey-style-confirm]');\n      if (styleConfirm) {\n        const first = buyingStyles[0];\n        if (first) {\n          journey.styleId       = first.styleId;\n          journey.doorHandle    = first.doorHandle;\n          journey.carcaseHandle = first.carcaseHandle;   // chosen on the card\n          const cols = (Catalogue.getDoorColoursForStyle && Catalogue.getDoorColoursForStyle(first.styleId)) || [];\n          journey.doorName = (cols.find(c => c.handle === first.doorHandle) || {}).name || '';\n          const carcs = (Catalogue.getCarcaseColoursForStyle && Catalogue.getCarcaseColoursForStyle(first.styleId)) || [];\n          journey.carcaseName = (carcs.find(c => c.handle === first.carcaseHandle) || {}).name || '';\n        }\n        renderJourneyName(); showJourneyStep('name');   // back to Plan Name (name-first)\n        return;\n      }\n      // Carcase tile \u2192 show its detail in the right panel (don't advance).\n      const carcaseBtn = e.target.closest('[data-btk-kp-journey-carcase]');\n      if (carcaseBtn) {\n        journeyEl.querySelectorAll('[data-btk-kp-journey-carcase]').forEach(t => t.classList.toggle('is-active', t === carcaseBtn));\n        renderJourneyCarcaseDetail(carcaseBtn.dataset.btkKpJourneyCarcase, carcaseBtn.dataset.btkKpJourneyCarcaseName || '');\n        return;\n      }\n      // Carcase Select (in the detail panel) \u2192 lock it in, then either the\n      // rail-colour step (True Handleless) or naming.\n      const carcaseSelect = e.target.closest('[data-btk-kp-journey-carcase-select]');\n      if (carcaseSelect) {\n        journey.carcaseHandle = carcaseSelect.dataset.handle;\n        journey.carcaseName   = carcaseSelect.dataset.name || '';\n        advanceAfterCarcase();\n        return;\n      }\n      // Rail profile tile \u2192 show its detail (don't advance).\n      const railBtn = e.target.closest('[data-btk-kp-journey-rail]');\n      if (railBtn) {\n        journeyEl.querySelectorAll('[data-btk-kp-journey-rail]').forEach(t => t.classList.toggle('is-active', t === railBtn));\n        renderJourneyRailDetail(railBtn.dataset.btkKpJourneyRail, railBtn.dataset.btkKpJourneyRailName || '');\n        return;\n      }\n      // Rail \"Add to Plan\" \u2192 add the profile-colour option (up to 3).\n      const railSelect = e.target.closest('[data-btk-kp-journey-rail-select]');\n      if (railSelect) {\n        optAdd(OPT.rails, { handle: railSelect.dataset.handle, name: railSelect.dataset.name || '' });\n        return;\n      }\n      // Multi-option: \"Add another\" placeholder, remove, set-main, confirm.\n      const optAddBtn = e.target.closest('[data-btk-kp-opt-add]');\n      if (optAddBtn) { const c = OPT[optAddBtn.dataset.btkKpOptAdd]; if (c) optOpenPicker(c); return; }\n      const optRemBtn = e.target.closest('[data-btk-kp-opt-remove]');\n      if (optRemBtn) { const c = OPT[optRemBtn.dataset.btkKpOptRemove]; if (c) optRemove(c, parseInt(optRemBtn.dataset.i, 10)); return; }\n      const optMkBtn = e.target.closest('[data-btk-kp-opt-makefirst]');\n      if (optMkBtn) { const c = OPT[optMkBtn.dataset.btkKpOptMakefirst]; if (c) optMakeFirst(c, parseInt(optMkBtn.dataset.i, 10)); return; }\n      if (e.target.closest('[data-btk-kp-journey-handle-confirm]'))  { optConfirm(OPT.handles);  return; }\n      if (e.target.closest('[data-btk-kp-journey-worktop-confirm]')) { optConfirm(OPT.worktops); return; }\n      if (e.target.closest('[data-btk-kp-journey-rail-confirm]'))    { optConfirm(OPT.rails);    return; }\n      // Start Planning: straight on when the plan is already named (it was\n      // named before the mood board), else the name popup first.\n      if (e.target.closest('[data-btk-kp-journey-finish]')) {\n        if (journeyPlanName()) finishGuidedJourney();\n        else openJourneyNamePopup({ mode: 'finish' });\n      }\n    });\n  }\n\n  // ---- Planner Home \"How To Guides\" (expandable text link) ------------\n  // Reuses the shared help content (window.BTKKPHelp) as an accordion in the\n  // home sidebar; clicking a guide renders its body in the right panel.\n  const howtoWrap    = root.querySelector('[data-btk-kp-howto]');\n  const howtoToggle  = root.querySelector('[data-btk-kp-howto-toggle]');\n  const howtoNav     = root.querySelector('[data-btk-kp-howto-nav]');\n  const howtoContent = root.querySelector('[data-btk-kp-howto-content]');\n  const howtoState   = { openSection: null, activeGuide: null };\n  const helpData = () => (window.BTKKPHelp && window.BTKKPHelp.getContent && window.BTKKPHelp.getContent()) || [];\n\n  function renderHowtoNav() {\n    if (!howtoNav) return;\n    howtoNav.innerHTML = helpData().map(s => {\n      const open = s.id === howtoState.openSection;\n      const guides = open\n        ? `<div class=\"btk-kp-howto-guides\">${(s.guides || []).map(g =>\n            `<button type=\"button\" class=\"btk-kp-howto-guide${howtoState.activeGuide === g.id ? ' is-active' : ''}\" data-btk-kp-howto-guide=\"${jEsc(g.id)}\" data-section=\"${jEsc(s.id)}\">${jEsc(g.title)}</button>`\n          ).join('')}</div>`\n        : '';\n      return `<div class=\"btk-kp-howto-section${open ? ' is-open' : ''}\">\n        <button type=\"button\" class=\"btk-kp-howto-section-btn\" data-btk-kp-howto-section=\"${jEsc(s.id)}\">\n          <span>${jEsc(s.title)}</span>\n          <svg class=\"btk-kp-howto-caret\" width=\"12\" height=\"12\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\"><path d=\"M9 18l6-6-6-6\"/></svg>\n        </button>${guides}</div>`;\n    }).join('');\n  }\n\n  function showHowtoGuide(sectionId, guideId) {\n    const section = helpData().find(s => s.id === sectionId);\n    const guide   = section && (section.guides || []).find(g => g.id === guideId);\n    if (howtoContent) {\n      const backBtn = '<button type=\"button\" class=\"btk-kp-action-btn btk-kp-action-btn--green btk-kp-action-btn--sm btk-kp-howto-back\" data-btk-kp-howto-back>'\n        + '<span class=\"btk-kp-action-btn-icon\" aria-hidden=\"true\"><svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M15 18l-6-6 6-6\"/></svg></span>'\n        + '<span class=\"btk-kp-action-btn-label\">Back to guides</span></button>';\n      howtoContent.innerHTML = guide\n        ? `${backBtn}<h2 class=\"btk-kp-home-title\">${jEsc(guide.title)}</h2><div class=\"btk-kp-howto-body\">${guide.body}</div>`\n        : '<h2 class=\"btk-kp-home-title\">How To Guides</h2>';\n    }\n    // Switch the right panel to the how-to view; clear tile active states.\n    root.querySelectorAll('[data-btk-kp-home-view]').forEach(t => t.classList.remove('is-active'));\n    root.querySelectorAll('[data-btk-kp-home-panel]').forEach(p => { p.hidden = p.dataset.btkKpHomePanel !== 'how-to'; });\n    setHeaderActive('how-to');\n  }\n\n  // The How To landing - top-level topics as large visual tiles.\n  function renderHowtoOverview() {\n    if (!howtoContent) return;\n    howtoContent.innerHTML =\n      '<h2 class=\"btk-kp-home-title\">How To Guides</h2>'\n      + '<p class=\"btk-kp-home-lead\">Everything you need to design your bedroom. Choose a topic to get started.</p>'\n      + '<div class=\"btk-kp-howto-tiles\">'\n      + helpData().map(s =>\n          `<div class=\"btk-kp-howto-tile\">\n             <div class=\"btk-kp-howto-tile-head\">\n               <div class=\"btk-kp-howto-tile-headrow\">\n                 <span class=\"btk-kp-howto-tile-icon\">${s.icon || ''}</span>\n                 <span class=\"btk-kp-howto-tile-title\">${jEsc(s.title)}</span>\n               </div>\n               <span class=\"btk-kp-howto-tile-text\">${jEsc(s.summary || '')}</span>\n             </div>\n             <div class=\"btk-kp-howto-tile-links\">\n               ${(s.guides || []).map(g =>\n                 `<button type=\"button\" class=\"btk-kp-howto-tile-link\" data-btk-kp-howto-guide-jump=\"${jEsc(g.id)}\" data-section=\"${jEsc(s.id)}\">${jEsc(g.title)}</button>`\n               ).join('')}\n             </div>\n           </div>`).join('')\n      + '</div>';\n    root.querySelectorAll('[data-btk-kp-home-view]').forEach(t => t.classList.remove('is-active'));\n    root.querySelectorAll('[data-btk-kp-home-panel]').forEach(p => { p.hidden = p.dataset.btkKpHomePanel !== 'how-to'; });\n  }\n\n  // Expand the sidebar How To menu AND show the overview tiles on the right.\n  // The help content is fetched from the store the first time help opens\n  // (BTKKPHelp.load, see btk-kitchen-planner-help.js), so it stays off the\n  // planner's first load. Everything below this renders synchronously from it,\n  // so this is the one place that has to wait.\n  function openHowtoGuides() {\n    if (howtoToggle) howtoToggle.setAttribute('aria-expanded', 'true');\n    if (howtoWrap) howtoWrap.classList.add('is-open');\n    setHeaderActive('how-to');\n    const show = () => {\n      if (howtoNav) { if (!howtoNav.innerHTML.trim()) renderHowtoNav(); howtoNav.hidden = false; }\n      renderHowtoOverview();\n    };\n    const help = window.BTKKPHelp;\n    if (helpData().length || !help || typeof help.load !== 'function') { show(); return; }\n    if (howtoContent) {\n      howtoContent.innerHTML = '<h2 class=\"btk-kp-home-title\">How To Guides</h2>'\n        + '<p class=\"btk-kp-home-lead\">Loading the guides\u2026</p>';\n    }\n    root.querySelectorAll('[data-btk-kp-home-panel]').forEach(p => { p.hidden = p.dataset.btkKpHomePanel !== 'how-to'; });\n    help.load().then(show).catch(() => {\n      if (howtoContent) {\n        howtoContent.innerHTML = '<h2 class=\"btk-kp-home-title\">How To Guides</h2>'\n          + '<div class=\"btk-kp-howto-body\">' + (help.FAILED_HTML || '') + '</div>';\n      }\n    });\n  }\n\n  if (howtoToggle) {\n    // The sidebar \"How To Guides\" link just shows the overview tiles - no\n    // sub-menu accordion.\n    howtoToggle.addEventListener('click', () => { openHowtoGuides(); });\n  }\n  if (howtoNav) {\n    howtoNav.addEventListener('click', (e) => {\n      const secBtn = e.target.closest('[data-btk-kp-howto-section]');\n      if (secBtn) {\n        const id = secBtn.dataset.btkKpHowtoSection;\n        howtoState.openSection = (howtoState.openSection === id) ? null : id;\n        renderHowtoNav();\n        return;\n      }\n      const gBtn = e.target.closest('[data-btk-kp-howto-guide]');\n      if (gBtn) {\n        howtoState.activeGuide = gBtn.dataset.btkKpHowtoGuide;\n        renderHowtoNav();\n        showHowtoGuide(gBtn.dataset.section, gBtn.dataset.btkKpHowtoGuide);\n      }\n    });\n  }\n\n  // Right-panel interactions: back button, in-tile guide links, and the\n  // tile header (opens the section's first guide).\n  if (howtoContent) {\n    howtoContent.addEventListener('click', (e) => {\n      if (e.target.closest('[data-btk-kp-howto-back]')) { renderHowtoOverview(); return; }\n      const jump = e.target.closest('[data-btk-kp-howto-guide-jump]');\n      if (jump) {\n        const sid = jump.dataset.section;\n        const gid = jump.dataset.btkKpHowtoGuideJump;\n        howtoState.openSection = sid;\n        howtoState.activeGuide = gid;\n        renderHowtoNav();\n        showHowtoGuide(sid, gid);\n        return;\n      }\n      const tile = e.target.closest('[data-btk-kp-howto-section-tile]');\n      if (tile) {\n        const id = tile.dataset.btkKpHowtoSectionTile;\n        const section = helpData().find(s => s.id === id);\n        const first = section && section.guides && section.guides[0];\n        howtoState.openSection = id;\n        howtoState.activeGuide = first ? first.id : null;\n        renderHowtoNav();\n        if (first) showHowtoGuide(id, first.id);\n      }\n    });\n  }\n\n  // Header \"How To Guides\" link \u2192 jump to Planner Home with the How To\n  // Guides menu open and the overview tiles showing.\n  root.querySelector('[data-btk-kp-howto-home]')?.addEventListener('click', () => {\n    stepperHandle.setStep('planner-home');\n    openHowtoGuides();\n  });\n\n  // Header \"Get Help\" link \u2192 jump to Planner Home and show the Get Help panel\n  // (same as the sidebar Get Help link).\n  root.querySelector('[data-btk-kp-header-gethelp]')?.addEventListener('click', () => {\n    stepperHandle.setStep('planner-home');\n    root.querySelectorAll('[data-btk-kp-home-panel]').forEach(p => { p.hidden = p.dataset.btkKpHomePanel !== 'get-help'; });\n    setHeaderActive('get-help');\n  });\n\n  // Clicking the \"Planner Home\" stepper link returns to the default home\n  // page (welcome content, nothing selected, How To menu collapsed).\n  function resetHomeToDefault() {\n    showJourneyNav(false);   // leave the setup stepper, restore Start + saved plans\n    root.querySelectorAll('[data-btk-kp-home-view]').forEach(t => t.classList.remove('is-active'));\n    root.querySelectorAll('[data-btk-kp-home-panel]').forEach(p => { p.hidden = p.dataset.btkKpHomePanel !== 'home'; });\n    if (howtoNav) howtoNav.hidden = true;\n    if (howtoToggle) howtoToggle.setAttribute('aria-expanded', 'false');\n    if (howtoWrap) howtoWrap.classList.remove('is-open');\n    setHeaderActive('home');\n  }\n  root.querySelector('[data-btk-kp-step=\"planner-home\"]')?.addEventListener('click', resetHomeToDefault);\n\n  // \"Request a FREE Plan\" - placeholder until the request form / page is wired.\n  root.querySelector('[data-btk-kp-request-plan]')?.addEventListener('click', () => {\n    if (window.BTKKPDialog && window.BTKKPDialog.alert) {\n      window.BTKKPDialog.alert(\n        'Send us your room sizes and any details, and our bedroom designers will create a plan and quote for you - completely free.\\n\\nThe request form is coming soon; in the meantime please contact our team.',\n        { title: 'Request a FREE Plan', okText: 'Got it' }\n      );\n    }\n  });\n\n  // ---- Viewport mode (2D/3D toggle + view-options cog) -------------\n  // The toggle is decoupled from the stepper so the customer can flip\n  // to 3D from any stage without losing their place in the sidebar.\n  // The cog opens an overlay popover whose content changes by mode:\n  //   2D \u2192 layer toggles (Floor units / Wall units / Worktops)\n  //   3D \u2192 six one-click lighting presets (no manual sliders)\n  const viewToggleRoot = root.querySelector('[data-btk-kp-view-toggle]');\n  const rcGearBtn      = root.querySelector('[data-btk-kp-rc-gear]');\n  const rcOverlay      = root.querySelector('[data-btk-kp-rc-overlay]');\n  const mainEl         = document.getElementById('btk-kp-main');\n\n  function applyViewLayers() {\n    if (!mainEl) return;\n    mainEl.classList.toggle('is-hide-floor',    !viewLayers.floor);\n    mainEl.classList.toggle('is-hide-wall',     !viewLayers.wall);\n    mainEl.classList.toggle('is-hide-worktops', !viewLayers.worktops);\n  }\n  applyViewLayers();\n\n  // Auto-add end panels & fillers toggle (Add Items sidebar tick-box). ON\n  // re-detects across the whole plan; OFF freezes them for manual editing and\n  // shows a one-time explainer (pros of auto + it's fine to do it yourself).\n  function handleSetAutoEndPanels(val) {\n    if (val) {\n      // Turning ON - re-detect across the whole plan (end panels + breakfast-bar back panels).\n      autoEndPanels = true;\n      // The sidebar's toggle follows (this can be pressed from the End Panels\n      // & Fillers popup too).\n      root.querySelectorAll('[data-btk-kp-auto-endpanels]').forEach(b => {\n        const on = b.dataset.btkKpAutoEndpanels === '1';\n        b.classList.toggle('is-active', on);\n        b.setAttribute('aria-pressed', on ? 'true' : 'false');\n      });\n      autoDetectEndPanels();\n      autoDetectBackPanels();\n      resizeFillers();\n      rerender();\n      awaitJourneySave().catch(() => {}).then(() => planStore.save(currentDesign())).catch(() => {});\n      return;\n    }\n    // Turning OFF - confirm first; the user can keep Auto on.\n    const applyManual = () => {\n      autoEndPanels = false;\n      // Clear every previously auto-added panel/filler so manual mode starts\n      // from a clean slate - end panels, fillers AND breakfast-bar back panels\n      // (they're all panels). The user then adds back only what they want by\n      // hand. Other data (style, width, setback) is preserved so re-adding a\n      // panel keeps its prior settings.\n      cabinets = cabinets.map(cab => {\n        const ep = cab.endPanels || {}, fil = cab.fillers || {};\n        return {\n          ...cab,\n          endPanels: {\n            left:  { ...ep.left,  active: false },\n            right: { ...ep.right, active: false }\n          },\n          fillers: {\n            left:  { ...fil.left,  active: false },\n            right: { ...fil.right, active: false }\n          },\n          backPanel: { ...(cab.backPanel || {}), active: false },\n          useFullSizeEndPanel: false\n        };\n      });\n      rerender();\n      awaitJourneySave().catch(() => {}).then(() => planStore.save(currentDesign())).catch(() => {});\n    };\n    const keepAuto = () => {\n      autoEndPanels = true;\n      // Put the segmented toggle back on Auto - the user pressed Manual and\n      // then backed out, so the control has to follow the state, not the\n      // click. (It was a tick box; setting .checked on a button did nothing.)\n      root.querySelectorAll('[data-btk-kp-auto-endpanels]').forEach(b => {\n        const active = b.dataset.btkKpAutoEndpanels === '1';\n        b.classList.toggle('is-active', active);\n        b.setAttribute('aria-pressed', active ? 'true' : 'false');\n      });\n    };\n    if (window.BTKKPDialog && window.BTKKPDialog.confirm) {\n      window.BTKKPDialog.confirm(\n        'You\u2019ll add end panels & fillers yourself.\\n\\nWith Auto on, we finish every exposed end for you \u2013 nothing is missed and your price stays accurate as you move units around. Turning it off gives you full control: select any unit and add or remove its end panels and fillers by hand.',\n        // Keeping Auto is the better choice for nearly everyone, so it is the\n        // green button (bug sheet, Neil, 2026-10-30).\n        { title: 'Add end panels & fillers manually?', confirmText: 'Switch to Manual', cancelText: 'Keep auto end panels on', cancelPrimary: true }\n      ).then((ok) => { if (ok) applyManual(); else keepAuto(); });\n    } else {\n      applyManual();\n    }\n  }\n\n  // \"Hide units\" (Room Setup): hide the 2D units only while on that stage, so\n  // ticking it doesn't blank the plan on Add Items / Customise etc. Looks the\n  // element up fresh (NOT the `mainEl` const below) - onChange calls this during\n  // initStepper's first setStep, before that const is initialised (TDZ).\n  function applyHideUnits() {\n    const el = document.getElementById('btk-kp-main');\n    if (el) el.classList.toggle('is-hide-units', hideUnits && currentStep === 'room-setup');\n    refreshDims();   // re-render dims so the per-unit tiers hide/show with the units\n  }\n  // Two named states rather than a tick box: \"Show | Hide\" says which way is\n  // on, where \"Hide units\" with a tick left the reader to work it out.\n  const hideUnitsToggle = root.querySelector('[data-btk-kp-hide-units-toggle]');\n  function syncHideUnitsToggle() {\n    if (!hideUnitsToggle) return;\n    hideUnitsToggle.querySelectorAll('[data-btk-kp-hide-units]').forEach(btn => {\n      const on = (btn.dataset.btkKpHideUnits === '1') === hideUnits;\n      btn.classList.toggle('is-active', on);\n      btn.setAttribute('aria-pressed', on ? 'true' : 'false');\n    });\n  }\n  if (hideUnitsToggle) {\n    hideUnitsToggle.addEventListener('click', (e) => {\n      const btn = e.target.closest('[data-btk-kp-hide-units]');\n      if (!btn) return;\n      hideUnits = btn.dataset.btkKpHideUnits === '1';\n      syncHideUnitsToggle();\n      applyHideUnits();\n    });\n    syncHideUnitsToggle();   // markup default and `hideUnits` can't drift apart\n  }\n\n  const escAttr = s => String(s == null ? '' : s).replace(/[&<>\"]/g, ch =>\n    ({ '&':'&amp;','<':'&lt;','>':'&gt;','\"':'&quot;' }[ch]));\n\n  function renderViewportOverlay() {\n    if (!rcOverlay) return;\n    if (viewMode === '2d') {\n      const layers = [\n        { key: 'floor',    label: 'Floor units' },\n        { key: 'wall',     label: 'Wall units'  },\n        { key: 'worktops', label: 'Worktops'    }\n      ];\n      rcOverlay.innerHTML = `\n        <div class=\"btk-kp-rc-panel\">\n          <div class=\"btk-kp-rc-panel-head\">\n            <h3 class=\"btk-kp-rc-panel-title\">View options</h3>\n            <button type=\"button\" class=\"btk-kp-magic-launch\" data-btk-kp-magic\n                    aria-label=\"Magic Layout\" title=\"Magic Layout (beta)\">\n              <svg viewBox=\"0 0 24 24\" width=\"18\" height=\"18\" aria-hidden=\"true\">\n                <path fill=\"currentColor\" d=\"M12 2.5l1.6 4.3 4.3 1.6-4.3 1.6L12 14.3l-1.6-4.3L6.1 8.4l4.3-1.6L12 2.5zM19 13l.9 2.4 2.4.9-2.4.9L19 19.6l-.9-2.4-2.4-.9 2.4-.9L19 13zM6 14l.8 2.1 2.1.8-2.1.8L6 19.8l-.8-2.1-2.1-.8 2.1-.8L6 14z\"/>\n              </svg>\n            </button>\n          </div>\n          <ul class=\"btk-kp-rc-layer-list\">\n            ${layers.map(l => `\n              <li>\n                <label class=\"btk-kp-rc-layer\">\n                  <input type=\"checkbox\" data-btk-kp-layer=\"${l.key}\" ${viewLayers[l.key] ? 'checked' : ''}>\n                  <span>${escAttr(l.label)}</span>\n                </label>\n              </li>\n            `).join('')}\n          </ul>\n        </div>\n      `;\n      rcOverlay.querySelectorAll('[data-btk-kp-layer]').forEach(input => {\n        input.addEventListener('change', () => {\n          const key = input.dataset.btkKpLayer;\n          viewLayers = { ...viewLayers, [key]: !!input.checked };\n          applyViewLayers();\n        });\n      });\n      const magicBtn = rcOverlay.querySelector('[data-btk-kp-magic]');\n      if (magicBtn) {\n        magicBtn.addEventListener('click', () => {\n          closeCogOverlay();\n          enterPaintMode();\n        });\n      }\n    } else {\n      // 3D - six one-click ambience presets from the renderer.\n      const presets = (handle3D && handle3D.getLightingPresets)\n        ? handle3D.getLightingPresets()\n        : [];\n      rcOverlay.innerHTML = `\n        <div class=\"btk-kp-rc-panel\">\n          <h3 class=\"btk-kp-rc-panel-title\">Lighting</h3>\n          ${presets.length\n            ? `<div class=\"btk-kp-rc-preset-grid\">\n                 ${presets.map(p => `\n                   <button type=\"button\" class=\"btk-kp-rc-preset\" data-btk-kp-preset=\"${escAttr(p.id)}\">\n                     ${escAttr(p.label)}\n                   </button>\n                 `).join('')}\n               </div>`\n            : `<p class=\"btk-kp-lighting-note\">Switch to 3D to choose a lighting preset.</p>`\n          }\n          <h3 class=\"btk-kp-rc-panel-title\" style=\"margin-top:14px;\">Flythrough speed</h3>\n          <div class=\"btk-kp-rc-speed\">\n            <input type=\"range\" min=\"0.5\" max=\"2\" step=\"0.05\" value=\"${flythroughSpeed}\"\n                   data-btk-kp-fly-speed aria-label=\"Flythrough speed\">\n            <span class=\"btk-kp-rc-speed-value\" data-btk-kp-fly-speed-value>${flythroughSpeed.toFixed(2)}\u00D7</span>\n          </div>\n        </div>\n      `;\n      const presetById = new Map(presets.map(p => [p.id, p]));\n      rcOverlay.querySelectorAll('[data-btk-kp-preset]').forEach(btn => {\n        btn.addEventListener('click', () => {\n          const preset = presetById.get(btn.dataset.btkKpPreset);\n          if (preset && handle3D?.setLighting) handle3D.setLighting(preset.settings);\n          rcOverlay.querySelectorAll('[data-btk-kp-preset]').forEach(b => b.classList.remove('is-active'));\n          btn.classList.add('is-active');\n        });\n      });\n      const speedInput = rcOverlay.querySelector('[data-btk-kp-fly-speed]');\n      const speedValueEl = rcOverlay.querySelector('[data-btk-kp-fly-speed-value]');\n      if (speedInput) {\n        speedInput.addEventListener('input', () => {\n          const v = parseFloat(speedInput.value);\n          if (!Number.isFinite(v) || v <= 0) return;\n          flythroughSpeed = v;\n          if (speedValueEl) speedValueEl.textContent = `${v.toFixed(2)}\u00D7`;\n        });\n      }\n    }\n  }\n\n  function closeCogOverlay() {\n    if (!rcOverlay || rcOverlay.hidden) return;\n    rcOverlay.hidden = true;\n    rcGearBtn?.classList.remove('is-open');\n    rcGearBtn?.setAttribute('aria-expanded', 'false');\n  }\n\n  // ---- Magic Paint mode - Stage 1 of Magic Layout ------------------\n  // The customer paints where each type of run goes on the graph-paper\n  // floor, THEN answers the trimmed style questionnaire. Painting turns\n  // the generator from \"guess the walls\" into \"fill what they drew\".\n  // Stage A here = the shell (graph paper + brush palette + enter/exit);\n  // the drag-to-paint (B), markers (C) and feed-to-allocator (D) follow.\n  // (paintMode is declared earlier - rerender reads it.)\n  let paintBrush = 'base';\n  // Free-grid paint state. cells[level] = Set(\"gx,gy\") of 100mm grid cells\n  // (gx=floor(xMm/100)); markers = [{kind,x,y}] (Stage C). The customer\n  // drags anywhere on the floor; a ~600mm brush fills cells under the path.\n  // cellWall: \"gx,gy\" \u2192 wall index the cell was painted AS A BAND against\n  // (set by paintWallBand). buildPaintedRuns trusts it so corner cells stay\n  // with the wall the user stroked along, instead of being stolen by the\n  // perpendicular wall they happen to sit closer to. Free / island cells\n  // have no entry and fall back to nearest-wall projection.\n  const paintData = { cells: { base: new Set(), wall: new Set(), tall: new Set() }, markers: [], cellWall: new Map() };\n  const paintUndoStack = [];   // snapshots of paintData, one per stroke / marker drop\n  let paintPaletteEl = null;\n  let paintingPointer = null;\n  let paintLastPt = null;\n  let paintStrokeWall = null;   // wall index locked for the current stroke (no corner jump)\n  // Level precedence - higher overwrites lower; a cell holds ONE level.\n  // (Base implies wall units above it at generation, so a base cell wins\n  // over a wall-only mark; tall is full-height and beats both.)\n  const PAINT_RANK = { wall: 1, base: 2, tall: 3 };\n  const PAINT_CELL_MM  = 100;   // graph-paper cell size\n  // Brush diameter \u2248 that level's unit depth: base/tall 600mm, wall 300mm.\n  const PAINT_BRUSH_MM_BY_LEVEL = { base: 600, wall: 300, tall: 600 };\n  const PAINT_LEVEL_COLOUR = { base: '#2d7a3a', wall: '#2a7fff', tall: '#8a5cd0' };\n\n  const PAINT_BRUSHES = [\n    { key: 'base', label: 'Base units', kind: 'run',    swatch: '#2d7a3a' },\n    { key: 'wall', label: 'Wall units', kind: 'run',    swatch: '#2a7fff' },\n    { key: 'tall', label: 'Tall units', kind: 'run',    swatch: '#8a5cd0' },\n    { key: 'sink',       label: 'Sink',       kind: 'marker', swatch: '#00a3b4' },\n    { key: 'hob',        label: 'Hob',        kind: 'marker', swatch: '#e8892b' },\n    { key: 'oven',       label: 'Oven',       kind: 'marker', swatch: '#c0392b' },\n    { key: 'fridge',     label: 'Fridge',     kind: 'marker', swatch: '#2b7fc0' },\n    { key: 'dishwasher', label: 'Dishwasher', kind: 'marker', swatch: '#5aa02b' }\n  ];\n\n  function enterPaintMode() {\n    if (paintMode) return;\n    if (viewMode !== '2d') setViewMode('2d');   // paint on the 2D plan\n    paintMode = true;\n    paintBrush = 'base';\n    paintData.cells = { base: new Set(), wall: new Set(), tall: new Set() };\n    paintData.markers = [];\n    paintData.cellWall = new Map();\n    paintUndoStack.length = 0;\n    root.classList.add('btk-kp-paint-mode');    // graph paper + cabinet lock (CSS)\n    buildPaintPalette();\n    renderPaint();\n  }\n\n  function exitPaintMode() {\n    if (!paintMode) return;\n    paintMode = false;\n    root.classList.remove('btk-kp-paint-mode');\n    if (paintPaletteEl) { paintPaletteEl.remove(); paintPaletteEl = null; }\n    if (currentGridEl) {\n      const l = currentGridEl.querySelector('.btk-kp-paint-layer');\n      if (l) l.remove();\n    }\n  }\n\n  function setPaintBrush(key) {\n    paintBrush = key;\n    if (!paintPaletteEl) return;\n    paintPaletteEl.querySelectorAll('[data-paint-brush]').forEach(b =>\n      b.classList.toggle('is-active', b.getAttribute('data-paint-brush') === key));\n  }\n\n  function buildPaintPalette() {\n    if (paintPaletteEl) paintPaletteEl.remove();\n    const el = document.createElement('div');\n    el.className = 'btk-kp-paint-palette';\n    el.innerHTML =\n      '<div class=\"btk-kp-paint-title\"><span class=\"btk-kp-magic-sparkle\" aria-hidden=\"true\">\u2726</span> Paint your bedroom</div>' +\n      '<div class=\"btk-kp-paint-hint\">Pick a unit type, then drag over the floor where you want it. Tap Sink / Hob / Oven / Fridge / Dishwasher to drop those in (an appliance is placed where you mark it - it isn\u2019t added automatically).</div>' +\n      '<div class=\"btk-kp-paint-brushes\">' +\n        PAINT_BRUSHES.map(b =>\n          '<button type=\"button\" class=\"btk-kp-paint-brush' + (b.key === paintBrush ? ' is-active' : '') +\n          '\" data-paint-brush=\"' + b.key + '\">' +\n            '<span class=\"btk-kp-paint-swatch\" style=\"background:' + b.swatch + '\"></span>' +\n            '<span>' + b.label + '</span>' +\n          '</button>').join('') +\n      '</div>' +\n      '<button type=\"button\" class=\"btk-kp-paint-undo\" data-paint-undo disabled>\u21B6 Undo</button>' +\n      '<div class=\"btk-kp-paint-actions\">' +\n        '<button type=\"button\" class=\"btk-kp-paint-btn btk-kp-paint-cancel\" data-paint-cancel>Cancel</button>' +\n        '<button type=\"button\" class=\"btk-kp-paint-btn btk-kp-paint-next\" data-paint-next>Next</button>' +\n      '</div>';\n    (document.getElementById('btk-kp-main') || root).appendChild(el);\n    el.querySelectorAll('[data-paint-brush]').forEach(b =>\n      b.addEventListener('click', () => setPaintBrush(b.getAttribute('data-paint-brush'))));\n    el.querySelector('[data-paint-undo]').addEventListener('click', paintUndo);\n    el.querySelector('[data-paint-cancel]').addEventListener('click', exitPaintMode);\n    el.querySelector('[data-paint-next]').addEventListener('click', () => {\n      // Stage A: hand straight to the style questionnaire. Stage D feeds the\n      // painted runs into the generator instead of the auto wall-picker.\n      exitPaintMode();\n      openMagicDialog();\n    });\n    paintPaletteEl = el;\n  }\n\n  // Screen pointer \u2192 ROOM millimetres (grid rect is post pan/zoom transform).\n  function paintPointerToMm(e) {\n    const gridEl = currentGridEl;\n    const ppm = (clearanceCtx && clearanceCtx.pxPerMm) || (worktops2dCtx && worktops2dCtx.pxPerMm) || 0;\n    if (!gridEl || !(ppm > 0)) return null;\n    const rect = gridEl.getBoundingClientRect();\n    return {\n      x: ((e.clientX - rect.left) / (view2d.zoom || 1)) / ppm,\n      y: ((e.clientY - rect.top)  / (view2d.zoom || 1)) / ppm\n    };\n  }\n\n  function paintRoomCentroid() {\n    const v = (room && room.vertices) || [];\n    const n = v.length || 1;\n    return v.reduce((s, p) => ({ x: s.x + p.x / n, y: s.y + p.y / n }), { x: 0, y: 0 });\n  }\n\n  // Set a cell's level. Base + Wall COEXIST (base below, wall above - wall\n  // renders on top so it's visible). Tall is full-height + exclusive: it\n  // clears base/wall, and base/wall \"stop\" at a tall cell (can't paint over).\n  function paintSetCell(key, level, wallIndex) {\n    // wallIndex: number = painted as a band against that wall (record it);\n    // null = free/island cell (clear any stale wall record); undefined = leave\n    // the existing record untouched.\n    if (wallIndex != null && typeof wallIndex === 'number') paintData.cellWall.set(key, wallIndex);\n    else if (wallIndex === null) paintData.cellWall.delete(key);\n    if (level === 'tall') {\n      paintData.cells.base.delete(key);\n      paintData.cells.wall.delete(key);\n      paintData.cells.tall.add(key);\n      return;\n    }\n    if (paintData.cells.tall.has(key)) return;   // base/wall stop at tall\n    paintData.cells[level].add(key);             // base + wall coexist\n  }\n\n  // Evaluate a wall for painting at `pt`: returns the along-position, inward\n  // normal and orientation, or null if the point isn't in that wall's band.\n  function paintEvalWall(w, pt, depth) {\n    const len = w.lengthMm; if (!(len > 0)) return null;\n    const ux = (w.to.x - w.from.x) / len, uy = (w.to.y - w.from.y) / len;\n    if (Math.abs(ux) > 0.02 && Math.abs(uy) > 0.02) return null;   // axis-aligned only\n    const along = (pt.x - w.from.x) * ux + (pt.y - w.from.y) * uy;\n    if (along < -150 || along > len + 150) return null;\n    const nx = -uy, ny = ux;\n    const c = paintRoomCentroid();\n    const inwardSign = ((c.x - w.from.x) * nx + (c.y - w.from.y) * ny) >= 0 ? 1 : -1;\n    const perpIn = ((pt.x - w.from.x) * nx + (pt.y - w.from.y) * ny) * inwardSign;\n    if (perpIn < -200 || perpIn > depth + 250) return null;\n    return {\n      ux, uy, along: Math.max(0, Math.min(len, along)),\n      inx: nx * inwardSign, iny: ny * inwardSign, horiz: Math.abs(uy) < 0.02, perpIn\n    };\n  }\n\n  // Paint a clean fixed-depth band along a wall. Locks to the wall the stroke\n  // started on so the fill doesn't narrow / jump to the perpendicular wall\n  // near a corner - it only switches once the cursor clearly leaves it.\n  function paintWallBand(pt, level) {\n    const depth = PAINT_BRUSH_MM_BY_LEVEL[level] || 600;\n    const walls = getWalls(room);\n    let w = null, r = null;\n    if (paintStrokeWall != null && walls[paintStrokeWall]) {\n      const rr = paintEvalWall(walls[paintStrokeWall], pt, depth);\n      if (rr) { w = walls[paintStrokeWall]; r = rr; }        // stay on the stroke's wall\n    }\n    if (!w) {\n      let bestR = null;\n      for (const ww of walls) {\n        const rr = paintEvalWall(ww, pt, depth);\n        if (rr && (!bestR || Math.abs(rr.perpIn) < Math.abs(bestR.perpIn))) { w = ww; bestR = rr; }\n      }\n      if (w) { r = bestR; paintStrokeWall = w.index; }\n    }\n    if (!w) return false;\n    // Band = a ~600mm-wide swath ALONG the wall (so a corner stamp fills the\n    // full square, not a 1-cell tongue) \u00D7 fixed depth INTO the room, clamped\n    // to the wall's extent.\n    const ALONG_HALF = 300;\n    const along0 = Math.max(0, r.along - ALONG_HALF);\n    const along1 = Math.min(w.lengthMm, r.along + ALONG_HALF);\n    const s0x = w.from.x + r.ux * along0, s0y = w.from.y + r.uy * along0;\n    const s1x = w.from.x + r.ux * along1, s1y = w.from.y + r.uy * along1;\n    if (r.horiz) {                               // along = x, depth across y\n      const gxLo = Math.floor(Math.min(s0x, s1x) / PAINT_CELL_MM);\n      const gxHi = Math.ceil(Math.max(s0x, s1x) / PAINT_CELL_MM);\n      const p0 = w.from.y, p1 = p0 + r.iny * depth;\n      const gyLo = Math.floor(Math.min(p0, p1) / PAINT_CELL_MM);\n      const gyHi = Math.ceil(Math.max(p0, p1) / PAINT_CELL_MM);\n      for (let gx = gxLo; gx < gxHi; gx++) for (let gy = gyLo; gy < gyHi; gy++) paintSetCell(gx + ',' + gy, level, w.index);\n    } else {                                     // vertical: along = y, depth across x\n      const gyLo = Math.floor(Math.min(s0y, s1y) / PAINT_CELL_MM);\n      const gyHi = Math.ceil(Math.max(s0y, s1y) / PAINT_CELL_MM);\n      const p0 = w.from.x, p1 = p0 + r.inx * depth;\n      const gxLo = Math.floor(Math.min(p0, p1) / PAINT_CELL_MM);\n      const gxHi = Math.ceil(Math.max(p0, p1) / PAINT_CELL_MM);\n      for (let gy = gyLo; gy < gyHi; gy++) for (let gx = gxLo; gx < gxHi; gx++) paintSetCell(gx + ',' + gy, level, w.index);\n    }\n    return true;\n  }\n\n  // Fill cells for one brush stamp: snap to a wall band if near one, else a\n  // free circle (open floor / island).\n  function paintFillBrush(pt, level) {\n    if (paintWallBand(pt, level)) return;\n    const r = (PAINT_BRUSH_MM_BY_LEVEL[level] || 600) / 2;\n    const bb = getBoundingBox(room);\n    const gx0 = Math.floor((pt.x - r) / PAINT_CELL_MM), gx1 = Math.floor((pt.x + r) / PAINT_CELL_MM);\n    const gy0 = Math.floor((pt.y - r) / PAINT_CELL_MM), gy1 = Math.floor((pt.y + r) / PAINT_CELL_MM);\n    for (let gx = gx0; gx <= gx1; gx++) {\n      for (let gy = gy0; gy <= gy1; gy++) {\n        const cx = (gx + 0.5) * PAINT_CELL_MM, cy = (gy + 0.5) * PAINT_CELL_MM;\n        if (cx < bb.minX || cx > bb.maxX || cy < bb.minY || cy > bb.maxY) continue;  // keep inside room bbox\n        if (Math.hypot(cx - pt.x, cy - pt.y) <= r) paintSetCell(gx + ',' + gy, level, null);\n      }\n    }\n  }\n\n  function paintAt(e) {\n    const brush = PAINT_BRUSHES.find(b => b.key === paintBrush);\n    if (!brush || brush.kind !== 'run') return;   // markers = Stage C\n    const pt = paintPointerToMm(e); if (!pt) return;\n    if (paintLastPt) {\n      // Sample along the drag so a fast flick doesn't leave gaps.\n      const dx = pt.x - paintLastPt.x, dy = pt.y - paintLastPt.y;\n      const steps = Math.max(1, Math.ceil(Math.hypot(dx, dy) / PAINT_CELL_MM));\n      for (let i = 1; i <= steps; i++) {\n        paintFillBrush({ x: paintLastPt.x + dx * i / steps, y: paintLastPt.y + dy * i / steps }, paintBrush);\n      }\n    } else {\n      paintFillBrush(pt, paintBrush);\n    }\n    paintLastPt = pt;\n    renderPaint();\n  }\n\n  // Draw the painted cells into the grid layer. Re-run on each paint stroke\n  // and after every rerender (the grid element is rebuilt each time).\n  function renderPaint() {\n    const gridEl = currentGridEl;\n    const ppm = (clearanceCtx && clearanceCtx.pxPerMm) || 0;\n    if (!gridEl || !(ppm > 0)) return;\n    const old = gridEl.querySelector('.btk-kp-paint-layer');\n    if (old) old.remove();\n    if (!paintMode) return;\n    const NS = 'http://www.w3.org/2000/svg';\n    const svg = document.createElementNS(NS, 'svg');\n    svg.setAttribute('class', 'btk-kp-paint-layer');\n    svg.style.cssText = 'position:absolute;left:0;top:0;width:100%;height:100%;overflow:visible;pointer-events:none;';\n    const cellPx = PAINT_CELL_MM * ppm;\n    for (const level of ['base', 'wall', 'tall']) {\n      const colour = PAINT_LEVEL_COLOUR[level];\n      for (const key of paintData.cells[level]) {\n        const p = key.split(','); const gx = +p[0], gy = +p[1];\n        const r = document.createElementNS(NS, 'rect');\n        r.setAttribute('x', (gx * cellPx).toFixed(1));\n        r.setAttribute('y', (gy * cellPx).toFixed(1));\n        r.setAttribute('width',  cellPx.toFixed(1));\n        r.setAttribute('height', cellPx.toFixed(1));\n        r.setAttribute('fill', colour);\n        r.setAttribute('fill-opacity', '0.42');\n        svg.appendChild(r);\n      }\n    }\n    // Sink / hob / oven markers - a labelled disc at each dropped point.\n    for (const m of paintData.markers) {\n      const brush = PAINT_BRUSHES.find(b => b.key === m.kind);\n      const colour = (brush && brush.swatch) || '#333';\n      const cx = m.x * ppm, cy = m.y * ppm;\n      const rad = Math.max(11, 150 * ppm);        // 150mm radius (min 11px)\n      const c = document.createElementNS(NS, 'circle');\n      c.setAttribute('cx', cx.toFixed(1)); c.setAttribute('cy', cy.toFixed(1));\n      c.setAttribute('r', rad.toFixed(1));\n      c.setAttribute('fill', colour); c.setAttribute('fill-opacity', '0.92');\n      c.setAttribute('stroke', '#fff'); c.setAttribute('stroke-width', '2');\n      svg.appendChild(c);\n      const t = document.createElementNS(NS, 'text');\n      t.setAttribute('x', cx.toFixed(1)); t.setAttribute('y', cy.toFixed(1));\n      t.setAttribute('text-anchor', 'middle'); t.setAttribute('dominant-baseline', 'central');\n      t.setAttribute('fill', '#fff'); t.setAttribute('font-weight', '700');\n      t.setAttribute('font-size', Math.max(10, rad * 0.9).toFixed(0));\n      t.setAttribute('font-family', '-apple-system, \"Segoe UI\", Arial, sans-serif');\n      t.textContent = (brush && brush.label ? brush.label.charAt(0) : '?').toUpperCase();  // S / H / O\n      svg.appendChild(t);\n    }\n    gridEl.appendChild(svg);\n  }\n\n  // Paint pointer handlers on the canvas (capture phase; gated on paint mode\n  // + a run brush). Let the palette + non-canvas targets pass through.\n  // ---- Paint undo (one step per stroke / marker drop) --------------\n  function paintSnapshot() {\n    return {\n      cells: {\n        base: new Set(paintData.cells.base),\n        wall: new Set(paintData.cells.wall),\n        tall: new Set(paintData.cells.tall)\n      },\n      markers: paintData.markers.map(m => ({ ...m })),\n      cellWall: new Map(paintData.cellWall)\n    };\n  }\n  function paintPushUndo() {\n    paintUndoStack.push(paintSnapshot());\n    if (paintUndoStack.length > 60) paintUndoStack.shift();\n    updatePaintUndoBtn();\n  }\n  function paintUndo() {\n    const prev = paintUndoStack.pop();\n    if (!prev) return;\n    paintData.cells = prev.cells;\n    paintData.markers = prev.markers;\n    paintData.cellWall = prev.cellWall || new Map();\n    renderPaint();\n    updatePaintUndoBtn();\n  }\n  function updatePaintUndoBtn() {\n    if (!paintPaletteEl) return;\n    const b = paintPaletteEl.querySelector('[data-paint-undo]');\n    if (b) b.disabled = paintUndoStack.length === 0;\n  }\n\n  // Drop a sink/hob/oven marker. MULTIPLE per kind are allowed (people often\n  // want more than one oven/sink). Tapping ON an existing marker of the same\n  // kind (within ~one cell) REMOVES it, so a mis-drop is easy to clear without\n  // hunting for Undo.\n  function placeMarker(kind, pt) {\n    const HIT_MM = 160;\n    const near = paintData.markers.find(m =>\n      m.kind === kind && Math.hypot(m.x - pt.x, m.y - pt.y) <= HIT_MM);\n    if (near) {\n      paintData.markers = paintData.markers.filter(m => m !== near);   // toggle off\n    } else {\n      paintData.markers.push({ kind, x: pt.x, y: pt.y });\n    }\n    renderPaint();\n  }\n\n  function onPaintPointerDown(e) {\n    if (!paintMode || viewMode !== '2d') return;\n    // Primary button only: a right-drag pans the view, and in capture phase\n    // this handler would otherwise swallow it and paint a stroke instead.\n    if (e.pointerType === 'mouse' && e.button !== 0) return;\n    if (!currentGridEl || !currentGridEl.contains(e.target)) return;\n    const brush = PAINT_BRUSHES.find(b => b.key === paintBrush);\n    if (!brush) return;\n    e.preventDefault(); e.stopPropagation();\n    paintPushUndo();                        // snapshot before this stroke / drop\n    if (brush.kind === 'marker') {          // Sink / Hob / Oven - tap to drop\n      const pt = paintPointerToMm(e);\n      if (pt) placeMarker(paintBrush, pt);\n      return;\n    }\n    paintingPointer = e.pointerId;          // run brush \u2192 start dragging\n    paintLastPt = null;\n    paintStrokeWall = null;                 // fresh wall lock for this stroke\n    try { main.setPointerCapture(e.pointerId); } catch (err) {}\n    paintAt(e);\n  }\n  function onPaintPointerMove(e) {\n    if (paintingPointer == null || e.pointerId !== paintingPointer) return;\n    paintAt(e);\n  }\n  function onPaintPointerUp(e) {\n    if (e.pointerId !== paintingPointer) return;\n    paintingPointer = null;\n    paintLastPt = null;\n    paintStrokeWall = null;\n    try { main.releasePointerCapture(e.pointerId); } catch (err) {}\n  }\n  if (main) {\n    main.addEventListener('pointerdown', onPaintPointerDown, true);\n    main.addEventListener('pointermove', onPaintPointerMove);\n    main.addEventListener('pointerup', onPaintPointerUp);\n    main.addEventListener('pointercancel', onPaintPointerUp);\n  }\n  document.addEventListener('keydown', (e) => {\n    if (!paintMode) return;\n    if ((e.ctrlKey || e.metaKey) && (e.key === 'z' || e.key === 'Z')) {\n      e.preventDefault();\n      paintUndo();\n    }\n  });\n\n  // ---- Magic Layout questionnaire (Stage 2) ------------------------\n  // Opens the questionnaire (btk-kitchen-planner-magic.js) and hands the\n  // captured design brief to generateMagicLayout(). The questionnaire is\n  // pure UI; all layout intelligence (\"design rules\") lives here so it\n  // has access to the catalogue, room geometry, and placement engine.\n  function openMagicDialog() {\n    if (!window.BTKKPMagic || typeof window.BTKKPMagic.open !== 'function') {\n      console.warn('[BTK Kitchen Planner] Magic module not loaded');\n      return;\n    }\n    const styles = (Catalogue.getKitchenStyles?.() || [])\n      .map(s => ({ id: s.id, name: s.name || s.id }));\n    const EPS = 1;\n    const walls = getWalls(room).map((w, i) => ({\n      index: i,\n      x1: w.from.x, y1: w.from.y, x2: w.to.x, y2: w.to.y,\n      lengthMm: w.lengthMm,\n      axisAligned: Math.abs(w.to.x - w.from.x) < EPS || Math.abs(w.to.y - w.from.y) < EPS\n    }));\n    window.BTKKPMagic.open({\n      styles,\n      defaultStyleId: kitchenStyleId || null,\n      walls,\n      onGenerate: generateMagicLayout\n    });\n  }\n\n  // Specialty / feature unit FAMILIES that Magic Layout must never auto-place\n  // in a run - corner, sink, appliance/oven housings, curved/radius, splay +\n  // end-wall, open-end, feature, bi-fold, glass, wine, dresser, filler,\n  // bridging, angled. These are end-of-run / feature pieces the customer\n  // places by hand. Shared by the run-fill palette (magicUnitCatalogue) AND\n  // the audit so the two never drift. Standard fill families (standard-base-\n  // units, multi-drawer-units, standard-wall-units, pantry/larder tall) match\n  // none of these keywords.\n  const MAGIC_BAD_GROUP = /corner|appliance|sink|oven|belfast|splay|end-panel|end-wall|filler|dresser|bridging|radius|curved?|angled|feature|open|bi.?fold|glass|wine/i;\n  const MAGIC_BAD_CODE  = /CORNER|BEL|SINK|SPLAY|OVEN|HOUS|RAD|CURV/;\n\n  // Diagnostic: run `btkMagicAudit()` in the console to see which unit\n  // families are set up in the catalogue and which Magic Layout uses.\n  window.btkMagicAudit = function (styleArg) {\n    const USED_BADGROUP = MAGIC_BAD_GROUP;\n    const USED_BADCODE  = MAGIC_BAD_CODE;\n    const ready = (Catalogue.getReadyUnitTypes && Catalogue.getReadyUnitTypes()) || [];\n    const all   = (Catalogue.getUnitTypes && Catalogue.getUnitTypes()) || [];\n    // Style to check product availability against (arg \u2192 current \u2192 first).\n    const styleId = styleArg || kitchenStyleId\n      || (Catalogue.getKitchenStyles && Catalogue.getKitchenStyles()[0] && Catalogue.getKitchenStyles()[0].id) || null;\n    const styleName = (Catalogue.getKitchenStyle && Catalogue.getKitchenStyle(styleId)?.name) || styleId || '(none)';\n    const rows = {};\n    for (const ut of all) {\n      const cat = ut.categoryHandle || '(no category)';\n      const grp = ut.unitTypeGroupHandle || '(no group)';\n      const isReady = ready.indexOf(ut) >= 0;\n      // Does a PRODUCT exist for this unit type in the chosen style? \"Ready\"\n      // only means the metaobject is set up; this is the real gate Magic hits.\n      const hasProduct = !!(styleId && Catalogue.getProductForUnitInStyle\n        && Catalogue.getProductForUnitInStyle(ut.id, styleId));\n      const shape = String(ut.planner2D?.shape || 'rectangle').trim().toLowerCase();\n      const notSpecial = shape === 'rectangle' && !ut.isMidiUnit\n        && !(ut.unitTypeGroupHandle && USED_BADGROUP.test(grp)) && !USED_BADCODE.test((ut.code || '').toUpperCase());\n      const magicPlainBase = cat === 'base-units' && !ut.sinkBase && notSpecial;\n      const magicPlainWall = cat === 'wall-units' && notSpecial;\n      const usedByMagic = magicPlainBase || magicPlainWall || ut.sinkBase; // + stub corners below\n      const k = cat + '  /  ' + grp;\n      (rows[k] = rows[k] || { ready: 0, notReady: 0, withProduct: 0, used: false, codes: [], noProd: [] });\n      rows[k][isReady ? 'ready' : 'notReady']++;\n      if (hasProduct) rows[k].withProduct++;\n      rows[k].used = rows[k].used || usedByMagic;\n      // \u26A0 = metaobject not ready; \u2717 = ready metaobject but NO product in style.\n      const flag = !isReady ? '\u26A0' : (!hasProduct ? '\u2717' : '');\n      if (ut.code && rows[k].codes.length < 12) rows[k].codes.push(ut.code + flag);\n      if (isReady && !hasProduct && ut.code) rows[k].noProd.push(ut.code);\n    }\n    console.group('%c[BTK Magic] Catalogue audit - style: ' + styleName + '  (\u26A0 metaobject not ready, \u2717 ready but NO product in this style)', 'font-weight:bold');\n    Object.keys(rows).sort().forEach(k => {\n      const r = rows[k];\n      console.log(\n        `${r.used ? '\u2705 used' : '\u2B1C NOT used'}  ${k}  -  ${r.ready} ready, ${r.withProduct} with-product` +\n        (r.notReady ? ` (+${r.notReady} not-ready)` : '') +\n        (r.noProd.length ? `  \u2717no-product: [${r.noProd.join(', ')}]` : '') +\n        `  [${r.codes.join(', ')}]`\n      );\n    });\n    console.log('Stub corners (base L-shape):', ((typeof getLShapeUnitCatalogue === 'function' && getLShapeUnitCatalogue()) || []).map(e => e.code).join(', '));\n    console.log('Stub corner WALL units:', ((typeof getCornerWallUnitCatalogue === 'function' && getCornerWallUnitCatalogue()) || []).map(e => e.code).join(', '));\n    console.groupEnd();\n    return rows;\n  };\n\n  // Focused diagnostic: run `btkFridgeCheck()` (optionally a style handle) to\n  // see EVERY appliance-housings unit type - its group, whether the metaobject\n  // is ready, and whether a PRODUCT resolves in the chosen style + variant\n  // widths. \uD83E\uDDCA = what pickFridgeHousing would treat as a fridge-freezer housing.\n  window.btkFridgeCheck = function (styleArg) {\n    const styleId = styleArg || kitchenStyleId\n      || (Catalogue.getKitchenStyles && Catalogue.getKitchenStyles()[0] && Catalogue.getKitchenStyles()[0].id) || null;\n    const styleName = (Catalogue.getKitchenStyle && Catalogue.getKitchenStyle(styleId)?.name) || styleId || '(none)';\n    const all = (Catalogue.getUnitTypes && Catalogue.getUnitTypes()) || [];\n    const ready = (Catalogue.getReadyUnitTypes && Catalogue.getReadyUnitTypes()) || [];\n    console.group('%c[BTK] Fridge / appliance-housing check - style: ' + styleName, 'font-weight:bold');\n    let any = false;\n    for (const ut of all) {\n      if (ut.categoryHandle !== 'appliance-housings') continue;\n      any = true;\n      const isReady = ready.indexOf(ut) >= 0;\n      const prod = styleId && Catalogue.getProductForUnitInStyle && Catalogue.getProductForUnitInStyle(ut.id, styleId);\n      const isFridge = /fridge|freezer|refriger/i.test(ut.unitTypeGroupHandle || '') || /(^|[^A-Z])T?FFH/i.test(ut.code || '');\n      const widths = prod ? (prod.variants || []).map(v => (Catalogue.getVariantInfo && Catalogue.getVariantInfo(v.id) || {}).widthMm).filter(Boolean).join('/') : '';\n      console.log(\n        (isFridge ? '\uD83E\uDDCA ' : '   ') + (ut.code || '(no code)') +\n        '  | group: ' + (ut.unitTypeGroupHandle || '(none)') +\n        '  | ready: ' + isReady + '  | product-in-style: ' + !!prod +\n        (widths ? '  | widths: ' + widths : '') +\n        '  | midi: ' + (ut.isMidiUnit === true));\n    }\n    if (!any) console.log('No appliance-housings unit types found at all.');\n    console.log('\u2192 pickFridgeHousing() returns:', JSON.stringify(pickFridgeHousing(styleId)));\n    console.groupEnd();\n  };\n\n  // Diagnostic: run `btkSplayCheck()` in the console when a splay end unit\n  // renders at the wrong depth. RETURNS the report (so the console prints it\n  // inline - no scrolling up through a log group) as well as logging it.\n  // `probe` is the one to read first: if SPLAYLW comes back 560/370 the loaded\n  // bundle predates the order-agnostic wall-code fix, so you are on a stale\n  // cache or the old theme. Wall splays must be deep 320 / shallow 140;\n  // base splays 560 / 370.\n  window.btkSplayCheck = function () {\n    const all = (Catalogue.getUnitTypes && Catalogue.getUnitTypes()) || [];\n    const markerFor = (ut) => (ut && Catalogue.getSplayEndMarker) ? Catalogue.getSplayEndMarker(ut.id) : null;\n    const byCode = (c) => all.find(u => String(u.code || '').toUpperCase() === c);\n    const fmt = (m) => m ? (m.deepDepthMm + '/' + m.shallowDepthMm + ' ' + m.hand) : 'NULL';\n    const out = {\n      PLANNER_BUILD:   'splay-wall-fix-v111',\n      CATALOGUE_BUILD: Catalogue.CATALOGUE_BUILD || '(pre-fix build - stale cached module)',\n      PROBE: 'SPLAYLW ' + fmt(markerFor(byCode('SPLAYLW'))) +\n             '   (expect 320/140 left)  |  SPLAYLB ' + fmt(markerFor(byCode('SPLAYLB'))) +\n             '   (expect 560/370 left)',\n      catalogue: [],\n      placed: []\n    };\n    for (const ut of all) {\n      if (!/^SPLAY/i.test(ut.code || '')) continue;\n      out.catalogue.push(String(ut.code) + '  cat=' + (ut.categoryHandle || '?') +\n        '  marker=' + fmt(markerFor(ut)) +\n        '  glb=' + (ut.carcaseModelGlbUrl ? String(ut.carcaseModelGlbUrl).split('/').pop().split('?')[0] : 'none'));\n    }\n    const epTxt = (side) => {\n      const e = (side || {});\n      if (!e.active) return 'OFF' + (e.userOff ? '(userOff)' : '');\n      return 'ON style=' + (e.style || '?') + (e.tng ? '+tng' : '') + ' thick=' + (e.thickMm || '?');\n    };\n    const filTxt = (f) => (f && f.active) ? ('filler ' + Math.round(f.widthMm || 0) + 'mm') : '-';\n    out.autoEndPanels = autoEndPanels;\n    for (const c of cabinets) {\n      if (!c || !(c.splayEnd || /^SPLAY/i.test(c.code || ''))) continue;\n      const ep = c.endPanels || {}, fl = c.fillers || {};\n      out.placed.push(String(c.code || '?') + '  W' + c.widthMm + ' D' + c.depthMm + ' H' + c.heightMm +\n        '  cat=' + (c.category || '?') +\n        '  marker=' + fmt(c.splayEnd) + '  style=' + (c.kitchenStyleId || '?'));\n      out.placed.push('     endPanels: left=' + epTxt(ep.left) + ' | right=' + epTxt(ep.right) +\n        '     fillers: left=' + filTxt(fl.left) + ' | right=' + filTxt(fl.right));\n      try {\n        const nbTxt = (side) => {\n          const nb = epFindNeighbourOnSide(c, side, epVerticalRange(c), cabinets);\n          return nb ? ((nb.code || nb.name || nb.id) + ' D' + nb.depthMm +\n                       ' -> keepPanel=' + epDecideActive(c, nb)) : 'none (free end)';\n        };\n        out.placed.push('     neighbour: left=' + nbTxt('left') + ' | right=' + nbTxt('right'));\n      } catch (e) { out.placed.push('     neighbour: (lookup failed: ' + e.message + ')'); }\n    }\n    if (!out.placed.length) out.placed.push('(no splay units placed)');\n    // Every cabinet's footprint, so an adjacency that \"should\" match can be\n    // checked against the real numbers instead of inferred from the outcome.\n    out.allCabs = cabinets.map(c => {\n      const ep = c.endPanels || {};\n      return String(c.code || c.name || c.id).padEnd(10) +\n        ' x=' + Math.round(c.x) + ' y=' + Math.round(c.y) +\n        ' W' + c.widthMm + ' D' + c.depthMm + ' H' + c.heightMm +\n        ' rot=' + (c.rotationDeg || 0) +\n        ' cat=' + (c.category || '?') +\n        ' ep(L/R)=' + (ep.left?.active ? 'ON' : 'off') + '/' + (ep.right?.active ? 'ON' : 'off');\n    });\n    // Why is a side NOT registering a neighbour? Report the closest other-cab\n    // face to each splay side: perpendicular offset + how much they overlap.\n    // Adjacency needs offset <= 6mm (END_PANEL_AUTO_TOL_MM) and overlap > 6mm.\n    out.adjacency = [];\n    const lineFit = (a, b) => {\n      const dx = a.p2.x - a.p1.x, dy = a.p2.y - a.p1.y;\n      const len = Math.hypot(dx, dy);\n      if (len < 0.1) return null;\n      const ux = dx / len, uy = dy / len, nx = -uy, ny = ux;\n      const d1 = (b.p1.x - a.p1.x) * nx + (b.p1.y - a.p1.y) * ny;\n      const d2 = (b.p2.x - a.p1.x) * nx + (b.p2.y - a.p1.y) * ny;\n      const tA = (b.p1.x - a.p1.x) * ux + (b.p1.y - a.p1.y) * uy;\n      const tB = (b.p2.x - a.p1.x) * ux + (b.p2.y - a.p1.y) * uy;\n      const lo = Math.max(0, Math.min(tA, tB)), hi = Math.min(len, Math.max(tA, tB));\n      return { off: Math.max(Math.abs(d1), Math.abs(d2)), overlap: hi - lo };\n    };\n    for (const c of cabinets) {\n      if (!c || !c.splayEnd) continue;\n      for (const side of ['left', 'right']) {\n        const mine = { carc: epCarcaseSides(c)[side], eff: epAllSides(c)[side] };\n        let best = null;\n        for (const o of cabinets) {\n          if (!o || o.id === c.id) continue;\n          const oc = epCarcaseSides(o), oe = epAllSides(o);\n          for (const mk of ['carc', 'eff']) {\n            for (const ok of ['left', 'right']) {\n              for (const of2 of [['carc', oc[ok]], ['eff', oe[ok]]]) {\n                const f = lineFit(mine[mk], of2[1]);\n                if (!f || f.overlap <= 0) continue;\n                if (!best || f.off < best.off) {\n                  best = { off: f.off, overlap: f.overlap,\n                           who: (o.code || o.name || o.id), oside: ok,\n                           pair: mk + '->' + of2[0] };\n                }\n              }\n            }\n          }\n        }\n        out.adjacency.push((c.code || '?') + '.' + side + ': ' + (best\n          ? (best.who + '.' + best.oside + ' [' + best.pair + '] offset=' +\n             best.off.toFixed(1) + 'mm overlap=' + Math.round(best.overlap) +\n             'mm  => ' + (best.off <= 6 && best.overlap > 6 ? 'ADJACENT' : 'NOT adjacent (needs offset<=6)'))\n          : 'no other cab found'));\n      }\n    }\n    const _fs = featureStyles || {};\n    out.featureStyles = 'cornice=' + _fs.cornice + ' pelmet=' + _fs.pelmet + ' plinth=' + _fs.plinth;\n    console.log('[BTK] splay check', out);\n    return out;\n  };\n\n  // Standard cabinet width band the Magic allocator will build with.\n  const MAGIC_MIN_UNIT_MM = 300;    // smallest BULK fill width (avoids tiny-unit swarms)\n  const MAGIC_MAX_UNIT_MM = 1000;\n  const MAGIC_MAKEUP_MIN_MM = 150;  // narrow \"make-up\" widths (150\u2013<300) - ONE allowed at a\n                                    // run end to shrink an oversized filler, never in the bulk\n\n  // Is this unit type an all-drawer (pan-drawer) base - drawers, no doors?\n  // Classified from the resolved cutout schema. Used for premium spec.\n  function isAllDrawerUnit(ut, styleId) {\n    const product = Catalogue.getProductForUnitInStyle(ut.id, styleId);\n    const v = product && product.variants && product.variants[0];\n    if (!v) return false;\n    const def = Catalogue.buildCabinetDefinition({ unitTypeId: ut.id, variantId: v.id, kitchenStyleId: styleId });\n    const ops = (def && def.cutoutSchema && def.cutoutSchema.openings) || [];\n    // A base pull-out's door front counts as its drawer, as it always has.\n    const poDrawer  = !!(Catalogue.pullOutFrontIsDrawer && Catalogue.pullOutFrontIsDrawer(def && def.cutoutSchema));\n    const hasDrawer = ops.some(o => o.type === 'drawer' || (poDrawer && o.type === 'door'));\n    const hasDoor   = !poDrawer && ops.some(o => o.type === 'door');\n    return hasDrawer && !hasDoor;\n  }\n\n  // Collect the plain (non-corner/sink/appliance) unit types in a\n  // category for the chosen style, indexed by their available widths.\n  // Returns { widths: [asc], byWidth: Map(width -> {unitTypeId, variantId,\n  // widthMm, depthMm, isDrawer}) }. With opts.preferDrawers (premium spec)\n  // an all-drawer base wins over a door base at the same width.\n  function magicUnitCatalogue(categoryHandle, styleId, opts = {}) {\n    const preferDrawers = !!opts.preferDrawers;\n    const up = s => String(s || '').toUpperCase();\n    const badGroup = MAGIC_BAD_GROUP;\n    const badCode  = MAGIC_BAD_CODE;\n    const readies = Catalogue.getReadyUnitTypesInL1Category(categoryHandle) || [];\n    const byWidth = new Map();\n    for (const ut of readies) {\n      if (ut.sinkBase) continue;\n      // Midi units live in the tall category but are worktop-height (not\n      // full-height larders) and unpopular - never auto-place them.\n      if (ut.isMidiUnit === true) continue;\n      // Only plain RECTANGULAR units fill a run. End units, splays, curved /\n      // radius, corner, diagonal and L-shape units are end-of-run / feature\n      // pieces - never sit them mid-run (the customer places them by hand).\n      const shape = String(ut.planner2D?.shape || 'rectangle').trim().toLowerCase();\n      if (shape && shape !== 'rectangle') continue;\n      if (ut.unitTypeGroupHandle && badGroup.test(ut.unitTypeGroupHandle)) continue;\n      if (badCode.test(up(ut.code))) continue;\n      const product = Catalogue.getProductForUnitInStyle(ut.id, styleId);\n      if (!product) continue;\n      const isDrawer = preferDrawers ? isAllDrawerUnit(ut, styleId) : false;\n      for (const v of (product.variants || [])) {\n        const info = Catalogue.getVariantInfo(v.id);\n        if (!info || !info.widthMm || !info.variant) continue;\n        // Bulk fill widths are 300\u20131000; narrow 150\u2013<300 widths are kept too\n        // but ONLY as an end-of-run make-up piece (see allocateRun). Anything\n        // below 150 or above 1000 is excluded (filler-thin / oversized).\n        if (info.widthMm < MAGIC_MAKEUP_MIN_MM || info.widthMm > MAGIC_MAX_UNIT_MM) continue;\n        const rec = {\n          unitTypeId: ut.id, variantId: info.variant.id,\n          widthMm: info.widthMm, depthMm: info.depthMm, isDrawer,\n          medium: (info.variant.options || []).some(o => /^med(ium)?$/i.test(String(o || '').trim()))\n        };\n        const existing = byWidth.get(info.widthMm);\n        // First unit per width wins, but a drawer base upgrades a door base\n        // when the premium spec asks for drawers everywhere. A unit sold Low /\n        // Medium / High goes in at Medium, whichever size its product lists first.\n        if (!existing || (preferDrawers && isDrawer && !existing.isDrawer)\n            || (existing.unitTypeId === ut.id && !existing.medium && rec.medium && existing.depthMm === rec.depthMm)) {\n          byWidth.set(info.widthMm, rec);\n        }\n      }\n    }\n    const allW = [...byWidth.keys()].sort((a, b) => a - b);\n    return {\n      widths:       allW.filter(w => w >= MAGIC_MIN_UNIT_MM),   // bulk (DP)\n      makeupWidths: allW.filter(w => w <  MAGIC_MIN_UNIT_MM),   // narrow end make-up\n      byWidth\n    };\n  }\n\n  // Allocate a wall-run span into an ordered list of slots. Design rules:\n  //   \u2022 a scribe filler (\u2265 minFillerMm) at each abutting end,\n  //   \u2022 units centred in the span (leftover split evenly to the fillers),\n  //   \u2022 widths chosen (unlimited supply) to pack as tightly as possible,\n  //   \u2022 arranged symmetrically (palindrome-ish, widest toward the centre).\n  // Corner-ready: pass startFiller/endFiller=false where a corner unit \u2014\n  // not a wall - bounds that end. Returns { slots:[{kind,widthMm,offset}],\n  // unitCount, unitTotalMm }. offset is measured from the span start.\n  function allocateRun(spanMm, widths, opts = {}) {\n    const minF = opts.minFillerMm != null ? opts.minFillerMm : 20;\n    const startFiller = opts.startFiller !== false;\n    const endFiller   = opts.endFiller   !== false;\n    const asc = (widths || []).filter(w => w > 0).sort((a, b) => a - b);\n    const reserved = (startFiller ? minF : 0) + (endFiller ? minF : 0);\n    const usable = spanMm - reserved;\n\n    if (!asc.length || usable < asc[0]) {\n      return { slots: [{ kind: 'filler', widthMm: Math.max(0, spanMm), offset: 0 }], unitCount: 0, unitTotalMm: 0 };\n    }\n\n    // DP: greatest reachable total \u2264 usable using unlimited copies.\n    // Reconstruct via the LARGEST fitting width so the run is built from\n    // the fewest, biggest standard units (600s etc.), not a swarm of\n    // narrow ones - smaller widths are used only to finish the span.\n    const target = Math.floor(usable);\n    const via = new Int32Array(target + 1).fill(-1);   // via[t] = width used to reach t; -1 = unreachable\n    via[0] = 0;\n    for (let t = 1; t <= target; t++) {\n      for (let k = asc.length - 1; k >= 0; k--) {\n        const w = asc[k];\n        if (w <= t && via[t - w] >= 0) { via[t] = w; break; }\n      }\n    }\n    let best = target;\n    while (best > 0 && via[best] < 0) best--;\n\n    // Oversized-filler make-up: the discrete bulk widths can leave a filler\n    // well above the minimum (e.g. 104mm) when no bulk combination lands near\n    // the span. If so, allow ONE narrow make-up cabinet (150\u2013<300) to reach a\n    // tighter total - it REPLACES bulk to hit a higher coverage (a 150 unit\n    // can't fit an 84mm gap, but swapping bulk 1000\u2192800 + a 250 make-up covers\n    // 1050). Keeps the bulk run in standard widths; the make-up lands at the\n    // run end (widths sort largest\u2192smallest below).\n    const makeup = (opts.makeupWidths || []).filter(w => w > 0).sort((a, b) => a - b);\n    const MAGIC_OVERSIZE_FILLER_MM = 40;\n    let useBulk = best, useMakeup = 0;\n    if (makeup.length && (spanMm - best - reserved) > MAGIC_OVERSIZE_FILLER_MM) {\n      let bestTotal = best;\n      for (const mw of makeup) {\n        if (mw > target) continue;\n        let bt = target - mw;                       // most bulk that still fits \u2264 target-mw\n        while (bt > 0 && via[bt] < 0) bt--;\n        const total = bt + mw;\n        if (total > bestTotal) { bestTotal = total; useBulk = bt; useMakeup = mw; }\n      }\n      if (useMakeup) best = bestTotal;\n    }\n\n    const counts = [];\n    for (let t = useBulk; t > 0; t -= via[t]) counts.push(via[t]);\n    if (useMakeup) counts.push(useMakeup);\n\n    // Order largest \u2192 smallest so equal widths sit together and any single\n    // narrow make-up unit lands at the run END (next to the wall/filler),\n    // never sandwiched between wide units - a lone narrow unit mid-run\n    // reads as a mistake, not a design.\n    const arranged = counts.sort((a, b) => b - a);\n\n    // Leftover (\u2265 reserved) split into the end fillers.\n    const leftover = spanMm - best;\n    const fStart = startFiller ? (endFiller ? Math.floor(leftover / 2) : leftover) : 0;\n    let   fEnd   = endFiller ? (leftover - fStart) : 0;\n    // Corner-bounded at BOTH ends (no scribe reserved): park the minimal\n    // tiling remainder as a single filler at the end rather than reserving\n    // scribe space a corner doesn't need - keeps corner-to-corner runs tight.\n    if (!startFiller && !endFiller && leftover > 0) fEnd = leftover;\n\n    const slots = [];\n    let off = 0;\n    if (fStart > 0) { slots.push({ kind: 'filler', widthMm: fStart, offset: off }); off += fStart; }\n    for (const w of arranged) { slots.push({ kind: 'unit', widthMm: w, offset: off }); off += w; }\n    if (fEnd > 0) { slots.push({ kind: 'filler', widthMm: fEnd, offset: off }); off += fEnd; }\n    return { slots, unitCount: arranged.length, unitTotalMm: best };\n  }\n\n  // Convert an axis-aligned wall's back-direction into a cardinal cabinet\n  // rotation. Cab-local +Y is the BACK (per engine convention), so:\n  //   back faces +Y \u2192 0   -X \u2192 90   -Y \u2192 180   +X \u2192 270\n  function rotationForBackDir(bx, by) {\n    if (Math.abs(by - 1) < 0.5) return 0;\n    if (Math.abs(bx + 1) < 0.5) return 90;\n    if (Math.abs(by + 1) < 0.5) return 180;\n    return 270;\n  }\n\n  // Build + place one cabinet flush to a wall at a given along-wall centre.\n  // wallFrame carries the wall + its tangent (u) / inward normal (n) / back\n  // rotation. Returns the placed cab (or null).\n  function spawnPlacedUnit(unitTypeId, variantId, styleId, wallFrame, alongCentreMm) {\n    const def = Catalogue.buildCabinetDefinition({ unitTypeId, variantId, kitchenStyleId: styleId });\n    if (!def) return null;\n    const before = cabinets.length;\n    addCabinet(def);\n    if (cabinets.length <= before) return null;\n    const cab = cabinets[cabinets.length - 1];\n    const cw = cab.widthMm, cd = cab.depthMm;\n    const { wall, ux, uy, nx, ny, rot } = wallFrame;\n    const cx = wall.from.x + ux * alongCentreMm + nx * (cd / 2);\n    const cy = wall.from.y + uy * alongCentreMm + ny * (cd / 2);\n    cab.rotationDeg = rot;\n    cab.x = cx - cw / 2;                            // unrotated top-left (centre-anchored)\n    cab.y = cy - cd / 2;\n    return cab;\n  }\n\n  // Build a wall \"frame\": tangent (u), inward normal (n, into room) and the\n  // cardinal back-rotation for units seated against it.\n  function makeWallFrame(wall) {\n    const len = wall.lengthMm || 1;\n    const ux = (wall.to.x - wall.from.x) / len;\n    const uy = (wall.to.y - wall.from.y) / len;\n    const nx = -uy, ny = ux;\n    return { wall, ux, uy, nx, ny, rot: rotationForBackDir(-nx, -ny) };\n  }\n\n  // Seat a placed cab (already built) flush to a wall at an along-centre.\n  // Mirrors spawnPlacedUnit's positioning for cabs built by a stub builder\n  // (oven housings) rather than from a product definition.\n  function seatCabOnWall(cab, wallFrame, alongCentreMm) {\n    const cw = cab.widthMm, cd = cab.depthMm;\n    const { wall, ux, uy, nx, ny, rot } = wallFrame;\n    const cx = wall.from.x + ux * alongCentreMm + nx * (cd / 2);\n    const cy = wall.from.y + uy * alongCentreMm + ny * (cd / 2);\n    cab.rotationDeg = rot;\n    cab.x = cx - cw / 2;\n    cab.y = cy - cd / 2;\n    return cab;\n  }\n\n  // Spawn an oven housing (stub-built, not product-built) flush to a wall at\n  // an along-centre. tall=true \u2192 eye-level tall single-oven housing (TOH);\n  // else a build-under base housing (OVH). Applies the current style colours\n  // + catalogue fill so it matches the rest of the run.\n  function spawnOvenHousing(styleId, wallFrame, alongCentreMm, tall) {\n    const cat = tall ? getTallOvenHousingUnitCatalogue() : getOvenHousingUnitCatalogue();\n    const entry = cat && cat[0];\n    if (!entry) return null;\n    const build = tall ? buildTallOvenHousingUnitCabinet : buildOvenHousingUnitCabinet;\n    const cab = build(entry, {\n      id: `cab-${tall ? 'toh' : 'ovh'}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 5)}`,\n      x: 0, y: 0\n    });\n    if (!cab) return null;\n    const behaviourCat = tall ? 'tall-units' : 'base-units';\n    cab.kitchenStyleId      = styleId;\n    cab.doorColourHandle    = globalDoorColourHandle    || (Catalogue.getDoorColoursForStyle(styleId)    || [])[0]?.handle || null;\n    cab.carcaseColourHandle = globalCarcaseColourHandle || (Catalogue.getCarcaseColoursForStyle(styleId) || [])[0]?.handle || null;\n    const fill = findCatalogueFillForCategory(behaviourCat);\n    if (fill) cab.planner2D = { fillColour: fill };\n    cab.displayNumber = nextDisplayNumber();\n    cabinets.push(cab);\n    return seatCabOnWall(cab, wallFrame, alongCentreMm);\n  }\n\n  // Spawn a plain base unit for a HOB marker + drop a hob on its worktop\n  // (first catalogue hob). The hob renders on the worktop above any base cab.\n  function spawnHobBase(styleId, wallFrame, alongCentreMm, bpick) {\n    if (!bpick) return null;\n    const cab = spawnPlacedUnit(bpick.unitTypeId, bpick.variantId, styleId, wallFrame, alongCentreMm);\n    if (cab) {\n      const hobs = (getWorktopItemCatalogue().hobs) || [];\n      if (hobs[0]) cab.hob = hobs[0];\n    }\n    return cab;\n  }\n\n  // Where a run should butt against a corner unit, using the planner's OWN\n  // snap engine - so it respects the corner post + hand (a fixed reserve\n  // can't, because the post sits on opposite sides for a left- vs right-\n  // hand blank). Drops a probe unit near the corner, snaps it to the corner\n  // cab, and reads back its along-wall offset. Returns the reserve (mm from\n  // the given wall end) or null to fall back to the geometric estimate.\n  function cornerReserveSnap(cornerCab, wall, atFrom, probeDepthMm) {\n    if (!cornerCab) return null;\n    const frame = makeWallFrame(wall);\n    const cw = 600, cd = probeDepthMm || 570;        // representative unit (base 570 / wall 330)\n    const near = cd + cw / 2;                        // near edge ~cd from the end\n    const centreAlong = atFrom ? near : (wall.lengthMm - near);\n    const cx = wall.from.x + frame.ux * centreAlong + frame.nx * (cd / 2);\n    const cy = wall.from.y + frame.uy * centreAlong + frame.ny * (cd / 2);\n    // Match the corner cab's category so the probe collides with it (same\n    // category \u21D2 push-out to butt; a mismatched pair may be allowed to\n    // overlap, giving a wrong offset).\n    const item = { widthMm: cw, depthMm: cd, rotationDeg: frame.rot, category: cornerCab.category || 'base-units' };\n    let s;\n    try {\n      s = snapAndClamp(item, cx - cw / 2, cy - cd / 2, room, [cornerCab],\n        (roomConfig && roomConfig.perimeterItems) || [], (roomConfig && roomConfig.wallOpenings) || []);\n    } catch (e) { return null; }\n    if (!s) return null;\n    const centre = (s.x + cw / 2 - wall.from.x) * frame.ux + (s.y + cd / 2 - wall.from.y) * frame.uy;\n    let reserve = atFrom ? (centre - cw / 2) : (wall.lengthMm - (centre + cw / 2));\n    // The snap butts against the corner's post-EXTENDED footprint. On a\n    // perpendicular (return) run that leaves the ~40mm post nub as a gap \u2014\n    // pull the run in by postY so it butts the carcase, post sitting beside\n    // it. (On the corner's OWN wall the door end has no such extension, and\n    // its rotation matches the wall frame, so we skip the adjustment.)\n    const cabRot  = (((cornerCab.rotationDeg || 0) % 360) + 360) % 360;\n    const wallRot = ((frame.rot % 360) + 360) % 360;\n    if (cabRot !== wallRot && cornerCab.cornerUnit) {\n      reserve -= (cornerCab.cornerUnit.postYMm || 0);\n    }\n    // Sane band: a corner butt is ~530 (perp) to ~1110 (host). Reject a\n    // wild snap (probe grabbed a wall/opening instead) \u2192 geometric fallback.\n    if (!(reserve >= 200 && reserve <= 1400)) return null;\n    console.log('[BTK Magic] corner snap reserve', { wall: wall.index, atFrom, reserve: Math.round(reserve) });\n    return reserve;\n  }\n\n  // The L-shape corner base unit to seat in corners (stub catalogue \u2014\n  // one 910\u00D7910 unit, orientation is hand-driven). null if unavailable.\n  function magicCornerEntry() {\n    const list = (typeof getLShapeUnitCatalogue === 'function') ? (getLShapeUnitCatalogue() || []) : [];\n    return list[0] || null;\n  }\n\n  const BLANK_CORNER_RESERVE_MM = 600;   // dead-corner reserve when no corner unit is available\n\n  // Resolve which corner unit to use, with the per-wall reservations it\n  // needs. Preference (user pref): blank-panel corner (sits along ONE\n  // host wall, return run butts its side) \u2192 L-shape \u2192 none (dead corner).\n  //   { kind, hostReserve (along host wall), perpReserve (perp wall),\n  //     unitTypeId/variantId | entry }\n  function magicCornerUnit(styleId) {\n    // 1) Blank-panel corner (preferred) - planner2D.shape 'corner-blank',\n    //    1000 cab / 500 door. Occupies cabinet+void along its host wall,\n    //    ~570mm (carcase depth) on the perpendicular wall.\n    const blanks = (Catalogue.getReadyUnitTypes() || [])\n      .filter(ut => ut.planner2D && isCornerBlankShape(ut.planner2D.shape));\n    for (const ut of blanks) {\n      const product = Catalogue.getProductForUnitInStyle(ut.id, styleId);\n      if (!product) continue;\n      const infos = (product.variants || []).map(v => Catalogue.getVariantInfo(v.id)).filter(Boolean);\n      const info = infos.find(i => i.widthMm === 1000 && i.doorMm === 500)\n                || infos.find(i => i.widthMm === 1000)\n                || infos[0];\n      if (!info || !info.variant) continue;\n      const cabinetMm = info.widthMm || CORNER_BLANK_DEFAULTS.cabinetMm;\n      const doorMm    = info.doorMm  || CORNER_BLANK_DEFAULTS.doorMm;\n      const blankMm   = Math.max(0, cabinetMm - doorMm - CORNER_BLANK_DEFAULTS.postXMm);\n      const voidMm    = Math.max(0, CORNER_POST_REACH_MM - blankMm);\n      return {\n        kind: 'blank', unitTypeId: ut.id, variantId: info.variant.id,\n        hostReserve: cabinetMm + voidMm,             // along host wall (door end ~1110)\n        // Perp wall: clear the corner unit's carcase depth so the return\n        // run butts flush against its side, with the post sitting at the\n        // junction. (The postY protrusion is only a 40mm nub - reserving\n        // past it just leaves an empty strip / gap.)\n        perpReserve: info.depthMm || CORNER_POST_REACH_MM\n      };\n    }\n    // 2) L-shape fallback (symmetric 910\u00D7910).\n    const l = magicCornerEntry();\n    if (l) return { kind: 'lshape', entry: l, hostReserve: l.widthMm || 910, perpReserve: l.depthMm || 910 };\n    // 3) None - leave a blank dead corner so the two runs clear each other.\n    return { kind: 'none', hostReserve: BLANK_CORNER_RESERVE_MM, perpReserve: BLANK_CORNER_RESERVE_MM };\n  }\n\n  // Seat an L-shape corner base unit into a room corner VERTEX, oriented\n  // toward the room interior (centroid decides which way the box extends;\n  // lShapeUnitDesiredHand sets the hand). Mirrors addLShapeUnit's colour\n  // setup. Returns the placed cab (or null).\n  function spawnCornerUnit(entry, vertex, centroid, styleId) {\n    const W = entry.widthMm || 910, Dd = entry.depthMm || 910;\n    const x = (centroid.x >= vertex.x) ? vertex.x : vertex.x - W;\n    const y = (centroid.y >= vertex.y) ? vertex.y : vertex.y - Dd;\n    const doorColours    = Catalogue.getDoorColoursForStyle(styleId)    || [];\n    const carcaseColours = Catalogue.getCarcaseColoursForStyle(styleId) || [];\n    const cab = buildLShapeUnitCabinet(entry, {\n      id: `cab-magic-corner-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 5)}`,\n      x, y, hand: 'NE'\n    });\n    const want = lShapeUnitDesiredHand(cab, x, y, room, (roomConfig && roomConfig.perimeterItems) || []);\n    if (want) cab.lShapeUnit = { ...cab.lShapeUnit, hand: want };\n    cab.kitchenStyleId      = styleId;\n    cab.doorColourHandle    = globalDoorColourHandle    || doorColours[0]?.handle    || null;\n    cab.carcaseColourHandle = globalCarcaseColourHandle || carcaseColours[0]?.handle || null;\n    const inheritedFill = findCatalogueFillForCategory(entry.category);\n    if (inheritedFill) cab.planner2D = { fillColour: inheritedFill };\n    cab.displayNumber = nextDisplayNumber();\n    cabinets.push(cab);\n    return cab;\n  }\n\n  // The corner WALL unit to seat above a corner. Prefer the REAL standard\n  // corner wall product (SCWU - the corner-wall-units unit that isn't a\n  // diagonal/L-shape), resolved the same way the base corner resolves its\n  // blank product; fall back to the CWB stub catalogue only if no real\n  // product exists in the style. Returns:\n  //   { isReal:true,  unitTypeId, variantId, hostReserve, perpReserve }  or\n  //   { isReal:false, entry (stub), hostReserve, perpReserve }  or  null.\n  function magicCornerWallEntry(styleId) {\n    const reals = (Catalogue.getReadyUnitTypes() || []).filter(ut =>\n      ut.categoryHandle === 'wall-units'\n      && /corner-wall/i.test(ut.unitTypeGroupHandle || '')\n      && !/DIAG|LSHAPE|CURVE|OCURVE/i.test(ut.code || ''));\n    // A corner-blank-shaped product first (matches the stub geometry), then\n    // any other standard corner wall unit; widest cabinet variant of it.\n    reals.sort((a, b) =>\n      (isCornerBlankShape(b.planner2D?.shape) ? 1 : 0) -\n      (isCornerBlankShape(a.planner2D?.shape) ? 1 : 0));\n    for (const ut of reals) {\n      const product = Catalogue.getProductForUnitInStyle(ut.id, styleId);\n      if (!product) continue;\n      const infos = (product.variants || []).map(v => Catalogue.getVariantInfo(v.id)).filter(Boolean);\n      const info = infos.reduce((a, b) => ((b.widthMm || 0) > (a.widthMm || 0) ? b : a), infos[0]);\n      if (!info || !info.variant) continue;\n      const cabinetMm = info.widthMm || 600;\n      const doorMm    = info.doorMm  || 0;\n      const depthMm   = info.depthMm || 330;\n      const blankMm   = doorMm ? Math.max(0, cabinetMm - doorMm - CORNER_BLANK_DEFAULTS.postXMm) : 0;\n      const voidMm    = doorMm ? Math.max(0, depthMm - blankMm) : 0;\n      return {\n        isReal: true, unitTypeId: ut.id, variantId: info.variant.id,\n        hostReserve: cabinetMm + voidMm, perpReserve: depthMm\n      };\n    }\n    // Fallback: CWB stub catalogue (600/700/800/900 cab \u00D7 330 deep).\n    const list = (typeof getCornerWallUnitCatalogue === 'function') ? (getCornerWallUnitCatalogue() || []) : [];\n    if (!list.length) return null;\n    const at720 = list.filter(e => e.heightMm === 720);\n    const pool = at720.length ? at720 : list;\n    const entry = pool.reduce((a, b) => (b.widthMm > a.widthMm ? b : a), pool[0]);\n    return { isReal: false, entry, hostReserve: entry.widthMm, perpReserve: entry.depthMm || 330 };\n  }\n\n  // Seat a REAL corner wall product flush along the HOST wall with the void\n  // end at the vertex. Builds via the normal product path (colours/fill/height\n  // handled), reads the built footprint to position it, and sets the corner\n  // hand if the product carries a cornerUnit descriptor. Returns the cab/null.\n  function placeRealCornerWallUnit(unitTypeId, variantId, vertex, hostWall, styleId) {\n    const frame = makeWallFrame(hostWall);\n    const cab = spawnPlacedUnit(unitTypeId, variantId, styleId, frame, 0);   // provisional\n    if (!cab) return null;\n    const cw = cab.widthMm, cd = cab.depthMm;\n    const atFrom = vNear(vertex, hostWall.from);\n    const alongCentre = atFrom ? cw / 2 : hostWall.lengthMm - cw / 2;\n    const cx = frame.wall.from.x + frame.ux * alongCentre + frame.nx * (cd / 2);\n    const cy = frame.wall.from.y + frame.uy * alongCentre + frame.ny * (cd / 2);\n    cab.rotationDeg = frame.rot;\n    cab.x = cx - cw / 2;\n    cab.y = cy - cd / 2;\n    if (cab.cornerUnit) {\n      const want = cornerUnitDesiredHand(cab, cab.x, cab.y, room, (roomConfig && roomConfig.perimeterItems) || []);\n      if (want) {\n        cab.cornerUnit = { ...cab.cornerUnit, hand: want };\n        syncCornerHandVariant(cab);\n      }\n    }\n    return cab;\n  }\n\n  // Seat a blank-panel corner WALL unit at a room corner, flush along the HOST\n  // wall with the void end at the vertex (mirrors placeCorner's blank branch,\n  // at wall depth/height). Returns the placed cab or null.\n  function placeCornerWallUnit(entry, vertex, hostWall, styleId) {\n    if (!entry) return null;\n    const cab = buildCornerWallUnitCabinet(entry, {\n      id: `cab-magic-cwall-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 5)}`,\n      x: 0, y: 0, hand: 'left'\n    });\n    if (!cab) return null;\n    const frame = makeWallFrame(hostWall);\n    const atFrom = vNear(vertex, hostWall.from);\n    const cw = cab.widthMm, cd = cab.depthMm;\n    const alongCentre = atFrom ? cw / 2 : hostWall.lengthMm - cw / 2;\n    const cx = frame.wall.from.x + frame.ux * alongCentre + frame.nx * (cd / 2);\n    const cy = frame.wall.from.y + frame.uy * alongCentre + frame.ny * (cd / 2);\n    cab.rotationDeg = frame.rot;\n    cab.x = cx - cw / 2;\n    cab.y = cy - cd / 2;\n    const doorColours    = Catalogue.getDoorColoursForStyle(styleId)    || [];\n    const carcaseColours = Catalogue.getCarcaseColoursForStyle(styleId) || [];\n    cab.kitchenStyleId      = styleId;\n    cab.doorColourHandle    = globalDoorColourHandle    || doorColours[0]?.handle    || null;\n    cab.carcaseColourHandle = globalCarcaseColourHandle || carcaseColours[0]?.handle || null;\n    const inheritedFill = findCatalogueFillForCategory('wall-units');\n    if (inheritedFill) cab.planner2D = { fillColour: inheritedFill };\n    const want = cornerUnitDesiredHand(cab, cab.x, cab.y, room, (roomConfig && roomConfig.perimeterItems) || []);\n    if (want) cab.cornerUnit = { ...cab.cornerUnit, hand: want };\n    cab.displayNumber = nextDisplayNumber();\n    cabinets.push(cab);\n    return cab;\n  }\n\n  // Place a corner unit at a room corner per the resolved spec. Blank-panel\n  // corners sit flush along the HOST wall with the void end at the vertex;\n  // L-shape corners seat into the vertex. Returns the placed cab, or null.\n  function placeCorner(spec, vertex, hostWall, centroid, styleId) {\n    if (!spec) return null;\n    if (spec.kind === 'lshape') {\n      return spawnCornerUnit(spec.entry, vertex, centroid, styleId) || null;\n    }\n    if (spec.kind === 'blank') {\n      const frame = makeWallFrame(hostWall);\n      const atFrom = vNear(vertex, hostWall.from);\n      const alongCentre = atFrom\n        ? spec.hostReserve / 2\n        : hostWall.lengthMm - spec.hostReserve / 2;\n      const cab = spawnPlacedUnit(spec.unitTypeId, spec.variantId, styleId, frame, alongCentre);\n      if (cab && cab.cornerUnit) {\n        // Seat the void into the corner (auto-hand pass also runs on render).\n        const want = cornerUnitDesiredHand(cab, cab.x, cab.y, room, (roomConfig && roomConfig.perimeterItems) || []);\n        if (want) {\n          cab.cornerUnit = { ...cab.cornerUnit, hand: want };\n          syncCornerHandVariant(cab);\n        }\n      }\n      return cab || null;\n    }\n    return null;   // 'none' - dead corner, reservation only\n  }\n\n  const vNear = (a, b) => Math.abs(a.x - b.x) < 1 && Math.abs(a.y - b.y) < 1;\n  const sharedVertex = (wA, wB) => {\n    for (const va of [wA.from, wA.to]) for (const vb of [wB.from, wB.to]) if (vNear(va, vb)) return va;\n    return null;\n  };\n\n  // Decide which walls carry runs (and where corner units sit) for the\n  // requested shape. Returns { runs:[{wall, reserveFrom, reserveTo}],\n  // corners:[{vertex}] }. reserveFrom/To is the mm eaten at that wall end\n  // by a corner unit (or blank-corner dead space).\n  function buildShapePlan(shape, walls, hostReserve, perpReserve, primaryWall) {\n    const longest = walls.reduce((a, b) => (b.lengthMm > a.lengthMm ? b : a));\n    // The user-tapped wall (if valid) is the anchor; otherwise the longest.\n    const primary = (primaryWall && walls.indexOf(primaryWall) >= 0) ? primaryWall : longest;\n    let selected = [primary];\n    let cornerDefs = [];   // { vertex, host, perp } - host carries the corner unit\n\n    if (shape === 'l') {\n      let a = null, b = null, v = null;\n      // Prefer the anchor wall + its longest adjacent neighbour; else the\n      // best-scoring adjacent pair anywhere in the room.\n      const primNbr = walls.filter(w => w !== primary && sharedVertex(primary, w))\n                           .sort((x, y) => y.lengthMm - x.lengthMm)[0];\n      if (primNbr) { a = primary; b = primNbr; v = sharedVertex(primary, primNbr); }\n      if (!v) {\n        let best = null;\n        for (let i = 0; i < walls.length; i++) {\n          for (let j = i + 1; j < walls.length; j++) {\n            const sv = sharedVertex(walls[i], walls[j]);\n            if (!sv) continue;\n            const score = walls[i].lengthMm + walls[j].lengthMm;\n            if (!best || score > best.score) best = { a: walls[i], b: walls[j], v: sv, score };\n          }\n        }\n        if (best) { a = best.a; b = best.b; v = best.v; }\n      }\n      if (v) {\n        // Longer wall hosts the corner unit (more room for its ~1110mm body).\n        const host = a.lengthMm >= b.lengthMm ? a : b;\n        const perp = host === a ? b : a;\n        selected = [a, b];\n        cornerDefs = [{ vertex: v, host, perp }];\n      }\n    } else if (shape === 'u') {\n      const base = primary;\n      const nbrs = walls.filter(w => w !== base && sharedVertex(base, w)).sort((a, b) => b.lengthMm - a.lengthMm);\n      if (nbrs.length >= 2) {\n        const arm1 = nbrs[0], arm2 = nbrs[1];\n        selected = [base, arm1, arm2];\n        // Host each corner on its ARM (not the base) so the base wall never\n        // carries two corner units at once - that combination causes fitting\n        // trouble. Each arm hosts one; the base butts their return sides.\n        cornerDefs = [\n          { vertex: sharedVertex(base, arm1), host: arm1, perp: base },\n          { vertex: sharedVertex(base, arm2), host: arm2, perp: base }\n        ];\n      }\n    }\n\n    const runs = selected.map(wall => {\n      let reserveFrom = 0, reserveTo = 0;\n      for (const c of cornerDefs) {\n        const r = (wall === c.host) ? hostReserve : (wall === c.perp) ? perpReserve : 0;\n        if (!r) continue;\n        if (vNear(c.vertex, wall.from)) reserveFrom = Math.max(reserveFrom, r);\n        if (vNear(c.vertex, wall.to))   reserveTo   = Math.max(reserveTo, r);\n      }\n      return { wall, reserveFrom, reserveTo };\n    });\n    return { runs, corners: cornerDefs.map(c => ({ vertex: c.vertex, hostWall: c.host })) };\n  }\n\n  // Project painted cells onto their nearest axis-aligned wall \u2192 per-wall\n  // along-spans \u2192 runs [{wall, spanStart, spanEnd}]. Contiguous cells (gap\n  // \u2264 200mm) merge into one span.\n  function buildPaintedRuns(cellsSet) {\n    const walls = getWalls(room);\n    const perWall = walls.map(() => []);\n    // Along-offset + perp distance of a point on an axis-aligned wall (or null).\n    const project = (w, cx, cy) => {\n      const len = w.lengthMm; if (!(len > 0)) return null;\n      const ux = (w.to.x - w.from.x) / len, uy = (w.to.y - w.from.y) / len;\n      if (Math.abs(ux) > 0.02 && Math.abs(uy) > 0.02) return null;\n      const along = (cx - w.from.x) * ux + (cy - w.from.y) * uy;\n      const nx = -uy, ny = ux;\n      const perp = Math.abs((cx - w.from.x) * nx + (cy - w.from.y) * ny);\n      return { along, perp, len };\n    };\n    for (const key of cellsSet) {\n      const p = key.split(','); const cx = (+p[0] + 0.5) * 100, cy = (+p[1] + 0.5) * 100;\n      // Trust the wall the user painted this cell against - a corner cell that\n      // sits perpendicularly closer to the side wall still belongs to the wall\n      // it was stroked along (otherwise the run is truncated at both corners).\n      const rec = paintData.cellWall.get(key);\n      if (rec != null && walls[rec]) {\n        const a = project(walls[rec], cx, cy);\n        if (a && a.along >= -60 && a.along <= a.len + 60) { perWall[rec].push(a.along); continue; }\n      }\n      // Free / island cell: nearest axis-aligned wall within band depth.\n      let bi = -1, bd = Infinity, ba = 0;\n      for (let i = 0; i < walls.length; i++) {\n        const a = project(walls[i], cx, cy);\n        if (!a || a.along < -60 || a.along > a.len + 60) continue;\n        if (a.perp < bd) { bd = a.perp; bi = i; ba = a.along; }\n      }\n      if (bi >= 0 && bd < 750) perWall[bi].push(ba);\n    }\n    const runs = [];\n    perWall.forEach((vals, i) => {\n      if (!vals.length) return;\n      vals.sort((a, b) => a - b);\n      let s = vals[0], prev = vals[0];\n      for (let k = 1; k < vals.length; k++) {\n        if (vals[k] - prev > 200) { runs.push({ wall: walls[i], spanStart: Math.max(0, s - 50), spanEnd: prev + 50 }); s = vals[k]; }\n        prev = vals[k];\n      }\n      runs.push({ wall: walls[i], spanStart: Math.max(0, s - 50), spanEnd: Math.min(walls[i].lengthMm, prev + 50) });\n    });\n\n    // Paint is a ROUGH guide - the \u00B1300mm brush makes it fiddly to reach exactly\n    // into a corner. If a run stops within CORNER_SNAP_MM of a wall end and no\n    // other run occupies that corner, extend it to the end so it fills cleanly\n    // into the corner. When another run DOES reach the shared corner (an L/U),\n    // leave the gap - the corner-reserve logic manages that join.\n    const CORNER_SNAP_MM = 750;\n    const near = (a, b) => Math.hypot(a.x - b.x, a.y - b.y) < 50;\n    const otherReachesVertex = (self, vx) => runs.some(o => {\n      if (o === self || o.wall.index === self.wall.index) return false;\n      if (near(o.wall.from, vx)) return o.spanStart <= CORNER_SNAP_MM;\n      if (near(o.wall.to, vx))   return o.spanEnd >= o.wall.lengthMm - CORNER_SNAP_MM;\n      return false;\n    });\n    for (const run of runs) {\n      const len = run.wall.lengthMm;\n      if (run.spanStart > 0 && run.spanStart <= CORNER_SNAP_MM\n          && !otherReachesVertex(run, run.wall.from)) run.spanStart = 0;\n      if (run.spanEnd < len && run.spanEnd >= len - CORNER_SNAP_MM\n          && !otherReachesVertex(run, run.wall.to)) run.spanEnd = len;\n    }\n    return runs;\n  }\n\n  // Build a plan (runs + corners) from PAINTED base cells - the customer's\n  // drawn footprint replaces the auto wall-picker. A corner is a vertex where\n  // two painted runs on perpendicular walls both reach it.\n  function buildPaintedPlan(cellsSet, hostReserve, perpReserve) {\n    const runs = buildPaintedRuns(cellsSet);\n    const NEAR = 300;\n    const reaches = (r, v) =>\n      vNear(v, r.wall.from) ? (r.spanStart <= NEAR)\n      : vNear(v, r.wall.to) ? (r.spanEnd >= r.wall.lengthMm - NEAR)\n      : false;\n    const cornerDefs = [];\n    for (let i = 0; i < runs.length; i++) {\n      for (let j = i + 1; j < runs.length; j++) {\n        const ra = runs[i], rb = runs[j];\n        if (ra.wall.index === rb.wall.index) continue;\n        const v = sharedVertex(ra.wall, rb.wall);\n        if (!v || !reaches(ra, v) || !reaches(rb, v)) continue;\n        if (cornerDefs.some(c => vNear(c.vertex, v))) continue;\n        const host = ra.wall.lengthMm >= rb.wall.lengthMm ? ra.wall : rb.wall;\n        cornerDefs.push({ vertex: v, host, perp: host === ra.wall ? rb.wall : ra.wall });\n      }\n    }\n    for (const run of runs) {\n      run.reserveFrom = 0; run.reserveTo = 0;\n      for (const c of cornerDefs) {\n        const rr = (run.wall === c.host) ? hostReserve : (run.wall === c.perp) ? perpReserve : 0;\n        if (!rr) continue;\n        if (vNear(c.vertex, run.wall.from)) run.reserveFrom = Math.max(run.reserveFrom, rr);\n        if (vNear(c.vertex, run.wall.to))   run.reserveTo   = Math.max(run.reserveTo, rr);\n      }\n    }\n    return { runs, corners: cornerDefs.map(c => ({ vertex: c.vertex, hostWall: c.host })) };\n  }\n\n  const DOOR_CLEARANCE_MM = 30;   // reveal left each side of a doorway\n\n  // Openings on a given wall (by getWalls index), width > 0. Shape:\n  // { wallIndex, offsetMm (from wall.from), widthMm, type:'door'|'window' }.\n  function openingsForWall(wallIndex) {\n    const list = (roomConfig && roomConfig.wallOpenings) || [];\n    return list.filter(o => o && o.wallIndex === wallIndex && o.widthMm > 0);\n  }\n\n  // Subtract blocked [start,end] spans from [a,b] \u2192 array of free sub-spans.\n  function subtractSpans(a, b, blocked) {\n    let segs = [[a, b]];\n    for (const [bs, be] of blocked) {\n      const next = [];\n      for (const [s, e] of segs) {\n        if (be <= s || bs >= e) { next.push([s, e]); continue; }   // no overlap\n        if (bs > s) next.push([s, Math.min(bs, e)]);\n        if (be < e) next.push([Math.max(be, s), e]);\n      }\n      segs = next;\n    }\n    return segs.filter(([s, e]) => e - s > 0);\n  }\n\n  // Choose a sink base (or Belfast) unit nearest a target width. Returns\n  // { unitTypeId, variantId, widthMm } or null.\n  function pickSinkUnit(styleId, targetWidth, belfast) {\n    const bases = Catalogue.getReadyUnitTypesInL1Category('base-units') || [];\n    const cands = [];\n    for (const ut of bases) {\n      const product = Catalogue.getProductForUnitInStyle(ut.id, styleId);\n      if (!product) continue;\n      if (belfast) {\n        const v0 = product.variants && product.variants[0];\n        if (!v0) continue;\n        const def = Catalogue.buildCabinetDefinition({ unitTypeId: ut.id, variantId: v0.id, kitchenStyleId: styleId });\n        if (!def || !def.belfastSink) continue;\n      } else if (ut.sinkBase !== true) {\n        continue;\n      }\n      for (const v of (product.variants || [])) {\n        const info = Catalogue.getVariantInfo(v.id);\n        if (!info || !info.widthMm || !info.variant) continue;\n        cands.push({ unitTypeId: ut.id, variantId: info.variant.id, widthMm: info.widthMm });\n      }\n    }\n    if (!cands.length) return null;\n    cands.sort((a, b) => Math.abs(a.widthMm - targetWidth) - Math.abs(b.widthMm - targetWidth));\n    return cands[0];\n  }\n\n  // Pick a REAL oven housing product (preferred over the OVH/TOH stubs).\n  //   tall=true  \u2192 a tall single-oven housing (appliance-housings /\n  //                single-oven-housings, e.g. TASODO - excludes microwave,\n  //                double-oven and midi-height variants).\n  //   tall=false \u2192 a built-under oven BASE (base-units / appliances-units,\n  //                the BUO* built-under oven, not the microwave BUM*).\n  // Returns { unitTypeId, variantId, widthMm } or null (\u2192 caller falls back\n  // to the stub builder).\n  function pickOvenHousing(styleId, tall) {\n    const reads = Catalogue.getReadyUnitTypes() || [];\n    let cands;\n    if (tall) {\n      cands = reads.filter(ut => ut.categoryHandle === 'appliance-housings'\n        && /single-oven-housing/i.test(ut.unitTypeGroupHandle || '')\n        && !/MIC/i.test(ut.code || '')\n        && ut.isMidiUnit !== true);\n      // Prefer a plain single-oven-over-door (\u2026SODO) then any single oven.\n      cands.sort((a, b) => (/SODO$/i.test(b.code || '') ? 1 : 0) - (/SODO$/i.test(a.code || '') ? 1 : 0));\n    } else {\n      cands = reads.filter(ut => ut.categoryHandle === 'base-units'\n        && /appliances?-unit/i.test(ut.unitTypeGroupHandle || '')\n        && /^BUO/i.test(ut.code || ''));   // built-under OVEN (not BUM microwave)\n    }\n    for (const ut of cands) {\n      const product = Catalogue.getProductForUnitInStyle(ut.id, styleId);\n      if (!product) continue;\n      const infos = (product.variants || []).map(v => Catalogue.getVariantInfo(v.id)).filter(Boolean);\n      const info = infos.find(i => i.widthMm === 600)\n        || infos.reduce((a, b) => ((b.widthMm || 0) > (a.widthMm || 0) ? b : a), infos[0]);\n      if (!info || !info.variant) continue;\n      return { unitTypeId: ut.id, variantId: info.variant.id, widthMm: info.widthMm || 600 };\n    }\n    return null;\n  }\n\n  // Pick a REAL tall fridge-freezer housing (appliance-housings /\n  // fridge-freezer-housings, e.g. TFFH). A fridge is inherently tall, used for\n  // BOTH tall-run banks and base-run features (a fridge tower in a base line).\n  // Returns { unitTypeId, variantId, widthMm } or null.\n  function pickFridgeHousing(styleId) {\n    const reads = Catalogue.getReadyUnitTypes() || [];\n    // Match a fridge-freezer housing by GROUP name OR CODE (TFFH\u2026), so it's\n    // found even if the group handle isn't literally \"fridge-freezer-housings\".\n    const cands = reads.filter(ut => ut.categoryHandle === 'appliance-housings'\n      && ut.isMidiUnit !== true\n      && (/fridge|freezer|refriger/i.test(ut.unitTypeGroupHandle || '')\n        || /(^|[^A-Z])T?FFH/i.test(ut.code || '')));\n    for (const ut of cands) {\n      const product = Catalogue.getProductForUnitInStyle(ut.id, styleId);\n      if (!product) continue;\n      const infos = (product.variants || []).map(v => Catalogue.getVariantInfo(v.id)).filter(Boolean);\n      const info = infos.find(i => i.widthMm === 600)\n        || infos.reduce((a, b) => ((b.widthMm || 0) > (a.widthMm || 0) ? b : a), infos[0]);\n      if (!info || !info.variant) continue;\n      return { unitTypeId: ut.id, variantId: info.variant.id, widthMm: info.widthMm || 600 };\n    }\n    return null;\n  }\n\n  // The sink feature for the brief: a sink base centred under the widest\n  // window on a run wall (or, failing a window, the centre of the longest\n  // run). Returns { wallIndex, centreOffset, widthMm, unitTypeId, variantId,\n  // kind:'sink' } or null.\n  // Nearest run wall to a point + the along-offset (clamped to the run's\n  // painted span). Returns { wallIndex, along } or null.\n  function nearestRunAlong(pt, runs) {\n    let best = null;\n    for (const run of runs) {\n      const w = run.wall; const len = w.lengthMm; if (!(len > 0)) continue;\n      const ux = (w.to.x - w.from.x) / len, uy = (w.to.y - w.from.y) / len;\n      let along = (pt.x - w.from.x) * ux + (pt.y - w.from.y) * uy;\n      const nx = -uy, ny = ux;\n      const perp = Math.abs((pt.x - w.from.x) * nx + (pt.y - w.from.y) * ny);\n      const lo = run.spanStart != null ? run.spanStart : 0;\n      const hi = run.spanEnd   != null ? run.spanEnd   : len;\n      along = Math.max(lo, Math.min(hi, along));\n      if (!best || perp < best.perp) best = { wallIndex: w.index, along, perp };\n    }\n    return best;\n  }\n\n  // Which paint LEVEL a marker sits over (routes an oven marker to a tall vs\n  // base housing). Checks the marker's own 100mm cell first, then a 2-cell\n  // ring (a marker dropped just off a painted cell still routes sensibly).\n  // Prefers tall > base > wall. Returns 'tall' | 'base' | 'wall' | null.\n  function markerLevel(m) {\n    const gx = Math.floor(m.x / PAINT_CELL_MM), gy = Math.floor(m.y / PAINT_CELL_MM);\n    const has = (lvl, dx, dy) => paintData.cells[lvl].has((gx + dx) + ',' + (gy + dy));\n    for (let d = 0; d <= 2; d++) {\n      for (let dx = -d; dx <= d; dx++) for (let dy = -d; dy <= d; dy++) {\n        if (Math.max(Math.abs(dx), Math.abs(dy)) !== d) continue;   // ring at radius d\n        for (const lvl of ['tall', 'base', 'wall']) if (has(lvl, dx, dy)) return lvl;\n      }\n    }\n    return null;\n  }\n\n  // Sink features (plural - one per Sink marker, or a single window/longest-run\n  // guess when no marker was dropped). A sink sits on a base run, so returns []\n  // when there are no base runs (e.g. tall-only paint).\n  function magicSinkFeatures(config, styleId, plan) {\n    if (config.sink === 'none' || !plan.runs.length) return [];\n    const belfast = config.sink === 'belfast';\n    const target = belfast ? 800\n      : config.sink === 'single' ? 600\n      : config.sink === 'double' ? 900\n      : 800;   // one-half / default\n    const pick = pickSinkUnit(styleId, target, belfast);\n    if (!pick) return [];\n    const mk = (wallIndex, centreOffset) => ({\n      wallIndex, centreOffset, widthMm: pick.widthMm,\n      unitTypeId: pick.unitTypeId, variantId: pick.variantId, kind: 'sink'\n    });\n\n    // Sink markers override the window guess - one sink per marker.\n    const markers = paintData.markers.filter(m => m.kind === 'sink');\n    if (markers.length) {\n      return markers.map(m => {\n        const hit = nearestRunAlong(m, plan.runs);\n        return hit ? mk(hit.wallIndex, hit.along) : null;\n      }).filter(Boolean);\n    }\n\n    // No marker \u2192 one sink under the widest window on a run wall, else the\n    // centre of the longest run.\n    let anchor = null;\n    for (const run of plan.runs) {\n      for (const o of openingsForWall(run.wall.index)) {\n        if (o.type !== 'window') continue;\n        if (!anchor || o.widthMm > anchor.win.widthMm) anchor = { run, win: o };\n      }\n    }\n    if (anchor) return [mk(anchor.run.wall.index, anchor.win.offsetMm + anchor.win.widthMm / 2)];\n    const run = plan.runs.reduce((a, b) =>\n      (b.wall.lengthMm - b.reserveFrom - b.reserveTo) > (a.wall.lengthMm - a.reserveFrom - a.reserveTo) ? b : a);\n    return [mk(run.wall.index, run.reserveFrom + (run.wall.lengthMm - run.reserveFrom - run.reserveTo) / 2)];\n  }\n\n  // Generic BASE-run appliance features: one placed unit per marker of `kind`\n  // that sits over a base run (tall-level markers go to the tall pass). Markers\n  // on the same run are BANKED (next to each other) centred on their cluster.\n  // Returns [{ wallIndex, centreOffset, widthMm, kind, spawn }].\n  function bankedBaseFeatures(kind, plan, width, spawn) {\n    const markers = paintData.markers.filter(m => m.kind === kind && markerLevel(m) !== 'tall');\n    if (!markers.length) return [];\n    const byRun = new Map();\n    markers.forEach(m => {\n      let bi = -1, bp = Infinity, ba = 0;\n      plan.runs.forEach((r, i) => { const h = nearestRunAlong(m, [r]); if (h && h.perp < bp) { bp = h.perp; bi = i; ba = h.along; } });\n      if (bi >= 0) { const a = byRun.get(bi) || []; a.push(ba); byRun.set(bi, a); }\n    });\n    const feats = [];\n    byRun.forEach((alongs, ri) => {\n      const run = plan.runs[ri];\n      const cluster = alongs.reduce((s, a) => s + a, 0) / alongs.length;\n      const lo = cluster - (alongs.length * width) / 2;\n      for (let i = 0; i < alongs.length; i++) {\n        feats.push({ wallIndex: run.wall.index, centreOffset: lo + i * width + width / 2, widthMm: width, kind, spawn });\n      }\n    });\n    return feats;\n  }\n\n  // BASE oven features - built-under base ovens (oven markers over TALL paint\n  // are placed by the tall pass). Banked, real product preferred, OVH stub\n  // fallback.\n  function magicOvenFeatures(config, styleId, plan) {\n    if (!plan.runs.length) return [];\n    const pick = pickOvenHousing(styleId, false);\n    const stub = getOvenHousingUnitCatalogue()[0];\n    if (!pick && !stub) return [];\n    const w = pick ? pick.widthMm : (stub.widthMm || 600);\n    const spawn = (frame, c) => pick\n      ? spawnPlacedUnit(pick.unitTypeId, pick.variantId, styleId, frame, c)\n      : spawnOvenHousing(styleId, frame, c, false);\n    const feats = bankedBaseFeatures('oven', plan, w, spawn);\n    if (feats.length) console.log('[BTK Magic] base oven', pick ? `REAL ${pick.unitTypeId}` : 'stub', '\u00D7', feats.length);\n    return feats;\n  }\n\n  // FRIDGE features - a fridge is inherently tall, so over a BASE run it seats\n  // a tall fridge-freezer tower in the base line (over TALL paint the tall pass\n  // banks it). Banked.\n  function magicFridgeFeatures(config, styleId, plan) {\n    if (!plan.runs.length) return [];\n    const pick = pickFridgeHousing(styleId);\n    if (!pick) return [];\n    const spawn = (frame, c) => spawnPlacedUnit(pick.unitTypeId, pick.variantId, styleId, frame, c);\n    const feats = bankedBaseFeatures('fridge', plan, pick.widthMm, spawn);\n    if (feats.length) console.log('[BTK Magic] base fridge tower', `REAL ${pick.unitTypeId}`, '\u00D7', feats.length);\n    return feats;\n  }\n\n  // DISHWASHER features - no dedicated unit exists (an integrated dishwasher\n  // sits behind a base decor door), so reserve a ~600 base space at each\n  // marker. Banked.\n  function magicDishwasherFeatures(config, styleId, plan, baseCat) {\n    if (!plan.runs.length || !baseCat.widths.length) return [];\n    const width = baseCat.widths.reduce(\n      (best, w) => Math.abs(w - 600) < Math.abs(best - 600) ? w : best, baseCat.widths[0]);\n    const bpick = baseCat.byWidth.get(width);\n    if (!bpick) return [];\n    const spawn = (frame, c) => spawnPlacedUnit(bpick.unitTypeId, bpick.variantId, styleId, frame, c);\n    return bankedBaseFeatures('dishwasher', plan, width, spawn);\n  }\n\n  // Hob features (plural - one per HOB marker). Places a plain base unit\n  // (nearest ~600) at each marked spot with a hob on the worktop above.\n  function magicHobFeatures(config, styleId, plan, baseCat) {\n    if (!plan.runs.length || !baseCat.widths.length) return [];\n    const width = baseCat.widths.reduce(\n      (best, w) => Math.abs(w - 600) < Math.abs(best - 600) ? w : best, baseCat.widths[0]);\n    const bpick = baseCat.byWidth.get(width);\n    if (!bpick) return [];\n    const spawn = (frame, c) => spawnHobBase(styleId, frame, c, bpick);\n    return bankedBaseFeatures('hob', plan, width, spawn);\n  }\n\n  // Magic Layout generator - STAGE 2 (straight + L/U corners).\n  // Per shape: seat corner units, then allocate each wall's run with the\n  // design-rule engine (centred, scribe fillers, mixed widths, symmetry)\n  // around the corner reservations, and mirror wall units above.\n  async function generateMagicLayout(config) {\n    window.__btkLastMagicBrief = config;\n    console.log('[BTK Magic] design brief:', config);\n    const D = window.BTKKPDialog;\n    const say = (msg, opts) => (D?.alert || window.alert)(msg, opts);\n\n    if (!Catalogue.isReady || !Catalogue.isReady()) {\n      say('The unit catalogue isn\u2019t ready yet - try again in a moment.', { title: 'Magic Layout' });\n      return;\n    }\n    if (!room || !Array.isArray(room.vertices) || room.vertices.length < 3) {\n      say('Set up your room shape first, then run Magic Layout.', { title: 'Magic Layout' });\n      return;\n    }\n\n    // Resolve the style + default colours from the brief.\n    const styleId = config.styleId || kitchenStyleId\n      || (Catalogue.getKitchenStyles()[0] && Catalogue.getKitchenStyles()[0].id) || null;\n    if (styleId && styleId !== kitchenStyleId) {\n      kitchenStyleId = styleId;\n      const doors = Catalogue.getDoorColoursForStyle(styleId) || [];\n      const carcs = Catalogue.getCarcaseColoursForStyle(styleId) || [];\n      globalDoorColourHandle    = doors[0]?.handle || null;\n      globalCarcaseColourHandle = carcs[0]?.handle || null;\n    }\n\n    // Premium spec \u2192 fill with all-drawer (pan-drawer) bases where a style\n    // offers them; door bases elsewhere.\n    const baseCat = magicUnitCatalogue('base-units', styleId, { preferDrawers: config.spec === 'premium' });\n    if (!baseCat.widths.length) {\n      say('Couldn\u2019t find base units available in this style to build with.', { title: 'Magic Layout' });\n      return;\n    }\n    const wallCat = (config.wallStrategy === 'standard')\n      ? magicUnitCatalogue('wall-units', styleId)\n      : { widths: [], byWidth: new Map() };\n\n    // Axis-aligned walls only (Stage 2 handles straight / L / U).\n    const EPS = 1;\n    const allWalls = getWalls(room);\n    const isAxis = w => Math.abs(w.to.x - w.from.x) < EPS || Math.abs(w.to.y - w.from.y) < EPS;\n    const straightWalls = allWalls.filter(w => w.lengthMm > 0 && isAxis(w));\n    if (!straightWalls.length) {\n      say('Magic Layout currently needs a room with straight walls - angled and curved shapes are coming in a later stage.', { title: 'Magic Layout' });\n      return;\n    }\n    // The wall the user tapped in the mini room-map (null = auto/longest).\n    const primaryWall = (config.wallIndex != null && allWalls[config.wallIndex]\n      && allWalls[config.wallIndex].lengthMm > 0 && isAxis(allWalls[config.wallIndex]))\n      ? allWalls[config.wallIndex] : null;\n\n    // Where the runs come from: the customer's PAINT if they used paint mode\n    // (ANY level), otherwise the questionnaire's shape (auto wall-picker).\n    // If they painted only tall/wall, the base plan is empty (no auto fill) \u2014\n    // the tall pass / wall-only pass handle those levels.\n    const hasPaint = paintData.cells.base.size > 0\n      || paintData.cells.tall.size > 0\n      || paintData.cells.wall.size > 0;\n    const hasTallPaint = paintData.cells.tall.size > 0;\n    const hasWallPaint = paintData.cells.wall.size > 0;\n    // Corner strategy (user pref): blank-panel corner first, then L-shape,\n    // then a blank dead-corner reserve so the two runs don't collide.\n    const cornerSpec = (hasPaint || config.shape === 'l' || config.shape === 'u')\n      ? magicCornerUnit(styleId) : null;\n    const plan = hasPaint\n      ? buildPaintedPlan(paintData.cells.base,\n          cornerSpec ? cornerSpec.hostReserve : 0,\n          cornerSpec ? cornerSpec.perpReserve : 0)\n      : buildShapePlan(config.shape, straightWalls,\n          cornerSpec ? cornerSpec.hostReserve : 0,\n          cornerSpec ? cornerSpec.perpReserve : 0,\n          primaryWall);\n    console.log('[BTK Magic] plan source', hasPaint ? 'PAINT' : 'questionnaire', 'runs:', plan.runs.length, 'corners:', plan.corners.length);\n    console.log('[BTK Magic] paint cells', { base: paintData.cells.base.size, wall: paintData.cells.wall.size, tall: paintData.cells.tall.size },\n      'baseCat widths:', baseCat.widths.length, 'wallCat widths:', wallCat.widths.length,\n      'plan.runs spans:', plan.runs.map(r => `${r.wall.index}:${Math.round(r.spanStart)}-${Math.round(r.spanEnd)}`));\n\n    const anyRunFits = plan.runs.some(r => {\n      const start = Math.max(r.reserveFrom, r.spanStart != null ? r.spanStart : 0);\n      const end   = Math.min(r.wall.lengthMm - r.reserveTo, r.spanEnd != null ? r.spanEnd : r.wall.lengthMm);\n      return (end - start) >= baseCat.widths[0];\n    });\n    const willPlaceCorner = !!(cornerSpec && cornerSpec.kind !== 'none' && plan.corners.length);\n    if (!anyRunFits && !willPlaceCorner && !hasTallPaint && !hasWallPaint) {\n      say('The room\u2019s walls are too short to fit any units.', { title: 'Magic Layout' });\n      return;\n    }\n\n    // Feature anchoring (Stage 3): a sink under the window (or on the\n    // longest run). Grouped by wall so the run loop reserves + places it.\n    const featuresByWall = new Map();\n    const addFeature = f => {\n      if (!f) return;\n      const arr = featuresByWall.get(f.wallIndex) || [];\n      arr.push(f);\n      featuresByWall.set(f.wallIndex, arr);\n    };\n    [].concat(\n      magicSinkFeatures(config, styleId, plan),\n      magicOvenFeatures(config, styleId, plan),\n      magicHobFeatures(config, styleId, plan, baseCat),\n      magicFridgeFeatures(config, styleId, plan),\n      magicDishwasherFeatures(config, styleId, plan, baseCat)\n    ).forEach(addFeature);\n\n    // Replace any existing plan (confirm first).\n    if (cabinets.length && D?.confirm) {\n      const ok = await D.confirm(\n        'This replaces your current layout with a fresh Magic Layout. Continue?',\n        { title: 'Magic Layout', confirmText: 'Replace layout', cancelText: 'Keep mine' }\n      );\n      if (!ok) return;\n    }\n    if (cabinets.length) cabinets.splice(0, cabinets.length);\n\n    // Room centroid seats each corner unit toward the interior.\n    const n = room.vertices.length;\n    const centroid = room.vertices.reduce(\n      (s, v) => ({ x: s.x + v.x / n, y: s.y + v.y / n }), { x: 0, y: 0 });\n\n    // 1) Corner units first, so wall runs can butt against them. Track the\n    //    placed cab per corner vertex so runs can snap-butt to it.\n    let cornerCount = 0;\n    const cornerCabByVertex = new Map();\n    const vKey = v => `${Math.round(v.x)},${Math.round(v.y)}`;\n    for (const c of plan.corners) {\n      const cab = placeCorner(cornerSpec, c.vertex, c.hostWall, centroid, styleId);\n      if (cab) { cornerCount++; cornerCabByVertex.set(vKey(c.vertex), cab); }\n    }\n\n    // Counters (declared before the tall pass, which now runs first).\n    let baseCount = 0, wallCount = 0, wallCornerCount = 0, tallCount = 0, sinkCount = 0, ovenCount = 0, hobCount = 0, fridgeCount = 0, dishwasherCount = 0, doorGaps = 0, windowSkips = 0;\n\n    // 1b) TALL runs FIRST - full-height tall units + OVEN BANKS. Placed before\n    //     the base fill so base units flow around any tall oven that overflows\n    //     the rough tall paint. Every tall unit's span is recorded per wall so\n    //     the base loop avoids it.\n    const tallBlocksByWall = new Map();\n    const addTallBlock = (wi, lo, hi) => {\n      const a = tallBlocksByWall.get(wi) || []; a.push([lo, hi]); tallBlocksByWall.set(wi, a);\n    };\n    if (paintData.cells.tall.size > 0) {\n      const tallCat    = magicUnitCatalogue('tall-units', styleId);\n      const ovenPick   = pickOvenHousing(styleId, true);        // tall single-oven housing\n      const fridgePick = pickFridgeHousing(styleId);            // tall fridge-freezer housing\n      // Tall appliance families that bank in a tall run (oven + fridge).\n      const applSpec = {\n        oven: {\n          width: ovenPick ? ovenPick.widthMm : 600,\n          spawn: (fr, c) => ovenPick\n            ? spawnPlacedUnit(ovenPick.unitTypeId, ovenPick.variantId, styleId, fr, c)\n            : spawnOvenHousing(styleId, fr, c, true),\n          bump: () => ovenCount++\n        },\n        fridge: {\n          width: fridgePick ? fridgePick.widthMm : 600,\n          spawn: (fr, c) => fridgePick\n            ? spawnPlacedUnit(fridgePick.unitTypeId, fridgePick.variantId, styleId, fr, c)\n            : null,\n          bump: () => fridgeCount++\n        }\n      };\n      const tallRuns = buildPaintedRuns(paintData.cells.tall);\n      // Route each tall-level appliance marker (oven / fridge) to its nearest\n      // tall run (\u2192 {kind, along}). Fridge needs a real pick; oven has a stub.\n      const applPerRun = tallRuns.map(() => []);\n      for (const m of paintData.markers.filter(mm => (mm.kind === 'oven' || mm.kind === 'fridge') && markerLevel(mm) === 'tall')) {\n        if (m.kind === 'fridge' && !fridgePick) continue;\n        let bi = -1, bp = Infinity, ba = 0;\n        tallRuns.forEach((r, i) => { const h = nearestRunAlong(m, [r]); if (h && h.perp < bp) { bp = h.perp; bi = i; ba = h.along; } });\n        if (bi >= 0) applPerRun[bi].push({ kind: m.kind, along: ba });\n      }\n      tallRuns.forEach((run, ri) => {\n        const wall  = run.wall;\n        const frame = makeWallFrame(wall);\n        const opens = openingsForWall(wall.index);\n        const blocks = opens.filter(o => o.type === 'door' || o.type === 'window')\n          .map(o => [o.offsetMm - DOOR_CLEARANCE_MM, o.offsetMm + o.widthMm + DOOR_CLEARANCE_MM]);\n        const appls = applPerRun[ri].slice().sort((a, b) => a.along - b.along);   // cluster order\n        const ovenBlocks = [];   // occupied appliance spans on this run\n        // Appliance bank - the tall appliances (oven/fridge) sit next to each\n        // other, centred on the markers' cluster. Overflows the rough paint but\n        // stays inside the free wall segment (never crosses a door/window).\n        // Paint is a ROUGH guide: a sub-minimum gap at a WALL/corner-fixed run\n        // edge can't become a cabinet, so the bank BUTTS that wall rather than\n        // leaving an odd filler (we design it, the customer just roughs).\n        if (appls.length) {\n          const total = appls.reduce((s, a) => s + applSpec[a.kind].width, 0);\n          const cluster = appls.reduce((s, a) => s + a.along, 0) / appls.length;\n          const wallSegs = subtractSpans(0, wall.lengthMm, blocks);\n          const seg = wallSegs.find(([s, e]) => cluster >= s && cluster <= e)\n            || wallSegs.slice().sort((a, b) => (b[1] - b[0]) - (a[1] - a[0]))[0] || [0, wall.lengthMm];\n          let lo = Math.max(seg[0], Math.min(cluster - total / 2, seg[1] - total));\n          // Butt to a wall/corner-fixed edge when the gap there is un-fillable.\n          const startFixed = run.spanStart <= 60;                       // run starts at a wall/corner\n          const endFixed   = run.spanEnd   >= wall.lengthMm - 60;       // run ends at a wall/corner\n          const leadGap  = lo - Math.max(seg[0], run.spanStart);\n          const trailGap = Math.min(seg[1], run.spanEnd) - (lo + total);\n          if (startFixed && leadGap > 0 && leadGap < MAGIC_MIN_UNIT_MM)      lo = Math.max(seg[0], run.spanStart);\n          else if (endFixed && trailGap > 0 && trailGap < MAGIC_MIN_UNIT_MM) lo = Math.min(seg[1] - total, run.spanEnd - total);\n          lo = Math.max(seg[0], Math.min(lo, Math.max(seg[0], seg[1] - total)));\n          let off = lo;\n          for (const a of appls) {\n            const spec = applSpec[a.kind];\n            const w = spec.width, c = off + w / 2;\n            off += w;\n            if (c - w / 2 < seg[0] - 0.5 || c + w / 2 > seg[1] + 0.5) continue;   // won't fit the free segment\n            if (spec.spawn(frame, c)) {\n              spec.bump();\n              ovenBlocks.push([c - w / 2, c + w / 2]);\n              addTallBlock(wall.index, c - w / 2, c + w / 2);\n            }\n          }\n          console.log('[BTK Magic] tall appliance bank \u00D7', appls.length,\n            '(' + appls.map(a => a.kind).join(',') + ') \u2192 placed', ovenBlocks.length, 'wall', wall.index);\n        }\n        // Fill the rest of the PAINTED tall span with tall units, around the\n        // ovens + doors/windows (overflow beyond the paint stays oven-only).\n        if (tallCat.widths.length) {\n          for (const [segStart, segEnd] of subtractSpans(run.spanStart, run.spanEnd, blocks.concat(ovenBlocks))) {\n            if (segEnd - segStart < tallCat.widths[0]) continue;\n            const alloc = allocateRun(segEnd - segStart, tallCat.widths, { minFillerMm: 20, makeupWidths: tallCat.makeupWidths });\n            if (!alloc.unitCount) continue;\n            for (const slot of alloc.slots) {\n              if (slot.kind !== 'unit') continue;\n              const centre = segStart + slot.offset + slot.widthMm / 2;\n              const tp = tallCat.byWidth.get(slot.widthMm);\n              if (tp && spawnPlacedUnit(tp.unitTypeId, tp.variantId, styleId, frame, centre)) {\n                tallCount++;\n                addTallBlock(wall.index, centre - slot.widthMm / 2, centre + slot.widthMm / 2);\n              }\n            }\n          }\n        }\n      });\n    }\n\n    // 2) Each wall run: reserve doorways (hard gaps) + feature bays (sink),\n    //    place the features, then allocate + fill the leftover sub-segments,\n    //    mirroring wall units above - skipping any bay under a window or a\n    //    feature (no wall unit over a sink/splashback). Also avoids any TALL\n    //    unit that overflowed into this wall's base region.\n    for (const run of plan.runs) {\n      const wall = run.wall;\n      // Prefer the snap-engine butt against a corner unit (post/hand aware);\n      // fall back to the geometric reserve if there's no corner cab there.\n      let runStart = run.reserveFrom;\n      let runEnd   = wall.lengthMm - run.reserveTo;\n      if (run.reserveFrom > 0) {\n        const cc = cornerCabByVertex.get(vKey(wall.from));\n        const r = cc ? cornerReserveSnap(cc, wall, true) : null;\n        runStart = (r != null) ? r : run.reserveFrom;\n      }\n      if (run.reserveTo > 0) {\n        const cc = cornerCabByVertex.get(vKey(wall.to));\n        const r = cc ? cornerReserveSnap(cc, wall, false) : null;\n        runEnd = wall.lengthMm - ((r != null) ? r : run.reserveTo);\n      }\n      // Painted runs only fill the drawn span (clamp to it).\n      if (run.spanStart != null) runStart = Math.max(runStart, run.spanStart);\n      if (run.spanEnd   != null) runEnd   = Math.min(runEnd, run.spanEnd);\n      // Tall units already placed on this wall (incl. an overflowed oven bank).\n      const tallBlk = tallBlocksByWall.get(wall.index) || [];\n      // Paint is rough: if the base run stops just short of the tall units\n      // (a sub-minimum gap the paint left at the fuzzy tall\u2194base boundary),\n      // extend the base run to BUTT them so base flows straight on - no odd\n      // filler between the last oven and the first base cabinet.\n      if (tallBlk.length) {\n        const tHi = Math.max(...tallBlk.map(b => b[1]));\n        const tLo = Math.min(...tallBlk.map(b => b[0]));\n        if (runStart > tHi && runStart - tHi < MAGIC_MIN_UNIT_MM) runStart = tHi;\n        if (runEnd   < tLo && tLo - runEnd   < MAGIC_MIN_UNIT_MM) runEnd   = tLo;\n      }\n      if (runEnd - runStart < baseCat.widths[0]) continue;\n\n      const opens = openingsForWall(wall.index);\n      const doorBlocks = opens.filter(o => o.type === 'door')\n        .map(o => [o.offsetMm - DOOR_CLEARANCE_MM, o.offsetMm + o.widthMm + DOOR_CLEARANCE_MM]);\n      const windowSpans = opens.filter(o => o.type === 'window')\n        .map(o => [o.offsetMm, o.offsetMm + o.widthMm]);\n      if (doorBlocks.length) doorGaps += doorBlocks.length;\n\n      const frame = makeWallFrame(wall);\n\n      // Feature bays on this wall (sink \u2026). Clamp each centre inside the run\n      // so it fits; drop it if it would land on a doorway.\n      const featBlocks = [];\n      for (const f of (featuresByWall.get(wall.index) || [])) {\n        const half = f.widthMm / 2;\n        if (runEnd - runStart < f.widthMm) continue;\n        const c = Math.max(runStart + half, Math.min(runEnd - half, f.centreOffset));\n        const block = [c - half, c + half];\n        if (doorBlocks.concat(tallBlk).some(([bs, be]) => block[0] < be && block[1] > bs)) continue;\n        // Don't stack two features (e.g. two oven markers dropped close) on the\n        // same spot - skip one that would overlap an already-placed bay.\n        if (featBlocks.some(([bs, be]) => block[0] < be && block[1] > bs)) continue;\n        f._centre = c;\n        featBlocks.push(block);\n        const placed = f.spawn\n          ? f.spawn(frame, c)\n          : spawnPlacedUnit(f.unitTypeId, f.variantId, styleId, frame, c);\n        if (placed) {\n          if (f.kind === 'sink') sinkCount++;\n          else if (f.kind === 'oven') ovenCount++;\n          else if (f.kind === 'hob') hobCount++;\n          else if (f.kind === 'fridge') fridgeCount++;\n          else if (f.kind === 'dishwasher') dishwasherCount++;\n        }\n      }\n\n      for (const [segStart, segEnd] of subtractSpans(runStart, runEnd, doorBlocks.concat(featBlocks).concat(tallBlk))) {\n        const span = segEnd - segStart;\n        if (span < baseCat.widths[0]) continue;\n        // Classify each segment end: a true WALL (needs a scribe filler), a\n        // CORNER (butt tight; the acceptable home for a tiling remainder), or\n        // a FEATURE/door edge (ALWAYS butt tight - never a gap against a sink\n        // or doorway). runStart/runEnd carry the corner reserves.\n        const startType = (segStart <= runStart + 0.5)\n          ? (run.reserveFrom === 0 ? 'wall' : 'corner') : 'feature';\n        const endType   = (segEnd >= runEnd - 0.5)\n          ? (run.reserveTo === 0 ? 'wall' : 'corner') : 'feature';\n        const hasWall = startType === 'wall' || endType === 'wall';\n        let startFiller = startType === 'wall';\n        let endFiller   = endType === 'wall';\n        if (!hasWall) {\n          // No wall to scribe against - park the remainder at a corner (the\n          // \"filler between corner post and next unit\" rule) rather than\n          // against a feature; butt the other end tight.\n          if (startType === 'corner') startFiller = true;\n          else endFiller = true;\n        }\n        // Scribe minimum only applies at walls; at a corner the filler is\n        // exactly the remainder (0 \u2192 butt tight, no forced 20mm gap).\n        const alloc = allocateRun(span, baseCat.widths,\n          { minFillerMm: hasWall ? 20 : 0, startFiller, endFiller, makeupWidths: baseCat.makeupWidths });\n        if (!alloc.unitCount) continue;\n        for (const slot of alloc.slots) {\n          if (slot.kind !== 'unit') continue;         // fillers are reserved gaps\n          const centre = segStart + slot.offset + slot.widthMm / 2;\n          const bpick = baseCat.byWidth.get(slot.widthMm);\n          if (bpick && spawnPlacedUnit(bpick.unitTypeId, bpick.variantId, styleId, frame, centre)) baseCount++;\n        }\n      }\n    }\n\n    // 3) Wall units (standard strategy) - seat a corner WALL unit at each\n    //    corner, then run an INDEPENDENT wall run that butts it (the wall\n    //    corner is a different size to the base corner, so wall units can't\n    //    simply mirror the base run). Wall units avoid doorways AND windows\n    //    (no wall unit over a window) and the sink bays (splashback space).\n    // In PAINT mode the wall units follow the WALL paint (their own runs),\n    // NOT an auto-mirror above the base runs - base + wall are painted\n    // independently. Painted wall runs get their OWN corner detection +\n    // reserves (a corner WALL unit where two perpendicular wall runs meet),\n    // exactly like the base plan. The questionnaire path keeps the legacy\n    // mirror-above-base with corner wall units at the base corners.\n    const doWallUnits = wallCat.widths.length\n      && (hasPaint ? hasWallPaint : config.wallStrategy === 'standard');\n    console.log('[BTK Magic] wall gate', {\n      paint: hasPaint, hasWallPaint, wallWidths: wallCat.widths.length, corners: plan.corners.length, doWallUnits\n    });\n    if (doWallUnits) {\n      const cwEntry = magicCornerWallEntry(styleId);\n      // Painted layouts: build a wall plan (runs + corners + reserves) from the\n      // wall paint - its own corners, not the base corners. Reserve the corner\n      // wall unit's footprint along the host wall + its depth on the perp wall\n      // (the run loop overrides both with the snap engine).\n      let wallRuns, wallCorners;\n      if (hasPaint) {\n        const wallPlan = buildPaintedPlan(paintData.cells.wall,\n          cwEntry ? cwEntry.hostReserve : 0,\n          cwEntry ? cwEntry.perpReserve : 0);\n        wallRuns = wallPlan.runs; wallCorners = wallPlan.corners;\n      } else {\n        wallRuns = plan.runs; wallCorners = plan.corners;\n      }\n      const cwByVertex = new Map();\n      console.log('[BTK Magic] corner wall entry',\n        cwEntry && (cwEntry.isReal ? `REAL ${cwEntry.unitTypeId}` : `stub ${cwEntry.entry?.code}`),\n        'wall corners:', wallCorners.length);\n      if (cwEntry) {\n        for (const c of wallCorners) {\n          const cab = cwEntry.isReal\n            ? placeRealCornerWallUnit(cwEntry.unitTypeId, cwEntry.variantId, c.vertex, c.hostWall, styleId)\n            : placeCornerWallUnit(cwEntry.entry, c.vertex, c.hostWall, styleId);\n          if (cab) { wallCornerCount++; cwByVertex.set(vKey(c.vertex), cab); }\n        }\n      }\n      for (const run of wallRuns) {\n        const wall = run.wall;\n        let runStart = 0, runEnd = wall.lengthMm;\n        if (run.reserveFrom > 0) {\n          const cc = cwByVertex.get(vKey(wall.from));\n          const r = cc ? cornerReserveSnap(cc, wall, true, 330) : null;\n          runStart = (r != null) ? r : run.reserveFrom;\n        }\n        if (run.reserveTo > 0) {\n          const cc = cwByVertex.get(vKey(wall.to));\n          const r = cc ? cornerReserveSnap(cc, wall, false, 330) : null;\n          runEnd = wall.lengthMm - ((r != null) ? r : run.reserveTo);\n        }\n        if (run.spanStart != null) runStart = Math.max(runStart, run.spanStart);\n        if (run.spanEnd   != null) runEnd   = Math.min(runEnd, run.spanEnd);\n        if (runEnd - runStart < wallCat.widths[0]) continue;\n\n        const opens = openingsForWall(wall.index);\n        const doorBlocks = opens.filter(o => o.type === 'door')\n          .map(o => [o.offsetMm - DOOR_CLEARANCE_MM, o.offsetMm + o.widthMm + DOOR_CLEARANCE_MM]);\n        const windowBlocks = opens.filter(o => o.type === 'window')\n          .map(o => [o.offsetMm, o.offsetMm + o.widthMm]);\n        const sinkBlocks = (featuresByWall.get(wall.index) || [])\n          .filter(f => f._centre != null)\n          .map(f => [f._centre - f.widthMm / 2, f._centre + f.widthMm / 2]);\n        const frame = makeWallFrame(wall);\n\n        for (const [segStart, segEnd] of subtractSpans(runStart, runEnd,\n              doorBlocks.concat(windowBlocks).concat(sinkBlocks))) {\n          const span = segEnd - segStart;\n          if (span < wallCat.widths[0]) continue;\n          const startType = (segStart <= runStart + 0.5)\n            ? ((run.reserveFrom || 0) === 0 ? 'wall' : 'corner') : 'feature';\n          const endType   = (segEnd >= runEnd - 0.5)\n            ? ((run.reserveTo || 0) === 0 ? 'wall' : 'corner') : 'feature';\n          const hasWall = startType === 'wall' || endType === 'wall';\n          let startFiller = startType === 'wall';\n          let endFiller   = endType === 'wall';\n          if (!hasWall) { if (startType === 'corner') startFiller = true; else endFiller = true; }\n          const alloc = allocateRun(span, wallCat.widths,\n            { minFillerMm: hasWall ? 20 : 0, startFiller, endFiller, makeupWidths: wallCat.makeupWidths });\n          if (!alloc.unitCount) continue;\n          for (const slot of alloc.slots) {\n            if (slot.kind !== 'unit') continue;\n            const centre = segStart + slot.offset + slot.widthMm / 2;\n            const wpick = wallCat.byWidth.get(slot.widthMm);\n            if (wpick && spawnPlacedUnit(wpick.unitTypeId, wpick.variantId, styleId, frame, centre)) wallCount++;\n          }\n        }\n      }\n    }\n\n    // (Tall runs + oven banks were placed FIRST - see step 1b above.)\n\n    console.log('[BTK Magic] placed', { baseCount, wallCount, wallCornerCount, tallCount, cornerCount, sinkCount, ovenCount, hobCount, fridgeCount, dishwasherCount });\n    if (!baseCount && !cornerCount && !sinkCount && !tallCount && !wallCount && !ovenCount && !hobCount && !fridgeCount && !dishwasherCount) {\n      say('The room\u2019s walls are too short to fit any units.', { title: 'Magic Layout' });\n      return;\n    }\n\n    // addCabinet ran the auto end-panel pass per unit while each was still\n    // stacked at room-centre (before we moved it). Re-run once over the\n    // FINAL positions so flush joins drop panels and only exposed run ends\n    // carry a panel / scribe filler.\n    autoDetectEndPanels();\n\n    // Validate + self-correct: read the design warnings and remove the\n    // offending unit (preferring a plain fill/wall unit over an anchored\n    // corner/sink/feature), then re-check - until the fixable warnings are\n    // gone. Walkway warnings are a room-geometry issue (can't fix by\n    // dropping a cabinet), so they're left for the user.\n    let warningsFixed = 0, warningsLeft = 0;\n    const REMOVABLE_RULES = new Set(['unit-overlap', 'unit-covers-door', 'door-clash']);\n    const removalScore = c => {\n      if (!c) return 99;\n      if (c.cornerUnit || c.lShapeUnit || c.diagonalCornerUnit) return 5;  // keep corners\n      if (c.sinkBase || c.belfastSink || c.ovenHousing)         return 5;  // keep features\n      if (c.category === 'wall-units')                          return 0;  // drop wall first\n      return 2;                                                            // then base\n    };\n    for (let pass = 0; pass < 10; pass++) {\n      const warns = computeWarnings({\n        cabinets, room,\n        wallOpenings:   roomConfig.wallOpenings   || [],\n        perimeterItems: roomConfig.perimeterItems || [],\n        walkwayMinMm:   900\n      });\n      const fixable = warns.filter(w => REMOVABLE_RULES.has(w.ruleId));\n      console.log('[BTK Magic] warnings pass', pass, warns.map(w => w.ruleId));\n      if (!fixable.length) { warningsLeft = warns.length; break; }\n      const removeIds = new Set();\n      for (const w of fixable) {\n        const byId = new Map(cabinets.map(c => [c.id, c]));\n        let bestId = null, best = Infinity;\n        for (const id of (w.itemIds || [])) {\n          const s = removalScore(byId.get(id));\n          if (s < best) { best = s; bestId = id; }\n        }\n        if (bestId) removeIds.add(bestId);\n      }\n      if (!removeIds.size) { warningsLeft = warns.length; break; }\n      cabinets = cabinets.filter(c => !removeIds.has(c.id));\n      warningsFixed += removeIds.size;\n      autoDetectEndPanels();\n    }\n\n    rerender();\n\n    // Report what was built + what the brief still has queued.\n    const styleName = Catalogue.getKitchenStyle?.(styleId)?.name || styleId || 'current style';\n    const shapeName = { straight: 'straight run', l: 'L-shape', u: 'U-shape' }[config.shape] || config.shape;\n    const parts = [`${baseCount} base unit${baseCount === 1 ? '' : 's'}`];\n    if (cornerCount) parts.push(`${cornerCount} corner unit${cornerCount === 1 ? '' : 's'}`);\n    if (sinkCount)   parts.push(`${sinkCount} sink unit${sinkCount === 1 ? '' : 's'}`);\n    if (ovenCount)   parts.push(`${ovenCount} oven housing${ovenCount === 1 ? '' : 's'}`);\n    if (hobCount)    parts.push(`${hobCount} hob unit${hobCount === 1 ? '' : 's'}`);\n    if (fridgeCount) parts.push(`${fridgeCount} fridge housing${fridgeCount === 1 ? '' : 's'}`);\n    if (dishwasherCount) parts.push(`${dishwasherCount} dishwasher space${dishwasherCount === 1 ? '' : 's'}`);\n    if (tallCount)   parts.push(`${tallCount} tall unit${tallCount === 1 ? '' : 's'}`);\n    if (wallCount)   parts.push(`${wallCount} wall unit${wallCount === 1 ? '' : 's'}`);\n    if (wallCornerCount) parts.push(`${wallCornerCount} corner wall unit${wallCornerCount === 1 ? '' : 's'}`);\n    if (config.spec === 'premium') parts[0] += ' (drawers where available)';\n    const deferred = [];\n    if (config.wallStrategy === 'tall-bank') deferred.push('tall-unit bank');\n    if (config.island)                       deferred.push('island');\n    if (config.sink !== 'none' && !sinkCount) deferred.push('sink unit');\n    deferred.push('work-triangle tuning');\n    const openingNotes = [];\n    if (doorGaps)    openingNotes.push(`left ${doorGaps} doorway${doorGaps === 1 ? '' : 's'} clear`);\n    if (windowSkips) openingNotes.push(`kept wall units off ${windowSkips} window bay${windowSkips === 1 ? '' : 's'}`);\n    const warnNote = warningsFixed\n      ? `\\n\\nCleared ${warningsFixed} clash${warningsFixed === 1 ? '' : 'es'} to keep the plan warning-free` +\n        (warningsLeft ? ` (${warningsLeft} walkway note${warningsLeft === 1 ? '' : 's'} left - that's a room-size thing).` : '.')\n      : (warningsLeft ? `\\n\\n${warningsLeft} walkway note${warningsLeft === 1 ? '' : 's'} remain (room-size, not fixable by moving a cabinet).` : '');\n    say(\n      `Placed ${parts.join(', ')} in a ${shapeName} (${styleName}), centred with scribe fillers` +\n      (openingNotes.length ? ` - ${openingNotes.join(' and ')}` : '') + `.` +\n      warnNote + `\\n\\n` +\n      `Still to come (from your answers): ${deferred.join(', ')}.`,\n      { title: 'Magic Layout', okText: 'Nice' }\n    );\n  }\n\n  function setViewMode(mode) {\n    if (mode !== '2d' && mode !== '3d') return;\n    if (mode === viewMode) return;\n    viewMode = mode;\n    viewBtnMode = mode;\n    // Expose the active mode on the app root so any component (e.g.\n    // the selection panel's Open Door icon) can react via CSS or a\n    // querySelector-attribute hook without needing a callback.\n    root.classList.toggle('btk-kp-view-2d', mode === '2d');\n    root.classList.toggle('btk-kp-view-3d', mode === '3d');\n    syncUnitsOverlay();\n    syncViewToggleButtons();\n    // Always close the cog on view switch - the popover content is\n    // mode-specific, and leaving it open across a mode change is\n    // confusing (the contents flip under the user's cursor).\n    closeCogOverlay();\n    // Stop a running flythrough whenever the user leaves 3D.\n    if (mode !== '3d' && handle3D?.isFlythroughPlaying?.()) {\n      handle3D.stopFlythrough?.();\n    }\n    // Leaving 3D: take the preview now. The renderer is mounted and the scene\n    // is exactly what the user has been looking at, so this costs one frame -\n    // the same shot from 2D would have to build the whole scene first.\n    // ...but not DURING the switch. capturePlanThumb reads the GL buffer back\n    // and encodes an image, and being a promise it drained inside the same\n    // blocking task: 884ms of a stage change spent on a thumbnail nobody is\n    // waiting for (?btktime=1, Arden 2026-09-30). Two frames later the view has\n    // settled and the scene is unchanged, so the shot is the same one.\n    if (mode !== '3d' && handle3D && typeof handle3D.snapshot === 'function') {\n      requestAnimationFrame(() => requestAnimationFrame(() => {\n        if (!handle3D || typeof handle3D.snapshot !== 'function') return;\n        capturePlanThumb().then(t => { if (t) { planThumb = t; scheduleAutosave(); } })\n          .catch(() => {});\n      }));\n    }\n    on3DStepActive(mode === '3d');\n    renderViewportOverlay();\n    if (typeof updateFlyPlayVisibility === 'function') updateFlyPlayVisibility();\n    if (typeof updateFlyRecordVisibility === 'function') updateFlyRecordVisibility();\n    if (typeof updateLifestyleVisibility === 'function') updateLifestyleVisibility();\n    if (typeof updateLightPinVisibility === 'function') updateLightPinVisibility();\n    if (typeof updateLightsToggleVisibility === 'function') updateLightsToggleVisibility();\n    // Re-render the selection panel so any view-dependent controls\n    // (e.g. the Open Door icon, which only acts in 3D) refresh.\n    if (selectionPanelHandle && typeof selectionPanelHandle.refresh === 'function') {\n      selectionPanelHandle.refresh();\n    }\n  }\n\n  root.querySelectorAll('[data-btk-kp-view-toggle] [data-btk-kp-view-mode]').forEach(btn => {\n    btn.addEventListener('click', () => {\n      // Customise is a 3D stage - the 2D plan is where units are laid out, so\n      // 2D there means Add Items. Not from the basket's own view toggle: that\n      // only changes the picture beside the basket.\n      const inBasket = !!btn.closest('[data-btk-kp-basket-embed]') ||\n        (typeof basketEmbedPanel !== 'undefined' && basketEmbedPanel && !basketEmbedPanel.hidden);\n      if (btn.dataset.btkKpViewMode === '2d' && currentStep === 'style-colours' && !inBasket) {\n        goToStage('add-units', '2d');\n        return;\n      }\n      setViewMode(btn.dataset.btkKpViewMode);\n    });\n  });\n\n  if (rcGearBtn && rcOverlay) {\n    rcGearBtn.addEventListener('click', () => {\n      const willOpen = rcOverlay.hidden;\n      rcOverlay.hidden = !willOpen;\n      rcGearBtn.classList.toggle('is-open', willOpen);\n      rcGearBtn.setAttribute('aria-expanded', willOpen ? 'true' : 'false');\n    });\n  }\n\n  // ---- Flythrough Play button ----\n  // Visible only in 3D mode. Click toggles between starting and stopping\n  // the cinematic flythrough on the 3D renderer.\n  const flyPlayBtn = root.querySelector('[data-btk-kp-fly-play]');\n  const flyPinBtn  = root.querySelector('[data-btk-kp-fly-pin]');\n  function updateFlyPlayVisibility() {\n    if (!flyPlayBtn) return;\n    flyPlayBtn.hidden = (viewMode !== '3d');\n    // Pin toggle is the 2D companion of the play button - show it\n    // only on the 2D plan, and turn waypoint-add mode off if the\n    // user switches to 3D mid-pin.\n    if (flyPinBtn) {\n      flyPinBtn.hidden = (viewMode !== '2d');\n      if (viewMode !== '2d' && waypointAddMode) {\n        waypointAddMode = false;\n        flyPinBtn.classList.remove('is-on');\n        flyPinBtn.setAttribute('aria-pressed', 'false');\n        root.classList.remove('btk-kp-waypoint-mode');\n      }\n    }\n  }\n  function updateFlyPlayState(isPlaying) {\n    if (!flyPlayBtn) return;\n    flyPlayBtn.classList.toggle('is-playing', !!isPlaying);\n    flyPlayBtn.setAttribute('aria-pressed', isPlaying ? 'true' : 'false');\n    flyPlayBtn.setAttribute(\n      'aria-label',\n      isPlaying ? 'Stop flythrough' : 'Play cinematic flythrough'\n    );\n  }\n  if (flyPlayBtn) {\n    flyPlayBtn.addEventListener('click', () => {\n      if (!handle3D) return;\n      if (handle3D.isFlythroughPlaying && handle3D.isFlythroughPlaying()) {\n        handle3D.stopFlythrough?.();\n      } else {\n        handle3D.playFlythrough?.(flythroughWaypoints, { speed: flythroughSpeed });\n      }\n    });\n  }\n  if (flyPinBtn) {\n    flyPinBtn.addEventListener('click', () => {\n      waypointAddMode = !waypointAddMode;\n      flyPinBtn.classList.toggle('is-on', waypointAddMode);\n      flyPinBtn.setAttribute('aria-pressed', waypointAddMode ? 'true' : 'false');\n      root.classList.toggle('btk-kp-waypoint-mode', waypointAddMode);\n    });\n  }\n\n  // ---- Lights ON / OFF toggle (3D view) ----\n  // Hides every placed light from the 3D scene without deleting them\n  // from the design. The button reflects the current state with an\n  // amber `is-on` colour and a diagonal slash when off.\n  const lightsToggleBtn = root.querySelector('[data-btk-kp-lights-toggle]');\n  function updateLightsToggleVisibility() {\n    if (!lightsToggleBtn) return;\n    lightsToggleBtn.hidden = (viewMode !== '3d');\n  }\n  function updateLightsToggleState() {\n    if (!lightsToggleBtn) return;\n    lightsToggleBtn.classList.toggle('is-on', !!lightsOn);\n    lightsToggleBtn.setAttribute('aria-pressed', lightsOn ? 'true' : 'false');\n    lightsToggleBtn.setAttribute(\n      'aria-label',\n      lightsOn ? 'Turn all lights off' : 'Turn all lights on'\n    );\n    lightsToggleBtn.setAttribute(\n      'title',\n      lightsOn ? 'All lights ON - click to turn off' : 'All lights OFF - click to turn on'\n    );\n  }\n  if (lightsToggleBtn) {\n    lightsToggleBtn.addEventListener('click', () => {\n      lightsOn = !lightsOn;\n      updateLightsToggleState();\n      rerender();\n    });\n  }\n  updateLightsToggleState();\n  updateLightsToggleVisibility();\n\n  // ---- Light placement button (2D plan only) ----\n  // Toggles a \"drop mode\": each subsequent click on the 2D plan\n  // adds a light at that position. The light's TYPE is auto-decided\n  // by the 3D renderer based on whether it sits inside a wall cab's\n  // plan footprint (= under-cab) or not (= ceiling).\n  const lightPinBtn = root.querySelector('[data-btk-kp-light-pin]');\n  function updateLightPinVisibility() {\n    if (!lightPinBtn) return;\n    lightPinBtn.hidden = (viewMode !== '2d');\n    if (viewMode !== '2d' && lightDropMode) {\n      lightDropMode = false;\n      lightPinBtn.classList.remove('is-on');\n      lightPinBtn.setAttribute('aria-pressed', 'false');\n      root.classList.remove('btk-kp-light-drop-mode');\n    }\n  }\n  if (lightPinBtn) {\n    lightPinBtn.addEventListener('click', () => {\n      lightDropMode = !lightDropMode;\n      lightPinBtn.classList.toggle('is-on', lightDropMode);\n      lightPinBtn.setAttribute('aria-pressed', lightDropMode ? 'true' : 'false');\n      root.classList.toggle('btk-kp-light-drop-mode', lightDropMode);\n    });\n  }\n  updateLightPinVisibility();\n\n  updateFlyPlayVisibility();\n\n  // ---- Flythrough record + download (WebM) ----\n  // Captures the 3D viewport canvas while the flythrough plays and\n  // saves a WebM video when it finishes. Uses MediaRecorder over the\n  // WebGL canvas's captureStream - no backend, no upload, no audio.\n  // Works in Chromium / Firefox / Edge; Safari's canvas MediaRecorder\n  // support is limited so we warn + bail there.\n  const flyRecordBtn = root.querySelector('[data-btk-kp-fly-record]');\n  let activeRecorder = null;\n  let recordedChunks = [];\n  function updateFlyRecordVisibility() {\n    if (!flyRecordBtn) return;\n    flyRecordBtn.hidden = (viewMode !== '3d');\n  }\n  function setRecordButtonState(recording) {\n    if (!flyRecordBtn) return;\n    flyRecordBtn.classList.toggle('is-recording', !!recording);\n    flyRecordBtn.setAttribute('aria-pressed', recording ? 'true' : 'false');\n    flyRecordBtn.title = recording\n      ? 'Recording flythrough - saves on completion'\n      : 'Download flythrough video (WebM)';\n  }\n  function downloadBlob(blob, filename) {\n    const url = URL.createObjectURL(blob);\n    const a = document.createElement('a');\n    a.href = url;\n    a.download = filename;\n    document.body.appendChild(a);\n    a.click();\n    document.body.removeChild(a);\n    setTimeout(() => URL.revokeObjectURL(url), 1000);\n  }\n  function startRecordingFlythrough() {\n    if (!handle3D || activeRecorder) return;\n    const canvas = handle3D.getCanvas?.();\n    if (!canvas) return;\n    if (typeof canvas.captureStream !== 'function' || typeof window.MediaRecorder !== 'function') {\n      window.BTKKPDialog.alert('Your browser doesn\\'t support canvas video capture. Try Chrome, Edge or Firefox.', { title: 'Not supported' });\n      return;\n    }\n    // Pick the best WebM codec the browser supports.\n    const candidates = [\n      'video/webm;codecs=vp9',\n      'video/webm;codecs=vp8',\n      'video/webm'\n    ];\n    const mimeType = candidates.find(t => MediaRecorder.isTypeSupported(t));\n    if (!mimeType) {\n      window.BTKKPDialog.alert('Your browser doesn\\'t support WebM recording.', { title: 'Not supported' });\n      return;\n    }\n    const stream = canvas.captureStream(60);\n    recordedChunks = [];\n    activeRecorder = new MediaRecorder(stream, { mimeType, videoBitsPerSecond: 8_000_000 });\n    activeRecorder.ondataavailable = (e) => {\n      if (e.data && e.data.size > 0) recordedChunks.push(e.data);\n    };\n    activeRecorder.onstop = () => {\n      const blob = new Blob(recordedChunks, { type: mimeType });\n      recordedChunks = [];\n      activeRecorder = null;\n      setRecordButtonState(false);\n      const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);\n      downloadBlob(blob, `btk-flythrough-${stamp}.webm`);\n    };\n    activeRecorder.start();\n    setRecordButtonState(true);\n    // Kick off the flythrough - when it finishes (or is stopped),\n    // the onFlythroughChange handler stops the recorder.\n    handle3D.playFlythrough?.(flythroughWaypoints, { speed: flythroughSpeed });\n  }\n  function stopRecordingFlythrough() {\n    if (!activeRecorder) return;\n    if (activeRecorder.state === 'recording') activeRecorder.stop();\n  }\n  if (flyRecordBtn) {\n    flyRecordBtn.addEventListener('click', () => {\n      if (activeRecorder) {\n        // User clicked again while recording - stop the flythrough,\n        // which triggers the playback-change callback below and\n        // finalises the recorder.\n        handle3D?.stopFlythrough?.();\n      } else {\n        startRecordingFlythrough();\n      }\n    });\n  }\n  updateFlyRecordVisibility();\n\n  // ---- Lifestyle photo (staff, 3D only) ----\n  // Staff snap up to three camera angles, pick Daytime or Evening, add any\n  // design requests, and FLUX 3 Image makes a photograph of each angle in\n  // the background (planner-api src/lifestyle-photo.js). The server makes\n  // angle 1 first and shows it to the others, so all three are dressed the\n  // same (sales team, 2026-11-04). The plan's own door, floor, worktop and handle\n  // pictures go with the render: tested by hand (Arden, 2026-10-31), the\n  // render and wording alone kept the door frames about one run in three;\n  // with the door photo and floor texture attached, three in three. The one\n  // staff keep is stored with the plan - the Plan report prints it and the\n  // order carries it into Odoo.\n  const lifestyleBtn = root.querySelector('[data-btk-kp-lifestyle]');\n  // Used when the theme editor's Lifestyle photo boxes are blank.\n  const LP_DEFAULTS = {\n    prompt: 'Make the first image look like a real professional interior photograph for a bedroom brochure. Keep the bedroom exactly the same: same cabinets in the same places, same camera angle.\\n\\n{references}\\n\\n{requests}\\n\\nKeep the worktop, glass units, sinks, taps, appliances, island and furniture exactly as in the first image. Keep the hob, sinks and taps clear: nothing on or over them. No under-cabinet or strip lighting. No added cabinets.\\n\\n{mood}',\n    daytime: 'Lighting: warm late-afternoon sun through the windows and patio doors, soft shadows, warm white light. Show a garden through any glazed doors and a few small accessories on the worktop.',\n    evening: 'Lighting: early evening with a deep blue dusk outside. Inside lit only by warm white (2700K) ceiling spotlights, with soft pools of light on the worktops and floor. No sunlight patches. Keep the door colour exactly as in the render, and the wood grain and floor texture fully detailed, not smooth. A few small accessories on the worktop.'\n  };\n  const LP_POLL_MS = 4000;\n  const LP_MAX_ANGLES = 3;\n  // Keeps the whole prompt under the server's 4000 characters even with\n  // three door finishes listed.\n  const LP_MAX_NOTES = 400;\n  const lp = {\n    panel: null, open: false, mood: 'daytime', busy: false, error: '',\n    basketId: null, jobId: null, photos: [], urls: {}, polling: false,\n    keptId: null, keptUrl: null,\n    snaps: [], notes: ''                   // the angles snapped, as JPEG data URLs\n  };\n  // Design requests are remembered per plan, on this computer.\n  const lpNotesKey = (basketId) => `btk_kp_lp_notes_${basketId}`;\n  function lpSaveNotes() {\n    if (!lp.basketId) return;\n    try {\n      if (lp.notes.trim()) localStorage.setItem(lpNotesKey(lp.basketId), lp.notes);\n      else localStorage.removeItem(lpNotesKey(lp.basketId));\n    } catch (e) {}\n  }\n  function lpLoadNotes(basketId) {\n    try { return localStorage.getItem(lpNotesKey(basketId)) || ''; } catch (e) { return ''; }\n  }\n  function lpStaff() {\n    return !!(window.BTKBasketAPI && window.BTKBasketAPI.isStaffMode && window.BTKBasketAPI.isStaffMode());\n  }\n  function updateLifestyleVisibility() {\n    if (!lifestyleBtn) return;\n    lifestyleBtn.hidden = (viewMode !== '3d') || !lpStaff();\n    if (lifestyleBtn.hidden && lp.open) lpClose();\n  }\n  async function lpBasketId() {\n    try {\n      return lastQuoteBasketId || (await window.BTKBasketAPI?.getActivePlannerBasketId?.()) || null;\n    } catch (e) { return null; }\n  }\n  // FLUX fetches the references itself, so they must be full https URLs\n  // (the server takes only our own CDN). A tinted bespoke-paint preview is a\n  // data: URL and is left out - the wording carries the colour instead.\n  function lpHttps(u) {\n    if (!u || typeof u !== 'string') return null;\n    if (u.startsWith('//')) u = 'https:' + u;\n    return /^https:\\/\\//i.test(u) ? u : null;\n  }\n  function lpMost(values) {\n    const n = new Map();\n    let best = null, top = 0;\n    for (const v of values) {\n      if (!v) continue;\n      const c = (n.get(v) || 0) + 1;\n      n.set(v, c);\n      if (c > top) { top = c; best = v; }\n    }\n    return best;\n  }\n  // Where a unit stands, in the words the prompt uses. An island unit is a\n  // floor unit whose back is not against a wall (the walkway rule's test in\n  // engine-warnings isAgainstWall, with a looser reach).\n  function lpUnitPlace(c, walls) {\n    const cat = String(c.category || '');\n    if (/^(wall|bridging)/i.test(cat)) return 'wall';\n    if (/^tall/i.test(cat) || /larder/i.test(cat)) return 'tall';\n    const th = (c.rotationDeg || 0) * Math.PI / 180;\n    const bx = c.x + c.widthMm / 2 - Math.sin(th) * c.depthMm / 2;\n    const by = c.y + c.depthMm / 2 + Math.cos(th) * c.depthMm / 2;\n    const near = (walls || []).some((w) => {\n      const dx = w.to.x - w.from.x, dy = w.to.y - w.from.y;\n      const len2 = dx * dx + dy * dy || 1;\n      const t = Math.max(0, Math.min(1, ((bx - w.from.x) * dx + (by - w.from.y) * dy) / len2));\n      return Math.hypot(bx - (w.from.x + t * dx), by - (w.from.y + t * dy)) <= 150;\n    });\n    return near ? 'base' : 'island';\n  }\n  const LP_PLACE_WORDS = { island: 'island', base: 'base', wall: 'wall', tall: 'tall' };\n  // The plan's doors, floor, worktop and handle: a name for the wording and\n  // a picture to attach. A plan can mix styles and colours, so every door\n  // style + colour is listed with where it is used, most units first, up to\n  // three. Sending only the commonest one, with \"every door must match it\",\n  // repainted the other colour (Arden, 2026-10-31).\n  function lpPlanChoices() {\n    const units = (cabinets || []).filter(c => c && !c.freestandingAppliance);\n    let walls = [];\n    try { walls = getWalls(room); } catch (e) {}\n    const combos = new Map();\n    for (const c of units) {\n      const key = `${c.kitchenStyleId || kitchenStyleId}|${c.doorColourHandle || globalDoorColourHandle || ''}`;\n      const e = combos.get(key) || { key, count: 0, places: new Set() };\n      e.count += 1;\n      e.places.add(lpUnitPlace(c, walls));\n      combos.set(key, e);\n    }\n    if (!combos.size) {\n      const key = `${kitchenStyleId}|${globalDoorColourHandle || ''}`;\n      combos.set(key, { key, count: 0, places: new Set() });\n    }\n    const doors = [...combos.values()].sort((a, b) => b.count - a.count).slice(0, 3).map((e) => {\n      const [styleId, colourH] = e.key.split('|');\n      const style = Catalogue.getKitchenStyle?.(styleId);\n      const colour = colourH ? Catalogue.getMasterDoorColour?.(colourH) : null;\n      return {\n        name: [colour && colour.name, style && style.name].filter(Boolean).join(' '),\n        image: lpHttps(Catalogue.getFrontDoorPreviewUrl?.(styleId, colourH)) || lpHttps(Catalogue.getDoorPreviewUrl?.(styleId, colourH)),\n        places: ['island', 'base', 'wall', 'tall'].filter(p => e.places.has(p))\n      };\n    });\n    // The upstands and splashbacks the plan draws, so the prompt can say\n    // what is there - and that the wall stays bare when nothing is. Naming\n    // an upstand in every prompt made FLUX add one to plans without.\n    const strips = splashbackStripsFor().filter(st => st.lengthMm > 0 && st.heightMm > 0);\n    const kinds = new Set(strips.map(st => st.kind));\n    const splash = {\n      upstand: kinds.has('upstand'),\n      splashback: kinds.has('splashback'),\n      hob: kinds.has('hob-splashback'),\n      matchWorktop: strips.length > 0 && strips.every(st => st.material === 'match-worktop')\n    };\n    const fc = resolveFloorColour(floorColourHandle);\n    const floor = { name: (fc && fc.name) || '', image: fc ? (lpHttps(fc.textureUrl) || lpHttps(fc.swatchUrl)) : null };\n    const wh = worktopMaterialForSlab();\n    const mat = wh ? Catalogue.getWorktopMaterial(wh) : null;\n    const worktop = { name: (mat && mat.title) || '', image: mat ? (lpHttps(mat.textureUrl) || lpHttps(mat.swatchUrl)) : null };\n    const grp = (handleGroups.base && handleGroups.base.designId) ? handleGroups.base\n      : Object.values(handleGroups || {}).find(g => g && g.designId) || null;\n    const design = grp ? Catalogue.getHandleDesign?.(grp.designId) : null;\n    const finish = grp && grp.finishHandle ? Catalogue.getHandleFinish?.(grp.finishHandle) : null;\n    const handle = {\n      name: [finish && finish.name, design && design.name].filter(Boolean).join(' '),\n      image: grp ? lpHttps(handleImageFor(grp.designId, grp.finishHandle)) : null\n    };\n    return { doors, floor, worktop, handle, splash };\n  }\n  function lpPlaces(places) {\n    const words = places.map(p => LP_PLACE_WORDS[p]);\n    if (!words.length) return 'the units';\n    const list = words.length === 1 ? words[0] : `${words.slice(0, -1).join(', ')} and ${words[words.length - 1]}`;\n    return `the ${list} units`;\n  }\n  // The wording plus the reference list, in matching order: the render is\n  // image 1, and each attached picture is named by its number.\n  function lpPrompt(choices, mood, notes) {\n    const cfg = window.BTK_KP_LIFESTYLE || {};\n    const refs = [];\n    const lines = [];\n    const nm = (s) => (s ? ` (${s})` : '');\n    const add = (image, withImage, withoutImage) => {\n      if (image) { refs.push(image); lines.push(withImage(refs.length + 1)); }\n      else if (withoutImage) lines.push(withoutImage);\n    };\n    const { doors, floor, worktop, handle, splash } = choices;\n    if (doors.length > 1) {\n      // Each finish with where it is used, so neither is repainted to match\n      // the other; image 1 already shows which unit is which.\n      lines.push(`This bedroom has ${doors.length} door finishes. Keep each unit's door colour exactly as in the first image - do not change any unit to match another.`);\n      for (const d of doors) {\n        const where = lpPlaces(d.places);\n        add(d.image,\n          (i) => `The doors and drawer fronts on ${where} match the door in image ${i}${nm(d.name)}: same frame, same profile, same colour and grain.`,\n          `The doors and drawer fronts on ${where}${nm(d.name)} stay exactly as in the first image: same frame, same profile, same colour.`);\n      }\n      lines.push('Do not make any door frames flatter, wider or plainer.');\n    } else {\n      const d = doors[0] || { name: '', image: null };\n      add(d.image,\n        (i) => `Every door and drawer front must match the door in image ${i}${nm(d.name)} exactly: same frame, same profile, same colour and grain.`,\n        `Keep every door and drawer front exactly as in the first image${nm(d.name)}: same frame, same profile, same colour. Do not make the frames flatter, wider or plainer.`);\n    }\n    add(floor.image,\n      (i) => `The floor must match the flooring in image ${i}${nm(floor.name)}: same board size, colour and grain.`,\n      floor.name ? `The floor is ${floor.name}, as in the first image.` : '');\n    add(worktop.image,\n      (i) => `The worktop must match the worktop in image ${i}${nm(worktop.name)}: same colour and pattern.`,\n      worktop.name ? `The worktop is ${worktop.name}, as in the first image.` : '');\n    add(handle.image,\n      (i) => `Handles must match the handle in image ${i}${nm(handle.name)}: same shape and finish.`,\n      'Keep every handle exactly as in the first image.');\n    // Upstands and splashbacks exactly as planned - and none where there are none.\n    const mat = splash.matchWorktop ? ', in the same material as the worktop' : '';\n    if (!splash.upstand && !splash.splashback && !splash.hob) {\n      lines.push('There is no upstand or splashback: the wall above the worktop stays bare, exactly as in the first image.');\n    } else {\n      const parts = [];\n      if (splash.upstand) parts.push('a low upstand along the back of the worktop');\n      if (splash.splashback) parts.push('a splashback on the wall behind the worktop');\n      if (splash.hob) parts.push('a splashback behind the hob');\n      lines.push(`There is ${parts.join(' and ')}${mat}, exactly as in the first image. Do not add any upstand or splashback anywhere else.`);\n    }\n    const refText = lines.join('\\n');\n    const moodText = String((mood === 'evening' ? cfg.evening : cfg.daytime) || LP_DEFAULTS[mood] || '').trim();\n    // Staff's own requests may add things, never change the kitchen: the\n    // keep rules that follow in the template still hold.\n    const want = String(notes || '').trim().slice(0, LP_MAX_NOTES);\n    const reqText = want\n      ? `Design requests: ${want}\\nAdd these only in empty space - on clear worktop, walls or floor - and only where they would be seen from this angle. They must not cover or change any cabinet, the hob, sinks or taps.`\n      : '';\n    let prompt = String(cfg.prompt || LP_DEFAULTS.prompt);\n    // A template without the placeholders still gets them, after the\n    // references or at the end.\n    if (!prompt.includes('{requests}')) {\n      prompt = prompt.includes('{references}') ? prompt.replace('{references}', '{references}\\n\\n{requests}') : `${prompt}\\n\\n{requests}`;\n    }\n    prompt = prompt.includes('{references}') ? prompt.replace('{references}', refText) : `${prompt}\\n\\n${refText}`;\n    prompt = prompt.replace('{requests}', reqText).replace(/\\n{3,}/g, '\\n\\n');\n    prompt = prompt.includes('{mood}') ? prompt.replace('{mood}', moodText) : `${prompt}\\n\\n${moodText}`;\n    return { prompt: prompt.trim(), refs };\n  }\n  // The view exactly as staff framed it, clean: nothing selected. JPEG keeps\n  // the upload small - three go in one request, under the server's 5MB body\n  // limit - and FLUX's 1k output needs no more. The shape follows the 3D\n  // view on screen.\n  async function lpCapture() {\n    await ensure3DReady();\n    selectItem(null);\n    await new Promise(r => requestAnimationFrame(() => setTimeout(r, 300)));\n    const canvas = handle3D?.getCanvas?.();\n    const cw = (canvas && canvas.clientWidth) || 16;\n    const ch = (canvas && canvas.clientHeight) || 9;\n    const W = 1280;\n    const H = Math.max(480, Math.min(1280, Math.round(W * ch / cw)));\n    return handle3D?.snapshotOffscreen?.({ view: 'current', width: W, height: H, type: 'image/jpeg', quality: 0.85 }) || null;\n  }\n  async function lpSnap() {\n    if (lp.busy || lp.snaps.length >= LP_MAX_ANGLES) return;\n    lp.error = '';\n    lp.busy = true;\n    lpRender();\n    try {\n      const shot = await lpCapture();\n      if (shot) lp.snaps.push(shot);\n      else lp.error = 'The 3D view could not be captured. Please try again.';\n    } finally {\n      lp.busy = false;\n      lpRender();\n    }\n  }\n  function lpResetJob() {\n    Object.values(lp.urls).forEach((u) => { try { URL.revokeObjectURL(u); } catch (e) {} });\n    lp.urls = {};\n    lp.photos = [];\n    lp.jobId = null;\n  }\n  function lpButtonState() {\n    if (!lifestyleBtn) return;\n    lifestyleBtn.classList.toggle('is-open', lp.open);\n    lifestyleBtn.classList.toggle('is-working', lp.polling);\n    lifestyleBtn.classList.toggle('is-ready', !lp.open && !lp.polling && lp.photos.some(p => p.status === 'ready' && lp.urls[p.id]));\n  }\n  async function lpStart() {\n    if (lp.busy || lp.polling || !lp.snaps.length) return;\n    lp.error = '';\n    const api = window.BTKBasketAPI;\n    const basketId = await lpBasketId();\n    if (!basketId) { lp.error = 'Save the plan first, then make the photos.'; return lpRender(); }\n    lp.busy = true;\n    lpRender();\n    try {\n      const angles = lp.snaps.slice(0, LP_MAX_ANGLES);\n      const { prompt, refs } = lpPrompt(lpPlanChoices(), lp.mood, lp.notes);\n      const r = await api.lifestylePhotoStart({ basketId, mood: lp.mood, prompt, refs, angles });\n      lpResetJob();\n      lp.basketId = basketId;\n      lp.jobId = r.jobId;\n      lp.photos = angles.map(() => ({ status: 'working' }));\n      lpPoll(r.jobId);\n    } catch (e) {\n      const code = e && e.body && e.body.error;\n      lp.error = code === 'daily_limit' ? 'Today\\'s photo limit has been reached. Please try again tomorrow.'\n        : code === 'not_configured' ? 'Lifestyle photos are not switched on yet.'\n        : code === 'capture' ? 'The 3D view could not be captured. Please try again.'\n        : 'The photos could not be started. Please try again.';\n    } finally {\n      lp.busy = false;\n      lpRender();\n    }\n  }\n  async function lpPoll(jobId) {\n    lp.polling = true;\n    lpButtonState();\n    const api = window.BTKBasketAPI;\n    while (lp.jobId === jobId) {\n      await new Promise(r => setTimeout(r, LP_POLL_MS));\n      if (lp.jobId !== jobId) break;\n      let s = null;\n      try { s = await api.lifestylePhotoJob(jobId); } catch (e) { continue; }\n      if (lp.jobId !== jobId || !s) break;\n      for (const p of s.photos || []) {\n        if (p.status === 'ready' && !lp.urls[p.id]) {\n          const blob = await api.lifestylePhotoImage(p.id);\n          if (blob) lp.urls[p.id] = URL.createObjectURL(blob);\n        }\n      }\n      lp.photos = s.photos || [];\n      lpRender();\n      if (s.status !== 'working') break;\n    }\n    if (lp.jobId === jobId) {\n      lp.polling = false;\n      if (lp.photos.length && lp.photos.every(p => p.status === 'failed')) {\n        lp.error = 'FLUX could not make these photos. Please try again.';\n      }\n      lpRender();\n    }\n  }\n  async function lpKeep(id) {\n    const api = window.BTKBasketAPI;\n    try {\n      await api.lifestylePhotoKeep(id, activePlanName || '');\n      if (lp.keptUrl && !Object.values(lp.urls).includes(lp.keptUrl)) URL.revokeObjectURL(lp.keptUrl);\n      lp.keptId = id;\n      lp.keptUrl = lp.urls[id] || null;\n      lp.error = '';\n    } catch (e) {\n      lp.error = 'That photo could not be kept. Please try again.';\n    }\n    lpRender();\n  }\n  async function lpRemove() {\n    const api = window.BTKBasketAPI;\n    const basketId = await lpBasketId();\n    if (!basketId) return;\n    try {\n      await api.lifestylePhotoRemove(basketId);\n      if (lp.keptUrl && !Object.values(lp.urls).includes(lp.keptUrl)) URL.revokeObjectURL(lp.keptUrl);\n      lp.keptId = null;\n      lp.keptUrl = null;\n    } catch (e) {\n      lp.error = 'The photo could not be removed. Please try again.';\n    }\n    lpRender();\n  }\n  // The photo already kept for the plan that is open now, and its design\n  // requests. A different plan than last time drops the other plan's\n  // angles and photos from the panel.\n  async function lpLoadKept() {\n    const basketId = await lpBasketId();\n    if (!basketId) return;\n    if (lp.basketId !== basketId) {\n      // Typed before the plan was known: kept for this plan.\n      const typed = lp.basketId ? '' : lp.notes;\n      if (lp.basketId) {\n        lpResetJob();\n        lp.polling = false;\n        lp.snaps = [];\n        lp.keptId = null;\n        if (lp.keptUrl) { try { URL.revokeObjectURL(lp.keptUrl); } catch (e) {} }\n        lp.keptUrl = null;\n      }\n      lp.notes = lpLoadNotes(basketId) || typed;\n      lp.basketId = basketId;\n      lpSaveNotes();\n      lpRender();\n    }\n    if (lp.keptUrl) return;\n    const blob = await window.BTKBasketAPI?.lifestylePhotoKept?.(basketId);\n    if (blob && lp.basketId === basketId) { lp.keptUrl = URL.createObjectURL(blob); lpRender(); }\n  }\n  function lpEsc(s) {\n    return String(s).replace(/[&<>\"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '\"': '&quot;' }[c]));\n  }\n  function lpRender() {\n    lpButtonState();\n    if (!lp.panel) return;\n    const shots = lp.photos.map((p, i) => {\n      const url = p.id != null ? lp.urls[p.id] : null;\n      if (p.status === 'ready' && url) {\n        const kept = lp.keptId === p.id;\n        return `<div class=\"btk-kp-lp-shot\">\n          <img src=\"${url}\" alt=\"Angle ${i + 1}\" data-lp-view=\"${p.id}\">\n          <div class=\"btk-kp-lp-shot-bar\"><span>Angle ${i + 1}${kept ? ' - Kept' : ''}</span>\n            ${kept\n              // Kept = in the Plan report; Remove takes it back out (row 97).\n              ? `<button type=\"button\" class=\"btk-kp-lp-shot-btn\" data-lp-remove>Remove</button>`\n              : `<button type=\"button\" class=\"btk-kp-lp-shot-btn\" data-lp-keep=\"${p.id}\">Keep</button>`}</div>\n        </div>`;\n      }\n      if (p.status === 'failed') return `<div class=\"btk-kp-lp-shot\"><div class=\"btk-kp-lp-shot-fail\">Angle ${i + 1} could not be made</div></div>`;\n      // Later angles wait for angle 1, so say so rather than look stuck.\n      const waitText = i > 0 && lp.photos[0].status === 'working' ? `Angle ${i + 1} starts when angle 1 is done\u2026` : `Making angle ${i + 1}\u2026`;\n      return `<div class=\"btk-kp-lp-shot\"><div class=\"btk-kp-lp-shot-wait\">${waitText}</div></div>`;\n    }).join('');\n    const n = lp.snaps.length;\n    const snaps = lp.snaps.map((src, i) => `<div class=\"btk-kp-lp-snap\">\n        <img src=\"${src}\" alt=\"Angle ${i + 1}\">\n        <span class=\"btk-kp-lp-snap-num\">${i + 1}</span>\n        <button type=\"button\" class=\"btk-kp-lp-snap-x\" data-lp-unsnap=\"${i}\" aria-label=\"Remove angle ${i + 1}\">\u00D7</button>\n      </div>`).join('');\n    const keptShown = lp.keptUrl && !(lp.keptId != null && lp.urls[lp.keptId]);\n    const kept = keptShown ? `<div class=\"btk-kp-lp-kept-label\">Kept with this plan</div>\n      <div class=\"btk-kp-lp-grid\"><div class=\"btk-kp-lp-shot\">\n        <img src=\"${lp.keptUrl}\" alt=\"Kept photo\" data-lp-view-kept>\n        <div class=\"btk-kp-lp-shot-bar\"><span>Shown in the Plan report</span>\n          <button type=\"button\" class=\"btk-kp-lp-shot-btn\" data-lp-remove>Remove</button></div>\n      </div></div>` : '';\n    const working = lp.busy || lp.polling;\n    // Typing must survive a re-render (the poll redraws every few seconds).\n    const ta = lp.panel.querySelector('[data-lp-notes]');\n    const typing = ta && document.activeElement === ta ? [ta.selectionStart, ta.selectionEnd] : null;\n    lp.panel.innerHTML = `\n      <div class=\"btk-kp-lp-head\"><div class=\"btk-kp-lp-title\">Lifestyle photo</div>\n        <button type=\"button\" class=\"btk-kp-lp-close\" data-lp-close aria-label=\"Close\">\u00D7</button></div>\n      <p class=\"btk-kp-lp-step\">${n < LP_MAX_ANGLES\n        ? `Turn the 3D view to angle ${n + 1}, then press Snap.${n ? ' Or make the photos now.' : ''}`\n        : 'Three angles snapped. Remove one to snap it again.'}</p>\n      ${n ? `<div class=\"btk-kp-lp-snaps\">${snaps}</div>` : ''}\n      ${n < LP_MAX_ANGLES ? `<button type=\"button\" class=\"btk-kp-lp-snap-btn\" data-lp-snap${lp.busy ? ' disabled' : ''}>Snap angle ${n + 1}</button>` : ''}\n      <div class=\"btk-kp-lp-moods\">\n        <button type=\"button\" class=\"btk-kp-lp-mood${lp.mood === 'daytime' ? ' is-on' : ''}\" data-lp-mood=\"daytime\">Daytime</button>\n        <button type=\"button\" class=\"btk-kp-lp-mood${lp.mood === 'evening' ? ' is-on' : ''}\" data-lp-mood=\"evening\">Evening</button>\n      </div>\n      <label class=\"btk-kp-lp-notes-label\" for=\"btk-kp-lp-notes\">Anything to add? (optional)</label>\n      <textarea id=\"btk-kp-lp-notes\" class=\"btk-kp-lp-notes\" data-lp-notes rows=\"3\" maxlength=\"${LP_MAX_NOTES}\"\n        placeholder=\"e.g. a TV on the wall opposite the island, fresh baking on the worktop, stacked plates\">${lpEsc(lp.notes)}</textarea>\n      <button type=\"button\" class=\"btk-kp-lp-go\" data-lp-go${working || !n ? ' disabled' : ''}>${working ? 'Making photos\u2026' : n > 1 ? `Make ${n} photos` : 'Make photo'}</button>\n      <p class=\"btk-kp-lp-note\">${n > 1\n        ? 'Angle 1 takes about a minute and a half, then the others follow so they match it - about 3 minutes in all.'\n        : 'Takes about a minute and a half.'} You can keep working on the plan meanwhile.</p>\n      ${lp.error ? `<p class=\"btk-kp-lp-status is-error\">${lpEsc(lp.error)}</p>` : ''}\n      ${lp.photos.length ? `<div class=\"btk-kp-lp-grid\">${shots}</div>` : ''}\n      ${kept}`;\n    if (typing) {\n      const t = lp.panel.querySelector('[data-lp-notes]');\n      t.focus();\n      t.setSelectionRange(typing[0], typing[1]);\n    }\n  }\n  function lpOpen() {\n    if (!lp.panel) {\n      lp.panel = document.createElement('div');\n      lp.panel.className = 'btk-kp-lp-panel';\n      lp.panel.setAttribute('role', 'dialog');\n      lp.panel.setAttribute('aria-label', 'Lifestyle photo');\n      lp.panel.addEventListener('click', (e) => {\n        const t = e.target.closest('[data-lp-close],[data-lp-mood],[data-lp-go],[data-lp-keep],[data-lp-remove],[data-lp-view],[data-lp-view-kept],[data-lp-snap],[data-lp-unsnap]');\n        if (!t) return;\n        if (t.hasAttribute('data-lp-close')) return lpClose();\n        if (t.hasAttribute('data-lp-snap')) return lpSnap();\n        if (t.hasAttribute('data-lp-unsnap')) {\n          lp.snaps.splice(Number(t.getAttribute('data-lp-unsnap')), 1);\n          return lpRender();\n        }\n        if (t.hasAttribute('data-lp-mood')) { lp.mood = t.getAttribute('data-lp-mood'); return lpRender(); }\n        if (t.hasAttribute('data-lp-go')) return lpStart();\n        if (t.hasAttribute('data-lp-keep')) return lpKeep(Number(t.getAttribute('data-lp-keep')));\n        if (t.hasAttribute('data-lp-remove')) return lpRemove();\n        // Full size in a new tab, to check the doors before keeping.\n        const url = t.hasAttribute('data-lp-view-kept') ? lp.keptUrl : lp.urls[t.getAttribute('data-lp-view')];\n        if (url) window.open(url, '_blank', 'noopener');\n      });\n      lp.panel.addEventListener('input', (e) => {\n        if (!e.target.matches('[data-lp-notes]')) return;\n        lp.notes = e.target.value.slice(0, LP_MAX_NOTES);\n        lpSaveNotes();\n      });\n      // Keys typed in the box are words, not planner shortcuts (Delete\n      // removing the selected unit, arrows nudging it).\n      lp.panel.addEventListener('keydown', (e) => {\n        if (e.target.matches('[data-lp-notes]')) e.stopPropagation();\n      });\n      root.appendChild(lp.panel);\n    }\n    lp.open = true;\n    lp.panel.hidden = false;\n    lpRender();\n    lpLoadKept();\n  }\n  function lpClose() {\n    lp.open = false;\n    if (lp.panel) lp.panel.hidden = true;\n    lpButtonState();\n  }\n  if (lifestyleBtn) {\n    lifestyleBtn.addEventListener('click', () => (lp.open ? lpClose() : lpOpen()));\n  }\n  updateLifestyleVisibility();\n  // Staff mode can settle after boot (a one-time Odoo link is exchanged\n  // first), so look again once it has.\n  window.BTKBasketAPI?.staffReady?.()?.then?.(() => updateLifestyleVisibility()).catch?.(() => {});\n\n  // Renders the placed lights onto the 2D plan grid. Click marker =\n  // remove the light. Re-renders on every rerender() AND after any\n  // light mutation. Markers are positioned in plan-mm and centred\n  // via CSS half-margin trick.\n  function renderLights() {\n    if (!currentGridEl) return;\n    currentGridEl.querySelectorAll('.btk-kp-light-marker').forEach(n => n.remove());\n    const pxPerMm = (clearanceCtx && clearanceCtx.pxPerMm) ||\n                    (worktops2dCtx && worktops2dCtx.pxPerMm);\n    if (!pxPerMm) return;\n    for (const light of lights) {\n      const marker = document.createElement('div');\n      marker.className = 'btk-kp-light-marker';\n      marker.dataset.lightId = String(light.id);\n      marker.title = 'Click to remove this light';\n      marker.style.left = `${light.x * pxPerMm}px`;\n      marker.style.top  = `${light.y * pxPerMm}px`;\n      marker.addEventListener('pointerdown', (e) => {\n        e.stopPropagation();\n        e.preventDefault();\n        handleRemoveLight(light.id);\n      });\n      currentGridEl.appendChild(marker);\n    }\n  }\n\n  // Renders the current waypoint markers + look-at indicators onto\n  // the 2D plan grid. Called from rerender() after the grid is\n  // populated, and again on every waypoint mutation.\n  function renderWaypoints() {\n    if (!currentGridEl) return;\n    // Drop any stale markers / look elements from a previous render.\n    currentGridEl.querySelectorAll(\n      '.btk-kp-waypoint, .btk-kp-waypoint-path, .btk-kp-waypoint-look'\n    ).forEach(n => n.remove());\n    if (!flythroughWaypoints.length) return;\n    const pxPerMm = (clearanceCtx && clearanceCtx.pxPerMm) ||\n                    (worktops2dCtx && worktops2dCtx.pxPerMm);\n    if (!pxPerMm) return;\n    // SVG path connecting the waypoints in order + each waypoint's\n    // optional look-at line (dashed orange from wp to look point).\n    const svgNS = 'http://www.w3.org/2000/svg';\n    const svg = document.createElementNS(svgNS, 'svg');\n    svg.classList.add('btk-kp-waypoint-path');\n    svg.setAttribute('width',  currentGridEl.scrollWidth);\n    svg.setAttribute('height', currentGridEl.scrollHeight);\n    svg.style.left = '0px';\n    svg.style.top  = '0px';\n    if (flythroughWaypoints.length >= 2) {\n      const pts = flythroughWaypoints\n        .map(w => `${w.x * pxPerMm},${w.y * pxPerMm}`)\n        .join(' ');\n      const poly = document.createElementNS(svgNS, 'polyline');\n      poly.setAttribute('points', pts);\n      poly.setAttribute('fill', 'none');\n      poly.setAttribute('stroke', '#2a9d3a');\n      poly.setAttribute('stroke-width', '2');\n      poly.setAttribute('stroke-dasharray', '4 4');\n      svg.appendChild(poly);\n      // Loop-closing dashed segment back to the first waypoint.\n      const first = flythroughWaypoints[0];\n      const last  = flythroughWaypoints[flythroughWaypoints.length - 1];\n      const close = document.createElementNS(svgNS, 'line');\n      close.setAttribute('x1', last.x * pxPerMm);\n      close.setAttribute('y1', last.y * pxPerMm);\n      close.setAttribute('x2', first.x * pxPerMm);\n      close.setAttribute('y2', first.y * pxPerMm);\n      close.setAttribute('stroke', '#2a9d3a');\n      close.setAttribute('stroke-width', '1.5');\n      close.setAttribute('stroke-dasharray', '2 6');\n      close.setAttribute('opacity', '0.6');\n      svg.appendChild(close);\n    }\n    // Look-at lines (orange) per waypoint that has an explicit look.\n    flythroughWaypoints.forEach((wp) => {\n      if (!wp.look) return;\n      const lookLine = document.createElementNS(svgNS, 'line');\n      lookLine.setAttribute('x1', wp.x * pxPerMm);\n      lookLine.setAttribute('y1', wp.y * pxPerMm);\n      lookLine.setAttribute('x2', wp.look.x * pxPerMm);\n      lookLine.setAttribute('y2', wp.look.y * pxPerMm);\n      lookLine.setAttribute('stroke', '#e67e22');\n      lookLine.setAttribute('stroke-width', '1.5');\n      lookLine.setAttribute('stroke-dasharray', '3 3');\n      svg.appendChild(lookLine);\n    });\n    currentGridEl.appendChild(svg);\n    flythroughWaypoints.forEach((wp, i) => {\n      const dot = document.createElement('div');\n      dot.className = 'btk-kp-waypoint' + (i === waypointLookSetIdx ? ' is-look-setting' : '');\n      dot.textContent = String(i + 1);\n      dot.style.left = `${wp.x * pxPerMm}px`;\n      dot.style.top  = `${wp.y * pxPerMm}px`;\n      dot.dataset.waypointIndex = String(i);\n      dot.title = `Waypoint ${i + 1} - left-click to remove, right-click to set look-at`;\n      dot.addEventListener('contextmenu', (e) => {\n        // Right-click on a waypoint marker: toggle look-at editing.\n        // If the waypoint already has a look, clear it; otherwise\n        // enter \"next click sets the look-at point\" mode.\n        e.preventDefault();\n        e.stopPropagation();\n        const idx = Number(dot.dataset.waypointIndex);\n        if (flythroughWaypoints[idx]?.look) {\n          delete flythroughWaypoints[idx].look;\n          waypointLookSetIdx = -1;\n        } else {\n          waypointLookSetIdx = (waypointLookSetIdx === idx) ? -1 : idx;\n        }\n        root.classList.toggle('btk-kp-waypoint-look-mode', waypointLookSetIdx >= 0);\n        renderWaypoints();\n      });\n      dot.addEventListener('pointerdown', (e) => {\n        if (e.button !== 0) return;       // only act on primary click\n        e.stopPropagation();\n        e.preventDefault();\n        const idx = Number(dot.dataset.waypointIndex);\n        flythroughWaypoints.splice(idx, 1);\n        if (waypointLookSetIdx === idx) waypointLookSetIdx = -1;\n        else if (waypointLookSetIdx > idx) waypointLookSetIdx -= 1;\n        root.classList.toggle('btk-kp-waypoint-look-mode', waypointLookSetIdx >= 0);\n        renderWaypoints();\n      });\n      currentGridEl.appendChild(dot);\n      // Look-point marker (small dot) at the look-at target.\n      if (wp.look) {\n        const look = document.createElement('div');\n        look.className = 'btk-kp-waypoint-look';\n        look.style.left = `${wp.look.x * pxPerMm}px`;\n        look.style.top  = `${wp.look.y * pxPerMm}px`;\n        look.title = `Look-at for waypoint ${i + 1}`;\n        currentGridEl.appendChild(look);\n      }\n    });\n  }\n\n  // Click anywhere on the 2D plan when EITHER waypoint-add mode is on\n  // OR a waypoint is waiting for its look-at point OR light drop mode\n  // is on. Runs in capture so it intercepts before the deselect\n  // handler.\n  main.addEventListener('pointerdown', e => {\n    const inLookMode = waypointLookSetIdx >= 0 && flythroughWaypoints[waypointLookSetIdx];\n    if (!waypointAddMode && !inLookMode && !lightDropMode) return;\n    if (viewMode !== '2d') return;\n    if (e.button !== 0) return;\n    if (!currentGridEl) return;\n    if (e.target && e.target.classList && (\n        e.target.classList.contains('btk-kp-waypoint') ||\n        e.target.classList.contains('btk-kp-light-marker'))) return;\n    if (e.target && typeof e.target.closest === 'function' &&\n        e.target.closest('.btk-kp-viewport-overlay')) return;\n    const pxPerMm = (clearanceCtx && clearanceCtx.pxPerMm) ||\n                    (worktops2dCtx && worktops2dCtx.pxPerMm);\n    if (!pxPerMm) return;\n    const rect = currentGridEl.getBoundingClientRect();\n    const mmX = ((e.clientX - rect.left) / view2d.zoom) / pxPerMm;\n    const mmY = ((e.clientY - rect.top)  / view2d.zoom) / pxPerMm;\n    e.preventDefault();\n    e.stopPropagation();\n    if (inLookMode) {\n      // Set the look-at target for the waypoint that's expecting it.\n      flythroughWaypoints[waypointLookSetIdx].look = { x: mmX, y: mmY };\n      waypointLookSetIdx = -1;\n      root.classList.remove('btk-kp-waypoint-look-mode');\n      renderWaypoints();\n    } else if (lightDropMode) {\n      // Drop a light at the clicked position. The 3D renderer handles\n      // type detection (under-cab vs ceiling) automatically.\n      handleAddLight(mmX, mmY);\n    } else {\n      flythroughWaypoints.push({ x: mmX, y: mmY });\n      renderWaypoints();\n    }\n  }, { capture: true });\n\n  // Build initial 2D overlay content so the cog works immediately.\n  renderViewportOverlay();\n\n  // Click anywhere on the 2D canvas that isn't an item \u2192 deselect.\n  // Skip in 3D - the 3D viewport is a single WebGL canvas with no\n  // data attributes, so EVERY click would otherwise pass the\n  // !closest() check and wipe the selection before the 3D\n  // raycaster can act on it.\n  main.addEventListener('pointerdown', e => {\n    if (viewMode === '3d') return;\n    // A right-press on the floor PANS the view (below); it must not also drop\n    // what you had selected - moving the camera is not a click on nothing.\n    if (e.pointerType === 'mouse' && e.button !== 0) return;\n    if (!selectedItem && selectedCabinetIds.size === 0) return;\n    if (!e.target.closest('[data-cabinet-id],[data-feature-id],[data-opening-id]')) {\n      selectItem(null);\n    }\n  });\n\n  // Scroll-wheel zoom for the 2D canvas, anchored at the cursor so the\n  // point under the pointer stays put. Skipped on the 3D step (the 3D\n  // viewport handles its own wheel input).\n  main.addEventListener('wheel', e => {\n    // Over the Planner Home content layer, let the wheel scroll the page\n    // natively instead of zooming the (hidden) 2D canvas behind it.\n    if (e.target.closest && e.target.closest('[data-btk-kp-home]')) return;\n    if (viewMode === '3d' || !currentGridEl || !e.deltaY) return;\n    e.preventDefault();\n    const z0 = view2d.zoom;\n    const factor = e.deltaY < 0 ? 1.12 : 1 / 1.12;\n    const z1 = Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, z0 * factor));\n    if (z1 === z0) return;\n\n    if (z1 <= 1) {\n      // Fully zoomed out - recentre.\n      view2d.panX = 0;\n      view2d.panY = 0;\n    } else {\n      // Keep the grid point under the cursor fixed on screen:\n      //   pan' = m - (m - pan) * (z1 / z0)\n      const rect = main.getBoundingClientRect();\n      const mx = e.clientX - (rect.left + rect.width  / 2);\n      const my = e.clientY - (rect.top  + rect.height / 2);\n      const ratio = z1 / z0;\n      view2d.panX = mx - (mx - view2d.panX) * ratio;\n      view2d.panY = my - (my - view2d.panY) * ratio;\n    }\n    view2d.zoom = z1;\n    applyView2dTransform();\n  }, { passive: false });\n\n  // Right-drag on OPEN FLOOR pans the 2D view - the same gesture the 3D view\n  // uses (its orbit controls pan on the right button), so moving around the\n  // plan works the same in both. Anything with its own right-click keeps it:\n  // a press that starts on a unit, room feature, opening, worktop item,\n  // furniture or a fly-through waypoint is left alone. On open floor the\n  // browser's own context menu is suppressed, as it is over the 3D canvas,\n  // so releasing without moving never pops a native menu over the plan.\n  // panX / panY are screen pixels, so the drag delta applies 1:1.\n  const RIGHT_PAN_SKIP = '[data-cabinet-id],[data-feature-id],[data-opening-id],'\n                       + '[data-worktop-item-id],[data-furniture-id],.btk-kp-waypoint,'\n                       + '[data-btk-kp-home]';\n  let rightPan = null;\n  // Windows raises contextmenu on RELEASE, so a pan that ends over a unit\n  // would pop that unit's menu. After a real pan, swallow the next one.\n  let suppressCtxUntil = 0;\n  const endRightPan = () => {\n    if (!rightPan) return;\n    try { main.releasePointerCapture(rightPan.id); } catch (_) {}\n    main.style.cursor = rightPan.prevCursor;\n    if (rightPan.moved) suppressCtxUntil = performance.now() + 400;\n    rightPan = null;\n  };\n  // Capture phase, so it runs before an item's own contextmenu handler.\n  main.addEventListener('contextmenu', e => {\n    if (performance.now() < suppressCtxUntil) {\n      suppressCtxUntil = 0;\n      e.preventDefault();\n      e.stopPropagation();\n    }\n  }, true);\n  main.addEventListener('pointerdown', e => {\n    if (viewMode === '3d' || !currentGridEl) return;\n    if (e.pointerType !== 'mouse' || e.button !== 2) return;\n    if (e.target.closest && e.target.closest(RIGHT_PAN_SKIP)) return;\n    rightPan = { id: e.pointerId, x: e.clientX, y: e.clientY,\n                 panX: view2d.panX, panY: view2d.panY, prevCursor: main.style.cursor };\n    try { main.setPointerCapture(e.pointerId); } catch (_) {}\n    main.style.cursor = 'grabbing';\n    e.preventDefault();\n  });\n  main.addEventListener('pointermove', e => {\n    if (!rightPan || e.pointerId !== rightPan.id) return;\n    // Released outside the window, or the capture was lost - stop cleanly\n    // rather than panning on plain hover.\n    if ((e.buttons & 2) === 0) { endRightPan(); return; }\n    if (!rightPan.moved && Math.hypot(e.clientX - rightPan.x, e.clientY - rightPan.y) > 3) rightPan.moved = true;\n    view2d.panX = rightPan.panX + (e.clientX - rightPan.x);\n    view2d.panY = rightPan.panY + (e.clientY - rightPan.y);\n    applyView2dTransform();\n  });\n  main.addEventListener('pointerup', e => {\n    if (rightPan && e.pointerId === rightPan.id) endRightPan();\n  });\n  main.addEventListener('pointercancel', endRightPan);\n  main.addEventListener('contextmenu', e => {\n    if (viewMode === '3d') return;                                  // 3D manages its own\n    if (e.target.closest && e.target.closest(RIGHT_PAN_SKIP)) return; // item menus stay\n    e.preventDefault();\n  });\n\n  // Two-finger pinch-zoom + pan on the 2D canvas (touch / trackpad).\n  // The single-finger path is owned by the cabinet drag handler (each\n  // cabinet captures its own pointer), so this only fires when \u2265 2\n  // distinct pointers land on the canvas background itself.\n  const pinchPointers = new Map();\n  let pinch = null;\n  main.addEventListener('pointerdown', e => {\n    if (viewMode === '3d') return;\n    if (e.pointerType === 'mouse') return;   // mouse uses wheel-zoom\n    pinchPointers.set(e.pointerId, { x: e.clientX, y: e.clientY });\n    if (pinchPointers.size === 2) {\n      const pts = [...pinchPointers.values()];\n      const dx = pts[1].x - pts[0].x, dy = pts[1].y - pts[0].y;\n      const rect = main.getBoundingClientRect();\n      pinch = {\n        startDist: Math.hypot(dx, dy) || 1,\n        startZoom: view2d.zoom,\n        startPanX: view2d.panX,\n        startPanY: view2d.panY,\n        midX: (pts[0].x + pts[1].x) / 2 - (rect.left + rect.width  / 2),\n        midY: (pts[0].y + pts[1].y) / 2 - (rect.top  + rect.height / 2)\n      };\n    }\n  });\n  main.addEventListener('pointermove', e => {\n    if (!pinchPointers.has(e.pointerId)) return;\n    pinchPointers.set(e.pointerId, { x: e.clientX, y: e.clientY });\n    if (pinchPointers.size === 2 && pinch) {\n      e.preventDefault();\n      const pts = [...pinchPointers.values()];\n      const dx = pts[1].x - pts[0].x, dy = pts[1].y - pts[0].y;\n      const dist = Math.hypot(dx, dy) || 1;\n      const z1 = Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, pinch.startZoom * (dist / pinch.startDist)));\n      const rect = main.getBoundingClientRect();\n      const midX = (pts[0].x + pts[1].x) / 2 - (rect.left + rect.width  / 2);\n      const midY = (pts[0].y + pts[1].y) / 2 - (rect.top  + rect.height / 2);\n      if (z1 <= 1) {\n        view2d.zoom = z1;\n        view2d.panX = 0;\n        view2d.panY = 0;\n      } else {\n        // Anchor scale at the initial midpoint, then apply the\n        // midpoint delta as a pan so two-finger drag also pans.\n        const ratio = z1 / pinch.startZoom;\n        view2d.panX = pinch.midX - (pinch.midX - pinch.startPanX) * ratio + (midX - pinch.midX);\n        view2d.panY = pinch.midY - (pinch.midY - pinch.startPanY) * ratio + (midY - pinch.midY);\n        view2d.zoom = z1;\n      }\n      applyView2dTransform();\n    }\n  }, { passive: false });\n  const endPinchPointer = e => {\n    pinchPointers.delete(e.pointerId);\n    if (pinchPointers.size < 2) pinch = null;\n  };\n  main.addEventListener('pointerup',     endPinchPointer);\n  main.addEventListener('pointercancel', endPinchPointer);\n\n  // Sidebar drawer toggle for mobile / small tablet. The hamburger\n  // button and the backdrop both carry data-btk-kp-sidebar-toggle, so\n  // one listener handles both open + close interactions.\n  const sidebarToggles = root.querySelectorAll('[data-btk-kp-sidebar-toggle]');\n  sidebarToggles.forEach(btn => {\n    btn.addEventListener('click', () => {\n      const opened = root.classList.toggle('btk-kp-sidebar-open');\n      const hamburger = root.querySelector('.btk-kp-topbar-hamburger');\n      if (hamburger) hamburger.setAttribute('aria-expanded', opened ? 'true' : 'false');\n    });\n  });\n  // Auto-close the drawer when the user picks a stage (Step button) \u2014\n  // touch flow: tap menu \u2192 tap a step \u2192 drawer slides out.\n  root.querySelectorAll('[data-btk-kp-step]').forEach(btn => {\n    btn.addEventListener('click', () => {\n      if (isDrawerMode()) {\n        root.classList.remove('btk-kp-sidebar-open');\n        const hamburger = root.querySelector('.btk-kp-topbar-hamburger');\n        if (hamburger) hamburger.setAttribute('aria-expanded', 'false');\n      }\n    });\n  });\n\n  // Close button on the properties panel header.\n  // ---- Warnings panel ----------------------------------------------------\n  // Red button by the 2D/3D toggle opens the list; its Back pill (and the x)\n  // slide back to the stage menu, exactly as a unit's properties do.\n  root.querySelector('[data-btk-kp-warnings-open]')?.addEventListener('click', () => {\n    openWarningsPanel();\n  });\n  root.querySelectorAll('[data-btk-kp-warnings-back]').forEach(btn => {\n    btn.addEventListener('click', () => {\n      expandedWarnKey = null;\n      focusWarningOnPlan(null);\n      setWarningsHeader(false);\n      setActivePanel(currentStep);\n    });\n  });\n\n  // One delegated listener for the whole list, so re-rendering rows never\n  // leaves a stale handler behind.\n  root.querySelector('[data-btk-kp-warnings-list]')?.addEventListener('click', (ev) => {\n    const row = ev.target.closest('[data-warn-key]');\n    if (!row) return;\n    const key = row.getAttribute('data-warn-key');\n    const wn  = designWarnings.find(w => warnKey(w) === key);\n    if (!wn) return;\n\n    if (ev.target.closest('[data-warn-details]')) {\n      window.BTKKPDialog?.alert(WARN_HELP[wn.ruleId] || wn.message, {\n        eyebrow: 'Warning',\n        title:   warnTitle(wn),\n        image:   WARN_HELP_IMAGE,   // placeholder until the metaobject exists\n        okText:  'Close'\n      });\n      return;\n    }\n\n    if (ev.target.closest('[data-warn-accept]')) {\n      acceptedWarnings.add(key);\n      expandedWarnKey = null;\n      focusWarningOnPlan(null);\n      renderWarningsButton();\n      renderWarningsPanel();\n      setWarningsHeader(true);\n      scheduleAutosave?.();\n      return;\n    }\n\n    if (ev.target.closest('[data-warn-toggle]')) {\n      // Accepted rows stay collapsed; re-opening one is done by unaccepting it,\n      // which is not a thing yet - it would need its own affordance.\n      if (acceptedWarnings.has(key)) return;\n      expandedWarnKey = (expandedWarnKey === key) ? null : key;\n      renderWarningsPanel();\n      // Highlight on the plan WITHOUT selecting: selecting would slide the\n      // menu to the unit's properties and lose the list (Arden, 2026-09-25).\n      focusWarningOnPlan(expandedWarnKey === key ? wn : null);\n    }\n  });\n\n  const closeBtn = root.querySelector('[data-btk-kp-close-selection]');\n  if (closeBtn) closeBtn.addEventListener('click', () => selectItem(null));\n\n  // Green Back pill at the top of the properties panel. Deselects the item,\n  // which is what returns the stage menu - the same thing clicking off the\n  // item does, just findable.\n  const selectionBackBtn = root.querySelector('[data-btk-kp-selection-back]');\n  if (selectionBackBtn) selectionBackBtn.addEventListener('click', () => {\n    deselectViaBack = true;   // Back steps back a level; see selectItem\n    selectItem(null);\n  });\n\n  // Room Setup's Edit Wall Sizes: slide on to the Edit Wall Size menu, and\n  // its Back pill slides back to the Room Setup menu.\n  root.querySelector('[data-btk-kp-outer-size-toggle]')?.addEventListener('click', (e) => {\n    syncOuterSizeCard(e.currentTarget.getAttribute('aria-expanded') !== 'true');\n  });\n  root.querySelector('[data-btk-kp-outer-size-apply]')?.addEventListener('click', () => {\n    if (!outerSizeEditable()) return;\n    const card = root.querySelector('[data-btk-kp-outer-size-card]');\n    const read = (sel) => Math.round(Number(card && card.querySelector(sel) && card.querySelector(sel).value));\n    const w = read('[data-btk-kp-outer-width]'), l = read('[data-btk-kp-outer-length]');\n    const ok = (v) => Number.isFinite(v) && v >= 500 && v <= 20000;\n    if (!ok(w) || !ok(l)) {\n      window.BTKKPDialog?.alert?.('Enter a width and a length between 500mm and 20,000mm.', { title: 'Outer Room Size' });\n      return;\n    }\n    const p = roomConfig.shapeParams || {};\n    if (w === Math.round(p.widthMm) && l === Math.round(p.heightMm)) return;\n    handleParamsApply({ widthMm: w, heightMm: l });\n    // The wall list shows the new lengths.\n    const list = root.querySelector('[data-btk-kp-edit-walls-list]');\n    if (list) selectionPanelHandle?.renderWallPicker?.(list, (wi) => selectWallFromList(wi));\n    syncOuterSizeCard(true);\n  });\n  root.querySelector('[data-btk-kp-edit-walls]')?.addEventListener('click', () => {\n    if (selectedItem) selectItem(null);\n    wallMenuReturn = false;\n    openEditWallsMenu();\n  });\n  root.querySelector('[data-btk-kp-position-back]')?.addEventListener('click', () => {\n    closeUnitPositionMenu();\n  });\n  root.querySelector('[data-btk-kp-edit-walls-back]')?.addEventListener('click', () => {\n    wallMenuReturn = false;\n    setActivePanel(currentStep);\n  });\n\n  // ---- Deep-link bootstrap (from the kitchen style pages) ----------\n  // The style pages link in with: ?style=<handle>&colour=<doorHandle>\n  // &carcase=<handlekey>&view=3d&seed=shb. The planner - not the URL \u2014\n  // decides what to do, based on whether a real (non-empty) plan was\n  // restored: no real plan \u2192 seed a default SHB; real plan \u2192 offer to\n  // restyle the existing plan to the linked style. No saving here.\n\n  // Set the global kitchen style + colours from the link. A linked\n  // colour is used only if it exists in the style; otherwise we fall\n  // back to the style's first-available colour (the agreed default).\n  function applyDeepLinkStyle(styleId, colourHandle, carcaseHandle) {\n    if (styleId) kitchenStyleId = styleId;\n    const doors    = Catalogue.getDoorColoursForStyle(kitchenStyleId)    || [];\n    const carcases = Catalogue.getCarcaseColoursForStyle(kitchenStyleId) || [];\n    const doorOk    = colourHandle  && doors.some(d => d.handle === colourHandle);\n    const carcaseOk = carcaseHandle && carcases.some(c => c.handle === carcaseHandle);\n    globalDoorColourHandle    = doorOk    ? colourHandle  : (doors[0]?.handle    || null);\n    globalCarcaseColourHandle = carcaseOk ? carcaseHandle : (carcases[0]?.handle || null);\n    cabinetsHandle.refresh();\n    styleColoursHandle?.refresh();\n    // Register the chosen style/colour/carcase with the shared buying-style\n    // storage so the buying-style bar + drawer (here in the planner AND on the\n    // units listing page) show it as the active style. Without this the guided\n    // \"Start New Plan\" journey + deep-links set the cabinets' colour but never\n    // told the drawer, so it stayed empty while old styles lingered elsewhere.\n    // syncBuyingStyleToSession is idempotent (no-ops when nothing changed).\n    syncBuyingStyleToSession();\n  }\n\n  // Seed one Single Highline Base (SHB) at 600 wide \u00D7 570 deep in the\n  // given style. addCabinet centres the first cabinet automatically\n  // and reads the global colours set above. Returns true if seeded.\n  function seedShbDefault(styleId) {\n    const shb = (Catalogue.getUnitTypes() || [])\n      .find(u => u.code && u.code.toUpperCase() === 'SHB');\n    if (!shb) { console.warn('[BTK Kitchen Planner] Deep-link seed: SHB unit type not found'); return false; }\n    const product = Catalogue.getProductForUnitInStyle(shb.id, styleId);\n    if (!product) { console.warn('[BTK Kitchen Planner] Deep-link seed: no SHB product for style', styleId); return false; }\n    const infos = (product.variants || [])\n      .map(v => Catalogue.getVariantInfo(v.id)).filter(Boolean);\n    // Prefer 600\u00D7570; fall back to 600 (any depth), then first variant.\n    const info = infos.find(i => i.widthMm === 600 && i.depthMm === 570)\n              || infos.find(i => i.widthMm === 600)\n              || infos[0];\n    if (!info || !info.variant) { console.warn('[BTK Kitchen Planner] Deep-link seed: no SHB variant'); return false; }\n    const def = Catalogue.buildCabinetDefinition({\n      unitTypeId: shb.id, variantId: info.variant.id, kitchenStyleId: styleId\n    });\n    if (!def) { console.warn('[BTK Kitchen Planner] Deep-link seed: could not build SHB definition'); return false; }\n    addCabinet(def);\n    return true;\n  }\n\n  // Restyle every cabinet in the current plan to the linked style +\n  // colours. Reuses the per-cabinet style patcher (handleApplyStyleToIds).\n  function applyRestyleToWholePlan(styleId, colourHandle, carcaseHandle) {\n    applyDeepLinkStyle(styleId, colourHandle, carcaseHandle);\n    const ids = cabinets.map(c => c.id);\n    if (ids.length) {\n      handleApplyStyleToIds(ids, {\n        styleId,\n        doorHandle:    globalDoorColourHandle,\n        carcaseHandle: globalCarcaseColourHandle\n      });\n    }\n  }\n\n  // Cold-boot 3D switch. Calling setViewMode('3d') synchronously at\n  // boot mounts the WebGL viewport before the planner has laid out, so\n  // the canvas initialises at zero size and the view comes up blank.\n  // Deferring two frames lets layout settle (same state as a user\n  // clicking the 3D toggle after load); the try/catch keeps a 3D\n  // hiccup from leaving the planner half-switched.\n  function enter3DAfterPaint() {\n    requestAnimationFrame(() => requestAnimationFrame(() => {\n      try { setViewMode('3d'); }\n      catch (e) { console.error('[BTK Kitchen Planner] Deep-link 3D switch failed', e); }\n    }));\n  }\n\n  // Styled confirm shown when a deep-link arrives for a style while a\n  // real plan already exists. onConfirm runs the restyle. Self-contained\n  // (inline styles, built with textContent so the style name is safe).\n  function showRestyleConfirm(styleName, onConfirm) {\n    const prev = document.getElementById('btk-kp-restyle-confirm');\n    if (prev) prev.remove();\n\n    const overlay = document.createElement('div');\n    overlay.id = 'btk-kp-restyle-confirm';\n    overlay.style.cssText = 'position:fixed;inset:0;z-index:100000;display:flex;align-items:center;'\n      + 'justify-content:center;background:rgba(0,0,0,0.55);backdrop-filter:blur(3px);padding:20px;';\n\n    const card = document.createElement('div');\n    card.setAttribute('role', 'dialog');\n    card.setAttribute('aria-modal', 'true');\n    card.style.cssText = 'background:#fff;max-width:440px;width:100%;border-radius:14px;'\n      + 'box-shadow:0 20px 60px rgba(0,0,0,0.3);overflow:hidden;';\n\n    const body = document.createElement('div');\n    body.style.cssText = 'padding:22px 24px 16px;';\n    const h = document.createElement('h2');\n    h.style.cssText = 'margin:0 0 8px;font-size:18px;font-weight:750;color:#1a1a1a;';\n    h.textContent = 'Update your plan to ' + styleName + '?';\n    const p = document.createElement('p');\n    p.style.cssText = 'margin:0;font-size:13.5px;line-height:1.5;color:#555;';\n    p.textContent = 'This switches every unit in your current plan to ' + styleName\n      + '. Some units may not be available in this style, and colours or prices may change.';\n    body.appendChild(h);\n    body.appendChild(p);\n\n    const footer = document.createElement('div');\n    footer.style.cssText = 'display:flex;gap:10px;padding:14px 24px 22px;justify-content:flex-end;';\n    const cancel = document.createElement('button');\n    cancel.type = 'button';\n    cancel.textContent = 'Keep current plan';\n    cancel.style.cssText = 'background:#f0f2f5;color:#333;border:1px solid #d8dde2;padding:10px 18px;'\n      + 'border-radius:9px;font-weight:600;font-size:13.5px;cursor:pointer;';\n    const confirm = document.createElement('button');\n    confirm.type = 'button';\n    confirm.textContent = 'Update plan';\n    confirm.style.cssText = 'background:#1a3b6b;color:#fff;border:none;padding:10px 18px;'\n      + 'border-radius:9px;font-weight:650;font-size:13.5px;cursor:pointer;';\n    footer.appendChild(cancel);\n    footer.appendChild(confirm);\n\n    card.appendChild(body);\n    card.appendChild(footer);\n    overlay.appendChild(card);\n    document.body.appendChild(overlay);\n\n    function close() {\n      overlay.remove();\n      document.removeEventListener('keydown', onKey);\n    }\n    function onKey(e) { if (e.key === 'Escape') close(); }\n    document.addEventListener('keydown', onKey);\n    overlay.addEventListener('click', e => { if (e.target === overlay) close(); });\n    cancel.addEventListener('click', close);\n    confirm.addEventListener('click', () => { close(); onConfirm(); });\n    confirm.focus();\n  }\n\n  const _tLoad0 = performance.now();   // ?btktime=1: the boot restore's fetch\n  planStore.load().then(async (auto) => {\n    const _tLoad1 = performance.now();\n    // A BOUGHT plan is never restored. Deciding this before drawing anything is\n    // the point: restoring first showed the bought kitchen's style, units and\n    // price for seconds, then reloaded (Arden, 2026-09-29). Its locks came\n    // down with the project, so this is local unless the plan is only held.\n    if (auto && !_bootOrdered) {\n      try {\n        const bkApi = window.BTKBasketAPI;\n        const activeId = await planStore.getActiveBasketId();\n        // Only what the server already says. A held plan waiting on its order is\n        // checked by startFreshIfOrdered, behind the loader, with the plan\n        // restored: holding the boot here let another boot step make a blank\n        // plan and take the customer off theirs.\n        const bootLock = bkApi && activeId && bkApi.getBasketLock && bkApi.getBasketLock(activeId);\n        if (bootLock && bootLock.status === 'ordered') {\n          await leaveBoughtPlan();\n          auto = null;   // open on Home, as a first visit does\n        }\n      } catch (e) { /* restore as normal */ }\n    }\n    // The checkout-hold question runs only once that is decided, so the two\n    // never race (it used to start separately at boot).\n    if (!_bootOrdered) {\n      if (_bootBasketStepReturn) await startFreshIfOrdered();\n      else startFreshIfOrdered();\n    }\n    // Not in the purchased-plan viewer: restoring the customer's current plan\n    // raced openOrderedPlan and could land second, drawing THEIR plan under\n    // the \"ordered kitchen\" heading - and, if the order failed to load,\n    // leaving it on screen with nothing saying whose it was.\n    // Not for a plan link either: the linked plan replaces it at once, so\n    // drawing the autosave first was seconds of work nobody saw. It is kept\n    // as the fallback if the linked plan cannot be found.\n    const restoreAutosave = () => {\n      applyState(auto.design);\n      planThumb = auto.thumbnail || null;   // keep the restored plan's 3D preview\n      takePlanPrice(auto.design);\n      // Restored plan LEADS: push its full buying-style set to the session\n      // store (see loadNamedPlan). Without this a relaunch shows a stale set.\n      syncBuyingStylesToSession();\n      // Auto-restore from autosave - re-evaluate back panels against\n      // the loaded room so older saves get the feature applied.\n      autoDetectBackPanels();\n      // Restore the saved name so a named plan opened from the basket\n      // (\"Edit Plan\") isn't treated as unsaved (which re-prompts on\n      // Add to Basket every time). Refresh the drawer AFTER setting it\n      // so the add button's label reflects the saved state.\n      if (auto.planName) {\n        activePlanName = auto.planName;\n        designControlsHandle.setPlanName(auto.planName);\n        basketDrawerHandle?.refresh?.();\n        refreshLiveQuoteLabels();\n      }\n      designControlsHandle.setStatus(`Restored from ${formatTime(auto.savedAt)}`);\n      lastSavedSig = designSig();   // as the server has it\n    };\n    // \u26A0 Restored for a plan link too. Skipping it (2026-09-29, to open plans\n    // faster) left the planner EMPTY while the linked plan loaded, and a save\n    // in that gap wrote the empty plan over the customer's current one - Arden\n    // lost a plan opened from Odoo's Edit Plan. Autosave is also held until the\n    // linked plan lands (scheduleAutosave / runAutosave).\n    const _npOn = npOn();\n    const _tRestore0 = performance.now();\n    if (auto && !_bootOrdered) restoreAutosave();\n    const _tRestore1 = performance.now();\n\n    const params = new URLSearchParams(window.location.search);\n    const linkStyle = window.BTKCtxClean.handle(params.get('style'));\n\n    // Deep-link into the guided journey (storefront \"Plan Online\" / \"Plan This\n    // Kitchen\" buttons): ?journey=carcase&style=&colour= starts a NEW-plan\n    // journey with the style + door colour preset (Choose Style & Colour ticked)\n    // and lands on the Choose Carcase step - NOT room-setup/seed.\n    const linkJourney = (params.get('journey') || '').trim();\n    if (linkJourney && linkStyle && Catalogue.getKitchenStyle && Catalogue.getKitchenStyle(linkStyle)) {\n      // ?btktime=1 (Arden, 2026-10-07): timed from the page starting to load.\n      if (_npOn) {\n        npT0 = 1e-9;   // performance.now() counts from the page starting to load\n        npTitle = 'Start Planning (from the website) timings';\n        npList.length = 0;\n        npList.push('page started loading: 0ms');\n        try {\n          const nav = performance.getEntriesByType('navigation')[0];\n          if (nav) {\n            npList.push('page HTML received: ' + Math.round(nav.responseEnd) + 'ms');\n            npList.push('page ready (DOMContentLoaded): ' + Math.round(nav.domContentLoadedEventEnd) + 'ms');\n          }\n        } catch (_) {}\n        npList.push('planner asked for the last plan: ' + Math.round(_tLoad0) + 'ms');\n        npList.push('last plan arrived from the server: ' + Math.round(_tLoad1) + 'ms');\n        npList.push('last plan restored on screen: ' + Math.round(_tRestore0) + 'ms -> ' + Math.round(_tRestore1) + 'ms' + (auto ? '' : ' (none)'));\n        npMark('website style read, journey starting');\n      }\n      try { history.replaceState({}, '', window.location.pathname); } catch (e) {}\n      const jColour = window.BTKCtxClean.handle(params.get('colour')) || null;\n      hideWelcome();\n      // Start the journey (switches to the Style Setup stage + reveals its\n      // right pane), then preset the storefront style+colour+carcase as the\n      // main buying style and land on the Style step (carcase now lives on the\n      // card, so there's no separate Carcase step).\n      startGuidedJourney();\n      journey.styleId    = linkStyle;\n      journey.doorHandle = jColour;\n      const _cols = (Catalogue.getDoorColoursForStyle && Catalogue.getDoorColoursForStyle(linkStyle)) || [];\n      const _dc = _cols.find(c => c.handle === jColour);\n      journey.doorName = _dc ? (_dc.name || '') : '';\n      const jCarcase = window.BTKCtxClean.handle(params.get('carcase')) || null;\n      const _carcs = (Catalogue.getCarcaseColoursForStyle && Catalogue.getCarcaseColoursForStyle(linkStyle)) || [];\n      const _carcHandle = (jCarcase && _carcs.some(c => c.handle === jCarcase)) ? jCarcase : ((_carcs[0] && _carcs[0].handle) || null);\n      // Set the carcase on `journey` too (not just buyingStyles) so the mood\n      // board renders its carcase overlay - syncJourneyFromOptions won't copy it\n      // across because journey.styleId is already set here.\n      journey.carcaseHandle = _carcHandle;\n      journey.carcaseName   = (_carcs.find(c => c.handle === _carcHandle) || {}).name || '';\n      buyingStyles = [{ styleId: linkStyle, doorHandle: jColour, carcaseHandle: _carcHandle }];\n      // The restored plan is exactly what the server sent: no save of it.\n      if (autosaveTimer) { clearTimeout(autosaveTimer); autosaveTimer = null; }\n      autosaveDirty = false;\n      autosaveHeldForLinkedNewPlan = true;\n      // Style + colour came from the website - go straight to naming the plan.\n      // With no Style Setup stage, finishing asks for the name (the plan has\n      // none yet) and its Save carries on into Room Setup in this style.\n      finishGuidedJourney();\n      requestAnimationFrame(() => npMark('name popup on screen'));\n      dropJourneyLinkLoader();\n      try { planNavStep('landed', 'journey asking for the plan name'); } catch (_) {}\n      return;\n    }\n\n    dropJourneyLinkLoader();   // a journey link that could not be used\n\n    // The planner now lands on the Planner Home stage by default. Any\n    // deep-link that drops the user straight into the plan (open a saved\n    // plan, apply a style, \"Edit in 3D\", a seed, or a live session) must\n    // leave Home and switch to a real planner stage so the canvas shows.\n    const _entersPlanner =\n      !!linkStyle ||\n      !!(params.get('plan') || '').trim() ||\n      !!(params.get('planId') || '').trim() ||\n      !!(params.get('restoreVersion') || '').trim() ||\n      params.get('view3d') === '1' ||\n      !!params.get('seed') ||\n      !!_bootLive.session;\n    // From the introduction page (/pages/kitchen-planner, Arden 2026-11-05):\n    // ?open=new|saved|resume. That page has already asked how they want to\n    // start, so the Welcome page would ask twice. new and saved press the\n    // Welcome page's own two buttons; resume shows the restored plan.\n    const linkOpen = (params.get('open') || '').trim();\n    if (!_entersPlanner && (linkOpen === 'new' || linkOpen === 'saved' || linkOpen === 'resume')) {\n      try { history.replaceState({}, '', window.location.pathname); } catch (e) {}\n      hideWelcome();\n      if (linkOpen === 'resume') {\n        try { if (planHasContent()) stepperHandle.setStep('room-setup'); } catch (e) {}\n      } else {\n        const view = linkOpen === 'new' ? 'home' : 'open-saved-plan';\n        root.querySelector('[data-btk-kp-home-view=\"' + view + '\"]')?.click();\n      }\n    }\n\n    // \"Convert Basket to Kitchen Plan\" handoff from /cart (?convert=1) - handled\n    // BEFORE the _entersPlanner room-setup nudge so processConvertPayload fully\n    // controls the stage + popup order (the auto room-shape popup stacking on\n    // our info dialog was freezing the page).\n    if (params.get('convert') === '1') {\n      try { history.replaceState({}, '', window.location.pathname); } catch (e) {}\n      processConvertPayload().catch(e => {\n        console.error('[BTK convert] failed', e);\n        if (window.BTKLoader) window.BTKLoader.hide();\n      });\n      return;\n    }\n\n    // Return from the pre-checkout page's \"Basket\" stage: leave Home, show the\n    // planner, and reopen the embedded basket over the restored plan.\n    if (params.get('openbasket') === '1') {\n      try { history.replaceState({}, '', window.location.pathname); } catch (e) {}\n      stepperHandle.setStep('room-setup');\n      try { openLiveQuote(); } catch (e) {}\n      return;\n    }\n\n    // A plan link goes to Add Units once the plan is in (below); stepping\n    // through Room Setup on the way is the jump Arden saw.\n    if (_entersPlanner && !_bootPlanLink) stepperHandle.setStep('room-setup');\n\n    // Live joint session. The VIEWER (customer) mirrors the salesperson and\n    // ignores any plan/style deep-link - it just joins (consent) then polls.\n    // The DRIVER (salesperson) starts pushing AFTER the plan resolves, so the\n    // first snapshot already carries the loaded plan (wired into each branch).\n    if (_bootLive.session && _bootLive.role === 'viewer') {\n      try { history.replaceState({}, '', window.location.pathname); } catch (e) {}\n      // Land the customer ON THE PLAN, not on the planner's own Home screen.\n      // The Home overlay is opaque and covers the whole canvas, and the Room\n      // Setup nudge opens on top of it - so a customer who joined a session was\n      // left picking a stage and a room shape while the salesperson was already\n      // working, and never saw the plan at all. Same skip the \"open this plan\"\n      // deep-link does; there is nothing here for them to choose, because their\n      // screen mirrors the salesperson's.\n      try { hideWelcome(); } catch (e) {}\n      roomShapePrompted = true;\n      // The customer's screen follows the salesperson through every stage\n      // (applyDriverView). The one-off helpers those stages show on arrival\n      // are the salesperson's to dismiss, not a box to pop up in front of the\n      // customer each time the stage changes.\n      styleIntroDone = true;\n      // Add Units is only the first frame: the salesperson's own stage arrives\n      // with their first view message and takes over.\n      try { stepperHandle.setStep('add-units'); } catch (e) {}\n      const _rsPopup = root.querySelector('[data-btk-kp-popup=\"room-shape\"]');\n      if (_rsPopup) _rsPopup.hidden = true;\n      // Marks the page as a watch-only screen. Paired with the input shield\n      // further up: that stops the controls working, this shows they are not\n      // theirs to work. Deliberately does NOT hide anything - the canvas is\n      // absolutely positioned while the sidebar is in a flex row, so removing\n      // the sidebar would leave a hole rather than widen the plan.\n      try { root.classList.add('btk-kp-live-viewing'); } catch (e) {}\n      LiveSession.joinAsViewer(_bootLive.session);\n      // The salesperson's own view arrives within a moment and takes over\n      // (applyDriverView); this is just a sensible first frame.\n      if (params.get('view3d') === '1') enter3DAfterPaint();\n      return;\n    }\n    const startDriverIfNeeded = () => {\n      if (_bootLive.session && _bootLive.role === 'driver') LiveSession.startAsDriver();\n    };\n\n    // A refresh or a crash mid-session: take the SAME session back rather than\n    // leaving the customer watching an abandoned one. Only when the URL isn't\n    // already asking to start a fresh session.\n    if (!(_bootLive.session && _bootLive.role === 'driver') && LiveSession.hasHeldSession()) {\n      LiveSession.resumeAsDriver().then((ok) => {\n        if (ok) console.log('[LiveSession] resumed the session this tab was driving');\n      });\n    }\n\n    // Guest\u2192login handoff: a guest who pressed Save had their design stashed\n    // and was sent to log in. They land back here as a customer, so this is\n    // where we offer it back. Skipped when a deep-link is driving the boot -\n    // that has its own plan to load and must not be overridden.\n    if (!_entersPlanner && params.get('convert') !== '1' && !_bootOrdered) {\n      maybeRestorePendingDesign();\n    }\n\n    // Restore as Copy (Odoo's Plan History): open an earlier version of a plan\n    // as a NEW plan, then land on Add Units as a plan link does. Autosave is\n    // held until it has landed (planLinkLanded), as for a plan link.\n    const linkRestore = (params.get('restoreVersion') || '').trim();\n    if (linkRestore) {\n      try { history.replaceState({}, '', window.location.pathname); } catch (e) {}\n      planLinkLanding = true;\n      openRestoredVersion(linkRestore).then((ok) => {\n        hideWelcome();\n        roomShapePrompted = true;\n        try { stepperHandle.setStep('add-units'); } catch (e) {}\n        const _rsPopup = root.querySelector('[data-btk-kp-popup=\"room-shape\"]');\n        if (_rsPopup) _rsPopup.hidden = true;\n        if (ok && params.get('view3d') === '1') enter3DAfterPaint();\n        startDriverIfNeeded();\n      }).catch((e) => {\n        console.error('[BTK Kitchen Planner] restoring a plan version failed', e);\n      }).finally(() => {\n        planLinkLanded = true;\n        requestAnimationFrame(() => requestAnimationFrame(() => {\n          if (window.BTKLoader) window.BTKLoader.hide();\n        }));\n      });\n      return;\n    }\n\n    // Worktop Quote (Sales line 108): the bought plan's linked worktop copy,\n    // landing on Customise with the worktop to choose.\n    const linkWorktopQuote = (params.get('worktopquote') || '').trim();\n    if (linkWorktopQuote) {\n      try { history.replaceState({}, '', window.location.pathname); } catch (e) {}\n      planLinkLanding = true;\n      openWorktopQuote(linkWorktopQuote).then((ok) => {\n        hideWelcome();\n        roomShapePrompted = true;\n        const _rsPopup = root.querySelector('[data-btk-kp-popup=\"room-shape\"]');\n        if (_rsPopup) _rsPopup.hidden = true;\n        try { stepperHandle.setStep(ok ? 'style-colours' : 'add-units'); } catch (e) {}\n        startDriverIfNeeded();\n      }).catch((e) => {\n        console.error('[BTK Kitchen Planner] opening the worktop quote failed', e);\n      }).finally(() => {\n        planLinkLanded = true;\n        requestAnimationFrame(() => requestAnimationFrame(() => {\n          if (window.BTKLoader) window.BTKLoader.hide();\n        }));\n      });\n      return;\n    }\n\n    // Open/Edit a specific saved plan by name (from the customer's Shopify\n    // account dashboard): ?plan=<name> loads that named plan; add &view3d=1\n    // to drop straight into 3D (\"Edit in 3D\"). Overrides the autosave restore.\n    const linkPlan = (params.get('plan') || '').trim();\n    // The plan's own id, when the link carries one (Odoo's \"Edit in Planner\"\n    // sends both). `plan` stays the fallback for older links.\n    const linkPlanId = (params.get('planId') || '').trim();\n    if (linkPlan || linkPlanId) {\n      try { history.replaceState({}, '', window.location.pathname); } catch (e) {}\n      planLinkLanding = true;\n      // ?btktime=1: how long an Edit Plan arrival takes, from the page starting.\n      try {\n        window.BTKKPTiming && window.BTKKPTiming.start(\n          `saved plans in, ${Math.round(performance.now())}ms after the page started`);\n      } catch (_) {}\n      loadLinkedPlan(linkPlanId, linkPlan, { backgroundSave: true }).then((loaded) => {\n        try { window.BTKKPMark && window.BTKKPMark('plan drawn'); } catch (_) {}\n        // A loaded plan ALREADY has its room, so the Room Setup nudge - which\n        // auto-opens the Room Shape popup whenever the room still looks like the\n        // default - is simply wrong on this path: opening a customer's plan\n        // (from their account, or a salesperson's \"Open Plan\" in Odoo) landed on\n        // \"what shape is your room?\" instead of the plan. Suppress the prompt\n        // and land on Add Units, the stage the plan is actually worked in. Same\n        // idiom as the convert-to-plan arrival.\n        hideWelcome();\n        roomShapePrompted = true;\n        try { stepperHandle.setStep('add-units'); } catch (e) {}\n        // Belt-and-braces: if anything opened the Room Shape popup while the\n        // plan was still loading, close it. Landing on Add Units with the popup\n        // still up is precisely the state this path exists to avoid.\n        const _rsPopup = root.querySelector('[data-btk-kp-popup=\"room-shape\"]');\n        if (_rsPopup) _rsPopup.hidden = true;\n        // setStep pulls the canvas to this stage's 2D view, so an explicit 3D\n        // request has to be honoured AFTER it or it gets stomped.\n        if (params.get('view3d') === '1') enter3DAfterPaint();\n        startDriverIfNeeded();\n      }).catch((e) => {\n        console.error('[BTK Kitchen Planner] opening the linked plan failed', e);\n      }).finally(() => {\n        planLinkLanded = true;\n        // Landed (or gave up): the first frame of Add Units paints, then the\n        // loader goes - two rAFs, as at boot, so no blank frame shows.\n        requestAnimationFrame(() => requestAnimationFrame(() => {\n          if (window.BTKLoader) window.BTKLoader.hide();\n          try {\n            window.BTKKPMark && window.BTKKPMark('on Add Units, loader down');\n            window.BTKKPTiming && window.BTKKPTiming.show('Opening a plan');\n          } catch (_) {}\n        }));\n      });\n      return;\n    }\n\n    // No style deep-link, but an explicit 3D request (the advanced\n    // basket's \"Edit Plan\" button) \u2192 the plan is already restored by\n    // the autoload above; just consume the param and drop into 3D.\n    if (!linkStyle && params.get('view3d') === '1') {\n      try { history.replaceState({}, '', window.location.pathname); } catch (e) {}\n      enter3DAfterPaint();\n      startDriverIfNeeded();\n      return;\n    }\n    if (!linkStyle) { startDriverIfNeeded(); return; }\n    if (!(Catalogue.getKitchenStyle && Catalogue.getKitchenStyle(linkStyle))) {\n      console.warn('[BTK Kitchen Planner] Deep-link style not found:', linkStyle);\n      return;\n    }\n\n    const linkColour  = window.BTKCtxClean.handle(params.get('colour')) || null;\n    const linkCarcase = window.BTKCtxClean.handle(params.get('carcase')) || null;\n    // NB: do NOT use a param named `view` - Shopify reserves it for\n    // alternate template views (?view=foo \u2192 page.<tpl>.foo), which\n    // renders the page WITHOUT the planner section. Use `view3d`.\n    const want3D      = params.get('view3d') === '1';\n    const seed        = params.get('seed');\n    const hasRealPlan = !!(auto && auto.design && (auto.design.cabinets || []).length > 0);\n\n    // Consume the deep-link ONCE: strip the query params from the URL so\n    // a reload - or leaving the planner and returning - doesn't re-apply\n    // them. Previously the params stayed in the address bar and re-showed\n    // the restyle prompt on every load, risking loss of in-progress work.\n    // `params` and the values above are already captured, so the logic\n    // below is unaffected by the URL change.\n    try { history.replaceState({}, '', window.location.pathname); } catch (e) {}\n\n    if (!hasRealPlan) {\n      applyDeepLinkStyle(linkStyle, linkColour, linkCarcase);\n      const seeded = seed === 'shb' ? seedShbDefault(linkStyle) : false;\n      if (want3D) enter3DAfterPaint();\n      if (seeded) designControlsHandle.setStatus('Started from bedroom style');\n    } else {\n      const ks = Catalogue.getKitchenStyle(linkStyle);\n      showRestyleConfirm(ks?.name || linkStyle, () => {\n        applyRestyleToWholePlan(linkStyle, linkColour, linkCarcase);\n        if (want3D) enter3DAfterPaint();\n      });\n    }\n  }).finally(() => {\n    // The restore has SETTLED (restored, empty, or failed) - from here\n    // planHasContent() can be trusted. Release anything that deferred on it.\n    bootRestoreSettled = true;\n    if (pendingStyleSetupEntry) {\n      pendingStyleSetupEntry = false;\n      try { enterStyleSetup(); } catch (e) { /* never break boot */ }\n    }\n    // New Plan was drawn before the restore landed: the room-shape card can\n    // only now tell a returning planner from a first-time one.\n    try { syncRoomShapeCard(); } catch (e) { /* never break boot */ }\n    // Boot settled - give the 3D view a beat to paint, then drop the\n    // loader (the one shown for \"Edit Plan\" / view3d=1 arrivals).\n    // A plan link whose landing never started (another deep link took the boot,\n    // or the restore failed) must not leave autosave held for good.\n    if (!planLinkLanding) planLinkLanded = true;\n    // Not while a plan link is still landing: it drops the loader itself.\n    // (If the restore failed before that path started, this still clears it.)\n    if (!planLinkLanding) setTimeout(() => { if (window.BTKLoader) window.BTKLoader.hide(); }, 600);\n    // ?btktime=1: a Plan Online link whose style did not start the journey.\n    try { planNavStep('landed', 'boot settled (journey NOT started)'); } catch (_) {}\n    // With the plan's style now known, pre-draw the Add Units pictures in the\n    // background (ui-cabinets prewarmUnitPictures) - almost everyone opens\n    // Add Units soon after landing. Not in the purchased-plan viewer.\n    if (!_bootOrdered) { try { cabinetsHandle?.prewarmPictures?.(3000); } catch (e) {} }\n  });\n}\n\n// Boot ordering matters: this is a type=\"module\" script, so it runs at\n// readyState 'interactive' - potentially BEFORE the deferred\n// btk-basket-api.js executes. If we init() then, window.BTKBasketAPI is\n// undefined and the PlanStore silently falls back to localStorage (which\n// loses the shared-basket features, e.g. the saved plan name). So we\n// wait for the basket API (a deferred script - guaranteed to run before\n// DOMContentLoaded), then init; with safety fallbacks so we never hang.\n// Merge the unit types Liquid cannot reach.\n//\n// Liquid caps at 250 metaobjects per type and the `page` parameter does not\n// advance it (see btk-unit-types-storefront.js). `.values` orders by HANDLE,\n// so the unreachable tail was `true-handleless-*` - 72 of 73 TH types, which\n// is why no TH tiles appeared in Add Units. The Storefront API has real cursor\n// pagination and no ceiling.\n//\n// Deliberately NOT awaited: it must not sit in front of the planner's first\n// paint, and Add Units rebuilds its tiles from the Catalogue each time it\n// opens, so a merge landing a moment later shows up on the next open.\n// Settles (never rejects) once the merge has landed or failed - checkout waits\n// on it, so every unit's hinge is known before the order goes (Sales row 152).\nlet unitTypeTailDone = Promise.resolve();\nfunction mergeUnitTypeTail() {\n  let boot = 0;\n  try { boot = (window.BTKKitchenCatalogue.unitTypes || []).length; } catch (_) { return; }\n  unitTypeTailDone = fetchUnitTypesFromStorefront()\n    .then((list) => {\n      const added = Catalogue.addUnitTypes(list);\n      console.log('[BTK Kitchen Planner] unit types: %d from Liquid, %d from the '\n                  + 'Storefront API, +%d new, %d total',\n                  boot, list.length, added, Catalogue.getUnitTypes().length);\n      // A plan loaded before this landed kept its saved copy of these units'\n      // schema, 2D shape and category - see the listener in init().\n      if (added) {\n        try {\n          window.dispatchEvent(new CustomEvent('btk:unit-types-merged',\n            { detail: { ids: list.map(u => u && u.id).filter(Boolean) } }));\n        } catch (_) {}\n      }\n    })\n    .catch((e) => {\n      console.warn('[BTK Kitchen Planner] unit-type tail merge failed - units past '\n                   + 'the Liquid 250 cap will be missing from Add Units', e);\n    });\n}\n\nfunction bootPlanner() {\n  mergeUnitTypeTail();\n  if (window.BTKBasketAPI || document.readyState === 'complete') {\n    init();\n    return;\n  }\n  let started = false;\n  const start = () => { if (!started) { started = true; init(); } };\n  document.addEventListener('DOMContentLoaded', start);\n  // Safety: don't wait forever if the API never loads or DCL has passed.\n  setTimeout(start, 1500);\n}\nbootPlanner();"],
  "mappings": "AAkBA,OAAS,eAAgB,aAA4B,2CACrD,OACE,oBACA,uBACA,iBACA,cACA,kBACA,qBACA,gBACA,yBACA,0BACA,kBACA,eACA,wBACA,qBACA,oBACA,2BACA,oBACA,oBACA,qBACA,wBACA,qBACA,gBACA,yBACA,qBACA,uBACA,yBACA,mBACoD,oDACtD,OAAS,WAAY,aAAc,cAAe,cAAe,eAAgB,mBAAoB,aAAc,kBAAqB,wCACxI,OAAS,qBAAsB,sBAAuB,qBAAwB,8CAC9E,OAAS,eAAgB,kBAAmB,eAAgB,oBAAuB,6CACnF,OAAS,mBAA4C,2CACrD,OAAS,uBAA4C,gDACrD,OAAS,2BAA4C,6CACrD,OAAS,sBAA4C,8CACrD,OAAS,wBAAyB,sBAAyB,mDAC3D,OAAS,eAAgB,sBAA4B,4CACrD,OAAS,eAAgB,qBAAsB,oBAAuB,4CACtE,OAAS,oBAAuB,8CAChC,OAAS,uBAA4C,oDACrD,OAAS,kBAA4C,uCACrD,OAAS,aAAc,YAAa,oBAAqB,iBAAkB,sBAAuB,iBAAkB,uBAAwB,mBAAoB,kBAAmB,eAAgB,kBAAmB,uBAA0B,kDAChP,OAAS,oBAA2C,4CACpD,OACE,aAAc,cACd,2BAA4B,4BAC5B,cAAe,mBACV,6CACP,OAAS,sBAAuB,uBAAwB,YAAa,oBAAsC,+CAC3G,OAAS,iCAA2C,qCACpD,OAAS,cAA4C,kDACrD,OAAS,gCACA,oBAC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AQ,QAAQ,EACvC,SAAS,mBAAoB,CAC3B,IAAI,KAAO,EACX,GAAI,CAAE,MAAQ,OAAO,oBAAoB,WAAa,CAAC,GAAG,MAAQ,MAAY,CAAE,MAAQ,CACxF,iBAAmB,6BAA6B,EAC7C,KAAM,MAAS,CACd,MAAM,MAAQ,UAAU,aAAa,IAAI,EAMzC,GALA,QAAQ,IAAI,kGAEA,KAAM,KAAK,OAAQ,MAAO,UAAU,aAAa,EAAE,MAAM,EAGjE,MACF,GAAI,CACF,OAAO,cAAc,IAAI,YAAY,wBACnC,CAAE,OAAQ,CAAE,IAAK,KAAK,IAAI,GAAK,GAAK,EAAE,EAAE,EAAE,OAAO,OAAO,CAAE,CAAE,CAAC,CAAC,CAClE,MAAY,CAAC,CAEjB,CAAC,EACA,MAAO,GAAM,CACZ,QAAQ,KAAK,mHACuD,CAAC,CACvE,CAAC,CACL,CAEA,SAAS,aAAc,CAErB,GADA,kBAAkB,EACd,OAAO,cAAgB,SAAS,aAAe,WAAY,CAC7D,KAAK,EACL,MACF,CACA,IAAI,QAAU,GACd,MAAM,MAAQ,IAAM,CAAO,UAAW,QAAU,GAAM,KAAK,EAAK,EAChE,SAAS,iBAAiB,mBAAoB,KAAK,EAEnD,WAAW,MAAO,IAAI,CACxB,CACA,YAAY",
  "names": ["cx", "cy", "def", "D", "main", "w", "root", "t", "s", "m", "v", "c", "cd", "nd", "myRange", "grp", "url", "CK", "mainEl", "p", "obstacles", "liveCabs", "at", "others", "x", "y", "insetNow", "back", "fwd", "x1", "y1", "wall", "oL", "ox", "oy", "order", "b", "_bin", "room", "api", "escAttr", "fr", "h", "head", "basket", "g", "closeBtn", "run", "kept"]
}
