/* ============================================================
   Contact Map – kleine MapLibre-Karte für die Kontakt-Seite,
   zeigt SPRUS-Firmensitz mit pulsierendem Pin + Brand-Recolor.
   Same-Style wie project-map und home-map.
   ============================================================ */

const { useState: useStateCM, useEffect: useEffectCM, useRef: useRefCM } = React;

const CM_PALETTES = {
  light: {
    background: '#F2EBDF', landuse: '#E8DFCF', vegetation: '#D8CCB0',
    buildings:  '#C8BCA4', water:   '#C5DBE3', waterEdge: '#5B7E8E',
    roadMain:   '#1A1714', roadMinor:'#A89F90',
  },
  dark: {
    background: '#161310', landuse: '#1F1B16', vegetation: '#2A2620',
    buildings:  '#38332C', water:   '#2A4F62', waterEdge: '#4A7388',
    roadMain:   '#A89F90', roadMinor:'#4A4540',
  },
};

function cmRecolor(map, mode) {
  const p = CM_PALETTES[mode] || CM_PALETTES.light;
  const layers = (map.getStyle() && map.getStyle().layers) || [];
  layers.forEach(layer => {
    const id = layer.id.toLowerCase();
    const t = layer.type;
    try {
      if (t === 'background')                                                                  { map.setPaintProperty(layer.id, 'background-color', p.background); return; }
      if (id.match(/water|ocean|lake|sea/) && t === 'fill')                                    { map.setPaintProperty(layer.id, 'fill-color', p.water); return; }
      if (id.match(/water|ocean|lake|sea/) && t === 'line')                                    { map.setPaintProperty(layer.id, 'line-color', p.waterEdge); return; }
      if (id.match(/park|forest|wood|grass|vegetation|meadow|scrub|farmland/) && t === 'fill') { map.setPaintProperty(layer.id, 'fill-color', p.vegetation); return; }
      if (id.includes('building') && t === 'fill')                                             { map.setPaintProperty(layer.id, 'fill-color', p.buildings); return; }
      if (id.match(/motorway|trunk|primary|highway/) && t === 'line')                          { map.setPaintProperty(layer.id, 'line-color', p.roadMain); return; }
      if (id.match(/road|street|path|track|rail|transport/) && t === 'line')                   { map.setPaintProperty(layer.id, 'line-color', p.roadMinor); return; }
      if (id.match(/landuse|landcover|land/) && t === 'fill')                                  { map.setPaintProperty(layer.id, 'fill-color', p.landuse); return; }
      if (t === 'symbol')                                                                      { map.setLayoutProperty(layer.id, 'visibility', 'none'); return; }
    } catch (e) {}
  });
}

/* Geteilter Helper: Satellit-Layer (ESRI World Imagery) ein/aus auf
   einer beliebigen MapLibre-Instanz. Wird auch von ProjectMap genutzt. */
window.toggleMapSatellite = function (map, currentlyOn) {
  if (!map) return currentlyOn;
  const SOURCE_ID = 'sat-esri';
  const LAYER_ID = 'sat-esri-layer';
  if (currentlyOn) {
    try { if (map.getLayer(LAYER_ID)) map.removeLayer(LAYER_ID); } catch(_) {}
    try { if (map.getSource(SOURCE_ID)) map.removeSource(SOURCE_ID); } catch(_) {}
    return false;
  }
  try {
    if (!map.getSource(SOURCE_ID)) {
      map.addSource(SOURCE_ID, {
        type: 'raster',
        tiles: ['https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}'],
        tileSize: 256,
        attribution: 'Tiles © Esri',
      });
    }
    if (!map.getLayer(LAYER_ID)) {
      const firstSymbolId = (map.getStyle().layers || []).find(l => l.type === 'symbol');
      map.addLayer({ id: LAYER_ID, type: 'raster', source: SOURCE_ID }, firstSymbolId && firstSymbolId.id);
    }
    return true;
  } catch (e) { return false; }
};

function ContactMap() {
  // Firmensitz Grassau, Mietenkamer Straße 47
  const HQ_LAT = 47.7825745;
  const HQ_LNG = 12.4624354;

  const containerRef = useRefCM(null);
  const mapRef = useRefCM(null);
  const [mode, setMode] = useStateCM(() =>
    (typeof document !== 'undefined' ? document.documentElement.getAttribute('data-theme') : null) || 'light'
  );
  const [ready, setReady] = useStateCM(false);
  const [satView, setSatView] = useStateCM(false);
  const onToggleSat = () => setSatView(window.toggleMapSatellite(mapRef.current, satView));

  useEffectCM(() => {
    if (!window.maplibregl || !containerRef.current) return;
    if (mapRef.current) return;

    const padLat = 0.005;
    const padLng = 0.0075;
    const bounds = [
      [HQ_LNG - padLng, HQ_LAT - padLat],
      [HQ_LNG + padLng, HQ_LAT + padLat],
    ];

    const map = new window.maplibregl.Map({
      container: containerRef.current,
      style: 'https://tiles.openfreemap.org/styles/positron',
      bounds,
      fitBoundsOptions: { padding: 12, animate: false },
      attributionControl: { compact: true },
      interactive: false,
      pitch: 0,
      bearing: 0,
    });

    map.on('load', () => {
      cmRecolor(map, mode);
      setTimeout(() => map.resize(), 100);

      // Attribution kollabiert
      const attribEl = containerRef.current && containerRef.current.querySelector('.maplibregl-ctrl-attrib');
      if (attribEl) {
        attribEl.removeAttribute('open');
        attribEl.classList.remove('maplibregl-compact-show');
      }

      // HQ-Pin: groß, mit Pulse + Label
      const wrap = document.createElement('div');
      wrap.className = 'contact-pin-wrap';

      const pin = document.createElement('div');
      pin.className = 'contact-pin';

      const label = document.createElement('div');
      label.className = 'contact-pin-label';
      label.innerHTML = '<strong>SPRUS</strong><span>Mietenkamer Straße 47</span>';
      pin.appendChild(label);

      wrap.appendChild(pin);

      new window.maplibregl.Marker({ element: wrap })
        .setLngLat([HQ_LNG, HQ_LAT])
        .addTo(map);

      setReady(true);
    });

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

  // Theme tracking
  useEffectCM(() => {
    const obs = new MutationObserver(() => {
      const newMode = document.documentElement.getAttribute('data-theme') || 'light';
      if (newMode !== mode) setMode(newMode);
    });
    obs.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });
    return () => obs.disconnect();
  }, [mode]);

  useEffectCM(() => {
    if (mapRef.current && ready) cmRecolor(mapRef.current, mode);
  }, [mode, ready]);

  return (
    <div className="contact-map-wrap reveal">
      <div className="contact-map-frame">
        <div ref={containerRef} className="contact-map-tiles" />
        <button type="button" className={'mini-map-sat-toggle' + (satView ? ' is-active' : '')} onClick={onToggleSat} aria-label="Satellitenbild umschalten">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
            <circle cx="12" cy="12" r="3"/>
            <path d="M12 1v2"/><path d="M12 21v2"/>
            <path d="M4.22 4.22l1.42 1.42"/><path d="M18.36 18.36l1.42 1.42"/>
            <path d="M1 12h2"/><path d="M21 12h2"/>
            <path d="M4.22 19.78l1.42-1.42"/><path d="M18.36 5.64l1.42-1.42"/>
          </svg>
          <span>{satView ? 'Karte' : 'Satellit'}</span>
        </button>
      </div>
      <div className="contact-map-info">
        <div className="contact-map-info-block">
          <span className="mono">Adresse</span>
          <p>SPRUS DESIGN GmbH<br/>Mietenkamer Straße 47<br/>83224 Grassau / Chiemgau</p>
        </div>
        <div className="contact-map-info-block">
          <span className="mono">Direkter Draht</span>
          <p>
            <a href="tel:+498641694500">+49 8641 694500</a><br/>
            <a href="mailto:info@sprusdesign.de">info@sprusdesign.de</a>
          </p>
        </div>
        <div className="contact-map-info-block">
          <span className="mono">Anfahrt</span>
          <a
            className="btn btn-primary contact-map-route"
            /* Direkt zum Firmen-Eintrag (Name + Adresse), damit Google Maps den
               Business-POI auflöst statt nur Koordinaten anzuzeigen. */
            href="https://www.google.com/maps/dir/?api=1&destination=SPRUS+Design+%26+Bautr%C3%A4ger+GmbH%2C+Mietenkamer+Stra%C3%9Fe+47%2C+83224+Grassau"
            target="_blank"
            rel="noopener"
          >
            Route mit Google Maps <span className="arrow">→</span>
          </a>
          <a
            className="contact-map-osm-link"
            href="https://www.openstreetmap.org/?mlat=47.7825745&mlon=12.4624354#map=17/47.78257/12.46244"
            target="_blank"
            rel="noopener"
          >
            oder auf OpenStreetMap öffnen
          </a>
        </div>
      </div>
    </div>
  );
}

window.ContactMap = ContactMap;
