// El Mirador — Editorial Map canvas + layer toggles
// A stylized, minimal cartography — printed-plate aesthetic, not Google Maps.
// Globals: EMMapCanvas, EMLayerToggles

const { useState: useMapState } = React;

const MAP_LAYERS = [
  { id: "cafe",   glyph: "☕", label: "Cafés tranquilos",  color: "#5C3D2E" },
  { id: "work",   glyph: "✎", label: "Trabajo",            color: "#5B5E3C" },
  { id: "walk",   glyph: "⌇", label: "Caminar",            color: "#A37A4A" },
  { id: "night",  glyph: "❍", label: "Noche",              color: "#2A2724" },
  { id: "classic",glyph: "▢", label: "Clásicos",           color: "#5C3D2E" },
  { id: "new",    glyph: "✦", label: "Nuevas aperturas",   color: "#5B5E3C" }
];

// A small dataset of pins, positioned on a normalized 0–100 grid.
const MAP_PINS = [
  { id: "p1", x: 28, y: 32, layer: "cafe",    label: "Don Rafael · café" },
  { id: "p2", x: 52, y: 24, layer: "work",    label: "Estudio Norte" },
  { id: "p3", x: 70, y: 42, layer: "new",     label: "Almacén 27" },
  { id: "p4", x: 38, y: 58, layer: "classic", label: "Mercado de la 23" },
  { id: "p5", x: 60, y: 70, layer: "night",   label: "Bar Atrio" },
  { id: "p6", x: 22, y: 76, layer: "cafe",    label: "Tostadora Luz" },
  { id: "p7", x: 80, y: 60, layer: "walk",    label: "Andador de jacarandas" },
  { id: "p8", x: 46, y: 44, layer: "new",     label: "Librería Ínsula" },
  { id: "p9", x: 64, y: 50, layer: "classic", label: "Sastrería Núñez" }
];

function EMMapCanvas({ activeLayers, onSelect }) {
  // Pueblo street grid — Puebla famously has a regular grid laid down in 1531.
  const cols = 8;
  const rows = 6;
  const layerColor = (id) => (MAP_LAYERS.find(l => l.id === id) || {}).color || "#5C3D2E";
  const layerGlyph = (id) => (MAP_LAYERS.find(l => l.id === id) || {}).glyph || "•";

  return (
    <div className="em-map-canvas">
      <svg viewBox="0 0 1000 600" width="100%" height="100%" preserveAspectRatio="xMidYMid slice"
           style={{ display: "block", background: "#F4EFE6" }}>
        {/* paper texture wash */}
        <defs>
          <pattern id="grain" x="0" y="0" width="3" height="3" patternUnits="userSpaceOnUse">
            <rect width="3" height="3" fill="#F4EFE6"/>
            <circle cx="1.5" cy="1.5" r="0.18" fill="#B8B1A3" opacity="0.35"/>
          </pattern>
          <pattern id="park" x="0" y="0" width="14" height="14" patternUnits="userSpaceOnUse">
            <rect width="14" height="14" fill="#E6D9C5"/>
            <path d="M 0 14 L 14 0" stroke="#B8B1A3" strokeWidth="0.5" opacity="0.6"/>
          </pattern>
        </defs>
        <rect width="1000" height="600" fill="url(#grain)"/>

        {/* parks / green spaces */}
        <rect x="120" y="380" width="180" height="120" fill="url(#park)" opacity="0.9"/>
        <rect x="700" y="80" width="140" height="80" fill="url(#park)" opacity="0.9"/>
        <circle cx="500" cy="300" r="46" fill="url(#park)" opacity="0.9"/>

        {/* boulevard — the diagonal */}
        <path d="M 0 540 L 1000 60" stroke="#8C8478" strokeWidth="3" opacity="0.6"/>

        {/* main street grid (Puebla traza) */}
        {Array.from({ length: rows + 1 }).map((_, i) => (
          <line key={`h${i}`} x1="40" y1={60 + i * 80} x2="960" y2={60 + i * 80}
                stroke="#B8B1A3" strokeWidth="1" opacity="0.7"/>
        ))}
        {Array.from({ length: cols + 1 }).map((_, i) => (
          <line key={`v${i}`} x1={60 + i * 115} y1="40" x2={60 + i * 115} y2="560"
                stroke="#B8B1A3" strokeWidth="1" opacity="0.7"/>
        ))}

        {/* hand-labelled streets */}
        <text x="500" y="36" textAnchor="middle" fontFamily="Instrument Sans, sans-serif"
              fontSize="10" letterSpacing="2" fill="#8C8478">CALLE 25 PONIENTE</text>
        <text x="500" y="585" textAnchor="middle" fontFamily="Instrument Sans, sans-serif"
              fontSize="10" letterSpacing="2" fill="#8C8478">CALLE 29 PONIENTE</text>
        <text x="20" y="300" textAnchor="middle" fontFamily="Instrument Sans, sans-serif"
              fontSize="10" letterSpacing="2" fill="#8C8478" transform="rotate(-90 20 300)">AV. 15 NORTE</text>
        <text x="980" y="300" textAnchor="middle" fontFamily="Instrument Sans, sans-serif"
              fontSize="10" letterSpacing="2" fill="#8C8478" transform="rotate(90 980 300)">AV. 25 NORTE</text>

        {/* compass mark */}
        <g transform="translate(910, 510)">
          <circle cx="0" cy="0" r="20" fill="none" stroke="#5C3D2E" strokeWidth="0.8"/>
          <path d="M 0 -14 L 4 0 L 0 14 L -4 0 Z" fill="#5C3D2E"/>
          <text x="0" y="-26" textAnchor="middle" fontFamily="Newsreader, serif" fontSize="11" fill="#5C3D2E">N</text>
        </g>

        {/* neighborhood label */}
        <g transform="translate(500, 220)">
          <text textAnchor="middle" fontFamily="Newsreader, serif" fontStyle="italic"
                fontSize="28" fill="#5C3D2E" opacity="0.5">El Mirador</text>
        </g>

        {/* pins */}
        {MAP_PINS.map(p => {
          const active = activeLayers.has(p.layer);
          const cx = (p.x / 100) * 1000;
          const cy = (p.y / 100) * 600;
          return (
            <g key={p.id} transform={`translate(${cx}, ${cy})`}
               style={{ cursor: "pointer", opacity: active ? 1 : 0.18, transition: "opacity 320ms cubic-bezier(.22,1,.36,1)" }}
               onClick={() => onSelect && onSelect(p)}>
              <circle cx="0" cy="0" r="14" fill="#FBF8F2" stroke={layerColor(p.layer)} strokeWidth="1"/>
              <text textAnchor="middle" dy="5" fontFamily="Newsreader, serif"
                    fontSize="13" fill={layerColor(p.layer)}>{layerGlyph(p.layer)}</text>
            </g>
          );
        })}
      </svg>
    </div>
  );
}

function EMLayerToggles({ activeLayers, onToggle }) {
  return (
    <div className="em-map-canvas__legend">
      {MAP_LAYERS.map(l => {
        const on = activeLayers.has(l.id);
        return (
          <div key={l.id} className="row" onClick={() => onToggle(l.id)}
               style={{ opacity: on ? 1 : 0.45 }}>
            <span className="glyph" style={{ color: l.color }}>{l.glyph}</span>
            <span>{l.label}</span>
          </div>
        );
      })}
    </div>
  );
}

function EMMapShell() {
  const [active, setActive] = useMapState(new Set(MAP_LAYERS.map(l => l.id)));
  const [selected, setSelected] = useMapState(null);

  const toggle = (id) => {
    setActive(prev => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id); else next.add(id);
      return next;
    });
  };

  return (
    <div className="em-map-canvas" style={{ position: "relative" }}>
      <EMMapCanvas activeLayers={active} onSelect={setSelected}/>
      <EMLayerToggles activeLayers={active} onToggle={toggle}/>
      <div className="em-map-canvas__controls">
        <button title="Acercar">+</button>
        <button title="Alejar">−</button>
        <button title="Centrar">⊙</button>
      </div>
      {selected && (
        <div style={{
          position: "absolute", bottom: 24, left: 24, maxWidth: 340,
          background: "var(--ivory-hi)", boxShadow: "var(--shadow-1)",
          padding: "16px 18px", borderRadius: 4, display: "flex",
          flexDirection: "column", gap: 6
        }}>
          <div style={{ fontFamily: "var(--font-sans)", fontSize: 10, letterSpacing: "0.12em",
                        textTransform: "uppercase", color: "var(--walnut)" }}>
            {(MAP_LAYERS.find(l => l.id === selected.layer) || {}).label}
          </div>
          <div style={{ fontFamily: "var(--font-serif)", fontSize: 22, lineHeight: 1.15, color: "var(--obsidian)" }}>
            {selected.label}
          </div>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 6 }}>
            <span style={{ fontFamily: "var(--font-sans)", fontSize: 11, color: "var(--olive)",
                           borderBottom: "1px solid currentColor", cursor: "pointer" }}>
              Leer la historia
            </span>
            <button onClick={() => setSelected(null)}
                    style={{ background: "transparent", border: 0, color: "var(--concrete)",
                             fontFamily: "var(--font-sans)", fontSize: 11, cursor: "pointer",
                             letterSpacing: "0.1em", textTransform: "uppercase" }}>
              Cerrar
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { EMMapCanvas, EMLayerToggles, EMMapShell, MAP_LAYERS, MAP_PINS });
