All files / src/components FloorPlanWebView.tsx

79.11% Statements 125/158
74.8% Branches 95/127
82.75% Functions 24/29
82.51% Lines 118/143

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                                                                                                  1x                                                             27x       2x       1x                             61x 61x 61x 61x 61x 61x 61x   61x   62x 62x 62x 62x         61x 27x 27x   27x 27x 27x 27x   27x           27x 27x 27x 27x 1x 1x     26x 26x 26x   26x 25x 25x 25x   25x 25x   25x 1x         25x 25x           25x 25x 25x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               25x 25x 25x     1x       27x 27x 27x       61x   3x 3x   2x                   2x         2x   1x 1x                                         61x 36x 9x 9x                   9x 1x                     61x 36x   9x 1x 1x 1x                     61x 36x   9x 1x 1x 1x                 8x                 61x   13x   3x     1x 1x             2x 1x 1x 1x                 1x 1x         1x 1x 1x                 1x 1x               61x   61x 27x               34x                       14x 14x 13x 9x 9x                 4x 1x 3x 1x 2x 1x     1x             1x     2x 1x 1x 1x                                   1x                                          
import React, {
  useRef,
  useEffect,
  useImperativeHandle,
  forwardRef,
} from "react";
import { View, StyleSheet, ActivityIndicator, Text } from "react-native";
import { WebView } from "react-native-webview";
import { Asset } from "expo-asset";
import { RoutePoint } from "../types/indoorDirections";
import { BuildingId } from "../data/buildings";
 
export interface PoiMarker {
  x: number;
  y: number;
  id: string;
  displayName: string;
  type: string;
}
 
export interface RoomMarkerData {
  x: number;
  y: number;
  id: string;
}
 
interface FloorPlanWebViewProps {
  buildingId?: BuildingId;
  floorNumber?: string;
  backgroundColor?: string;
  invertSvg?: boolean;
  onPoiTap?: (poi: PoiMarker) => void;
  onRoomTap?: (room: RoomMarkerData) => void;
  routePoints?: RoutePoint[];
  poiData?: PoiMarker[];
  roomData?: RoomMarkerData[];
}
 
export interface FloorPlanWebViewRef {
  drawRoute: (routePoints: RoutePoint[]) => void;
  clearRoute: () => void;
  showRoomMarkers: (
    roomPoints: Array<{ x: number; y: number; id: string }>,
  ) => void;
  hideRoomMarkers: () => void;
  showPois: (pois: PoiMarker[]) => void;
  hidePois: () => void;
}
 
const SVG_ASSETS: Record<string, Record<string, any>> = {
  H: {
    "8": require("../../assets/building_plans/h8.svg"),
    "9": require("../../assets/building_plans/Hall-9.svg"),
    "2": require("../../assets/building_plans/Hall-2.svg"),
    "1": require("../../assets/building_plans/Hall-1.svg"),
  },
  VL: {
    "1": require("../../assets/building_plans/VL-1.svg"),
    "2": require("../../assets/building_plans/VL-2.svg"),
  },
  LB: {
    "2": require("../../assets/building_plans/LB2-n-s.svg"),
    "3": require("../../assets/building_plans/LB3-n-s.svg"),
    "4": require("../../assets/building_plans/LB4-n-s.svg"),
    "5": require("../../assets/building_plans/LB5-n-s.svg"),
  },
  MB: {
    S2: require("../../assets/building_plans/MB-S2.svg"),
    "1": require("../../assets/building_plans/MB-1.svg"),
  },
  CC: {
    "1": require("../../assets/building_plans/CC1.svg"),
  },
  VE: {
    "1": require("../../assets/building_plans/VE-1.svg"),
    "2": require("../../assets/building_plans/VE-2.svg"),
  },
};
 
function getSvgAsset(buildingId: BuildingId, floorNumber: string): any {
  return SVG_ASSETS[buildingId]?.[floorNumber] ?? null;
}
 
function getErrorMessage(error: unknown): string {
  Eif (error instanceof Error) return error.message;
  return String(error);
}
 
const FloorPlanWebView = forwardRef<FloorPlanWebViewRef, FloorPlanWebViewProps>(
  (
    {
      buildingId = "H",
      floorNumber = "8",
      backgroundColor,
      invertSvg = false,
      onPoiTap,
      onRoomTap,
      routePoints: propRoutePoints,
      poiData,
      roomData,
    },
    ref,
  ) => {
    const webViewRef = useRef<WebView>(null);
    const [svgHtml, setSvgHtml] = React.useState<string | null>(null);
    const [isWebViewReady, setIsWebViewReady] = React.useState(false);
    const isWebViewReadyRef = React.useRef(false);
    const pendingRouteRef = React.useRef<RoutePoint[] | null>(null);
    const floorVersionRef = React.useRef(0);
    const loadedFloorRef = React.useRef<string | null>(null);
 
    const markWebViewReady = React.useCallback(
      (ready: boolean, floor?: string) => {
        isWebViewReadyRef.current = ready;
        if (floor !== undefined) loadedFloorRef.current = floor;
        if (!ready) loadedFloorRef.current = null;
        setIsWebViewReady(ready);
      },
      [],
    );
 
    useEffect(() => {
      const version = floorVersionRef.current + 1;
      let cancelled = false;
 
      floorVersionRef.current = version;
      markWebViewReady(false);
      pendingRouteRef.current = null;
      setSvgHtml(null);
 
      Iif (webViewRef.current) {
        webViewRef.current.injectJavaScript(`
          (function() { if (window.clearRoute) window.clearRoute(); true; })();
        `);
      }
 
      const loadSvg = async () => {
        try {
          const asset = getSvgAsset(buildingId, floorNumber);
          if (!asset) {
            console.error("No SVG asset found for", buildingId, floorNumber);
            return;
          }
 
          const assetModule = await Asset.fromModule(asset).downloadAsync();
          Iif (cancelled || version !== floorVersionRef.current) return;
          const uri = assetModule.localUri || assetModule.uri;
 
          const response = await fetch(uri);
          const svgText = await response.text();
          Iif (cancelled || version !== floorVersionRef.current) return;
          const svgMatch = new RegExp(/<svg[\s\S]*<\/svg>/i).exec(svgText);
 
          Eif (svgMatch) {
            let svgContent = svgMatch[0];
 
            if (!svgContent.includes("viewBox")) {
              svgContent = svgContent.replace(
                /<svg/,
                '<svg viewBox="0 0 1024 1024"',
              );
            }
            Eif (!svgContent.includes("preserveAspectRatio")) {
              svgContent = svgContent.replace(
                /<svg/,
                '<svg preserveAspectRatio="xMidYMid meet"',
              );
            }
 
            const bg = backgroundColor ?? "white";
            const svgFilter = invertSvg ? "filter: invert(1);" : "";
            const html = `
            <!DOCTYPE html>
            <html>
              <head>
                <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=10.0, minimum-scale=0.1, user-scalable=yes">
                <style>
                  * { margin: 0; padding: 0; box-sizing: border-box; }
                  html, body {
                    width: 100%;
                    height: 100%;
                    background: ${bg};
                    overflow: auto;
                    -webkit-overflow-scrolling: touch;
                  }
                  body {
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    min-height: 100vh;
                    padding: 10px;
                  }
                  svg { 
                    display: block;
                    max-width: 100vw;
                    max-height: 100vh;
                    width: auto;
                    height: auto;
                    ${svgFilter}
                  }
                </style>
              </head>
              <body>
                ${svgContent}
                <script>
                  (function() {
                    const svg = document.querySelector('svg');
                    if (!svg) return;
                    
                    const SVG_NS = 'http://www.w3.org/2000/svg';
                    
                    // All coordinates are pre-transformed in the backend to root SVG space.
                    // The frontend simply renders them as-is (pass-through).
                    
                    window.drawRouteFromPoints = function(routePoints) {
                      try {
                        if (!routePoints || routePoints.length < 2) return false;
                      
                        
                        ['#routePath', '#routePathOutline', '#startMarker', '#endMarker'].forEach(function(sel) {
                          try {
                            var el = svg.querySelector(sel);
                            if (el && el.parentNode) el.parentNode.removeChild(el);
                          } catch(e) {}
                        });
 
                        // Build SVG path data through all waypoints
                        var pathData = 'M ' + routePoints[0].x + ' ' + routePoints[0].y;
                        for (var i = 1; i < routePoints.length; i++) {
                        pathData += ' L ' + routePoints[i].x + ' ' + routePoints[i].y;
                      }
                      
                        
                        var pathOutline = document.createElementNS(SVG_NS, 'path');
                        pathOutline.id = 'routePathOutline';
                        pathOutline.setAttribute('d', pathData);
                        pathOutline.setAttribute('stroke', '#FFFFFF');
                        pathOutline.setAttribute('stroke-width', '16');
                        pathOutline.setAttribute('fill', 'none');
                        pathOutline.setAttribute('stroke-linecap', 'round');
                        pathOutline.setAttribute('stroke-linejoin', 'round');
                        pathOutline.setAttribute('stroke-dasharray', '4 18');
                        pathOutline.setAttribute('style', 'pointer-events: none;');
                        svg.appendChild(pathOutline);
                        
                        
                        var path = document.createElementNS(SVG_NS, 'path');
                      path.id = 'routePath';
                      path.setAttribute('d', pathData);
                      path.setAttribute('stroke', '#8B1538');
                        path.setAttribute('stroke-width', '12');
                      path.setAttribute('fill', 'none');
                      path.setAttribute('stroke-linecap', 'round');
                      path.setAttribute('stroke-linejoin', 'round');
                        path.setAttribute('stroke-dasharray', '4 18');
                        path.setAttribute('style', 'pointer-events: none;');
                        svg.appendChild(path);
                      
                      
                        var startPoint = routePoints[0];
                        var startMarker = document.createElementNS(SVG_NS, 'g');
                        startMarker.id = 'startMarker';
                        startMarker.setAttribute('transform', 'translate(' + startPoint.x + ',' + startPoint.y + ')');
                        startMarker.setAttribute('style', 'pointer-events: none;');
                        
                        var sc = document.createElementNS(SVG_NS, 'circle');
                        sc.setAttribute('cx', '0'); sc.setAttribute('cy', '-8'); sc.setAttribute('r', '10');
                        sc.setAttribute('fill', '#8B1538'); sc.setAttribute('stroke', '#fff'); sc.setAttribute('stroke-width', '2');
                        startMarker.appendChild(sc);
                        var st = document.createElementNS(SVG_NS, 'path');
                        st.setAttribute('d', 'M -6,2 L 0,18 L 6,2 Z');
                        st.setAttribute('fill', '#8B1538'); st.setAttribute('stroke', '#fff'); st.setAttribute('stroke-width', '2');
                        startMarker.appendChild(st);
                        var sd = document.createElementNS(SVG_NS, 'circle');
                        sd.setAttribute('cx', '0'); sd.setAttribute('cy', '-8'); sd.setAttribute('r', '4');
                        sd.setAttribute('fill', '#fff');
                        startMarker.appendChild(sd);
                        svg.appendChild(startMarker);
                        
                        
                        var endPoint = routePoints[routePoints.length - 1];
                        var endMarker = document.createElementNS(SVG_NS, 'g');
                        endMarker.id = 'endMarker';
                        endMarker.setAttribute('transform', 'translate(' + endPoint.x + ',' + endPoint.y + ')');
                        endMarker.setAttribute('style', 'pointer-events: none;');
                        
                        var ec = document.createElementNS(SVG_NS, 'circle');
                        ec.setAttribute('cx', '0'); ec.setAttribute('cy', '-8'); ec.setAttribute('r', '10');
                        ec.setAttribute('fill', '#8B1538'); ec.setAttribute('stroke', '#fff'); ec.setAttribute('stroke-width', '2');
                        endMarker.appendChild(ec);
                        var et = document.createElementNS(SVG_NS, 'path');
                        et.setAttribute('d', 'M -6,2 L 0,18 L 6,2 Z');
                        et.setAttribute('fill', '#8B1538'); et.setAttribute('stroke', '#fff'); et.setAttribute('stroke-width', '2');
                        endMarker.appendChild(et);
                        var ed = document.createElementNS(SVG_NS, 'circle');
                        ed.setAttribute('cx', '0'); ed.setAttribute('cy', '-8'); ed.setAttribute('r', '4');
                        ed.setAttribute('fill', '#fff');
                        endMarker.appendChild(ed);
                        svg.appendChild(endMarker);
                      
                        return true;
                      } catch (error) {
                        console.error('Error in drawRouteFromPoints:', error);
                        return false;
                      }
                    };
                    
                    window.clearRoute = function() {
                      ['#routePath', '#routePathOutline', '#startMarker', '#endMarker'].forEach(function(sel) {
                        try {
                          var el = svg.querySelector(sel);
                          if (el && el.parentNode) el.parentNode.removeChild(el);
                        } catch(e) {}
                      });
                    };
                    
                    window.showRoomMarkers = function(roomPoints) {
                      try {
                        if (!roomPoints || roomPoints.length === 0) return;
                        window.hideRoomMarkers();
                        
                        var g = document.createElementNS(SVG_NS, 'g');
                        g.id = 'roomMarkersGroup';
                        
                        roomPoints.forEach(function(room) {
                          if (!room || !room.id) return;
                          var x = room.x, y = room.y;
                          if (isNaN(x) || isNaN(y)) return;
                          
                          var sz = 10;
                          var rect = document.createElementNS(SVG_NS, 'rect');
                          rect.setAttribute('x', (x - sz).toString());
                          rect.setAttribute('y', (y - sz).toString());
                          rect.setAttribute('width', (sz * 2).toString());
                          rect.setAttribute('height', (sz * 2).toString());
                          rect.setAttribute('rx', '3'); rect.setAttribute('ry', '3');
                          rect.setAttribute('fill', '#FF6B35');
                          rect.setAttribute('stroke', '#fff'); rect.setAttribute('stroke-width', '1.5');
                          rect.setAttribute('opacity', '0.9');
                          rect.setAttribute('cursor', 'pointer');
                          rect.addEventListener('click', function() {
                            if (window.ReactNativeWebView) {
                              window.ReactNativeWebView.postMessage(JSON.stringify({ type: 'roomTap', room: room }));
                            }
                          });
                          g.appendChild(rect);
                          
                          var icon = document.createElementNS(SVG_NS, 'text');
                          icon.setAttribute('x', x.toString());
                          icon.setAttribute('y', (y + 4).toString());
                          icon.setAttribute('text-anchor', 'middle');
                          icon.setAttribute('font-size', '12'); icon.setAttribute('font-weight', 'bold');
                          icon.setAttribute('fill', '#fff');
                          icon.setAttribute('style', 'pointer-events: none;');
                          icon.textContent = 'R';
                          g.appendChild(icon);
                          
                          var label = document.createElementNS(SVG_NS, 'text');
                          label.setAttribute('x', x.toString());
                          label.setAttribute('y', (y + sz + 12).toString());
                          label.setAttribute('text-anchor', 'middle');
                          label.setAttribute('font-size', '9'); label.setAttribute('font-weight', '700');
                          label.setAttribute('fill', '#333');
                          label.setAttribute('stroke', '#fff'); label.setAttribute('stroke-width', '2');
                          label.setAttribute('paint-order', 'stroke');
                          label.setAttribute('style', 'pointer-events: none;');
                          label.textContent = room.id;
                          g.appendChild(label);
                        });
                        
                        svg.appendChild(g);
                      } catch(e) {
                        console.error('Error showing room markers:', e);
                      }
                    };
                    
                    window.hideRoomMarkers = function() {
                      try {
                        var g = svg.querySelector('#roomMarkersGroup');
                        if (g && g.parentNode) g.parentNode.removeChild(g);
                      } catch(e) {}
                    };
                    
                    // POI icon config per type
                    var POI_ICONS = {
                      'elevator':        { bg: '#FFC107', letter: 'E',  color: '#000' },
                      'stairs':          { bg: '#4CAF50', letter: 'S',  color: '#fff' },
                      'stairs-down':     { bg: '#388E3C', letter: '↓',  color: '#fff' },
                      'stairs-up':       { bg: '#66BB6A', letter: '↑',  color: '#fff' },
                      'emergency-exit':  { bg: '#F44336', letter: '!',  color: '#fff' },
                      'bathroom-men':    { bg: '#2196F3', letter: 'M',  color: '#fff' },
                      'bathroom-women':  { bg: '#E91E63', letter: 'W',  color: '#fff' },
                      'water-fountain':  { bg: '#00BCD4', letter: '💧', color: '#fff' },
                      'computer-station':{ bg: '#9C27B0', letter: 'C',  color: '#fff' },
                      'study-area':      { bg: '#FF9800', letter: 'A',  color: '#fff' },
                      'printer':         { bg: '#607D8B', letter: 'P',  color: '#fff' },
                      'bookshelf':       { bg: '#795548', letter: 'B',  color: '#fff' },
                      'entrance-exit':   { bg: '#FF5722', letter: 'D',  color: '#fff' },
                      'exit':            { bg: '#FF5722', letter: 'D',  color: '#fff' }
                    };
 
                    window.showPois = function(pois) {
                      try {
                        if (!pois || pois.length === 0) return;
                        window.hidePois();
 
                        var g = document.createElementNS(SVG_NS, 'g');
                        g.id = 'poisGroup';
 
                        pois.forEach(function(poi) {
                          var x = poi.x, y = poi.y;
                          if (isNaN(x) || isNaN(y)) return;
                          var icon = POI_ICONS[poi.type] || { bg: '#888', letter: '?', color: '#fff' };
                          var sz = 14;
 
                          var rect = document.createElementNS(SVG_NS, 'rect');
                          rect.setAttribute('x', (x - sz).toString());
                          rect.setAttribute('y', (y - sz).toString());
                          rect.setAttribute('width', (sz * 2).toString());
                          rect.setAttribute('height', (sz * 2).toString());
                          rect.setAttribute('rx', '4'); rect.setAttribute('ry', '4');
                          rect.setAttribute('fill', icon.bg);
                          rect.setAttribute('stroke', '#fff'); rect.setAttribute('stroke-width', '2');
                          rect.setAttribute('opacity', '0.95');
                          rect.setAttribute('cursor', 'pointer');
                          rect.addEventListener('click', function() {
                            if (window.ReactNativeWebView) {
                              window.ReactNativeWebView.postMessage(JSON.stringify({ type: 'poiTap', poi: poi }));
                            }
                          });
                          g.appendChild(rect);
 
                          var txt = document.createElementNS(SVG_NS, 'text');
                          txt.setAttribute('x', x.toString());
                          txt.setAttribute('y', (y + 5).toString());
                          txt.setAttribute('text-anchor', 'middle');
                          txt.setAttribute('font-size', '16'); txt.setAttribute('font-weight', 'bold');
                          txt.setAttribute('fill', icon.color);
                          txt.setAttribute('style', 'pointer-events: none;');
                          txt.textContent = icon.letter;
                          g.appendChild(txt);
 
                          var label = document.createElementNS(SVG_NS, 'text');
                          label.setAttribute('x', x.toString());
                          label.setAttribute('y', (y + sz + 14).toString());
                          label.setAttribute('text-anchor', 'middle');
                          label.setAttribute('font-size', '10'); label.setAttribute('font-weight', '600');
                          label.setAttribute('fill', '#333');
                          label.setAttribute('style', 'pointer-events: none;');
                          label.textContent = poi.displayName || poi.type;
                          g.appendChild(label);
                        });
 
                        svg.appendChild(g);
                      } catch(e) {
                        console.error('Error showing POIs:', e);
                      }
                    };
 
                    window.hidePois = function() {
                      try {
                        var g = svg.querySelector('#poisGroup');
                        if (g && g.parentNode) g.parentNode.removeChild(g);
                      } catch(e) {}
                    };
 
                   
                    if (window.ReactNativeWebView) {
                      window.ReactNativeWebView.postMessage(JSON.stringify({ type: 'webViewReady' }));
                    }
                  })();
                </script>
              </body>
            </html>
          `;
            Iif (cancelled || version !== floorVersionRef.current) return;
            setSvgHtml(html);
            markWebViewReady(false);
          }
        } catch (error) {
          console.error("Error loading SVG:", getErrorMessage(error));
        }
      };
 
      loadSvg();
      return () => {
        cancelled = true;
      };
    }, [buildingId, floorNumber, backgroundColor, invertSvg, markWebViewReady]);
 
    const executeDrawRoute = React.useCallback(
      (routePoints: RoutePoint[], version: number, retryCount = 0) => {
        Iif (version !== floorVersionRef.current) return;
        if (!loadedFloorRef.current) return;
 
        Iif (!webViewRef.current) {
          if (retryCount < 3) {
            setTimeout(
              () => executeDrawRoute(routePoints, version, retryCount + 1),
              500,
            );
          }
          return;
        }
 
        Iif (!isWebViewReadyRef.current) {
          pendingRouteRef.current = routePoints;
          return;
        }
 
        if (!routePoints || routePoints.length === 0) return;
 
        const pointsJson = JSON.stringify(routePoints);
        webViewRef.current.injectJavaScript(`
      (function() {
        if (typeof window.drawRouteFromPoints === 'function') {
          try {
            var result = window.drawRouteFromPoints(${pointsJson});
            if (window.ReactNativeWebView) {
              window.ReactNativeWebView.postMessage(JSON.stringify({
                type: 'routeDrawn', success: result, pointCount: ${routePoints.length}
              }));
            }
          } catch (e) {
            console.error('Error in drawRouteFromPoints:', e);
          }
        }
        true;
      })();
    `);
      },
      [],
    );
 
    React.useEffect(() => {
      if (isWebViewReady && loadedFloorRef.current === floorNumber) {
        const version = floorVersionRef.current;
        Iif (pendingRouteRef.current) {
          const pendingRoute = pendingRouteRef.current;
          pendingRouteRef.current = null;
          setTimeout(() => {
            if (
              version === floorVersionRef.current &&
              isWebViewReadyRef.current
            )
              executeDrawRoute(pendingRoute, version, 0);
          }, 300);
        } else if (propRoutePoints && propRoutePoints.length > 0) {
          setTimeout(() => {
            if (
              version === floorVersionRef.current &&
              isWebViewReadyRef.current
            )
              executeDrawRoute(propRoutePoints, version, 0);
          }, 300);
        }
      }
    }, [isWebViewReady, propRoutePoints, executeDrawRoute, floorNumber]);
 
    React.useEffect(() => {
      if (!isWebViewReady || !webViewRef.current) return;
 
      if (roomData && roomData.length > 0) {
        const roomsJson = JSON.stringify(roomData);
        setTimeout(() => {
          webViewRef.current?.injectJavaScript(`
          (function() {
            try { if (typeof window.showRoomMarkers === 'function') window.showRoomMarkers(${roomsJson}); }
            catch(e) { console.error('Error auto-showing rooms:', e); }
            true;
          })();
        `);
        }, 300);
      }
    }, [isWebViewReady, roomData]);
 
    React.useEffect(() => {
      if (!isWebViewReady || !webViewRef.current) return;
 
      if (poiData && poiData.length > 0) {
        const poisJson = JSON.stringify(poiData);
        setTimeout(() => {
          webViewRef.current?.injectJavaScript(`
          (function() {
            try { if (typeof window.showPois === 'function') window.showPois(${poisJson}); }
            catch(e) { console.error('Error auto-showing POIs:', e); }
            true;
          })();
        `);
        }, 400);
      } else {
        webViewRef.current?.injectJavaScript(`
        (function() {
          if (typeof window.hidePois === 'function') window.hidePois();
          true;
        })();
      `);
      }
    }, [isWebViewReady, poiData]);
 
    useImperativeHandle(
      ref,
      () => ({
        drawRoute: (routePoints: RoutePoint[]) => {
          executeDrawRoute(routePoints, floorVersionRef.current);
        },
        clearRoute: () => {
          Iif (!webViewRef.current) return;
          webViewRef.current.injectJavaScript(`
        (function() { if (window.clearRoute) window.clearRoute(); true; })();
      `);
        },
        showRoomMarkers: (
          roomPoints: Array<{ x: number; y: number; id: string }>,
        ) => {
          if (!webViewRef.current || !roomPoints || roomPoints.length === 0)
            return;
          const roomPointsJson = JSON.stringify(roomPoints);
          webViewRef.current.injectJavaScript(`
        (function() {
          try { if (typeof window.showRoomMarkers === 'function') window.showRoomMarkers(${roomPointsJson}); }
          catch(e) { console.error('Error in showRoomMarkers:', e); }
          true;
        })();
      `);
        },
        hideRoomMarkers: () => {
          Iif (!webViewRef.current) return;
          webViewRef.current.injectJavaScript(`
        (function() { if (typeof window.hideRoomMarkers === 'function') window.hideRoomMarkers(); true; })();
      `);
        },
        showPois: (pois: PoiMarker[]) => {
          Iif (!webViewRef.current || !isWebViewReady) return;
          const poisJson = JSON.stringify(pois);
          webViewRef.current.injectJavaScript(`
        (function() {
          try { if (typeof window.showPois === 'function') window.showPois(${poisJson}); }
          catch(e) { console.error('Error in showPois:', e); }
          true;
        })();
      `);
        },
        hidePois: () => {
          Iif (!webViewRef.current) return;
          webViewRef.current.injectJavaScript(`
        (function() { if (typeof window.hidePois === 'function') window.hidePois(); true; })();
      `);
        },
      }),
      [isWebViewReady],
    );
 
    const bgColor = backgroundColor ?? "white";
 
    if (!svgHtml) {
      return (
        <View style={[styles.loadingContainer, { backgroundColor: bgColor }]}>
          <ActivityIndicator size="large" color="#4285F4" />
          <Text style={styles.loadingText}>Loading floor plan...</Text>
        </View>
      );
    }
 
    return (
      <View style={styles.container}>
        <WebView
          key={`${buildingId}-${floorNumber}`}
          ref={webViewRef}
          source={{ html: svgHtml }}
          style={[styles.webView, { backgroundColor: bgColor }]}
          scalesPageToFit={true}
          bounces={true}
          scrollEnabled={true}
          javaScriptEnabled={true}
          onMessage={(event) => {
            try {
              const data = JSON.parse(event.nativeEvent.data);
              if (data.type === "webViewReady") {
                markWebViewReady(true, floorNumber);
                Iif (pendingRouteRef.current) {
                  const pendingRoute = pendingRouteRef.current;
                  const version = floorVersionRef.current;
                  pendingRouteRef.current = null;
                  setTimeout(
                    () => executeDrawRoute(pendingRoute, version, 0),
                    100,
                  );
                }
              } else if (data.type === "poiTap" && onPoiTap && data.poi) {
                onPoiTap(data.poi as PoiMarker);
              } else if (data.type === "roomTap" && onRoomTap && data.room) {
                onRoomTap(data.room as RoomMarkerData);
              } else if (data.type === "routeDrawError") {
                console.error("Route draw error:", data.message);
              }
            } catch (error) {
              console.error(
                "Failed to parse WebView message:",
                getErrorMessage(error),
              );
            }
          }}
          onError={(syntheticEvent) => {
            console.error("WebView error:", syntheticEvent.nativeEvent);
          }}
          onLoadEnd={() => {
            setTimeout(() => {
              Eif (!isWebViewReadyRef.current) {
                markWebViewReady(true, floorNumber);
                Iif (pendingRouteRef.current) {
                  const pendingRoute = pendingRouteRef.current;
                  const version = floorVersionRef.current;
                  pendingRouteRef.current = null;
                  setTimeout(
                    () => executeDrawRoute(pendingRoute, version, 0),
                    100,
                  );
                }
              }
            }, 500);
          }}
        />
      </View>
    );
  },
);
 
const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  webView: {
    flex: 1,
    backgroundColor: "#FFFFFF",
  },
  loadingContainer: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
  loadingText: {
    marginTop: 12,
    fontSize: 16,
    color: "#757575",
  },
});
 
export default FloorPlanWebView;