// MDC strategic map — dark basemap, glowing arcs, submarine cable, pulsing pins.
// Pins: hover → preview tooltip, click → pinned detail card with site photo (opens Google satellite)
window.MDCMap = function MDCMap({ id='mdc-map', sites=window.MDC_SITES,
                                  pinnedKey=null, onPin=()=>{}, mapStyle='dark',
                                  showFuture=false }) {
  const ref = React.useRef(null);
  const mapRef = React.useRef(null);
  const markersRef = React.useRef({});
  const futureLayerRef = React.useRef(null);
  const [hovered, setHovered] = React.useState(null);

  React.useEffect(() => {
    if (!ref.current || mapRef.current) return;
    const map = L.map(ref.current, {
      center:[22,-98], zoom:5, zoomControl:false, scrollWheelZoom:true,
      attributionControl:false, minZoom:3, maxZoom:9, zoomSnap:.25, preferCanvas:true,
    });
    mapRef.current = map;

    // Basemap
    if (mapStyle==='dark') {
      L.tileLayer('https://{s}.basemaps.cartocdn.com/dark_nolabels/{z}/{x}/{y}{r}.png',
        { subdomains:'abcd', maxZoom:19 }).addTo(map);
    } else {
      L.tileLayer('https://{s}.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}{r}.png',
        { subdomains:'abcd', maxZoom:19 }).addTo(map);
    }

    // Custom sparse city labels — only the cities that matter contextually for MDC's footprint.
    const CITIES = [
      // USA
      { name:'Ashburn, VA',     lat: 39.04, lng: -77.49 },
      { name:'Atlanta, GA',     lat: 33.75, lng: -84.39 },
      { name:'Dallas, TX',      lat: 32.78, lng: -96.80 },
      { name:'Phoenix, AZ',     lat: 33.45, lng: -112.07 },
      { name:'Los Angeles, CA', lat: 34.05, lng: -118.24 },
      { name:'San Diego, CA',   lat: 32.72, lng: -117.16 },
      { name:'Tucson, AZ',      lat: 32.22, lng: -110.93 },
      // Mexico
      { name:'Tijuana',         lat: 32.51, lng: -117.04 },
      { name:'Hermosillo',      lat: 29.07, lng: -110.96 },
      { name:'Chihuahua',       lat: 28.63, lng: -106.07 },
      { name:'Guadalajara',     lat: 20.67, lng: -103.35 },
      { name:'Monterrey',       lat: 25.67, lng: -100.31 },
      { name:'Durango',         lat: 24.02, lng: -104.65 },
      { name:'San Luis Potosí', lat: 22.15, lng: -100.98 },
    ];
    CITIES.forEach(c => {
      // A tiny dot marker
      L.circleMarker([c.lat, c.lng], {
        radius: 1.5, color: '#64748b', fillColor: '#64748b',
        fillOpacity: .9, weight: 1, interactive: false,
      }).addTo(map);
      // The label to the right of the dot
      L.marker([c.lat, c.lng], {
        interactive: false, keyboard: false,
        icon: L.divIcon({
          className: '',
          html: `<div class="mdc-ctx-city">${c.name}</div>`,
          iconSize: [130, 14], iconAnchor: [-6, 7]
        })
      }).addTo(map);
    });

    // Connecting arcs between sites — removed per request (was the cyan dashed web)

    // Submarine cable
    const ver = sites.find(s=>s.key==='ver'), cun = sites.find(s=>s.key==='cun');
    if (ver && cun) {
      // Manta cable system — actual route (per submarinecablemap.com)
      // Central branching unit in the Caribbean off the Yucatán channel,
      // trunks radiating to: San Blas FL, North Miami FL (branch),
      // Cancún MX, Veracruz MX, María Chiquita Panama, + a stubbed spur toward Colombia.
      // Central branching unit — placed in the deep Yucatán Channel,
      // roughly midway between Cabo San Antonio (Cuba) and Cabo Catoche (MX).
      const HUB = [21.80, -85.60];
      const COL_STUB = [10.39, -75.51]; // Cartagena, Colombia landing (future extension)

      const mantaLandings = [
        { key:'mt-sb',  name:'San Blas, FL',         lat: 29.68, lng: -85.36, country:'USA' },
        { key:'mt-nmi', name:'North Miami, FL',      lat: 25.89, lng: -80.19, country:'USA · branch' },
        { key:'mt-cun', name:'Cancún, MX',           lat: 21.16, lng: -86.85, country:'MX', mdc:true },
        { key:'mt-ver', name:'Veracruz, MX',         lat: 19.17, lng: -96.13, country:'MX · southern Gulf', mdc:true },
        { key:'mt-mc',  name:'María Chiquita, PA',   lat:  9.47, lng: -79.66, country:'Panama · Caribbean coast' },
      ];

      // Submarine routes — every waypoint is in open water.
      // Densified so the path still stays offshore when zoomed in.
      const trunks = [
        // San Blas, FL → HUB : south through deep Gulf of Mexico, arcing east
        // around the Campeche Bank into the Yucatán Channel.
        { path: [
          [29.68,-85.36],[29.20,-85.60],[28.40,-86.00],[27.40,-86.20],
          [26.20,-86.10],[24.80,-85.90],[23.60,-85.75],[22.60,-85.65],HUB
        ]},

        // North Miami, FL → HUB : south-west down the Straits of Florida centerline
        // (between FL and the Bahamas/Cuba), then west through the Old Bahama Channel
        // keeping ~35 km off Cuba's north coast, then into the Yucatán Channel.
        { path: [
          [25.89,-80.19],[25.40,-79.90],[24.70,-79.70],[23.90,-79.70],
          [23.50,-80.40],[23.35,-81.50],[23.25,-82.60],[23.10,-83.60],
          [22.80,-84.40],[22.40,-85.10],HUB
        ]},

        // Cancún → HUB : short offshore run north-east from Cancún,
        // staying in the Yucatán Channel.
        { path: [
          [21.16,-86.85],[21.35,-86.60],[21.55,-86.30],[21.70,-86.00],HUB
        ]},

        // Veracruz → HUB : north-east across Bay of Campeche, around the
        // NORTH tip of the Yucatán peninsula (offshore of the Campeche Bank),
        // then east into the Yucatán Channel.
        { path: [
          [19.17,-96.13],[19.80,-95.60],[20.60,-94.80],[21.30,-93.80],
          [22.00,-92.40],[22.40,-90.80],[22.50,-89.20],[22.40,-87.80],
          [22.20,-86.60],HUB
        ]},

        // HUB → María Chiquita, PA : south-east across the Cayman Trough,
        // threading between Grand Cayman and Jamaica, then south well EAST
        // of Nicaragua's Miskito Cays and Providencia, finally west to Colón.
        { path: [
          HUB,[20.80,-84.60],[19.60,-83.40],[18.40,-82.40],[17.20,-81.60],
          [15.80,-80.90],[14.20,-80.40],[12.60,-80.00],[11.20,-79.90],
          [10.30,-79.85],[9.70,-79.75],[9.47,-79.66]
        ]},
      ];

      // Stubbed future branch — splits off the south-Caribbean trunk near
      // Providencia and runs east along Colombia's Caribbean shelf to Cartagena.
      const stubBranch = [
        [12.60,-80.00],[12.10,-78.60],[11.60,-77.40],[11.10,-76.40],
        [10.70,-75.80],COL_STUB
      ];

      trunks.forEach(({path}) => {
        L.polyline(path,{color:'#074FEA',weight:8,opacity:.18,lineCap:'round'}).addTo(map);
        L.polyline(path,{color:'#60a5fa',weight:2,opacity:.85,dashArray:'10,6'}).addTo(map);
      });
      // Stub = faded + dotted to indicate reserved/future
      L.polyline(stubBranch,{color:'#60a5fa',weight:1.5,opacity:.45,dashArray:'2,6'}).addTo(map);
      // Stub end marker
      L.circleMarker(COL_STUB, {
        radius:4, color:'#60a5fa', fillColor:'rgba(96,165,250,.2)',
        fillOpacity:.6, weight:1.5, opacity:.75, dashArray:'3,3',
      }).addTo(map).bindTooltip(
        `<div style="font-family:Poppins;font-size:11px;font-weight:600;color:white">Cartagena, CO</div>
         <div style="font-family:Poppins;font-size:10px;color:#94a3b8">Reserved branching unit — future extension</div>`,
        { direction:'top', offset:[0,-6], className:'mdc-manta-tip' }
      );

      // Central hub marker (the branching unit itself)
      L.circleMarker(HUB, {
        radius: 4, color:'#60a5fa', fillColor:'#0a0e1a',
        fillOpacity: .9, weight: 2,
      }).addTo(map).bindTooltip(
        `<div style="font-family:Poppins;font-size:11px;font-weight:600;color:white">Manta Branching Unit</div>
         <div style="font-family:Poppins;font-size:10px;color:#94a3b8">Yucatán Channel — central splice</div>`,
        { direction:'top', offset:[0,-6], className:'mdc-manta-tip' }
      );

      // Landing-point markers
      mantaLandings.forEach(p => {
        const isMDC = p.mdc;
        L.circleMarker([p.lat,p.lng], {
          radius: isMDC ? 5 : 4,
          color: isMDC ? '#22d3ee' : '#60a5fa',
          fillColor: isMDC ? '#22d3ee' : '#60a5fa',
          fillOpacity: .95,
          weight: 2,
          className: 'mdc-manta-landing',
        }).addTo(map).bindTooltip(
          `<div style="font-family:Poppins;font-size:11px;font-weight:600;color:white">${p.name}</div>
           <div style="font-family:Poppins;font-size:10px;color:#94a3b8">${p.country} — Manta landing</div>`,
          { direction:'top', offset:[0,-6], className:'mdc-manta-tip' }
        );

        // Persistent city-name label on the map (skip Cancún + Veracruz — they already have MDC site labels)
        if (!isMDC) {
          const labelIcon = L.divIcon({
            className:'',
            html:`<div class="mdc-manta-citylabel">${p.name}</div>`,
            iconSize:[140,16], iconAnchor:[-8, 8] // offset to the right of the pin
          });
          L.marker([p.lat,p.lng], { icon:labelIcon, interactive:false, keyboard:false }).addTo(map);
        }
      });

      // Cartagena stub — also labeled
      const cartIcon = L.divIcon({
        className:'',
        html:`<div class="mdc-manta-citylabel mdc-manta-citylabel--muted">Cartagena, CO</div>`,
        iconSize:[140,16], iconAnchor:[-8, 8]
      });
      L.marker(COL_STUB, { icon:cartIcon, interactive:false, keyboard:false }).addTo(map);

      // Clickable Manta cable label
      const mantaIcon = L.divIcon({
        className:'',
        html:`<div class="mdc-cable-label mdc-cable-clickable">∿ Manta Submarine Cable System</div>`,
        iconSize:[230,24], iconAnchor:[115,12]
      });
      // Place label near the hub so it's central to the spoke pattern
      const mantaMarker = L.marker([17.5,-84.5],{ icon:mantaIcon, riseOnHover:true }).addTo(map);
      mantaMarker.on('mouseover', () => setHovered('manta'));
      mantaMarker.on('mouseout',  () => setHovered(h => h==='manta' ? null : h));
      mantaMarker.on('click',     (e) => { L.DomEvent.stopPropagation(e); onPin('manta'); });
      markersRef.current['manta'] = mantaMarker;
    }

    // Click on bare map closes any pinned card
    map.on('click', () => onPin(null));

    // Pins
    sites.forEach(site => {
      const ragC = window.MDC_RAG[site.rag];
      const typeC = window.MDC_TYPES[site.type].color;
      const isActive = site.status==='active';
      // Pulse halo only on sites under distress (amber/red RAG).
      // Green pins stay calm — solid, reassuring. Amber/red pulse to draw the eye.
      const shouldPulse = site.rag === 'amber' || site.rag === 'red';
      const html = `
        <div class="mdc-pin" data-site="${site.key}">
          ${shouldPulse ? `<div class="mdc-pin-pulse" style="background:${ragC};"></div>` : ''}
          <div class="mdc-pin-core" style="background:${typeC};border-color:${ragC};">
            <span class="mdc-pin-num">P${site.priority}</span>
          </div>
          ${isActive ? '<div class="mdc-pin-live"></div>' : ''}
        </div>`;
      const icon = L.divIcon({ className:'mdc-pin-wrap', html,
                                iconSize:[40,40], iconAnchor:[20,20] });
      const marker = L.marker([site.lat,site.lng],{icon,riseOnHover:true}).addTo(map);
      marker.on('mouseover', () => setHovered(site.key));
      marker.on('mouseout',  () => setHovered(h => h===site.key ? null : h));
      marker.on('click',     (e) => { L.DomEvent.stopPropagation(e); onPin(site.key); });
      markersRef.current[site.key] = marker;

      // Persistent city-name label under each Px pin
      const cityName = site.name.split(',')[0];
      const labelIcon = L.divIcon({
        className: '',
        html: `<div class="mdc-pin-citylabel">${cityName}</div>`,
        iconSize: [120, 14], iconAnchor: [60, -14],
      });
      L.marker([site.lat, site.lng], {
        icon: labelIcon, interactive: false, keyboard: false,
        zIndexOffset: -100,
      }).addTo(map);
    });

    setTimeout(()=>map.invalidateSize(), 80);
    return () => { map.remove(); mapRef.current = null; };
  }, [mapStyle]);

  // Selection highlight
  React.useEffect(() => {
    Object.entries(markersRef.current).forEach(([k,m]) => {
      const el = m.getElement();
      if (el) el.classList.toggle('mdc-pin-selected', k===pinnedKey);
    });
  }, [pinnedKey]);

  // Future sites layer — toggleable
  React.useEffect(() => {
    if (!mapRef.current) return;
    // Tear down any existing future layer
    if (futureLayerRef.current) {
      futureLayerRef.current.forEach(m => mapRef.current.removeLayer(m));
      futureLayerRef.current = null;
    }
    if (!showFuture || !window.MDC_FUTURE) return;
    const layer = [];
    window.MDC_FUTURE.forEach(site => {
      const html = `
        <div class="mdc-future-pin">
          <div class="mdc-future-core">
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="3">
              <path d="M12 5v14M5 12h14"/>
            </svg>
          </div>
          <div class="mdc-future-label">${site.name.split(',')[0]}</div>
        </div>`;
      const icon = L.divIcon({ className:'mdc-future-wrap', html,
                                iconSize:[28,28], iconAnchor:[14,14] });
      const marker = L.marker([site.lat, site.lng], { icon, riseOnHover:true }).addTo(mapRef.current);
      marker.bindTooltip(
        `<div style="font-family:Poppins;font-size:12px;font-weight:700;color:#c4b5fd">${site.name}</div>
         <div style="font-family:Poppins;font-size:10.5px;color:#94a3b8;margin-top:2px;max-width:220px;">${site.rationale}</div>
         <div style="font-family:Poppins;font-size:9px;color:#a78bfa;margin-top:4px;letter-spacing:.5px;text-transform:uppercase;font-weight:700;">Projected Future Site</div>`,
        { direction:'top', offset:[0,-8], className:'mdc-future-tip' }
      );
      layer.push(marker);
    });
    futureLayerRef.current = layer;
  }, [showFuture]);

  // Compute screen coords of pinned/hovered marker for overlay cards
  const [coords, setCoords] = React.useState({});
  React.useEffect(() => {
    const upd = () => {
      if (!mapRef.current) return;
      const out = {};
      Object.entries(markersRef.current).forEach(([k,m]) => {
        const pt = mapRef.current.latLngToContainerPoint(m.getLatLng());
        out[k] = { x: pt.x, y: pt.y };
      });
      setCoords(out);
    };
    if (mapRef.current) {
      upd();
      mapRef.current.on('move zoom', upd);
      return () => mapRef.current && mapRef.current.off('move zoom', upd);
    }
  }, []);

  const MANTA = {
    key:'manta', isCable:true,
    name:'Manta Submarine Cable System',
    code:'CABLE-MANTA', type:'CLH',
    operator:'Telxius / Meta (co-build)',
    landings:'San Blas FL · North Miami FL · Cancún MX · Veracruz MX · María Chiquita PA',
    capacity:'~190 Tbps design · 8 fiber pairs',
    rfs:'2027 (planned RFS)',
    length:'~5,200 km · Gulf + Caribbean spoke system',
    note:'Central branching unit in the Yucatán Channel. Trunks radiate to San Blas FL, North Miami FL (branch), Cancún, Veracruz, and María Chiquita Panama, with a reserved stub toward Cartagena Colombia. MDC CLH sites (Cancún + Veracruz) anchor the Mexico landings.',
    photo:'https://images.unsplash.com/photo-1583244532610-2a234e5cc1f5?w=800&q=70',
  };

  const previewSite = hovered && hovered !== pinnedKey
    ? (hovered === 'manta' ? MANTA : sites.find(s=>s.key===hovered))
    : null;
  const pinnedSite = pinnedKey
    ? (pinnedKey === 'manta' ? MANTA : sites.find(s=>s.key===pinnedKey))
    : null;

  return (
    <div style={{ position:'relative', width:'100%', height:'100%' }}>
      <div ref={ref} id={id} style={{ width:'100%', height:'100%' }} />
      {/* Hover preview (small tooltip) */}
      {previewSite && coords[previewSite.key] && (
        <HoverPreview site={previewSite} pos={coords[previewSite.key]} />
      )}
      {/* Pinned detail card (large, persistent) */}
      {pinnedSite && coords[pinnedSite.key] && (
        <PinnedCard site={pinnedSite} pos={coords[pinnedSite.key]}
                    onClose={()=>onPin(null)} />
      )}
    </div>
  );
};

// ── Hover preview ──
function HoverPreview({ site, pos }) {
  const style = {
    position:'absolute', left: pos.x + 22, top: pos.y - 20,
    zIndex:700, pointerEvents:'none'
  };
  if (site.isCable) {
    return (
      <div style={style} className="mdc-hover">
        <div style={{ display:'flex', alignItems:'center', gap:6, marginBottom:4 }}>
          <span style={{ fontSize:14, color:'#60a5fa' }}>∿</span>
          <span style={{ fontSize:13, fontWeight:700, color:'white' }}>{site.name}</span>
        </div>
        <div style={{ fontSize:11, color:'#cbd5e1' }}>{site.capacity}</div>
        <div style={{ fontSize:10.5, color:'#94a3b8', marginTop:2 }}>RFS {site.rfs}</div>
        <div style={{ marginTop:6, fontSize:10, color:'#94a3b8', fontStyle:'italic' }}>Click to open</div>
      </div>
    );
  }
  const t = window.MDC_TYPES[site.type];
  return (
    <div style={style} className="mdc-hover">
      <div className="mdc-cl-head">
        <span className="mdc-cl-pri">P{site.priority}</span>
        <span className="mdc-cl-name">{site.name}</span>
        <span className="mdc-cl-type" style={{ background:t.color+'22', color:t.color }}>{site.type}</span>
      </div>
      <div className="mdc-cl-meta">
        <span className="mdc-cl-mw">{site.mw} MW</span>
        <span className="mdc-cl-sep">·</span>
        <span className="mdc-cl-anchor">{site.anchor}</span>
        <span className="mdc-cl-sep">·</span>
        <span className="mdc-cl-tgt">{site.target}</span>
      </div>
      <div style={{ marginTop:6, fontSize:10, color:'#94a3b8', fontStyle:'italic' }}>Click pin to open</div>
    </div>
  );
}

// ── Pinned detail card (rich, draggable + resizable) ──
function PinnedCard({ site, pos, onClose }) {
  // Decide side on first render; then user controls it
  const [box, setBox] = React.useState(() => {
    const parent = document.querySelector('.mdc-map-host');
    const leftSide = parent ? (pos.x > parent.clientWidth / 2) : false;
    const w = 340, h = 520;
    const left = leftSide ? Math.max(12, pos.x - 26 - w) : Math.min((parent?.clientWidth||9999) - w - 12, pos.x + 26);
    const top = Math.max(12, Math.min(pos.y - 120, (window.innerHeight - h - 40)));
    return { left, top, w, h };
  });
  // Only recompute when switching to a different site (key changes via React remount)

  const ref = React.useRef(null);

  // Resize observer → update height so scroll works properly
  React.useEffect(() => {
    if (!ref.current) return;
    const ro = new ResizeObserver(entries => {
      for (const e of entries) {
        setBox(b => ({ ...b, w: Math.round(e.contentRect.width + 2), h: Math.round(e.contentRect.height + 2) }));
      }
    });
    ro.observe(ref.current);
    return () => ro.disconnect();
  }, []);

  const onDragStart = (e) => {
    // only drag from the handle (photo area), not buttons/links/body content
    if (e.target.closest('.mdc-pinned-close') || e.target.closest('.mdc-pinned-photo-label')) return;
    const startX = e.clientX, startY = e.clientY;
    const startL = box.left, startT = box.top;
    const onMove = (ev) => {
      const parent = ref.current?.parentElement;
      const maxL = parent ? parent.clientWidth - 80 : 9999;
      const maxT = parent ? parent.clientHeight - 60 : 9999;
      setBox(b => ({ ...b,
        left: Math.max(0, Math.min(maxL, startL + ev.clientX - startX)),
        top:  Math.max(0, Math.min(maxT, startT + ev.clientY - startY)),
      }));
    };
    const onUp = () => {
      window.removeEventListener('mousemove', onMove);
      window.removeEventListener('mouseup', onUp);
    };
    window.addEventListener('mousemove', onMove);
    window.addEventListener('mouseup', onUp);
    e.preventDefault();
  };

  const stop = e => e.stopPropagation();
  const BASE_W = 340;
  const scale = Math.max(1, Math.min(2.2, box.w / BASE_W));
  const style = {
    position:'absolute', left: box.left, top: box.top, width: box.w, height: box.h,
    zIndex: 800,
    display:'flex', flexDirection:'column',
  };
  const zoomStyle = { zoom: scale, flex:1, overflow:'auto', display:'flex', flexDirection:'column' };

  if (site.isCable) {
    return (
      <div ref={ref} style={style} className="mdc-pinned mdc-pinned-rs" onClick={stop} onMouseDown={stop}>
        <div style={zoomStyle}>
        <div className="mdc-pinned-photo"
             onMouseDown={onDragStart}
             style={{ backgroundImage:`linear-gradient(180deg, rgba(15,23,41,0) 50%, rgba(15,23,41,.95)), url(${site.photo})`, cursor:'grab' }}>
          <div className="mdc-pinned-photo-label" style={{ background:'rgba(96,165,250,.92)' }}>
            <span style={{ fontSize:13 }}>∿</span> Submarine Cable
          </div>
          <div className="mdc-pinned-close" onClick={e=>{e.preventDefault(); e.stopPropagation(); onClose();}}>✕</div>
        </div>
        <div className="mdc-pinned-body">
          <div className="mdc-pinned-head">
            <span className="mdc-pinned-type" style={{ background:'#60a5fa', color:'white' }}>CABLE</span>
            <span style={{ marginLeft:'auto', fontSize:10, color:'#60a5fa', fontWeight:600 }}>Planned RFS 2027</span>
          </div>
          <div className="mdc-pinned-name">{site.name}</div>
          <div className="mdc-pinned-code">{site.code} · Subsea Infrastructure</div>

          <div className="mdc-pinned-stats">
            <div><span>Capacity</span><b>{site.capacity}</b></div>
            <div><span>Length</span><b>{site.length}</b></div>
            <div><span>RFS</span><b>{site.rfs}</b></div>
            <div><span>Operator</span><b>{site.operator}</b></div>
          </div>

          <div className="mdc-pinned-anchor">
            <div style={{ fontSize:9.5, color:'#94a3b8', textTransform:'uppercase', letterSpacing:.6,
                           fontWeight:600, marginBottom:3 }}>Landings</div>
            <div style={{ color:'white', fontSize:13, fontWeight:600 }}>{site.landings}</div>
          </div>

          {site.note && <div className="mdc-pinned-note">{site.note}</div>}
        </div>
        </div>
      </div>
    );
  }

  const t = window.MDC_TYPES[site.type];
  const ragC = window.MDC_RAG[site.rag];
  const mapLink = site.earthUrl || `https://www.google.com/maps/@${site.lat},${site.lng},17z/data=!3m1!1e3`;
  const linkLabel = site.earthUrl ? (site.earthLabel || 'View Parcel on Google Earth') : 'View on Google Satellite';
  const linkIcon = site.earthUrl ? 'earth' : 'cube';
  const photo = site.parcelImg
    ? site.parcelImg
    : `https://tile.openstreetmap.org/${7}/${Math.floor((site.lng+180)/360*128)}/${Math.floor((1-Math.log(Math.tan(site.lat*Math.PI/180)+1/Math.cos(site.lat*Math.PI/180))/Math.PI)/2*128)}.png`;

  return (
    <div ref={ref} style={style} className="mdc-pinned mdc-pinned-rs" onClick={stop} onMouseDown={stop}>
      <div style={zoomStyle}>
      <div className="mdc-pinned-photo"
           onMouseDown={onDragStart}
           style={{ backgroundImage: site.parcelImg
                      ? `linear-gradient(180deg, rgba(15,23,41,0) 70%, rgba(15,23,41,.75)), url(${photo})`
                      : `linear-gradient(180deg, rgba(15,23,41,0) 60%, rgba(15,23,41,.9)), url(${photo})`,
                    backgroundSize: site.parcelImg ? 'cover' : undefined,
                    cursor:'grab' }}>
        <a href={mapLink} target="_blank" rel="noopener noreferrer"
           className="mdc-pinned-photo-label"
           onClick={e=>{
             e.stopPropagation();
             // Force top-level open so X-Frame-Options-protected pages
             // (like Google Earth) don't get blocked when we're in an iframe.
             e.preventDefault();
             const w = window.open(mapLink, '_blank', 'noopener,noreferrer');
             if (!w) {
               // pop-up blocked → fall back to top-frame navigation
               try { window.top.location.href = mapLink; } catch(_) { window.location.href = mapLink; }
             }
           }}
           onMouseDown={e=>e.stopPropagation()}>
          {site.earthUrl ? (
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
              <circle cx="12" cy="12" r="10"/>
              <path d="M2 12h20"/>
              <path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/>
            </svg>
          ) : (
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
              <path d="M12 2l9 4.5v11L12 22 3 17.5v-11z"/><path d="M3 6.5L12 11l9-4.5"/><path d="M12 11v11"/>
            </svg>
          )}
          {linkLabel} →
        </a>
        {site.parcelName && (
          <div style={{ position:'absolute', top:10, left:12, fontSize:10, fontWeight:600,
                         color:'#fff', letterSpacing:.3, textShadow:'0 1px 3px rgba(0,0,0,.8)',
                         background:'rgba(10,14,26,.55)', padding:'3px 8px', borderRadius:6,
                         backdropFilter:'blur(4px)' }}>
            {site.parcelName}
          </div>
        )}
        <div className="mdc-pinned-close" onClick={e=>{e.preventDefault(); e.stopPropagation(); onClose();}} onMouseDown={e=>e.stopPropagation()}>✕</div>
      </div>
      <div className="mdc-pinned-body">
        <div className="mdc-pinned-head">
          <span className="mdc-cl-pri">P{site.priority}</span>
          <span className="mdc-pinned-type" style={{ background:t.color, color:'white' }}>{site.type}</span>
          <span className={`rag-dot rag-${site.rag}`} style={{ marginLeft:'auto' }}/>
          <span style={{ fontSize:10, color:ragC, fontWeight:600 }}>{site.ragLabel}</span>
        </div>
        <div className="mdc-pinned-name">{site.name}</div>
        <div className="mdc-pinned-code">{site.code} · {t.label}</div>

        <div className="mdc-pinned-stats">
          <div><span>MW</span><b>{site.mwCommitted} / {site.mwTarget}</b></div>
          <div><span>Capex</span><b>{site.capex?`$${site.capex}M`:'Operational'}</b></div>
          <div><span>Target</span><b>{site.target}</b></div>
          <div><span>Schedule</span><b style={{ color: window.MDC_RAG[site.scheduleColor] }}>{site.schedule}</b></div>
          <div><span>Permit</span><b style={{ color: window.MDC_RAG[site.permitColor] || '#94a3b8' }}>{site.permit}</b></div>
          <div><span>Power</span><b>{site.powerStatus}</b></div>
        </div>

        <div className="mdc-pinned-anchor">
          <div style={{ fontSize:9.5, color:'#94a3b8', textTransform:'uppercase', letterSpacing:.6,
                         fontWeight:600, marginBottom:3 }}>Anchor</div>
          <div style={{ color:'white', fontSize:13, fontWeight:600 }}>{site.anchor}</div>
          <div style={{ color:'#cbd5e1', fontSize:11, marginTop:2 }}>{site.anchorDetail}</div>
        </div>

        {site.note && (
          <div className="mdc-pinned-note">{site.note}</div>
        )}
      </div>
      </div>
    </div>
  );
}
