// Crown Heights map — driven by REAL latitude/longitude coordinates.
// All landmarks, street lines, and 770 are positioned by their actual
// geographic coordinates and projected into SVG space using a simple
// equirectangular projection (with cos-latitude correction so the
// north-south scale matches east-west at this latitude).
//
// Bounding box covers Crown Heights from Eastern Pkwy down past Empire Blvd,
// Washington Ave on the west to Buffalo Ave on the east.

function CrownHeightsMap({ p, serif, hebFont }) {
  // ── Geographic bounds (lat north-up, lng east-positive) ──────────────────
  const BOUNDS = {
    n: 40.6810, // north edge — north of Eastern Parkway
    s: 40.6580, // south edge — south of Empire Blvd / Lincoln Terrace
    w: -73.9620, // west edge — Washington Ave area
    e: -73.9180, // east edge — Buffalo Ave area
  };

  // SVG canvas — keep aspect roughly matching geographic aspect.
  // At lat ~40.67, 1° lng ≈ 0.76 × 1° lat in horizontal distance.
  // (n−s) lat span in km × 111 ≈ 2.55 km tall
  // (e−w) lng span in km × 111 × cos(lat) ≈ 3.66 km wide
  // Aspect ≈ 1.43 → use 2000 × 1400.
  const W = 2000, H = 1400;

  // Equirectangular projection with cos-latitude correction.
  // Project(lat, lng) → { x, y } in SVG space.
  const COS_LAT = Math.cos(((BOUNDS.n + BOUNDS.s) / 2) * Math.PI / 180);
  const project = (lat, lng) => {
    const xFrac = (lng - BOUNDS.w) / (BOUNDS.e - BOUNDS.w);
    // Aspect-correct y so degrees lat and lng have same metric scale.
    // Compute fraction with proper aspect ratio of the bounding box.
    const lngSpan = (BOUNDS.e - BOUNDS.w) * COS_LAT;
    const latSpan = (BOUNDS.n - BOUNDS.s);
    const xPx = xFrac * W;
    const yFrac = (BOUNDS.n - lat) / latSpan;
    // Match canvas aspect to geo aspect: H should equal W * latSpan/lngSpan
    // Canvas is fixed 2000×1400; recompute yPx so 1° lat maps to true vertical px.
    const truePxPerDegLat = W / (lngSpan); // px per 1° at this latitude when corrected
    const yPx = yFrac * latSpan * truePxPerDegLat;
    return { x: xPx, y: yPx };
  };

  const paper = p.card || '#f5efe3';
  const line = p.line || '#d9cfba';
  const ink = p.ink || '#2a241c';
  const muted = p.muted || '#6b5e47';
  const accent = p.accent || '#b8532a';

  // ── Real street geometry — west→east horizontal streets, north→south vertical streets ──
  // Coordinates are approximate but accurate to ~50m for Crown Heights.
  const hStreets = [
    { lat: 40.6745, label: 'EASTERN PARKWAY', wide: true },
    { lat: 40.6720, label: 'UNION ST' },
    { lat: 40.6700, label: 'PRESIDENT ST' },
    { lat: 40.6680, label: 'CARROLL ST' },
    { lat: 40.6660, label: 'CROWN ST' },
    { lat: 40.6640, label: 'MONTGOMERY ST' },
    { lat: 40.6620, label: 'EMPIRE BLVD', wide: true },
    { lat: 40.6595, label: 'LEFFERTS AVE' },
  ];
  const vStreets = [
    { lng: -73.9595, label: 'WASHINGTON' },
    { lng: -73.9560, label: 'CLASSON' },
    { lng: -73.9530, label: 'FRANKLIN' },
    { lng: -73.9495, label: 'BEDFORD' },
    { lng: -73.9460, label: 'ROGERS' },
    { lng: -73.9430, label: 'NOSTRAND' },
    { lng: -73.9395, label: 'NEW YORK' },
    { lng: -73.9360, label: 'BROOKLYN' },
    { lng: -73.9330, label: 'KINGSTON', wide: true },
    { lng: -73.9300, label: 'ALBANY' },
    { lng: -73.9265, label: 'TROY' },
    { lng: -73.9230, label: 'SCHENECTADY' },
    { lng: -73.9200, label: 'UTICA' },
  ];

  // ── 770 Eastern Parkway — the flagship ──
  // Real coordinates: 40.6694° N, -73.9422° W
  const PIN_770 = { lat: 40.6694, lng: -73.9422 };

  // ── Community landmarks at real coordinates ──
  // c = category; align = label side (left/right of pin)
  const landmarks = [
    // SHULS
    { lat: 40.6692, lng: -73.9418, t: 'Cong. Lubavitch', s: 'Shul · daily minyanim', align: 'right', c: 'shul' },
    { lat: 40.6724, lng: -73.9460, t: 'Anash — Eastern Pkwy', s: 'Nusach Ari minyan', align: 'left', c: 'shul' },
    { lat: 40.6630, lng: -73.9355, t: 'Empire Shteible', s: 'Heimish minyan', align: 'right', c: 'shul' },
    { lat: 40.6675, lng: -73.9395, t: 'Bobover Shteible', s: 'Afternoon minyanim', align: 'left', c: 'shul' },
    { lat: 40.6705, lng: -73.9290, t: 'Ahavas Yisroel', s: "Women's programs", align: 'right', c: 'shul' },
    { lat: 40.6685, lng: -73.9495, t: 'Kol Menachem', s: 'Morning kollel', align: 'left', c: 'shul' },

    // MIKVAH (Crown Heights mikvaos near Kingston)
    { lat: 40.6687, lng: -73.9410, t: 'Mikvah Chaya Mushka', s: 'Women · 5 min from 770', align: 'right', c: 'service' },
    { lat: 40.6710, lng: -73.9420, t: 'Mikvah Mei Menachem', s: 'Men · daily', align: 'left', c: 'service' },

    // SCHOOLS — real Crown Heights mosdos
    { lat: 40.6680, lng: -73.9418, t: 'Oholei Torah', s: 'Boys cheder & mesivta', align: 'right', c: 'school' },
    { lat: 40.6645, lng: -73.9385, t: 'Beth Rivkah', s: "Girls' school", align: 'right', c: 'school' },
    { lat: 40.6730, lng: -73.9430, t: 'Bais Rivka HS', s: 'High school campus', align: 'left', c: 'school' },
    { lat: 40.6660, lng: -73.9460, t: 'Gan Israel preschool', s: 'Pre-K · 3–5', align: 'left', c: 'school' },
    { lat: 40.6700, lng: -73.9305, t: 'Machon Chana', s: "Women's seminary", align: 'right', c: 'school' },
    { lat: 40.6670, lng: -73.9445, t: 'Cheder Menachem', s: 'Chassidic cheder', align: 'left', c: 'school' },

    // KOSHER MARKETS & FOOD — concentrated on Kingston Ave
    { lat: 40.6650, lng: -73.9335, t: 'Kol Tuv Groceries', s: 'Kosher supermarket', align: 'right', c: 'market' },
    { lat: 40.6670, lng: -73.9332, t: "Kahan's Bakery", s: 'Kingston · fresh daily', align: 'right', c: 'market' },
    { lat: 40.6640, lng: -73.9333, t: 'Empire Kosher', s: 'Butcher & deli', align: 'right', c: 'market' },
    { lat: 40.6680, lng: -73.9332, t: 'Chadash Pizza', s: 'Pareve · mehadrin', align: 'left', c: 'food' },
    { lat: 40.6655, lng: -73.9325, t: 'Gombo Fish & Meat', s: 'Prepared foods', align: 'right', c: 'food' },
    { lat: 40.6635, lng: -73.9332, t: 'Crown Heights Wine', s: 'Kosher wine & spirits', align: 'right', c: 'market' },
    { lat: 40.6688, lng: -73.9335, t: "Izzy's Smokehouse", s: 'BBQ · meat', align: 'right', c: 'food' },
    { lat: 40.6625, lng: -73.9355, t: 'Boruchs Coffee', s: 'Cafe · pareve', align: 'left', c: 'food' },
    { lat: 40.6645, lng: -73.9300, t: "Carlos & Gabby's", s: 'Family restaurant', align: 'right', c: 'food' },
    { lat: 40.6700, lng: -73.9530, t: "Albert's Bakery", s: 'Challah & cakes', align: 'left', c: 'market' },
    { lat: 40.6660, lng: -73.9305, t: "Raskin's Fish", s: 'Fresh fish market', align: 'right', c: 'market' },

    // CULTURE / LIBRARIES
    { lat: 40.6680, lng: -73.9395, t: "Jewish Children's Museum", s: 'Family programming · Eastern Pkwy', align: 'left', c: 'culture' },
    { lat: 40.6695, lng: -73.9425, t: 'Agudas Chassidei Chabad', s: 'Library & seforim', align: 'left', c: 'culture' },
    { lat: 40.6724, lng: -73.9685, t: 'Brooklyn Public Library', s: 'Grand Army Plaza', align: 'left', c: 'culture' },
    { lat: 40.6675, lng: -73.9320, t: 'Judaica World', s: 'Seforim & gifts', align: 'right', c: 'culture' },

    // SERVICES
    { lat: 40.6660, lng: -73.9320, t: 'Hatzolah Crown Heights', s: 'Emergency medical', align: 'right', c: 'service' },
    { lat: 40.6630, lng: -73.9320, t: 'Shomrim Crown Heights', s: 'Neighborhood watch', align: 'right', c: 'service' },
    { lat: 40.6700, lng: -73.9500, t: 'Duane Reade', s: 'Pharmacy', align: 'left', c: 'service' },
    { lat: 40.6670, lng: -73.9290, t: "Drimmer's Optical", s: 'Eyewear', align: 'right', c: 'service' },
    { lat: 40.6720, lng: -73.9430, t: 'Chase / Capital One', s: 'Banks · ATMs', align: 'left', c: 'service' },

    // TRANSIT — real subway stops
    { lat: 40.6750, lng: -73.9710, t: 'Grand Army Plaza (2/3)', s: 'Subway · 10 min walk', align: 'left', c: 'transit' },
    { lat: 40.6790, lng: -73.9410, t: 'Kingston–Throop (A/C)', s: 'Subway', align: 'right', c: 'transit' },
    { lat: 40.6732, lng: -73.9300, t: 'Kingston Ave (3)', s: 'Subway · 5 min walk', align: 'right', c: 'transit' },
    { lat: 40.6731, lng: -73.9220, t: 'Utica Ave (3/4)', s: 'Subway', align: 'right', c: 'transit' },

    // PARKS — real
    { lat: 40.6610, lng: -73.9290, t: 'Lincoln Terrace Park', s: 'Playground & fields', align: 'right', c: 'park' },
    { lat: 40.6745, lng: -73.9495, t: 'Brower Park', s: 'Local park', align: 'left', c: 'park' },
  ];

  // Eruv — stylized rounded rectangle around the projected canvas.
  // (Real eruv loosely follows Eastern Pkwy, Buffalo Ave, Empire Blvd, Washington Ave.)
  const eruvPath = `M 80 50 L ${W - 80} 50 Q ${W - 30} 50 ${W - 30} 110 L ${W - 30} ${H - 110} Q ${W - 30} ${H - 50} ${W - 80} ${H - 50} L 80 ${H - 50} Q 30 ${H - 50} 30 ${H - 110} L 30 110 Q 30 50 80 50 Z`;

  // Project all streets to pixel positions for SVG.
  const proj770 = project(PIN_770.lat, PIN_770.lng);
  const projStreetsH = hStreets.map(s => ({ ...s, y: project(s.lat, BOUNDS.w).y }));
  const projStreetsV = vStreets.map(s => ({ ...s, x: project(BOUNDS.s, s.lng).x }));
  const projLandmarks = landmarks.map(L => ({ ...L, ...project(L.lat, L.lng) }));

  return (
    <div style={{
      position: 'relative',
      borderRadius: 12,
      overflow: 'hidden',
      border: `1px solid ${line}`,
      background: paper,
      aspectRatio: `${W}/${H}`,
    }}>
      <svg viewBox={`0 0 ${W} ${H}`} width="100%" height="100%" style={{ display: 'block' }}>
        <defs>
          <pattern id="paper-dots" width="14" height="14" patternUnits="userSpaceOnUse">
            <circle cx="2" cy="2" r="0.5" fill={muted} opacity="0.08"/>
          </pattern>
          <pattern id="park-hatch" width="10" height="10" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
            <line x1="0" y1="0" x2="0" y2="10" stroke="#a8b89a" strokeWidth="2" opacity="0.4"/>
          </pattern>
        </defs>

        <rect width={W} height={H} fill={paper}/>
        <rect width={W} height={H} fill="url(#paper-dots)"/>

        {/* Prospect Park — NW of Crown Heights, projected from real lat/lng */}
        {(() => {
          // Prospect Park east edge runs along Flatbush Ave (~-73.965 lng).
          const pts = [
            { lat: 40.6810, lng: -73.9620 },
            { lat: 40.6790, lng: -73.9685 },
            { lat: 40.6740, lng: -73.9720 },
            { lat: 40.6700, lng: -73.9700 },
            { lat: 40.6700, lng: -73.9620 },
          ].map(c => project(c.lat, c.lng));
          const d = pts.map((p, i) => `${i === 0 ? 'M' : 'L'} ${p.x} ${p.y}`).join(' ') + ' Z';
          const c = project(40.6760, -73.9680);
          return (
            <g>
              <path d={d} fill="url(#park-hatch)" opacity="0.85"/>
              <text x={c.x} y={c.y} fontFamily={serif} fontSize="22" fontStyle="italic" fill="#6a7a5c" opacity="0.85" textAnchor="middle">Prospect Park</text>
            </g>
          );
        })()}

        {/* Lincoln Terrace Park — SE corner */}
        {(() => {
          const pts = [
            { lat: 40.6620, lng: -73.9300 },
            { lat: 40.6600, lng: -73.9270 },
            { lat: 40.6590, lng: -73.9290 },
            { lat: 40.6610, lng: -73.9320 },
          ].map(c => project(c.lat, c.lng));
          const d = pts.map((p, i) => `${i === 0 ? 'M' : 'L'} ${p.x} ${p.y}`).join(' ') + ' Z';
          const c = project(40.6605, -73.9295);
          return (
            <g>
              <path d={d} fill="url(#park-hatch)" opacity="0.85"/>
              <text x={c.x} y={c.y} fontFamily={serif} fontSize="13" fontStyle="italic" fill="#6a7a5c" opacity="0.85" textAnchor="middle">Lincoln Terrace Park</text>
            </g>
          );
        })()}

        {/* Neighborhood frame — stylized boundary, no label (visual only). */}
        <path d={eruvPath} fill="none" stroke={accent} strokeWidth="1.6" strokeDasharray="7 5" opacity="0.4"/>

        {/* Horizontal streets — drawn at projected lat */}
        {projStreetsH.map((s, i) => (
          <g key={'h' + i}>
            <line x1={30} y1={s.y} x2={W - 30} y2={s.y} stroke={ink} strokeWidth={s.wide ? 2.2 : 0.7} opacity={s.wide ? 0.85 : 0.32}/>
            <text x={W - 40} y={s.y - 6} fontFamily="ui-monospace, Menlo, monospace" fontSize={s.wide ? 10 : 8.5} fill={muted} textAnchor="end" letterSpacing="1.3" opacity={s.wide ? 0.9 : 0.55}>
              {s.label}
            </text>
          </g>
        ))}

        {/* Vertical streets — drawn at projected lng */}
        {projStreetsV.map((s, i) => (
          <g key={'v' + i}>
            <line x1={s.x} y1={40} x2={s.x} y2={H - 30} stroke={ink} strokeWidth={s.wide ? 1.8 : 0.7} opacity={s.wide ? 0.85 : 0.32}/>
            <text
              x={s.x + 4}
              y={H - 40}
              fontFamily="ui-monospace, Menlo, monospace"
              fontSize={s.wide ? 10 : 8.5}
              fill={muted}
              letterSpacing="1.3"
              opacity={s.wide ? 0.9 : 0.55}
              transform={`rotate(-90, ${s.x + 4}, ${H - 40})`}
            >
              {s.label}
            </text>
          </g>
        ))}

        {/* 770 — the flagship, at real coordinates */}
        <g transform={`translate(${proj770.x}, ${proj770.y})`}>
          <path d="M -22 -8 L -22 -40 L 0 -58 L 22 -40 L 22 -8 Z" fill={accent} stroke={ink} strokeWidth="1.3"/>
          <rect x="-8" y="-30" width="16" height="22" fill={paper} stroke={ink} strokeWidth="1"/>
          <circle cx="0" cy="0" r="5" fill={ink}/>
          <circle cx="0" cy="0" r="2.5" fill={paper}/>
          <text x="32" y="-40" fontFamily={serif} fontSize="28" fill={ink} fontWeight="500">770</text>
          <text x="32" y="-22" fontFamily="ui-monospace, Menlo, monospace" fontSize="9" fill={muted} letterSpacing="1.4">BEIS CHAYEINU</text>
          <text x="32" y="-8" fontFamily={hebFont} fontSize="14" fill={accent} direction="rtl">770 ליובאוויטש</text>
        </g>

        {/* Community landmark pins */}
        {projLandmarks.map((L, i) => {
          const catColor = {
            shul: accent,
            school: '#6a7a5c',
            market: '#8b6a2a',
            food: '#b8532a',
            service: ink,
            culture: '#8a5a8a',
            transit: '#3a6a8a',
            park: '#6a8a5c',
          }[L.c] || accent;
          return (
            <g key={'lm' + i} transform={`translate(${L.x}, ${L.y})`}>
              <circle cx="0" cy="0" r="5.5" fill={paper} stroke={ink} strokeWidth="1.2"/>
              <circle cx="0" cy="0" r="2.4" fill={catColor}/>
              {L.align === 'left' ? (
                <>
                  <text x={-12} y={-3} fontFamily={serif} fontSize="13" fontStyle="italic" fill={ink} textAnchor="end">{L.t}</text>
                  <text x={-12} y={10} fontFamily="ui-monospace, Menlo, monospace" fontSize="8.5" fill={muted} textAnchor="end" letterSpacing="1.1">{L.s}</text>
                </>
              ) : (
                <>
                  <text x={12} y={-3} fontFamily={serif} fontSize="13" fontStyle="italic" fill={ink}>{L.t}</text>
                  <text x={12} y={10} fontFamily="ui-monospace, Menlo, monospace" fontSize="8.5" fill={muted} letterSpacing="1.1">{L.s}</text>
                </>
              )}
            </g>
          );
        })}

        {/* Compass */}
        <g transform={`translate(${W - 100}, 130)`}>
          <circle r="26" fill={paper} stroke={ink} strokeWidth="0.8"/>
          <path d="M 0 -20 L 5 0 L 0 20 L -5 0 Z" fill={ink}/>
          <text y="-30" textAnchor="middle" fontFamily="ui-monospace, Menlo, monospace" fontSize="10" fill={muted} letterSpacing="1.5">N</text>
        </g>

        {/* Title block */}
        <g transform="translate(80, 110)">
          <text fontFamily={serif} fontSize="44" fontStyle="italic" fill={ink} fontWeight="400">Crown&nbsp;Heights</text>
          <text y="26" fontFamily="ui-monospace, Menlo, monospace" fontSize="11" fill={muted} letterSpacing="2.2">BROOKLYN · NEW YORK</text>
          <text y="52" fontFamily={hebFont} fontSize="20" fill={accent} direction="rtl">קראון הייטס</text>
        </g>

        {/* Legend */}
        <g transform={`translate(80, ${H - 130})`}>
          <rect width="720" height="92" fill={paper} stroke={line} strokeWidth="0.8" opacity="0.95"/>
          <g transform="translate(22, 24)">
            <path d="M -8 0 L -8 -12 L 0 -20 L 8 -12 L 8 0 Z" fill={accent} stroke={ink} strokeWidth="0.8" transform="translate(8,10) scale(0.55)"/>
          </g>
          <text x="48" y="30" fontFamily="ui-monospace, Menlo, monospace" fontSize="9" fill={muted} letterSpacing="1.2">770</text>

          {[
            { c: accent, l: 'SHUL' },
            { c: '#6a7a5c', l: 'SCHOOL' },
            { c: '#8b6a2a', l: 'MARKET' },
            { c: '#b8532a', l: 'FOOD' },
            { c: ink, l: 'SERVICE' },
            { c: '#8a5a8a', l: 'CULTURE' },
            { c: '#3a6a8a', l: 'TRANSIT' },
          ].map((d, i) => {
            const x = 100 + i * 88;
            return (
              <g key={i}>
                <circle cx={x} cy="26" r="4" fill={paper} stroke={ink} strokeWidth="1"/>
                <circle cx={x} cy="26" r="1.8" fill={d.c}/>
                <text x={x + 10} y="30" fontFamily="ui-monospace, Menlo, monospace" fontSize="9" fill={muted} letterSpacing="1.1">{d.l}</text>
              </g>
            );
          })}

          <line x1="22" y1="56" x2="52" y2="56" stroke={accent} strokeWidth="1.4" strokeDasharray="4 3"/>
          <text x="58" y="60" fontFamily="ui-monospace, Menlo, monospace" fontSize="9" fill={muted} letterSpacing="1.2">NEIGHBORHOOD</text>
          <rect x="148" y="50" width="12" height="12" fill="url(#park-hatch)"/>
          <text x="166" y="60" fontFamily="ui-monospace, Menlo, monospace" fontSize="9" fill={muted} letterSpacing="1.2">PARK</text>
          <line x1="180" y1="56" x2="210" y2="56" stroke={ink} strokeWidth="2" opacity="0.85"/>
          <text x="216" y="60" fontFamily="ui-monospace, Menlo, monospace" fontSize="9" fill={muted} letterSpacing="1.2">MAJOR AVE</text>

          <text x="22" y="82" fontFamily={serif} fontStyle="italic" fontSize="13" fill={muted}>Pinned by real coordinates · every Dyra home sits in the heart of Crown Heights, within a short walk of 770.</text>
        </g>
      </svg>
    </div>
  );
}

window.CrownHeightsMap = CrownHeightsMap;
