/// <reference types="google.maps" />
import { importLibrary, setOptions } from '@googlemaps/js-api-loader';

const GPS_COORDS_TEXT = '48.87569, 19.54456';
const GPS_LABEL = `GPS: ${GPS_COORDS_TEXT}`;
const CHALET_LABEL = 'Chata na kopčeku';
const CHALET_SUBTITLE = 'Krpáčovo · Nízke Tatry (k. ú. Dolná Lehota)';
const GOOGLE_MAPS_EXTERNAL_URL =
  'https://www.google.com/maps/search/?api=1&query=48.87569%2C19.54456';
const QUOTA_EVENT = 'gmp-quota-exceeded';
const EMBED_FALLBACK_EVENT = 'chalet-map-embed-fallback';

type MapViewKey = 'aerial-detail' | 'satellite' | 'roadmap' | 'terrain';

interface MapViewPreset {
  mapTypeId: 'hybrid' | 'satellite' | 'roadmap' | 'terrain';
  embedType: 'h' | 'k' | 'm' | 'p';
  zoom: number;
}

const VIEW_PRESETS: Record<MapViewKey, MapViewPreset> = {
  'aerial-detail': { mapTypeId: 'hybrid', embedType: 'h', zoom: 17 },
  satellite: { mapTypeId: 'satellite', embedType: 'k', zoom: 18 },
  roadmap: { mapTypeId: 'roadmap', embedType: 'm', zoom: 14 },
  terrain: { mapTypeId: 'terrain', embedType: 'p', zoom: 13 },
};

const win = window as Window & {
  gm_authFailure?: () => void;
  __chaletMapBootStarted?: boolean;
};
win.__chaletMapBootStarted = true;

let currentPresetKey: MapViewKey = 'aerial-detail';
let domainOrKeyRestricted = false;
let quotaErrorDetected = false;
let embedFallbackActive = false;

function isAiStudioOrLocalHost(): boolean {
  const host = window.location.hostname.toLowerCase();
  return (
    host === 'localhost' ||
    host === '127.0.0.1' ||
    host.endsWith('.run.app') ||
    host.endsWith('.google.com')
  );
}

// Tier 1 Client-Side Quota & Referrer Restriction Listeners
function installQuotaListeners(): void {
  win.gm_authFailure = () => {
    const wasExplicitlyRestricted = domainOrKeyRestricted;
    domainOrKeyRestricted = true;
    window.dispatchEvent(new CustomEvent(EMBED_FALLBACK_EVENT));
    // Only surface quota banner when a true quota error occurred or inside AI Studio dev/preview
    if (quotaErrorDetected || (!wasExplicitlyRestricted && isAiStudioOrLocalHost())) {
      window.dispatchEvent(new CustomEvent(QUOTA_EVENT));
    }
  };

  const origError = console.error;
  console.error = (...args: unknown[]) => {
    origError.apply(console, args);
    const msg = args.map((item) => String(item)).join(' ');
    if (msg.includes('OverQuotaMapError') || msg.includes('QuotaExceededError')) {
      quotaErrorDetected = true;
      window.dispatchEvent(new CustomEvent(QUOTA_EVENT));
    }
    if (
      msg.includes('RefererNotAllowedMapError') ||
      msg.includes('ApiTargetBlockedMapError') ||
      msg.includes('InvalidKeyMapError') ||
      msg.includes('ApiNotActivatedMapError') ||
      msg.includes('UnauthorizedURLForClientIdMapError')
    ) {
      domainOrKeyRestricted = true;
      window.dispatchEvent(new CustomEvent(EMBED_FALLBACK_EVENT));
    }
  };
}

function isQuotaError(err: unknown): boolean {
  if (!err) return false;
  const text = String(err);
  if (
    text.includes('RESOURCE_EXHAUSTED') ||
    text.includes('OVER_QUERY_LIMIT') ||
    text.includes('429') ||
    text.includes('OverQuotaMapError') ||
    text.includes('QuotaExceededError')
  ) {
    return true;
  }
  if (typeof err === 'object' && err !== null) {
    const maybeErr = err as { status?: unknown; code?: unknown };
    if (maybeErr.status === 429 || maybeErr.status === 'RESOURCE_EXHAUSTED') {
      return true;
    }
    if (maybeErr.code === 429 || maybeErr.code === 'OVER_QUERY_LIMIT') {
      return true;
    }
  }
  return false;
}

function isRestrictionError(err: unknown): boolean {
  if (!err) return false;
  const text = String(err);
  return (
    text.includes('RefererNotAllowed') ||
    text.includes('REQUEST_DENIED') ||
    text.includes('PERMISSION_DENIED') ||
    text.includes('API_KEY') ||
    text.includes('blocked') ||
    text.includes('403')
  );
}

function attachQuotaBannerListener(): void {
  const banner = document.getElementById('gmp-quota-banner');
  if (!banner) return;
  window.addEventListener(QUOTA_EVENT, () => {
    if (!domainOrKeyRestricted || quotaErrorDetected) {
      banner.hidden = false;
    }
  });
}

function setMapStatus(message: string, isHidden = false): void {
  const statusEl = document.getElementById('chalet-map-status');
  if (!statusEl) return;
  statusEl.textContent = message;
  statusEl.hidden = isHidden;
}

function buildGoogleMapsEmbedUrl(presetKey: MapViewKey): string {
  const preset = VIEW_PRESETS[presetKey] || VIEW_PRESETS['aerial-detail'];
  const params = new URLSearchParams({
    q: '48.87569,19.54456',
    t: preset.embedType,
    z: String(preset.zoom),
    hl: 'sk',
    ie: 'UTF8',
    output: 'embed',
  });
  return `https://maps.google.com/maps?${params.toString()}`;
}

function activateEmbedFallback(): void {
  const mapEl = document.getElementById('chalet-map');
  if (!mapEl) return;

  embedFallbackActive = true;
  setMapStatus('', true);

  let iframe = mapEl.querySelector<HTMLIFrameElement>('iframe.chalet-map-iframe');
  if (!iframe) {
    mapEl.innerHTML = '';
    iframe = document.createElement('iframe');
    iframe.className = 'chalet-map-iframe';
    iframe.title = `${CHALET_LABEL} — ${GPS_LABEL}`;
    iframe.loading = 'lazy';
    iframe.referrerPolicy = 'strict-origin-when-cross-origin';
    iframe.allowFullscreen = true;
    mapEl.appendChild(iframe);
  }
  iframe.src = buildGoogleMapsEmbedUrl(currentPresetKey);

  if (mapEl.getAttribute('data-embed-controls-bound') === 'true') {
    return;
  }
  mapEl.setAttribute('data-embed-controls-bound', 'true');

  const viewButtons = document.querySelectorAll<HTMLButtonElement>('[data-map-view]');
  viewButtons.forEach((btn) => {
    btn.addEventListener('click', () => {
      if (!embedFallbackActive) return;
      const key = (btn.getAttribute('data-map-view') || 'aerial-detail') as MapViewKey;
      currentPresetKey = VIEW_PRESETS[key] ? key : 'aerial-detail';
      viewButtons.forEach((item) => {
        item.setAttribute('aria-selected', item === btn ? 'true' : 'false');
      });
      if (iframe) {
        iframe.src = buildGoogleMapsEmbedUrl(currentPresetKey);
      }
    });
  });

  const recenterBtn = document.getElementById('map-recenter-btn');
  if (recenterBtn) {
    recenterBtn.addEventListener('click', () => {
      if (!embedFallbackActive || !iframe) return;
      iframe.src = buildGoogleMapsEmbedUrl(currentPresetKey);
    });
  }
}

function sanitizeFormattedAddress(formattedAddress?: string | null): string {
  if (!formattedAddress) return CHALET_SUBTITLE;
  const cleaned = formattedAddress.replace(/^VGGV\+7R[\s,]*/i, '').trim();
  return cleaned ? `Krpáčovo · ${cleaned}` : CHALET_SUBTITLE;
}

function buildInfoWindowContent(formattedAddress?: string | null): HTMLElement {
  const wrapper = document.createElement('div');
  wrapper.className = 'map-info-content';

  const codeLine = document.createElement('p');
  codeLine.className = 'map-info-line';
  codeLine.textContent = GPS_LABEL;
  wrapper.appendChild(codeLine);

  const areaLine = document.createElement('p');
  areaLine.className = 'map-info-sub';
  areaLine.textContent = sanitizeFormattedAddress(formattedAddress);
  wrapper.appendChild(areaLine);

  const link = document.createElement('a');
  link.href = GOOGLE_MAPS_EXTERNAL_URL;
  link.target = '_blank';
  link.rel = 'noopener noreferrer';
  link.className = 'map-info-link';
  link.textContent = 'Otvoriť v Google Maps ↗';
  wrapper.appendChild(link);

  return wrapper;
}

const CHALET_LOOKUP_QUERY = 'VGGV+7R Dolná Lehota';

async function resolveChaletLocation(): Promise<{
  position: google.maps.LatLngLiteral;
  formattedAddress: string | null;
}> {
  const { Place } = (await importLibrary('places')) as google.maps.PlacesLibrary;

  try {
    const { places } = await Place.searchByText({
      textQuery: CHALET_LOOKUP_QUERY,
      fields: ['displayName', 'location', 'formattedAddress'],
      language: 'sk',
      region: 'SK',
      maxResultCount: 1,
    });

    const first = places?.[0];
    if (first?.location) {
      return {
        position: {
          lat: first.location.lat(),
          lng: first.location.lng(),
        },
        formattedAddress: first.formattedAddress ?? null,
      };
    }
  } catch (err) {
    if (isQuotaError(err)) {
      quotaErrorDetected = true;
      window.dispatchEvent(new CustomEvent(QUOTA_EVENT));
      throw err;
    }
    if (isRestrictionError(err)) {
      domainOrKeyRestricted = true;
      throw err;
    }
  }

  // Secondary Places query scoped to Slovensko if needed
  const { places: fallbackPlaces } = await Place.searchByText({
    textQuery: `${CHALET_LOOKUP_QUERY}, Slovensko`,
    fields: ['displayName', 'location', 'formattedAddress'],
    language: 'sk',
    region: 'SK',
    maxResultCount: 1,
  });

  const match = fallbackPlaces?.[0];
  if (match?.location) {
    return {
      position: {
        lat: match.location.lat(),
        lng: match.location.lng(),
      },
      formattedAddress: match.formattedAddress ?? null,
    };
  }

  throw new Error(`Nepodarilo sa načítať súradnice pre polohu ${GPS_LABEL}.`);
}

async function initChaletGoogleMap(): Promise<void> {
  const mapEl = document.getElementById('chalet-map');
  if (!mapEl) return;

  window.addEventListener(EMBED_FALLBACK_EVENT, () => {
    activateEmbedFallback();
  });

  const apiKey = import.meta.env.VITE_GOOGLE_MAPS_API_KEY;
  if (!apiKey) {
    activateEmbedFallback();
    return;
  }

  setOptions({
    key: apiKey,
    v: 'weekly',
    language: 'sk',
    region: 'SK',
  });

  try {
    const [{ Map, InfoWindow }, { AdvancedMarkerElement, PinElement }] = await Promise.all([
      importLibrary('maps') as Promise<google.maps.MapsLibrary>,
      importLibrary('marker') as Promise<google.maps.MarkerLibrary>,
    ]);

    const { position, formattedAddress } = await resolveChaletLocation();
    if (domainOrKeyRestricted || embedFallbackActive) {
      activateEmbedFallback();
      return;
    }

    const coordsEl = document.getElementById('map-coords-value');
    if (coordsEl) {
      coordsEl.textContent = `${position.lat.toFixed(5)}, ${position.lng.toFixed(5)}`;
    }

    const initialPreset = VIEW_PRESETS[currentPresetKey];

    const map = new Map(mapEl, {
      center: position,
      zoom: initialPreset.zoom,
      mapTypeId: initialPreset.mapTypeId,
      mapId: 'DEMO_MAP_ID',
      gestureHandling: 'cooperative',
      mapTypeControl: false,
      streetViewControl: true,
      fullscreenControl: true,
      zoomControl: true,
      internalUsageAttributionIds: ['gmp_mcp_codeassist_v1_aistudio'],
    });

    const pin = new PinElement({
      background: '#1F3A2E',
      borderColor: '#FFFFFF',
      glyphColor: '#F7F6F3',
      glyphText: '★',
      scale: 1.2,
    });

    const marker = new AdvancedMarkerElement({
      map,
      position,
      title: `${CHALET_LABEL} (${GPS_LABEL})`,
    });
    marker.append(pin);

    const headerEl = document.createElement('strong');
    headerEl.className = 'map-info-header';
    headerEl.textContent = CHALET_LABEL;

    const infoWindow = new InfoWindow({
      headerContent: headerEl,
      content: buildInfoWindowContent(formattedAddress),
      ariaLabel: `${CHALET_LABEL} — ${GPS_LABEL}`,
      maxWidth: 300,
    });

    const openChaletInfo = (recenterFirst: boolean) => {
      if (embedFallbackActive) return;
      if (recenterFirst) {
        map.setCenter(position);
      }
      infoWindow.open({
        map,
        anchor: marker,
        shouldFocus: false,
      });
      // Give the InfoWindow above the marker comfortable clearance inside shorter mobile viewports
      window.setTimeout(() => {
        if (!embedFallbackActive) {
          map.panBy(0, window.innerWidth < 640 ? -56 : -24);
        }
      }, 60);
    };

    openChaletInfo(false);

    marker.addEventListener('click', () => {
      infoWindow.open({
        map,
        anchor: marker,
        shouldFocus: false,
      });
    });

    setMapStatus('', true);

    const viewButtons = document.querySelectorAll<HTMLButtonElement>('[data-map-view]');
    viewButtons.forEach((btn) => {
      btn.addEventListener('click', () => {
        if (embedFallbackActive) return;
        const key = (btn.getAttribute('data-map-view') || 'aerial-detail') as MapViewKey;
        const preset = VIEW_PRESETS[key] || VIEW_PRESETS['aerial-detail'];
        currentPresetKey = key;

        viewButtons.forEach((item) => {
          item.setAttribute('aria-selected', item === btn ? 'true' : 'false');
        });

        map.setMapTypeId(preset.mapTypeId);
        map.setZoom(preset.zoom);
        openChaletInfo(true);
      });
    });

    const recenterBtn = document.getElementById('map-recenter-btn');
    if (recenterBtn) {
      recenterBtn.addEventListener('click', () => {
        if (embedFallbackActive) return;
        const preset = VIEW_PRESETS[currentPresetKey] || VIEW_PRESETS['aerial-detail'];
        map.setZoom(preset.zoom);
        openChaletInfo(true);
      });
    }
  } catch (err) {
    if (isQuotaError(err)) {
      quotaErrorDetected = true;
      window.dispatchEvent(new CustomEvent(QUOTA_EVENT));
    }
    activateEmbedFallback();
  }
}

installQuotaListeners();

document.addEventListener('DOMContentLoaded', () => {
  attachQuotaBannerListener();
  void initChaletGoogleMap();
});
