All files / web/src/components/toys/euclid EuclidMap.tsx

0% Statements 0/975
0% Branches 0/1
0% Functions 0/1
0% Lines 0/975

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
'use client'

import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import {
  IMPLEMENTED_PROPS,
  getNodeStatus,
  getVisibleNodes,
  computeLayout,
  getProposition,
  getPrerequisites,
} from './data/propositionGraph'
import type { NodeStatus, LayoutEdge } from './data/propositionGraph'

// ---------------------------------------------------------------------------
// Colors and sizing
// ---------------------------------------------------------------------------

const NODE_W = 130
const NODE_H = 48 // layout computation height (matches pre-computed layout)
const RENDER_H = 120 // rendered height (room for diagram + text)
const Y_SCALE = 1.5 // stretch Y to add vertical breathing room between taller nodes
const NODE_RX = 8
const ICON_SIZE = 44 // geometric thumbnail area
const PREVIEW_THUMB_W = 100 // real construction preview width (wider to match canvas aspect ratio)
const PREVIEW_THUMB_H = 56 // real construction preview height

const STATUS_STYLES: Record<
  NodeStatus,
  {
    fill: string
    stroke: string
    textColor: string
    strokeDash?: string
    opacity: number
  }
> = {
  completed: {
    fill: 'rgba(16, 185, 129, 0.12)',
    stroke: '#10b981',
    textColor: '#065f46',
    opacity: 1,
  },
  available: {
    fill: 'rgba(59, 130, 246, 0.08)',
    stroke: '#3b82f6',
    textColor: '#1e40af',
    opacity: 1,
  },
  locked: {
    fill: 'rgba(156, 163, 175, 0.08)',
    stroke: '#9ca3af',
    textColor: '#6b7280',
    opacity: 0.7,
  },
  'coming-soon': {
    fill: 'rgba(156, 163, 175, 0.04)',
    stroke: '#d1d5db',
    textColor: '#9ca3af',
    strokeDash: '4 3',
    opacity: 1,
  },
}

// ---------------------------------------------------------------------------
// Geometric thumbnails per proposition / thematic block
// ---------------------------------------------------------------------------

import { usePropPreviews } from './render/usePropPreviews'
import { PropThumbnail } from './render/PropThumbnailSvg'
import { ToyDebugPanel, DebugSlider } from '../ToyDebugPanel'
import { useVisualDebugSafe } from '@/contexts/VisualDebugContext'

// ---------------------------------------------------------------------------
// Edge helpers — simplify, trim to node borders, smooth Catmull-Rom spline
// ---------------------------------------------------------------------------

type Pt = { x: number; y: number }

/**
 * Remove near-collinear intermediate points (perpendicular distance < epsilon).
 * Keeps first and last points unconditionally.
 */
function simplifyPoints(pts: Pt[], epsilon: number): Pt[] {
  if (pts.length <= 2) return pts
  const result = [pts[0]]
  for (let i = 1; i < pts.length - 1; i++) {
    const prev = result[result.length - 1]
    const curr = pts[i]
    const next = pts[i + 1]
    const dx = next.x - prev.x
    const dy = next.y - prev.y
    const len = Math.sqrt(dx * dx + dy * dy)
    if (len === 0) continue
    const dist = Math.abs((curr.x - prev.x) * dy - (curr.y - prev.y) * dx) / len
    if (dist > epsilon) {
      result.push(curr)
    }
  }
  result.push(pts[pts.length - 1])
  return result
}

/**
 * Find where a ray from a rect's center toward an external point
 * intersects the rect border. Handles all 4 sides.
 */
function rectBorderPoint(cx: number, cy: number, w: number, h: number, px: number, py: number): Pt {
  const dx = px - cx
  const dy = py - cy
  if (dx === 0 && dy === 0) return { x: cx, y: cy + h / 2 }

  const halfW = w / 2
  const halfH = h / 2
  let t = Infinity

  // Side intersections (left/right)
  if (dx !== 0) {
    const tSide = (dx > 0 ? halfW : -halfW) / dx
    if (tSide > 0 && Math.abs(dy * tSide) <= halfH) t = Math.min(t, tSide)
  }
  // Top/bottom intersections
  if (dy !== 0) {
    const tVert = (dy > 0 ? halfH : -halfH) / dy
    if (tVert > 0 && Math.abs(dx * tVert) <= halfW) t = Math.min(t, tVert)
  }

  return { x: cx + dx * t, y: cy + dy * t }
}

/**
 * Trim edge endpoints to node borders using ray-rect intersection.
 * Handles edges exiting/entering from any side of the node.
 */
function trimToBorders(pts: Pt[], srcX: number, srcY: number, tgtX: number, tgtY: number): Pt[] {
  if (pts.length < 2) return pts
  const result = pts.map((p) => ({ ...p }))

  // Trim start → source border (ray from center toward next point)
  result[0] = rectBorderPoint(srcX, srcY, NODE_W, RENDER_H, result[1].x, result[1].y)

  // Trim end → target border (ray from center toward prev point)
  const last = result.length - 1
  result[last] = rectBorderPoint(
    tgtX,
    tgtY,
    NODE_W,
    RENDER_H,
    result[last - 1].x,
    result[last - 1].y
  )

  return result
}

/**
 * Convert points to SVG path using Catmull-Rom → cubic bezier.
 */
function pointsToPath(pts: Pt[]): string {
  if (pts.length === 0) return ''
  if (pts.length === 1) return `M ${pts[0].x} ${pts[0].y}`
  if (pts.length === 2) {
    return `M ${pts[0].x} ${pts[0].y} L ${pts[1].x} ${pts[1].y}`
  }

  let d = `M ${pts[0].x} ${pts[0].y}`
  for (let i = 0; i < pts.length - 1; i++) {
    const p0 = pts[i - 1] ?? pts[0]
    const p1 = pts[i]
    const p2 = pts[i + 1]
    const p3 = pts[i + 2] ?? pts[pts.length - 1]

    const cp1x = p1.x + (p2.x - p0.x) / 6
    const cp1y = p1.y + (p2.y - p0.y) / 6
    const cp2x = p2.x - (p3.x - p1.x) / 6
    const cp2y = p2.y - (p3.y - p1.y) / 6

    d += ` C ${cp1x} ${cp1y}, ${cp2x} ${cp2y}, ${p2.x} ${p2.y}`
  }
  return d
}

// ---------------------------------------------------------------------------
// Component
// ---------------------------------------------------------------------------

interface EuclidMapProps {
  completed: Set<number>
  onSelectProp: (propId: number) => void
  onSelectPlayground?: () => void
  hideHeader?: boolean
  showAll?: boolean
  onToggleShowAll?: () => void
}

export function EuclidMap({
  completed,
  onSelectProp,
  onSelectPlayground,
  hideHeader,
  showAll: showAllProp,
  onToggleShowAll,
}: EuclidMapProps) {
  // showAll can be controlled externally (foundations page) or internally (main map page)
  const [showAllInternal, setShowAllInternal] = useState(false)
  const showAll = showAllProp ?? showAllInternal
  const setShowAll = onToggleShowAll ?? (() => setShowAllInternal((prev) => !prev))
  const [hoveredNode, setHoveredNode] = useState<number | null>(null)
  const [comingSoonOpacity, setComingSoonOpacity] = useState(1)
  const [rowWindow, setRowWindow] = useState(3) // how many rows from center to fit in viewport
  const previews = usePropPreviews()
  const { isVisualDebugEnabled } = useVisualDebugSafe()

  const completedCount = completed.size
  const totalImplemented = IMPLEMENTED_PROPS.size

  // Compute visible nodes + layout (dagre-powered)
  const visibleIds = useMemo(() => getVisibleNodes(completed, showAll), [completed, showAll])

  const { nodes: layout, edges } = useMemo(() => {
    const raw = computeLayout(visibleIds)
    // Scale Y coordinates to add vertical breathing room
    const scaledNodes = new Map<number, { x: number; y: number; level: number }>()
    for (const [id, pos] of raw.nodes) {
      scaledNodes.set(id, { x: pos.x, y: pos.y * Y_SCALE, level: pos.level })
    }
    const scaledEdges = raw.edges.map((e) => ({
      ...e,
      points: e.points.map((p) => ({ x: p.x, y: p.y * Y_SCALE })),
    }))
    return { nodes: scaledNodes, edges: scaledEdges }
  }, [visibleIds])

  // Compute SVG viewBox (static — used for normal map page)
  const viewBox = useMemo(() => {
    if (layout.size === 0) return '0 0 400 300'
    let minX = Infinity,
      maxX = -Infinity,
      minY = Infinity,
      maxY = -Infinity
    for (const pos of layout.values()) {
      const halfW = NODE_W / 2
      const halfH = RENDER_H / 2
      minX = Math.min(minX, pos.x - halfW)
      maxX = Math.max(maxX, pos.x + halfW)
      minY = Math.min(minY, pos.y - halfH)
      maxY = Math.max(maxY, pos.y + halfH)
    }
    // Also account for edge routing points
    for (const edge of edges) {
      for (const pt of edge.points) {
        minX = Math.min(minX, pt.x - 5)
        maxX = Math.max(maxX, pt.x + 5)
        minY = Math.min(minY, pt.y - 5)
        maxY = Math.max(maxY, pt.y + 5)
      }
    }
    const padX = 20
    const padY = 20
    const contentW = maxX - minX + padX * 2
    const contentH = maxY - minY + padY * 2
    const w = Math.max(contentW, 400)
    const offsetX = minX - padX - (w - contentW) / 2
    return `${offsetX} ${minY - padY} ${w} ${contentH}`
  }, [layout, edges])

  // -------------------------------------------------------------------------
  // Scroll-driven viewport (foundations page only)
  // The SVG is sticky in the viewport; scrolling pans/zooms through the graph.
  //
  // 1:1 finger tracking: the adaptive zoom changes the scale (pixels per SVG
  // unit) as you scroll. Without correction, content moves faster when zoomed
  // in and slower when zoomed out, making it feel decoupled from the finger.
  //
  // Fix: pre-compute a cumulative integral of vbW over progress. This warps
  // the progress→vbY mapping so each scroll pixel produces exactly 1 screen
  // pixel of apparent vertical movement regardless of the current zoom level.
  // The spacer height is sized to match the total screen-pixel travel.
  // -------------------------------------------------------------------------

  // Per-row metadata for scroll-driven viewport
  const rowMeta = useMemo(() => {
    if (!hideHeader || layout.size === 0) return null
    const byY = new Map<number, number[]>()
    for (const [, pos] of layout) {
      let xs = byY.get(pos.y)
      if (!xs) {
        xs = []
        byY.set(pos.y, xs)
      }
      xs.push(pos.x)
    }
    const rows: { y: number; centerX: number; width: number }[] = []
    for (const [y, xs] of byY) {
      const minX = Math.min(...xs)
      const maxX = Math.max(...xs)
      rows.push({ y, centerX: (minX + maxX) / 2, width: maxX - minX + NODE_W })
    }
    rows.sort((a, b) => a.y - b.y)

    // Global center X for horizontal panning
    let gMinX = Infinity,
      gMaxX = -Infinity
    for (const pos of layout.values()) {
      gMinX = Math.min(gMinX, pos.x)
      gMaxX = Math.max(gMaxX, pos.x)
    }
    return { rows, globalCenterX: (gMinX + gMaxX) / 2 }
  }, [layout, hideHeader])

  const stickyRef = useRef<HTMLDivElement>(null)
  const containerRef = useRef<HTMLDivElement>(null)
  const scrollContainerRef = useRef<HTMLElement | null>(null)
  const [scrollViewBox, setScrollViewBox] = useState<string | null>(null)
  const [spacerHeight, setSpacerHeight] = useState(0)

  // Cache for the 1:1 scroll mapping (recomputed when layout/container changes)
  const scrollMappingRef = useRef<{
    /** Normalized cumulative integral of vbW: maps progress (0→1) to yFraction (0→1) */
    normalizedCumulative: number[]
    /** Total SVG Y travel from start to end */
    totalYTravel: number
    /** Starting vbY (first row at top of viewport) */
    startVbY: number
    /** Ideal spacer height in CSS pixels for 1:1 tracking */
    idealSpacerPx: number
    /** Cache key to detect when recomputation is needed */
    key: string
  } | null>(null)

  const updateScrollViewBox = useCallback(() => {
    const container = containerRef.current
    const sticky = stickyRef.current
    if (!container || !sticky || !rowMeta || rowMeta.rows.length === 0) return

    const stickyH = sticky.clientHeight
    const stickyW = sticky.clientWidth
    if (stickyH === 0 || stickyW === 0) return

    const { rows } = rowMeta
    const firstY = rows[0].y
    const lastY = rows[rows.length - 1].y
    const aspect = stickyW / stickyH

    // --- Row width computation (unchanged — feeds Catmull-Rom adaptive zoom) ---
    const PAD = 140
    const MIN_VB_W = 280
    const rawWidths = rows.map((r) => Math.max(MIN_VB_W, r.width + PAD))
    const radius = rowWindow - 1
    const rowWidths = rawWidths.map((_, i) => {
      let maxW = rawWidths[i]
      for (let d = 1; d <= radius; d++) {
        if (i - d >= 0) maxW = Math.max(maxW, rawWidths[i - d])
        if (i + d < rawWidths.length) maxW = Math.max(maxW, rawWidths[i + d])
      }
      return maxW
    })
    const rowCenters = rows.map((r) => r.centerX)

    // Catmull-Rom interpolation (reused for both adaptive zoom and mapping)
    const catmullRom = (values: number[], idx: number, u: number) => {
      const p0 = values[Math.max(0, idx - 1)]
      const p1 = values[idx]
      const p2 = values[Math.min(values.length - 1, idx + 1)]
      const p3 = values[Math.min(values.length - 1, idx + 2)]
      const u2 = u * u
      const u3 = u2 * u
      return (
        0.5 *
        (2 * p1 +
          (-p0 + p2) * u +
          (2 * p0 - 5 * p1 + 4 * p2 - p3) * u2 +
          (-p0 + 3 * p1 - 3 * p2 + p3) * u3)
      )
    }

    // Helper: compute vbW at a given progress value
    const vbWAtProgress = (p: number) => {
      const cy = firstY + p * (lastY - firstY)
      let si = 0
      for (let i = 0; i < rows.length - 1; i++) {
        if (rows[i].y <= cy && rows[i + 1].y > cy) {
          si = i
          break
        }
        if (i === rows.length - 2) si = i
      }
      const st =
        rows[si + 1].y === rows[si].y ? 0 : (cy - rows[si].y) / (rows[si + 1].y - rows[si].y)
      return catmullRom(rowWidths, si, st)
    }

    // --- Pre-compute 1:1 scroll mapping (cached, recomputed on layout/resize) ---
    const mappingKey = `${rows.length}-${firstY}-${lastY}-${stickyW}-${stickyH}-${rowWindow}`
    if (!scrollMappingRef.current || scrollMappingRef.current.key !== mappingKey) {
      const N = 200
      // Sample vbW at N+1 progress points and build cumulative integral
      const vbWSamples: number[] = []
      for (let i = 0; i <= N; i++) {
        vbWSamples.push(vbWAtProgress(i / N))
      }

      // Cumulative integral of vbW over progress (trapezoidal rule)
      // This represents how much SVG-Y-displacement each progress increment
      // corresponds to, weighted by zoom level.
      const cumulative: number[] = [0]
      for (let i = 1; i <= N; i++) {
        const avg = (vbWSamples[i - 1] + vbWSamples[i]) / 2
        cumulative.push(cumulative[i - 1] + avg / N)
      }
      const totalIntegral = cumulative[N] // = average vbW

      // Normalize: maps progress (0→1) to yFraction (0→1)
      const normalizedCumulative = cumulative.map((v) => v / totalIntegral)

      // Compute total SVG Y travel
      const vPad = 20
      const startVbY = firstY - RENDER_H / 2 - vPad
      const endVbW = vbWSamples[N]
      const endVbH = endVbW / aspect
      const endVbY = lastY + RENDER_H / 2 + vPad - endVbH
      const totalYTravel = endVbY - startVbY

      // Ideal spacer height: total screen pixels needed for 1:1 tracking
      // d(vbY)/d(scroll) = vbW / containerW, so:
      // totalScroll = totalYTravel * containerW / avgVbW
      const idealSpacerPx = (totalYTravel * stickyW) / totalIntegral

      scrollMappingRef.current = {
        normalizedCumulative,
        totalYTravel,
        startVbY,
        idealSpacerPx,
        key: mappingKey,
      }

      // Update spacer height (will cause a re-render, but only on layout/resize changes)
      setSpacerHeight(Math.max(0, idealSpacerPx))
    }

    const mapping = scrollMappingRef.current!

    // --- Compute scroll progress ---
    // Use the full scroll range of the scroll parent — no containerTop offset.
    // The map is sticky and visible from page load, so it should respond to
    // scrolling from the very first pixel. The ~136px of content above the map
    // (nav padding, tab pills spacer) is part of the scroll travel.
    const scrollParent = scrollContainerRef.current
    let scrollTop: number
    let scrollRange: number
    if (scrollParent) {
      scrollTop = scrollParent.scrollTop
      scrollRange = Math.max(1, scrollParent.scrollHeight - scrollParent.clientHeight)
    } else {
      scrollTop = Math.max(0, -container.getBoundingClientRect().top)
      scrollRange = Math.max(1, document.documentElement.scrollHeight - window.innerHeight)
    }
    const progress = Math.min(1, scrollTop / scrollRange)

    // --- Adaptive zoom (unchanged — Catmull-Rom for vbW and centerX) ---
    const currentY = firstY + progress * (lastY - firstY)
    let segIdx = 0
    for (let i = 0; i < rows.length - 1; i++) {
      if (rows[i].y <= currentY && rows[i + 1].y > currentY) {
        segIdx = i
        break
      }
      if (i === rows.length - 2) segIdx = i
    }
    const t =
      rows[segIdx + 1].y === rows[segIdx].y
        ? 0
        : (currentY - rows[segIdx].y) / (rows[segIdx + 1].y - rows[segIdx].y)

    const vbW = catmullRom(rowWidths, segIdx, t)
    const centerX = catmullRom(rowCenters, segIdx, t)
    const vbH = vbW / aspect

    // --- 1:1 tracked vbY via lookup table ---
    // Interpolate the normalized cumulative to get yFraction at this progress
    const N = mapping.normalizedCumulative.length - 1
    const pScaled = progress * N
    const lo = Math.min(Math.floor(pScaled), N - 1)
    const hi = lo + 1
    const frac = pScaled - lo
    const yFraction =
      mapping.normalizedCumulative[lo] * (1 - frac) + mapping.normalizedCumulative[hi] * frac

    const vbY = mapping.startVbY + yFraction * mapping.totalYTravel

    setScrollViewBox(`${centerX - vbW / 2} ${vbY} ${vbW} ${vbH}`)
  }, [rowMeta, rowWindow])

  // Find the actual scroll container and attach scroll listener
  useEffect(() => {
    if (!hideHeader || !rowMeta) return
    // Walk up from the container to find the scrollable ancestor
    let el: HTMLElement | null = containerRef.current
    while (el) {
      const style = getComputedStyle(el)
      if (style.overflowY === 'auto' || style.overflowY === 'scroll') {
        scrollContainerRef.current = el
        break
      }
      el = el.parentElement
    }
    const scrollTarget = scrollContainerRef.current ?? window
    scrollTarget.addEventListener('scroll', updateScrollViewBox, {
      passive: true,
    } as EventListenerOptions)
    window.addEventListener('resize', updateScrollViewBox, { passive: true })
    // Initial computation
    updateScrollViewBox()
    return () => {
      scrollTarget.removeEventListener('scroll', updateScrollViewBox)
      window.removeEventListener('resize', updateScrollViewBox)
    }
  }, [hideHeader, rowMeta, updateScrollViewBox])

  // Tooltip info for hovered locked node
  const hoveredInfo = useMemo(() => {
    if (hoveredNode === null) return null
    const status = getNodeStatus(hoveredNode, completed)
    if (status !== 'locked') return null
    const deps = getPrerequisites(hoveredNode)
    const missing = deps.filter((d) => !completed.has(d))
    return { propId: hoveredNode, missing }
  }, [hoveredNode, completed])

  // SVG content shared between scroll-driven and static viewport modes
  const svgContent = (
    <>
      {/* Arrowhead marker */}
      <defs>
        <marker id="arrowhead" markerWidth="4" markerHeight="3" refX="3.5" refY="1.5" orient="auto">
          <polygon points="0 0, 4 1.5, 0 3" fill="#cbd5e1" fillOpacity={0.6} />
        </marker>
      </defs>

      {/* Edges — simplified, trimmed, with arrowheads */}
      {edges.map((edge) => {
        const srcPos = layout.get(edge.from)
        const tgtPos = layout.get(edge.to)
        if (!srcPos || !tgtPos) return null

        const trimmed = trimToBorders(edge.points, srcPos.x, srcPos.y, tgtPos.x, tgtPos.y)
        const simplified = simplifyPoints(trimmed, 4)
        const d = pointsToPath(simplified)
        if (!d) return null

        return (
          <path
            key={`${edge.from}-${edge.to}`}
            data-element="map-edge"
            d={d}
            fill="none"
            stroke="#cbd5e1"
            strokeWidth={3}
            strokeOpacity={0.4}
            markerEnd="url(#arrowhead)"
          />
        )
      })}

      {/* Nodes */}
      {visibleIds.map((id) => {
        const pos = layout.get(id)
        if (!pos) return null
        const status = getNodeStatus(id, completed)
        const style = STATUS_STYLES[status]
        const prop = getProposition(id)
        const isClickable = status === 'completed' || status === 'available'
        const titleLines = prop ? wrapTitle(prop.title, 20) : []

        // Vertical layout: thumbnail | number | title lines
        const topY = pos.y - RENDER_H / 2
        const thumbCenterY = topY + 5 // top of thumbnail area
        const thumbH = previews.has(id) ? PREVIEW_THUMB_H : ICON_SIZE
        const numberY = topY + thumbH + 12
        const titleStartY = numberY + 13

        return (
          <g
            key={id}
            data-element="map-node"
            data-prop-id={id}
            data-status={status}
            style={{
              cursor: isClickable ? 'pointer' : 'default',
              opacity: status === 'coming-soon' ? comingSoonOpacity : style.opacity,
            }}
            onClick={() => isClickable && onSelectProp(id)}
            onMouseEnter={() => setHoveredNode(id)}
            onMouseLeave={() => setHoveredNode(null)}
          >
            {/* Opaque background so edges are occluded behind node */}
            <rect
              x={pos.x - NODE_W / 2}
              y={topY}
              width={NODE_W}
              height={RENDER_H}
              rx={NODE_RX}
              fill="#FAFAF0"
            />
            <rect
              x={pos.x - NODE_W / 2}
              y={topY}
              width={NODE_W}
              height={RENDER_H}
              rx={NODE_RX}
              fill={style.fill}
              stroke={style.stroke}
              strokeWidth={status === 'available' ? 2 : 1.5}
              strokeDasharray={style.strokeDash}
            />

            {/* Geometric thumbnail — real construction preview or generic icon */}
            {prop &&
              (previews.get(id) ? (
                <image
                  href={previews.get(id)}
                  x={pos.x - PREVIEW_THUMB_W / 2}
                  y={thumbCenterY}
                  width={PREVIEW_THUMB_W}
                  height={PREVIEW_THUMB_H}
                  preserveAspectRatio="xMidYMid meet"
                />
              ) : (
                <g transform={`translate(${pos.x - ICON_SIZE / 2}, ${thumbCenterY})`}>
                  <PropThumbnail propId={id} block={prop.block} color={style.textColor} />
                </g>
              ))}

            {/* Type badge (P = Problem/construction, T = Theorem) */}
            {prop && (
              <g data-element="type-badge">
                <rect
                  x={pos.x - NODE_W / 2 + 4}
                  y={topY + 4}
                  width={14}
                  height={14}
                  rx={3}
                  fill={
                    prop.type === 'construction' ? 'rgba(245,158,11,0.15)' : 'rgba(99,102,241,0.12)'
                  }
                />
                <text
                  x={pos.x - NODE_W / 2 + 11}
                  y={topY + 11}
                  fontSize={8}
                  fontWeight={700}
                  fontFamily="system-ui, sans-serif"
                  fill={prop.type === 'construction' ? '#d97706' : '#4f46e5'}
                  textAnchor="middle"
                  dominantBaseline="central"
                >
                  {prop.type === 'construction' ? 'P' : 'T'}
                </text>
              </g>
            )}

            {/* Checkmark for completed */}
            {status === 'completed' && (
              <text
                x={pos.x + NODE_W / 2 - 14}
                y={topY + 10}
                fontSize={11}
                fill="#10b981"
                textAnchor="middle"
                dominantBaseline="central"
                fontWeight={700}
              >

              </text>
            )}

            {/* Prop number */}
            <text
              x={pos.x}
              y={numberY}
              fontSize={12}
              fontWeight={700}
              fontFamily="Georgia, serif"
              fill={style.textColor}
              textAnchor="middle"
              dominantBaseline="central"
            >
              I.{id}
            </text>

            {/* Wrapped title (up to 3 lines) */}
            {titleLines.map((line, i, arr) => (
              <text
                key={i}
                x={pos.x}
                y={titleStartY + i * 10}
                fontSize={8}
                fontFamily="Georgia, serif"
                fill={style.textColor}
                textAnchor="middle"
                dominantBaseline="central"
                opacity={0.65}
              >
                {i === arr.length - 1 && line.length >= 20 ? line.slice(0, 19) + '…' : line}
              </text>
            ))}
          </g>
        )
      })}
    </>
  )

  return (
    <div
      data-component="euclid-map"
      style={{
        width: '100%',
        ...(hideHeader ? {} : { height: '100%' }),
        display: 'flex',
        flexDirection: 'column',
        background: '#FAFAF0',
      }}
    >
      {/* Header bar */}
      {!hideHeader && (
        <div
          data-element="map-header"
          style={{
            padding: '16px 24px',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            borderBottom: '1px solid rgba(203, 213, 225, 0.4)',
            flexShrink: 0,
          }}
        >
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 12 }}>
            <span
              style={{
                fontSize: 18,
                fontWeight: 700,
                fontFamily: 'Georgia, serif',
                color: '#1e293b',
              }}
            >
              Book I
            </span>
            <span
              style={{
                fontSize: 13,
                color: '#6b7280',
                fontFamily: 'Georgia, serif',
              }}
            >
              {completedCount} of {totalImplemented} complete
            </span>
          </div>

          <div style={{ display: 'flex', gap: 8 }}>
            {onSelectPlayground && (
              <button
                type="button"
                data-action="open-playground"
                onClick={onSelectPlayground}
                style={{
                  padding: '6px 14px',
                  fontSize: 13,
                  fontWeight: 500,
                  fontFamily: 'system-ui, sans-serif',
                  background: 'rgba(245, 158, 11, 0.08)',
                  color: '#d97706',
                  border: '1px solid #fbbf24',
                  borderRadius: 8,
                  cursor: 'pointer',
                  transition: 'all 0.15s',
                }}
              >
                Playground
              </button>
            )}
            <button
              type="button"
              data-action="toggle-show-all"
              onClick={setShowAll}
              style={{
                padding: '6px 14px',
                fontSize: 13,
                fontWeight: 500,
                fontFamily: 'system-ui, sans-serif',
                background: showAll ? 'rgba(59, 130, 246, 0.08)' : 'transparent',
                color: showAll ? '#3b82f6' : '#6b7280',
                border: `1px solid ${showAll ? '#93c5fd' : '#d1d5db'}`,
                borderRadius: 8,
                cursor: 'pointer',
                transition: 'all 0.15s',
              }}
            >
              {showAll ? 'Show available' : 'Show all 48'}
            </button>
          </div>
        </div>
      )}

      {/* SVG map */}
      {hideHeader ? (
        /* Scroll-driven viewport: sticky SVG + scroll spacer */
        <div ref={containerRef} data-element="map-viewport-scroll" style={{ position: 'relative' }}>
          <div
            ref={stickyRef}
            style={{
              position: 'sticky',
              top: 'calc(var(--app-nav-height, 0px) + 3rem)',
              height: 'calc(100vh - var(--app-nav-height, 0px) - 3rem)',
            }}
          >
            <svg
              data-element="map-svg"
              viewBox={scrollViewBox ?? viewBox}
              preserveAspectRatio="xMidYMid meet"
              style={{ display: 'block', width: '100%', height: '100%', overflow: 'visible' }}
            >
              {svgContent}
            </svg>
          </div>
          {/* Spacer sized for 1:1 finger tracking — each scroll pixel produces
              exactly 1 screen pixel of apparent content movement. Height is computed
              from the integral of vbW over the adaptive zoom curve. */}
          <div style={{ height: spacerHeight }} />
        </div>
      ) : (
        /* Normal scrollable map */
        <div
          data-element="map-viewport"
          style={{ flex: 1, minHeight: 0, overflow: 'auto', padding: '24px 20px' }}
        >
          <svg
            data-element="map-svg"
            viewBox={viewBox}
            style={{ display: 'block', width: '100%', maxWidth: 900, margin: '0 auto' }}
          >
            {svgContent}
          </svg>
        </div>
      )}

      {/* Legend — type badges */}
      {!hideHeader && (
        <div
          data-element="map-legend"
          style={{
            display: 'flex',
            justifyContent: 'center',
            gap: 20,
            padding: '12px 0 4px',
            fontSize: 12,
            fontFamily: 'system-ui, sans-serif',
            color: '#6b7280',
          }}
        >
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
            <span
              style={{
                display: 'inline-flex',
                alignItems: 'center',
                justifyContent: 'center',
                width: 16,
                height: 16,
                borderRadius: 3,
                background: 'rgba(245,158,11,0.15)',
                color: '#d97706',
                fontSize: 9,
                fontWeight: 700,
              }}
            >
              P
            </span>
            Problem (construction)
          </span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
            <span
              style={{
                display: 'inline-flex',
                alignItems: 'center',
                justifyContent: 'center',
                width: 16,
                height: 16,
                borderRadius: 3,
                background: 'rgba(99,102,241,0.12)',
                color: '#4f46e5',
                fontSize: 9,
                fontWeight: 700,
              }}
            >
              T
            </span>
            Theorem
          </span>
        </div>
      )}

      {/* Tooltip for locked nodes */}
      {hoveredInfo && (
        <div
          data-element="map-tooltip"
          style={{
            position: 'absolute',
            bottom: 16,
            left: '50%',
            transform: 'translateX(-50%)',
            background: 'rgba(17, 24, 39, 0.92)',
            color: '#e5e7eb',
            padding: '8px 14px',
            borderRadius: 8,
            fontSize: 12,
            fontFamily: 'system-ui, sans-serif',
            whiteSpace: 'nowrap',
            pointerEvents: 'none',
            zIndex: 10,
          }}
        >
          Requires: {hoveredInfo.missing.map((d) => `I.${d}`).join(', ')}
        </div>
      )}

      <ToyDebugPanel title="Euclid Map">
        <DebugSlider
          label="Coming-soon opacity"
          value={comingSoonOpacity}
          min={0}
          max={1}
          step={0.05}
          onChange={setComingSoonOpacity}
          formatValue={(v) => v.toFixed(2)}
        />
        {hideHeader && (
          <DebugSlider
            label="Row window"
            value={rowWindow}
            min={1}
            max={3}
            step={1}
            onChange={setRowWindow}
            formatValue={(v) => (v === 1 ? '1 (center only)' : `${v} (±${v - 1} rows)`)}
          />
        )}
      </ToyDebugPanel>
    </div>
  )
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/**
 * Word-wrap a title into lines of at most `maxLen` characters.
 * Breaks on word boundaries; returns at most 3 lines.
 */
function wrapTitle(title: string, maxLen: number): string[] {
  if (title.length <= maxLen) return [title]
  const words = title.split(' ')
  const lines: string[] = []
  let current = ''
  for (const word of words) {
    const candidate = current ? `${current} ${word}` : word
    if (candidate.length > maxLen && current) {
      lines.push(current)
      current = word
      if (lines.length >= 3) break
    } else {
      current = candidate
    }
  }
  if (current && lines.length < 3) lines.push(current)
  return lines.slice(0, 3)
}