/* closeup-map.jsx — v0.4 bone-restyled OSM tile closeup with adaptive zoom
   ============================================================
   Stacked UNDER the world LineMap. Renders real OpenStreetMap tiles
   centered on the pin, then applies a CSS filter to push them into
   bone-toned cartography (no API key, no billing).

   v0.4 changes (May 12 evening):
   - Zoom adapts to project bracket: XS=18 (single building),
     S=17 (small plot), M=16 (block), L=15 (neighborhood), XL=14 (district)
   - Tile source switched from CARTO light_nolabels to light_all
     — labels give spatial context (street names, neighborhood) that
     make the map readable as cartography, not abstract texture
   - Scale indicator now derives from zoom level, not hardcoded
   - Stronger CSS filter via cm-tiles class for cleaner bone register

   Layers:
     - Tile grid (3×3) at zoom from bracket, fetched from CARTO light_all
     - CSS filter applied via .cm-tiles (in site.css)
     - Bone-tone gradient overlay for the gradient request
     - Crosshair + pin marker drawn in SVG on top
     - mono caption foot with attribution
   ============================================================ */

const TILE_SIZE = 256;

/* Bracket → zoom level. Higher number = closer view.
   Tuned so the visible frame shows context appropriate to bracket size. */
const ZOOM_BY_BRACKET = {
  XS: 18, /* single building, 30m frame */
  S: 17,  /* small plot, 60m frame */
  M: 16,  /* full block, 120m frame */
  L: 15,  /* neighborhood, 250m frame */
  XL: 14, /* district, 500m frame */
};
const DEFAULT_ZOOM = 16;

/* Scale indicator: approximate horizontal distance across the visible
   frame (768px) at each zoom level. Earth circumference / 2^z * 3 tiles
   visible. Values rounded for editorial legibility. */
const SCALE_BY_ZOOM = {
  18: '~150m ACROSS',
  17: '~300m ACROSS',
  16: '~600m ACROSS',
  15: '~1.2km ACROSS',
  14: '~2.5km ACROSS',
};

const lng2tx = (lng, z) => Math.floor((lng + 180) / 360 * Math.pow(2, z));
const lat2ty = (lat, z) => {
  const r = lat * Math.PI / 180;
  return Math.floor((1 - Math.log(Math.tan(r) + 1 / Math.cos(r)) / Math.PI) / 2 * Math.pow(2, z));
};
const lng2px = (lng, z) => (lng + 180) / 360 * Math.pow(2, z) * TILE_SIZE;
const lat2py = (lat, z) => {
  const r = lat * Math.PI / 180;
  return (1 - Math.log(Math.tan(r) + 1 / Math.cos(r)) / Math.PI) / 2 * Math.pow(2, z) * TILE_SIZE;
};

const RHB_CARTO_KEY = 'cb1_3pb9_1_ca870eb7f26a04ac4b75090c';

const CloseupMap = ({ pin, bracket }) => {
  /* Derive zoom from bracket. Falls back to default if bracket unknown. */
  const z = (bracket && ZOOM_BY_BRACKET[bracket]) || DEFAULT_ZOOM;
  const scaleLabel = SCALE_BY_ZOOM[z] || '~600m ACROSS';

  if (!pin) {
    return (
      <div className="cm cm-empty">
        <div className="cm-l mono">◆ CLOSEUP · BONE-TONED · WAITING FOR PIN</div>
        <div className="cm-empty-body">
          <div className="cm-empty-cross">
            <svg viewBox="0 0 200 200" preserveAspectRatio="xMidYMid meet">
              <defs>
                <radialGradient id="cm-empty-grad" cx="50%" cy="50%" r="60%">
                  <stop offset="0%" stopColor="rgba(31,31,29,0.04)" />
                  <stop offset="100%" stopColor="rgba(31,31,29,0)" />
                </radialGradient>
              </defs>
              <rect width="200" height="200" fill="url(#cm-empty-grad)" />
              <g stroke="rgba(31,31,29,0.18)" strokeWidth="0.4" fill="none">
                {[40, 80, 120, 160].map(v => <line key={`h${v}`} x1="0" y1={v} x2="200" y2={v} />)}
                {[40, 80, 120, 160].map(v => <line key={`v${v}`} x1={v} y1="0" x2={v} y2="200" />)}
              </g>
              <g stroke="rgba(31,31,29,0.45)" strokeWidth="0.6" fill="none">
                <line x1="100" y1="80" x2="100" y2="120" />
                <line x1="80" y1="100" x2="120" y2="100" />
                <circle cx="100" cy="100" r="14" strokeDasharray="2 2" />
              </g>
            </svg>
          </div>
          <div className="cm-empty-cap mono">◆ DROP A PIN ABOVE · THE CLOSEUP APPEARS</div>
        </div>
      </div>
    );
  }

  const pinPxX = lng2px(pin.lng, z);
  const pinPxY = lat2py(pin.lat, z);
  const tileX = lng2tx(pin.lng, z);
  const tileY = lat2ty(pin.lat, z);

  /* 3×3 grid centered on pin's tile — CartoDB Voyager (lighter than
     light_all but retains label hierarchy). CC-licensed, hotlink OK. */
  const tiles = [];
  for (let dy = -1; dy <= 1; dy++) {
    for (let dx = -1; dx <= 1; dx++) {
      const tx = tileX + dx;
      const ty = tileY + dy;
      const max = Math.pow(2, z);
      if (tx < 0 || tx >= max || ty < 0 || ty >= max) continue;
      const sub = ['a','b','c','d'][(Math.abs(tx + ty)) % 4];
      tiles.push({
        tx, ty,
        /* Sept 2026: CARTO now requires a free key on raster basemaps. Key is
           domain-restricted to our hosts, so it is safe client-side. Raster is
           being retired; vector migration is a logged later task. */
        url: `https://${sub}.basemaps.cartocdn.com/rastertiles/light_all/${z}/${tx}/${ty}.png?key=${RHB_CARTO_KEY}`,
        left: (tx * TILE_SIZE) - (pinPxX - 384),
        top:  (ty * TILE_SIZE) - (pinPxY - 256),
      });
    }
  }

  return (
    <div className="cm">
      <div className="cm-l mono">◆ CLOSEUP · BONE-TONED · OSM · Z{z}{bracket ? ` · BRACKET ${bracket}` : ''}</div>
      <div className="cm-frame">
        <div className="cm-tiles">
          {tiles.map(t => (
            <img
              key={`${t.tx}-${t.ty}`}
              src={t.url}
              alt=""
              loading="lazy"
              referrerPolicy="no-referrer"
              style={{
                position: 'absolute',
                left: `${t.left}px`,
                top: `${t.top}px`,
                width: `${TILE_SIZE}px`,
                height: `${TILE_SIZE}px`,
                pointerEvents: 'none',
              }}
            />
          ))}
        </div>
        <div className="cm-grad"></div>
        <svg className="cm-overlay" viewBox="0 0 768 512" preserveAspectRatio="xMidYMid meet">
          <g stroke="rgba(31,31,29,0.30)" strokeWidth="0.5" fill="none" strokeDasharray="3 3">
            <line x1="384" y1="0" x2="384" y2="512" />
            <line x1="0" y1="256" x2="768" y2="256" />
          </g>
          <g>
            <circle cx="384" cy="256" r="22" fill="none" stroke="rgba(201,107,90,0.85)" strokeWidth="1.5" />
            <circle cx="384" cy="256" r="36" fill="none" stroke="rgba(201,107,90,0.45)" strokeWidth="0.8" strokeDasharray="2 3" />
            <circle cx="384" cy="256" r="4" fill="#C96B5A" stroke="#1F1F1D" strokeWidth="0.8" />
            <line x1="384" y1="252" x2="384" y2="232" stroke="#1F1F1D" strokeWidth="0.8" />
            <text x="390" y="240" fontSize="10" fill="#1F1F1D" fontFamily="JetBrains Mono" letterSpacing="0.08em">SITE</text>
          </g>
          <g fontFamily="JetBrains Mono" fontSize="8" fill="rgba(31,31,29,0.55)" letterSpacing="0.10em">
            <text x="12" y="20">◆ Z{z}</text>
            <text x="12" y="500">◆ {pin.lat.toFixed(4)}, {pin.lng.toFixed(4)}</text>
            <text x="700" y="500" textAnchor="end">◆ {scaleLabel}</text>
          </g>
        </svg>
      </div>
      <div className="cm-foot mono">
        ◆ {pin.display.length > 80 ? pin.display.slice(0, 80) + '…' : pin.display} · © OpenStreetMap · © CARTO
      </div>
    </div>
  );
};

Object.assign(window, { CloseupMap });
